From 5cbda35e3237f39b53a9e265e35f62c98b05c443 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:54:04 -0700 Subject: [PATCH 1/3] Start every Rule private, with a rotating link and files that follow its readers. New Rules stay off lists until the person who holds the pen turns on a share link, or the team features one. Uploaded files are readable only by those readers, stripped of location metadata, and deleted with the Rule, draft, or account. --- .env.example | 3 + app/(marketing)/r/[shareSlug]/page.tsx | 90 +++++++ app/(marketing)/rules/[id]/page.tsx | 23 +- app/api/drafts/me/route.ts | 14 ++ app/api/rules/[id]/route.ts | 38 +-- app/api/rules/[id]/share/route.ts | 86 +++++++ app/api/rules/route.ts | 18 ++ app/api/uploads/[id]/route.ts | 75 +++++- app/api/uploads/route.ts | 10 + app/api/user/me/route.ts | 9 +- lib/create/ruleExport.ts | 10 +- lib/publishedRuleAccess.ts | 27 +-- lib/ruleShareTypes.ts | 36 +++ lib/ruleVisibility.ts | 88 +++++++ lib/server/adminRuleReadLog.ts | 23 ++ lib/server/env.ts | 10 + lib/server/guestRuleClaim.ts | 27 +++ lib/server/publishedRules.ts | 170 ++++++++++--- lib/server/ruleAdmins.ts | 8 + lib/server/ruleShare.ts | 167 +++++++++++++ lib/server/shareSlug.ts | 32 +++ lib/server/uploads/deleteUploadedFiles.ts | 77 ++++++ lib/server/uploads/extractUploadIds.ts | 20 ++ lib/server/uploads/linkUploads.ts | 44 ++++ lib/server/uploads/saveCreateFlowUpload.ts | 23 +- lib/server/uploads/stripImageMetadata.ts | 86 +++++++ lib/server/uploads/uploadGrantCookie.ts | 65 +++++ lib/server/validation/createFlowSchemas.ts | 7 + lib/sharePaths.ts | 56 +++++ lib/siteMetadata.ts | 2 +- .../migration.sql | 112 +++++++++ prisma/schema.prisma | 48 +++- tests/unit/extractUploadIds.test.ts | 20 ++ tests/unit/publishedRuleAccess.test.ts | 26 +- tests/unit/publishedRules.test.ts | 200 ++++++++++++--- tests/unit/ruleShare.test.ts | 228 ++++++++++++++++++ tests/unit/ruleShareTypes.test.ts | 36 +++ tests/unit/ruleVisibility.test.ts | 111 +++++++++ tests/unit/rulesByIdDeleteRoute.test.ts | 4 + tests/unit/rulesByIdPatchRoute.test.ts | 4 + tests/unit/rulesByIdRoute.test.ts | 188 +++++++++------ tests/unit/rulesPublishPostRoute.test.ts | 4 + tests/unit/rulesShareRoute.test.ts | 90 +++++++ tests/unit/saveCreateFlowUpload.test.ts | 8 + tests/unit/sharePaths.test.ts | 46 ++++ tests/unit/shareSlug.test.ts | 20 ++ tests/unit/siteMetadata.test.ts | 2 +- tests/unit/stripImageMetadata.test.ts | 20 ++ tests/unit/uploadsByIdRoute.test.ts | 133 +++++++++- tests/unit/userMeDeleteRoute.test.ts | 4 + 50 files changed, 2429 insertions(+), 219 deletions(-) create mode 100644 app/(marketing)/r/[shareSlug]/page.tsx create mode 100644 app/api/rules/[id]/share/route.ts create mode 100644 lib/ruleShareTypes.ts create mode 100644 lib/ruleVisibility.ts create mode 100644 lib/server/adminRuleReadLog.ts create mode 100644 lib/server/ruleAdmins.ts create mode 100644 lib/server/ruleShare.ts create mode 100644 lib/server/shareSlug.ts create mode 100644 lib/server/uploads/deleteUploadedFiles.ts create mode 100644 lib/server/uploads/extractUploadIds.ts create mode 100644 lib/server/uploads/linkUploads.ts create mode 100644 lib/server/uploads/stripImageMetadata.ts create mode 100644 lib/server/uploads/uploadGrantCookie.ts create mode 100644 lib/sharePaths.ts create mode 100644 prisma/migrations/20261110000000_rule_visibility_and_uploads/migration.sql create mode 100644 tests/unit/extractUploadIds.test.ts create mode 100644 tests/unit/ruleShare.test.ts create mode 100644 tests/unit/ruleShareTypes.test.ts create mode 100644 tests/unit/ruleVisibility.test.ts create mode 100644 tests/unit/rulesShareRoute.test.ts create mode 100644 tests/unit/sharePaths.test.ts create mode 100644 tests/unit/shareSlug.test.ts create mode 100644 tests/unit/stripImageMetadata.test.ts diff --git a/.env.example b/.env.example index 56e76f3..9351644 100644 --- a/.env.example +++ b/.env.example @@ -46,6 +46,9 @@ NEXT_PUBLIC_ENABLE_BACKEND_SYNC= # SITE_INDEXING=true # SITE_INDEXING=false +# Named admins who may open a private Rule. Comma-separated emails. Every such read is logged. +# RULE_ADMIN_EMAILS=ops@example.org + # Writable directory for `POST /api/uploads` (community photo + custom-method attachments). # In production (e.g. Cloudron localstorage mount), set to the mounted path. Local dev example: # UPLOAD_ROOT="/absolute/path/to/community-rule/var/uploads" diff --git a/app/(marketing)/r/[shareSlug]/page.tsx b/app/(marketing)/r/[shareSlug]/page.tsx new file mode 100644 index 0000000..74dc1a0 --- /dev/null +++ b/app/(marketing)/r/[shareSlug]/page.tsx @@ -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 { + 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 ( +
+
+ + +
+
+ ); +} diff --git a/app/(marketing)/rules/[id]/page.tsx b/app/(marketing)/rules/[id]/page.tsx index eba494d..ff27737 100644 --- a/app/(marketing)/rules/[id]/page.tsx +++ b/app/(marketing)/rules/[id]/page.tsx @@ -1,7 +1,8 @@ import type { Metadata } from "next"; import { notFound } from "next/navigation"; import messages from "../../../../messages/en/index"; -import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules"; +import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; +import { getSessionUser } from "../../../../lib/server/session"; import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections"; import { robotsForPublishedRule, @@ -14,17 +15,28 @@ interface PageProps { params: Promise<{ id: string }>; } +async function loadReadableRule(id: string) { + const user = await getSessionUser(); + return getReadablePublishedRule({ + idOrSlug: id, + user, + viaShareSlug: false, + requestPath: `/rules/${id}`, + }); +} + export async function generateMetadata({ params, }: PageProps): Promise { const { id } = await params; - const rule = await getPublicPublishedRuleById(id); - if (!rule) { + const resolved = await loadReadableRule(id); + if (!resolved) { return { title: messages.pages.ruleDetail.notFoundTitle, description: "The requested CommunityRule could not be found.", }; } + const { rule } = resolved; const description = typeof rule.summary === "string" && rule.summary.trim().length > 0 ? rule.summary @@ -51,10 +63,11 @@ export async function generateMetadata({ export default async function PublicRuleDetailPage({ params }: PageProps) { const { id } = await params; - const rule = await getPublicPublishedRuleById(id); - if (!rule) { + const resolved = await loadReadableRule(id); + if (!resolved) { notFound(); } + const { rule } = resolved; const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document); const description = diff --git a/app/api/drafts/me/route.ts b/app/api/drafts/me/route.ts index 667cc9d..e5fed6c 100644 --- a/app/api/drafts/me/route.ts +++ b/app/api/drafts/me/route.ts @@ -11,6 +11,8 @@ import { apiRoute } from "../../../../lib/server/apiRoute"; import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas"; import { readLimitedJson } from "../../../../lib/server/validation/requestBody"; import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp"; +import { deleteUploadsForDraft } from "../../../../lib/server/uploads/deleteUploadedFiles"; +import { linkUploadsToDraft } from "../../../../lib/server/uploads/linkUploads"; export const GET = apiRoute("drafts.me.get", async () => { if (!isDatabaseConfigured()) { @@ -67,6 +69,11 @@ export const PUT = apiRoute("drafts.me.put", async (request: NextRequest) => { payload: jsonPayload, }, }); + await linkUploadsToDraft({ + draftId: draft.id, + payload, + userId: user.id, + }); return NextResponse.json({ draft: { payload: draft.payload, updatedAt: draft.updatedAt }, @@ -85,6 +92,13 @@ export const DELETE = apiRoute("drafts.me.delete", async () => { // Idempotent: missing draft is a no-op so callers can fire-and-forget after // publish / exit without worrying about prior state. + const draft = await prisma.ruleDraft.findUnique({ + where: { userId: user.id }, + select: { id: true }, + }); + if (draft) { + await deleteUploadsForDraft(draft.id); + } await prisma.ruleDraft.deleteMany({ where: { userId: user.id } }); return NextResponse.json({ ok: true }); diff --git a/app/api/rules/[id]/route.ts b/app/api/rules/[id]/route.ts index 517b97c..ce6c7f4 100644 --- a/app/api/rules/[id]/route.ts +++ b/app/api/rules/[id]/route.ts @@ -8,9 +8,11 @@ import { notFound, unauthorized, } from "../../../../lib/server/responses"; -import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules"; +import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import { getSessionUser } from "../../../../lib/server/session"; import { apiRoute } from "../../../../lib/server/apiRoute"; +import { deleteUploadsForRule } from "../../../../lib/server/uploads/deleteUploadedFiles"; +import { linkUploadsToRule } from "../../../../lib/server/uploads/linkUploads"; import { publishRuleBodySchema } from "../../../../lib/server/validation/createFlowSchemas"; import { readLimitedJson } from "../../../../lib/server/validation/requestBody"; import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp"; @@ -19,29 +21,27 @@ type RouteContext = { params: Promise<{ id: string }> }; export const GET = apiRoute( "rules.byId", - async (_request, context) => { + async (request, context) => { if (!isDatabaseConfigured()) { return dbUnavailable(); } const { id } = await context.params; - - const rule = await getPublicPublishedRuleById(id); - if (!rule) { + const user = await getSessionUser(); + const resolved = await getReadablePublishedRule({ + idOrSlug: id, + user, + viaShareSlug: false, + requestPath: request.nextUrl.pathname, + }); + if (!resolved) { return notFound(); } - const user = await getSessionUser(); - let viewerIsOwner = false; - if (user) { - const ownerRow = await prisma.publishedRule.findUnique({ - where: { id }, - select: { userId: true }, - }); - viewerIsOwner = ownerRow?.userId === user.id; - } - - return NextResponse.json({ rule, viewerIsOwner }); + return NextResponse.json({ + rule: resolved.rule, + viewerIsOwner: resolved.viewerIsOwner, + }); }, ); @@ -90,6 +90,11 @@ export const PATCH = apiRoute( document: document as Prisma.InputJsonValue, }, }); + await linkUploadsToRule({ + ruleId: row.id, + document, + userId: user.id, + }); return NextResponse.json({ ok: true }); }, @@ -120,6 +125,7 @@ export const DELETE = apiRoute( return forbidden("You do not have permission to delete this rule"); } + await deleteUploadsForRule(row.id); await prisma.publishedRule.delete({ where: { id: row.id } }); return NextResponse.json({ ok: true }); diff --git a/app/api/rules/[id]/share/route.ts b/app/api/rules/[id]/share/route.ts new file mode 100644 index 0000000..74a7124 --- /dev/null +++ b/app/api/rules/[id]/share/route.ts @@ -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( + "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( + "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 }); + }, +); diff --git a/app/api/rules/route.ts b/app/api/rules/route.ts index 53b7e8d..b972262 100644 --- a/app/api/rules/route.ts +++ b/app/api/rules/route.ts @@ -25,6 +25,7 @@ import { stakeholderInviteVerifyUrl } from "../../../lib/server/ruleStakeholderI import { STAKEHOLDER_INVITE_TTL_MS } from "../../../lib/server/ruleStakeholders"; import { getSessionUser } from "../../../lib/server/session"; import { issueGuestRuleClaimCookie } from "../../../lib/server/guestRuleClaim"; +import { linkUploadsToRule } from "../../../lib/server/uploads/linkUploads"; import { apiRoute } from "../../../lib/server/apiRoute"; import { getPublicOrigin } from "../../../lib/server/publicOrigin"; import { @@ -123,6 +124,12 @@ export const POST = apiRoute( }); } + await linkUploadsToRule({ + ruleId: rule.id, + document, + userId: null, + }); + return NextResponse.json({ rule: { id: rule.id, @@ -155,6 +162,11 @@ export const POST = apiRoute( document: document as Prisma.InputJsonValue, }, }); + await linkUploadsToRule({ + ruleId: rule.id, + document, + userId: user.id, + }); return NextResponse.json({ rule: { @@ -241,6 +253,12 @@ export const POST = apiRoute( ); } + await linkUploadsToRule({ + ruleId: rule.id, + document, + userId: user.id, + }); + return NextResponse.json({ rule: { id: rule.id, diff --git a/app/api/uploads/[id]/route.ts b/app/api/uploads/[id]/route.ts index e1359d4..413d7eb 100644 --- a/app/api/uploads/[id]/route.ts +++ b/app/api/uploads/[id]/route.ts @@ -1,30 +1,91 @@ import { readFile } from "node:fs/promises"; import { NextResponse } from "next/server"; import { apiRoute } from "../../../../lib/server/apiRoute"; +import { prisma } from "../../../../lib/server/db"; +import { isDatabaseConfigured } from "../../../../lib/server/env"; import { + dbUnavailable, notFound, serverMisconfigured, } from "../../../../lib/server/responses"; +import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; +import { getSessionUser } from "../../../../lib/server/session"; +import { isValidUploadFileId } from "../../../../lib/server/uploads/uploadConstants"; import { resolveUploadedFileById } from "../../../../lib/server/uploads/resolveUploadedFile"; import { getUploadRootFromEnv } from "../../../../lib/server/uploads/uploadRoot"; +import { browserHoldsUploadGrant } from "../../../../lib/server/uploads/uploadGrantCookie"; +import { RULE_VISIBILITY } from "../../../../lib/ruleVisibility"; type RouteContext = { params: Promise<{ id: string }> }; -/** - * Public read for opaque upload ids (no auth). Unguessable UUID stem; - * do not use for sensitive documents without revisiting policy. - */ +function cacheControlForVisibility( + visibility: "private" | "shared_by_link" | "public_and_featured" | null, +): string { + if (visibility === RULE_VISIBILITY.public_and_featured) { + return "public, max-age=3600"; + } + return "private, no-store"; +} + export const GET = apiRoute( "uploads.byId", - async (_request, context) => { + async (request, context) => { if (!getUploadRootFromEnv()) { return serverMisconfigured( "File uploads are not configured (UPLOAD_ROOT is unset).", ); } + if (!isDatabaseConfigured()) { + return dbUnavailable(); + } const { id } = await context.params; - const resolved = await resolveUploadedFileById(id); + if (!isValidUploadFileId(id)) { + return notFound("Upload not found"); + } + + const row = await prisma.upload.findUnique({ + where: { id: id.toLowerCase() }, + select: { + id: true, + userId: true, + draftId: true, + ruleId: true, + rule: { select: { visibility: true } }, + draft: { select: { userId: true } }, + }, + }); + if (!row) { + return notFound("Upload not found"); + } + + const user = await getSessionUser(); + let allowed = false; + let visibility: "private" | "shared_by_link" | "public_and_featured" | null = + row.rule?.visibility ?? null; + + if (row.ruleId) { + const resolved = await getReadablePublishedRule({ + idOrSlug: row.ruleId, + user, + viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link, + requestPath: request.nextUrl.pathname, + }); + allowed = resolved != null; + visibility = resolved?.visibility ?? visibility; + } else if (row.draftId) { + allowed = Boolean(user && row.draft?.userId === user.id); + } else if (user && row.userId === user.id) { + allowed = true; + } else if (!user) { + allowed = await browserHoldsUploadGrant(row.id); + } + + if (!allowed) { + return notFound("Upload not found"); + } + + const resolved = await resolveUploadedFileById(row.id); if (!resolved) { return notFound("Upload not found"); } @@ -34,7 +95,7 @@ export const GET = apiRoute( status: 200, headers: { "Content-Type": resolved.contentType, - "Cache-Control": "public, max-age=31536000, immutable", + "Cache-Control": cacheControlForVisibility(visibility), "X-Content-Type-Options": "nosniff", }, }); diff --git a/app/api/uploads/route.ts b/app/api/uploads/route.ts index 8494801..f40ce0b 100644 --- a/app/api/uploads/route.ts +++ b/app/api/uploads/route.ts @@ -11,6 +11,7 @@ import { getSessionUser } from "../../../lib/server/session"; import { apiRoute } from "../../../lib/server/apiRoute"; import { rateLimitKey } from "../../../lib/server/rateLimit"; import { saveCreateFlowUpload } from "../../../lib/server/uploads/saveCreateFlowUpload"; +import { issueGuestUploadGrantCookie } from "../../../lib/server/uploads/uploadGrantCookie"; import { getUploadRootFromEnv } from "../../../lib/server/uploads/uploadRoot"; import { CREATE_FLOW_UPLOAD_MAX_BYTES, @@ -146,6 +147,7 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => { const saved = await saveCreateFlowUpload({ purpose: purposeRaw, buffer: buf, + userId: user?.id ?? null, }); if ("error" in saved) { @@ -171,6 +173,14 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => { ); } + if (!user) { + try { + await issueGuestUploadGrantCookie(saved.id); + } catch { + // Cookie is best-effort; the file is already stored. + } + } + return NextResponse.json({ url: saved.urlPath, id: saved.id, diff --git a/app/api/user/me/route.ts b/app/api/user/me/route.ts index 40e26ee..7548601 100644 --- a/app/api/user/me/route.ts +++ b/app/api/user/me/route.ts @@ -11,15 +11,13 @@ import { getSessionUser, } from "../../../../lib/server/session"; import { apiRoute } from "../../../../lib/server/apiRoute"; +import { deleteUploadsForUser } from "../../../../lib/server/uploads/deleteUploadedFiles"; /** * Delete the signed-in user and associated data. * - * **Policy (CR-86 / Ticket 15):** Prisma `User` deletion cascades `Session` and - * `RuleDraft`. `PublishedRule` uses `onDelete: SetNull` on `userId`, so published - * rules remain public with `userId = null` (anonymous/orphan rows) rather than - * being removed with the account. Change would require a schema migration if - * product later requires deleting all published rules with the user. + * Prisma `User` deletion cascades `Session`, `RuleDraft`, and `PublishedRule` + * (and uploads linked to those rows). Disk files are removed first. */ export const DELETE = apiRoute("user.me.delete", async () => { if (!isDatabaseConfigured()) { @@ -32,6 +30,7 @@ export const DELETE = apiRoute("user.me.delete", async () => { } try { + await deleteUploadsForUser(user.id); await prisma.user.delete({ where: { id: user.id } }); } catch { return internalError("Failed to delete account"); diff --git a/lib/create/ruleExport.ts b/lib/create/ruleExport.ts index f766676..468e6f6 100644 --- a/lib/create/ruleExport.ts +++ b/lib/create/ruleExport.ts @@ -8,10 +8,12 @@ import type { import type { StoredLastPublishedRule } from "./lastPublishedRule"; import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections"; -export function buildPublicRuleUrl(origin: string, ruleId: string): string { - const base = origin.replace(/\/$/, ""); - return `${base}/rules/${encodeURIComponent(ruleId)}`; -} +export { + buildPublicRuleUrl, + buildShareRuleUrl, + formatShareUrlDisplay, + shareCopyUrl, +} from "../sharePaths"; /** Safe filename fragment from rule title, with stable fallback. */ export function exportFilenameBase(rule: StoredLastPublishedRule): string { diff --git a/lib/publishedRuleAccess.ts b/lib/publishedRuleAccess.ts index eddb75a..84b39e9 100644 --- a/lib/publishedRuleAccess.ts +++ b/lib/publishedRuleAccess.ts @@ -1,24 +1,15 @@ import type { Prisma } from "@prisma/client"; +import { RULE_VISIBILITY } from "./ruleVisibility"; -/** - * Access model for published CommunityRules: - * - * - **Readable without sign-in:** every published row is share-by-link at - * `/rules/[id]` and `GET /api/rules/[id]`. - * - **Listed** (public catalog `GET /api/rules`, sitemap, indexable): owned - * rows, and ownerless rows that are *not* waiting on a guest claim - * (including rules orphaned when an account is deleted). - * - **Unlisted** (omitted from the catalog and sitemap, `noindex`): guest - * publishes with `userId` null and `claimTokenHash` set, until claimed. - */ -export function isListedPublishedRule(row: { - userId: string | null; - claimTokenHash: string | null; -}): boolean { - return row.userId != null || row.claimTokenHash == null; -} +export { + RULE_VISIBILITY, + isListedPublishedRule, + canReadPublishedRule, + isPrivilegedAdminRead, +} from "./ruleVisibility"; +export type { RuleVisibility, PublishedRuleReadAccess } from "./ruleVisibility"; /** Prisma `where` for the public catalog and sitemap. */ export const LISTED_PUBLISHED_RULE_WHERE: Prisma.PublishedRuleWhereInput = { - OR: [{ userId: { not: null } }, { claimTokenHash: null }], + visibility: RULE_VISIBILITY.public_and_featured, }; diff --git a/lib/ruleShareTypes.ts b/lib/ruleShareTypes.ts new file mode 100644 index 0000000..25d8510 --- /dev/null +++ b/lib/ruleShareTypes.ts @@ -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 }; +} diff --git a/lib/ruleVisibility.ts b/lib/ruleVisibility.ts new file mode 100644 index 0000000..17fde10 --- /dev/null +++ b/lib/ruleVisibility.ts @@ -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; +} diff --git a/lib/server/adminRuleReadLog.ts b/lib/server/adminRuleReadLog.ts new file mode 100644 index 0000000..cc3d938 --- /dev/null +++ b/lib/server/adminRuleReadLog.ts @@ -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 { + 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); + } +} diff --git a/lib/server/env.ts b/lib/server/env.ts index 7f11729..09381ab 100644 --- a/lib/server/env.ts +++ b/lib/server/env.ts @@ -29,3 +29,13 @@ export function getSmtpUrl(): string | undefined { export function isDatabaseConfigured(): boolean { return Boolean(getDatabaseUrl()); } + +/** Named admins who may open a private Rule. Comma-separated emails. */ +export function getRuleAdminEmails(): string[] { + const raw = process.env.RULE_ADMIN_EMAILS?.trim(); + if (!raw) return []; + return raw + .split(",") + .map((item) => item.trim().toLowerCase()) + .filter((item) => item.length > 0); +} diff --git a/lib/server/guestRuleClaim.ts b/lib/server/guestRuleClaim.ts index 0966ee7..3af1b11 100644 --- a/lib/server/guestRuleClaim.ts +++ b/lib/server/guestRuleClaim.ts @@ -69,6 +69,33 @@ async function clearGuestRuleClaimCookie(): Promise { }); } +/** True when this browser's claim cookie hashes to `claimTokenHash`. */ +export async function browserHoldsClaimForHash( + claimTokenHash: string | null | undefined, +): Promise { + if (typeof claimTokenHash !== "string" || claimTokenHash.length === 0) { + return false; + } + try { + const store = await cookies(); + const tokens = parseClaimTokens( + store.get(GUEST_RULE_CLAIM_COOKIE_NAME)?.value, + ); + if (tokens.length === 0) return false; + let pepper: string; + try { + pepper = getSessionPepper(); + } catch { + return false; + } + return tokens.some( + (token) => hashRuleClaimToken(token, pepper) === claimTokenHash, + ); + } catch { + return false; + } +} + /** * Attach ownerless published rules whose claim secrets are in this browser's * cookie to `userId`, then drop the cookie. Never throws to the caller. diff --git a/lib/server/publishedRules.ts b/lib/server/publishedRules.ts index a3ae502..6c547b2 100644 --- a/lib/server/publishedRules.ts +++ b/lib/server/publishedRules.ts @@ -1,14 +1,22 @@ +import type { User } from "@prisma/client"; import { LISTED_PUBLISHED_RULE_WHERE, + canReadPublishedRule, isListedPublishedRule, + isPrivilegedAdminRead, + type RuleVisibility, } from "../publishedRuleAccess"; import { prisma } from "./db"; import { isDatabaseConfigured } from "./env"; +import { browserHoldsClaimForHash } from "./guestRuleClaim"; +import { isRuleAdminEmail } from "./ruleAdmins"; +import { logAdminRuleRead } from "./adminRuleReadLog"; /** - * Public fields safe to expose via the unauthenticated rule detail surfaces - * (`GET /api/rules/[id]` and `/rules/[id]`). `userId` and `claimTokenHash` - * stay server-side; callers get {@link PublicPublishedRule.isListed} instead. + * Public fields safe to expose via readable rule detail surfaces + * (`GET /api/rules/[id]` and `/rules/[id]` / `/r/[shareSlug]`). + * `userId` and `claimTokenHash` stay server-side; callers get + * {@link PublicPublishedRule.isListed} instead. */ const PUBLISHED_RULE_PUBLIC_SELECT = { id: true, @@ -26,38 +34,136 @@ export type PublicPublishedRule = { document: unknown; createdAt: Date; updatedAt: Date; - /** False for guest-claim rows; true for owned and orphaned-after-delete rows. */ + /** True only for public-and-featured Rules. */ isListed: boolean; }; -/** - * Fetch a single published rule by id for public read surfaces. - * - * Returns `null` when the database is not configured, the id does not match - * any row, or the query throws — callers render a 404 in all missing cases - * and are expected to surface the "DB not configured" state separately if - * they care about distinguishing it (the API route does; the page does not). - */ -export async function getPublicPublishedRuleById( - id: string, -): Promise { - if (!isDatabaseConfigured()) return null; - if (typeof id !== "string" || id.trim() === "") return null; - try { - const rule = await prisma.publishedRule.findUnique({ - where: { id }, - select: { - ...PUBLISHED_RULE_PUBLIC_SELECT, - userId: true, - claimTokenHash: true, - }, +export type ReadablePublishedRule = { + rule: PublicPublishedRule; + viewerIsOwner: boolean; + visibility: RuleVisibility; + shareSlug: string | null; +}; + +const RULE_ACCESS_SELECT = { + ...PUBLISHED_RULE_PUBLIC_SELECT, + userId: true, + claimTokenHash: true, + visibility: true, + shareSlug: true, + stakeholders: { + select: { email: true, userId: true }, + }, +} as const; + +function toPublicRule(row: { + id: string; + title: string; + summary: string | null; + document: unknown; + createdAt: Date; + updatedAt: Date; + visibility: RuleVisibility; +}): PublicPublishedRule { + return { + id: row.id, + title: row.title, + summary: row.summary, + document: row.document, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + isListed: isListedPublishedRule({ visibility: row.visibility }), + }; +} + +async function resolveAccessForRow(opts: { + row: { + id: string; + title: string; + summary: string | null; + document: unknown; + createdAt: Date; + updatedAt: Date; + userId: string | null; + claimTokenHash: string | null; + visibility: RuleVisibility; + shareSlug: string | null; + stakeholders: Array<{ email: string; userId: string | null }>; + }; + viaShareSlug: boolean; + user: User | null; + requestPath: string; +}): Promise { + const { row, viaShareSlug, user, requestPath } = opts; + const viewerEmail = user?.email.trim().toLowerCase() ?? null; + const invitedEmails = row.stakeholders.map((s) => s.email.toLowerCase()); + const invitedUserIds = row.stakeholders + .map((s) => s.userId) + .filter((id): id is string => typeof id === "string" && id.length > 0); + const isAdmin = isRuleAdminEmail(user?.email ?? null); + const holdsGuestClaim = await browserHoldsClaimForHash(row.claimTokenHash); + const access = { + visibility: row.visibility, + viaShareSlug, + userId: user?.id ?? null, + ownerUserId: row.userId, + viewerEmail, + invitedEmails, + invitedUserIds, + isAdmin, + holdsGuestClaim, + }; + if (!canReadPublishedRule(access)) return null; + if (isPrivilegedAdminRead(access) && viewerEmail) { + await logAdminRuleRead({ + ruleId: row.id, + adminEmail: viewerEmail, + adminUserId: user?.id ?? null, + path: requestPath, + }); + } + return { + rule: toPublicRule(row), + viewerIsOwner: user != null && row.userId === user.id, + visibility: row.visibility, + shareSlug: row.shareSlug, + }; +} + +/** + * Fetch a published rule the viewer is allowed to read. + * + * Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link + * strangers must use the rotating slug so turning the link off invalidates it. + * Returns `null` for missing rows, denied readers, and DB failures — callers + * render the same 404 as a missing Rule. + */ +export async function getReadablePublishedRule(opts: { + idOrSlug: string; + user: User | null; + viaShareSlug: boolean; + requestPath: string; +}): Promise { + if (!isDatabaseConfigured()) return null; + const idOrSlug = opts.idOrSlug.trim(); + if (idOrSlug.length === 0) return null; + try { + const row = opts.viaShareSlug + ? await prisma.publishedRule.findUnique({ + where: { shareSlug: idOrSlug }, + select: RULE_ACCESS_SELECT, + }) + : await prisma.publishedRule.findUnique({ + where: { id: idOrSlug }, + select: RULE_ACCESS_SELECT, + }); + if (!row) return null; + return resolveAccessForRow({ + row, + viaShareSlug: opts.viaShareSlug, + user: opts.user, + requestPath: opts.requestPath, }); - if (!rule) return null; - const { userId, claimTokenHash, ...publicFields } = rule; - return { - ...publicFields, - isListed: isListedPublishedRule({ userId, claimTokenHash }), - }; } catch { return null; } @@ -89,7 +195,7 @@ const LISTED_PUBLISHED_RULE_SITEMAP_CAP = 10_000; /** * Public catalog of listed published rules (**most recently updated first**, - * then stable `id` tie-break). Guest-claim rows are omitted. + * then stable `id` tie-break). Only public-and-featured rows. * Returns `null` when the database is not configured or the query throws. */ export async function listListedPublishedRules( diff --git a/lib/server/ruleAdmins.ts b/lib/server/ruleAdmins.ts new file mode 100644 index 0000000..91675ec --- /dev/null +++ b/lib/server/ruleAdmins.ts @@ -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); +} diff --git a/lib/server/ruleShare.ts b/lib/server/ruleShare.ts new file mode 100644 index 0000000..529aac2 --- /dev/null +++ b/lib/server/ruleShare.ts @@ -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 { + 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 }; +} diff --git a/lib/server/shareSlug.ts b/lib/server/shareSlug.ts new file mode 100644 index 0000000..fdeaf7e --- /dev/null +++ b/lib/server/shareSlug.ts @@ -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 { + 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"); +} diff --git a/lib/server/uploads/deleteUploadedFiles.ts b/lib/server/uploads/deleteUploadedFiles.ts new file mode 100644 index 0000000..5095457 --- /dev/null +++ b/lib/server/uploads/deleteUploadedFiles.ts @@ -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 { + 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 { + const unique = [...new Set(ids)]; + for (const id of unique) { + await unlinkResolved(id); + } +} + +export async function deleteUploadsForRule(ruleId: string): Promise { + 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 { + 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 { + 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); +} diff --git a/lib/server/uploads/extractUploadIds.ts b/lib/server/uploads/extractUploadIds.ts new file mode 100644 index 0000000..f7eabeb --- /dev/null +++ b/lib/server/uploads/extractUploadIds.ts @@ -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(); + for (const match of text.matchAll(UPLOAD_PATH_RE)) { + const id = match[1]?.toLowerCase(); + if (id && isValidUploadFileId(id)) ids.add(id); + } + return [...ids]; +} diff --git a/lib/server/uploads/linkUploads.ts b/lib/server/uploads/linkUploads.ts new file mode 100644 index 0000000..e71c2c6 --- /dev/null +++ b/lib/server/uploads/linkUploads.ts @@ -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 { + 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 { + 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); + } +} diff --git a/lib/server/uploads/saveCreateFlowUpload.ts b/lib/server/uploads/saveCreateFlowUpload.ts index 4badd73..9fb9ae1 100644 --- a/lib/server/uploads/saveCreateFlowUpload.ts +++ b/lib/server/uploads/saveCreateFlowUpload.ts @@ -1,9 +1,12 @@ import { writeFile } from "node:fs/promises"; import path from "node:path"; import { randomUUID } from "node:crypto"; +import { logger } from "../../logger"; +import { prisma } from "../db"; import type { CreateFlowUploadPurpose } from "./uploadConstants"; import { extensionForMime } from "./uploadConstants"; import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot"; +import { stripImageMetadata } from "./stripImageMetadata"; import { validateCreateFlowUploadBytes, type CreateFlowUploadValidationReason, @@ -30,6 +33,7 @@ export type SaveCreateFlowUploadFailure = { export async function saveCreateFlowUpload(params: { purpose: CreateFlowUploadPurpose; buffer: Buffer; + userId?: string | null; }): Promise { const root = getUploadRootFromEnv(); if (!root) { @@ -42,18 +46,33 @@ export async function saveCreateFlowUpload(params: { return { error: "validation", reason: validated.reason }; } + const stripped = stripImageMetadata(buffer, validated.mimeType); const id = randomUUID(); const ext = extensionForMime(validated.mimeType); const fileName = `${id}${ext}`; const absolutePath = path.join(root, fileName); await ensureUploadRootExists(root); - await writeFile(absolutePath, buffer, { mode: 0o644 }); + await writeFile(absolutePath, stripped, { mode: 0o644 }); + + try { + await prisma.upload.create({ + data: { + id, + mimeType: validated.mimeType, + byteLength: stripped.length, + purpose, + userId: params.userId ?? null, + }, + }); + } catch (err) { + logger.warn("[uploads] failed to record upload row", id, err); + } return { id, urlPath: `/api/uploads/${id}`, mimeType: validated.mimeType, - byteLength: buffer.length, + byteLength: stripped.length, }; } diff --git a/lib/server/uploads/stripImageMetadata.ts b/lib/server/uploads/stripImageMetadata.ts new file mode 100644 index 0000000..43d617e --- /dev/null +++ b/lib/server/uploads/stripImageMetadata.ts @@ -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); +} diff --git a/lib/server/uploads/uploadGrantCookie.ts b/lib/server/uploads/uploadGrantCookie.ts new file mode 100644 index 0000000..bdbf09d --- /dev/null +++ b/lib/server/uploads/uploadGrantCookie.ts @@ -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 { + 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 { + 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; + } +} diff --git a/lib/server/validation/createFlowSchemas.ts b/lib/server/validation/createFlowSchemas.ts index 52b8c40..de02529 100644 --- a/lib/server/validation/createFlowSchemas.ts +++ b/lib/server/validation/createFlowSchemas.ts @@ -219,6 +219,13 @@ export const publishRuleBodySchema = z.object({ export type PublishRuleBody = z.infer; +export const patchRuleShareBodySchema = z.object({ + visibility: z.enum(["private", "shared_by_link", "public_and_featured"]), + communityAgreed: z.boolean().optional(), +}); + +export type PatchRuleShareBody = z.infer; + export const postRuleStakeholderBodySchema = z.object({ email: stakeholderEmailSchema, }); diff --git a/lib/sharePaths.ts b/lib/sharePaths.ts new file mode 100644 index 0000000..c551e93 --- /dev/null +++ b/lib/sharePaths.ts @@ -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); +} diff --git a/lib/siteMetadata.ts b/lib/siteMetadata.ts index 3b66922..1a03692 100644 --- a/lib/siteMetadata.ts +++ b/lib/siteMetadata.ts @@ -25,7 +25,7 @@ const INDEXABLE_HOSTS = new Set([ export const NO_INDEX_ROBOTS = { index: false, follow: false } as const; -/** Unlisted (guest-claim) rule pages stay shareable but must not be indexed. */ +/** Shared-by-link and private rule pages stay shareable but must not be indexed. */ export function robotsForPublishedRule(isListed: boolean): | { index: false; diff --git a/prisma/migrations/20261110000000_rule_visibility_and_uploads/migration.sql b/prisma/migrations/20261110000000_rule_visibility_and_uploads/migration.sql new file mode 100644 index 0000000..87550c7 --- /dev/null +++ b/prisma/migrations/20261110000000_rule_visibility_and_uploads/migration.sql @@ -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"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 97d20b6..3b00500 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -16,6 +16,7 @@ model User { sessions Session[] draft RuleDraft? rules PublishedRule[] + uploads Upload[] /// At most one pending verified email change (CR-103). emailChangeToken EmailChangeToken? /// Rules this user was invited to as a stakeholder (after accepting invite). @@ -68,12 +69,19 @@ model RuleDraft { user User @relation(fields: [userId], references: [id], onDelete: Cascade) payload Json updatedAt DateTime @updatedAt + uploads Upload[] +} + +enum RuleVisibility { + private + shared_by_link + public_and_featured } model PublishedRule { id String @id @default(cuid()) userId String? - user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) title String summary String? document Json @@ -82,10 +90,48 @@ model PublishedRule { /// Hashed one-time secret so the publishing browser can claim this row on sign-in. /// Null for owned publishes and after a successful claim. claimTokenHash String? @unique + /// Who can read this Rule. New rows start private. + visibility RuleVisibility @default(private) + /// Rotating public path `/r/{shareSlug}`. Null while private. Replaced when a link is turned back on. + shareSlug String? @unique stakeholders RuleStakeholder[] + uploads Upload[] @@index([userId]) + @@index([visibility, updatedAt]) +} + +/// File written under UPLOAD_ROOT. Readers follow the linked Rule or draft. +model Upload { + id String @id + mimeType String + byteLength Int + purpose String + userId String? + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + draftId String? + draft RuleDraft? @relation(fields: [draftId], references: [id], onDelete: Cascade) + ruleId String? + rule PublishedRule? @relation(fields: [ruleId], references: [id], onDelete: Cascade) + createdAt DateTime @default(now()) + + @@index([ruleId]) + @@index([draftId]) + @@index([userId]) +} + +/// Named-admin reads of Rules they do not already hold the pen for or belong to. +model AdminRuleReadLog { + id String @id @default(cuid()) + ruleId String + adminEmail String + adminUserId String? + path String + createdAt DateTime @default(now()) + + @@index([ruleId, createdAt]) + @@index([adminEmail, createdAt]) } /// Invite + access for a published rule: email invite at publish; userId set after magic-link-style accept. diff --git a/tests/unit/extractUploadIds.test.ts b/tests/unit/extractUploadIds.test.ts new file mode 100644 index 0000000..56a9107 --- /dev/null +++ b/tests/unit/extractUploadIds.test.ts @@ -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([]); + }); +}); diff --git a/tests/unit/publishedRuleAccess.test.ts b/tests/unit/publishedRuleAccess.test.ts index ec6cc1d..a0e77ae 100644 --- a/tests/unit/publishedRuleAccess.test.ts +++ b/tests/unit/publishedRuleAccess.test.ts @@ -3,34 +3,26 @@ import { LISTED_PUBLISHED_RULE_WHERE, isListedPublishedRule, } from "../../lib/publishedRuleAccess"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; describe("isListedPublishedRule", () => { - it("lists owned rules", () => { + it("lists public and featured Rules only", () => { expect( - isListedPublishedRule({ userId: "user-1", claimTokenHash: null }), + isListedPublishedRule({ visibility: RULE_VISIBILITY.public_and_featured }), ).toBe(true); - }); - - it("lists ownerless rows that are not waiting on a guest claim", () => { - expect(isListedPublishedRule({ userId: null, claimTokenHash: null })).toBe( - true, - ); - }); - - it("keeps guest-claim rows unlisted", () => { expect( - isListedPublishedRule({ - userId: null, - claimTokenHash: "claim-hash", - }), + isListedPublishedRule({ visibility: RULE_VISIBILITY.private }), + ).toBe(false); + expect( + isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }), ).toBe(false); }); }); describe("LISTED_PUBLISHED_RULE_WHERE", () => { - it("matches owned rows or rows with no claim token", () => { + it("matches public and featured rows", () => { expect(LISTED_PUBLISHED_RULE_WHERE).toEqual({ - OR: [{ userId: { not: null } }, { claimTokenHash: null }], + visibility: RULE_VISIBILITY.public_and_featured, }); }); }); diff --git a/tests/unit/publishedRules.test.ts b/tests/unit/publishedRules.test.ts index 8f05d27..d851e4f 100644 --- a/tests/unit/publishedRules.test.ts +++ b/tests/unit/publishedRules.test.ts @@ -3,6 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const isDatabaseConfiguredMock = vi.fn(); const findUniqueMock = vi.fn(); const findManyMock = vi.fn(); +const browserHoldsClaimForHashMock = vi.fn(); +const isRuleAdminEmailMock = vi.fn(); +const logAdminRuleReadMock = vi.fn(); vi.mock("../../lib/server/env", () => ({ isDatabaseConfigured: () => isDatabaseConfiguredMock(), @@ -17,58 +20,178 @@ vi.mock("../../lib/server/db", () => ({ }, })); +vi.mock("../../lib/server/guestRuleClaim", () => ({ + browserHoldsClaimForHash: (...args: unknown[]) => + browserHoldsClaimForHashMock(...args), +})); + +vi.mock("../../lib/server/ruleAdmins", () => ({ + isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args), +})); + +vi.mock("../../lib/server/adminRuleReadLog", () => ({ + logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args), +})); + import { - getPublicPublishedRuleById, + getReadablePublishedRule, listListedPublishedRules, listListedPublishedRulesForSitemap, } from "../../lib/server/publishedRules"; import { LISTED_PUBLISHED_RULE_WHERE } from "../../lib/publishedRuleAccess"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; + +function row(overrides: Record = {}) { + return { + id: "owned-1", + title: "Owned", + summary: "Hi", + document: {}, + createdAt: new Date("2026-01-01T00:00:00.000Z"), + updatedAt: new Date("2026-01-02T00:00:00.000Z"), + userId: "user-1", + claimTokenHash: null, + visibility: RULE_VISIBILITY.private, + shareSlug: null, + stakeholders: [], + ...overrides, + }; +} beforeEach(() => { isDatabaseConfiguredMock.mockReset(); findUniqueMock.mockReset(); findManyMock.mockReset(); + browserHoldsClaimForHashMock.mockReset(); + isRuleAdminEmailMock.mockReset(); + logAdminRuleReadMock.mockReset(); + browserHoldsClaimForHashMock.mockResolvedValue(false); + isRuleAdminEmailMock.mockReturnValue(false); + logAdminRuleReadMock.mockResolvedValue(undefined); }); -describe("getPublicPublishedRuleById", () => { - it("returns isListed false for guest-claim rows without exposing claim tokens", async () => { +describe("getReadablePublishedRule", () => { + it("returns listed public-and-featured Rules to anonymous readers", async () => { isDatabaseConfiguredMock.mockReturnValue(true); - findUniqueMock.mockResolvedValueOnce({ - id: "guest-1", - title: "Guest rule", - summary: null, - document: {}, - createdAt: new Date("2026-01-01T00:00:00.000Z"), - updatedAt: new Date("2026-01-02T00:00:00.000Z"), - userId: null, - claimTokenHash: "secret-hash", - }); + findUniqueMock.mockResolvedValueOnce( + row({ visibility: RULE_VISIBILITY.public_and_featured }), + ); - const rule = await getPublicPublishedRuleById("guest-1"); - expect(rule).toMatchObject({ - id: "guest-1", - title: "Guest rule", - isListed: false, + const resolved = await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: null, + viaShareSlug: false, + requestPath: "/rules/owned-1", }); - expect(rule).not.toHaveProperty("userId"); - expect(rule).not.toHaveProperty("claimTokenHash"); - }); - - it("returns isListed true for owned rules", async () => { - isDatabaseConfiguredMock.mockReturnValue(true); - findUniqueMock.mockResolvedValueOnce({ + expect(resolved?.rule).toMatchObject({ id: "owned-1", title: "Owned", - summary: "Hi", - document: {}, - createdAt: new Date("2026-01-01T00:00:00.000Z"), - updatedAt: new Date("2026-01-02T00:00:00.000Z"), - userId: "user-1", - claimTokenHash: null, + isListed: true, }); + expect(resolved?.rule).not.toHaveProperty("userId"); + expect(resolved?.rule).not.toHaveProperty("claimTokenHash"); + }); - const rule = await getPublicPublishedRuleById("owned-1"); - expect(rule?.isListed).toBe(true); + it("hides private Rules from anonymous readers", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce(row()); + expect( + await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: null, + viaShareSlug: false, + requestPath: "/rules/owned-1", + }), + ).toBeNull(); + }); + + it("lets the publishing browser read a private Rule with the guest claim", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + browserHoldsClaimForHashMock.mockResolvedValue(true); + findUniqueMock.mockResolvedValueOnce( + row({ userId: null, claimTokenHash: "claim-hash" }), + ); + const resolved = await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: null, + viaShareSlug: false, + requestPath: "/rules/owned-1", + }); + expect(resolved?.rule.id).toBe("owned-1"); + expect(browserHoldsClaimForHashMock).toHaveBeenCalledWith("claim-hash"); + }); + + it("lets the owner read a private Rule by id", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce(row()); + const resolved = await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: { id: "user-1", email: "owner@example.org" } as never, + viaShareSlug: false, + requestPath: "/rules/owned-1", + }); + expect(resolved?.rule.id).toBe("owned-1"); + expect(resolved?.viewerIsOwner).toBe(true); + expect(resolved?.rule.isListed).toBe(false); + }); + + it("does not treat a shared-by-link Rule as public at /rules/{id}", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce( + row({ + visibility: RULE_VISIBILITY.shared_by_link, + shareSlug: "k7f2-9qxm", + }), + ); + expect( + await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: null, + viaShareSlug: false, + requestPath: "/rules/owned-1", + }), + ).toBeNull(); + }); + + it("lets anonymous readers use the rotating slug", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce( + row({ + visibility: RULE_VISIBILITY.shared_by_link, + shareSlug: "k7f2-9qxm", + }), + ); + const resolved = await getReadablePublishedRule({ + idOrSlug: "k7f2-9qxm", + user: null, + viaShareSlug: true, + requestPath: "/r/k7f2-9qxm", + }); + expect(resolved?.rule.id).toBe("owned-1"); + expect(resolved?.rule.isListed).toBe(false); + expect(findUniqueMock).toHaveBeenCalledWith( + expect.objectContaining({ where: { shareSlug: "k7f2-9qxm" } }), + ); + }); + + it("logs named-admin reads of private Rules", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + isRuleAdminEmailMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce(row()); + const resolved = await getReadablePublishedRule({ + idOrSlug: "owned-1", + user: { id: "admin-1", email: "admin@example.org" } as never, + viaShareSlug: false, + requestPath: "/rules/owned-1", + }); + expect(resolved?.viewerIsOwner).toBe(false); + expect(logAdminRuleReadMock).toHaveBeenCalledWith( + expect.objectContaining({ + ruleId: "owned-1", + adminEmail: "admin@example.org", + path: "/rules/owned-1", + }), + ); }); }); @@ -100,4 +223,15 @@ describe("listListedPublishedRulesForSitemap", () => { expect(await listListedPublishedRulesForSitemap()).toEqual([]); expect(findManyMock).not.toHaveBeenCalled(); }); + + it("queries only public and featured Rules", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findManyMock.mockResolvedValueOnce([]); + await listListedPublishedRulesForSitemap(); + expect(findManyMock).toHaveBeenCalledWith( + expect.objectContaining({ + where: LISTED_PUBLISHED_RULE_WHERE, + }), + ); + }); }); diff --git a/tests/unit/ruleShare.test.ts b/tests/unit/ruleShare.test.ts new file mode 100644 index 0000000..a947b6b --- /dev/null +++ b/tests/unit/ruleShare.test.ts @@ -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 = {}) { + 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, + }, + }), + ); + }); +}); diff --git a/tests/unit/ruleShareTypes.test.ts b/tests/unit/ruleShareTypes.test.ts new file mode 100644 index 0000000..a43407e --- /dev/null +++ b/tests/unit/ruleShareTypes.test.ts @@ -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("?"); + }); +}); diff --git a/tests/unit/ruleVisibility.test.ts b/tests/unit/ruleVisibility.test.ts new file mode 100644 index 0000000..09b8fb0 --- /dev/null +++ b/tests/unit/ruleVisibility.test.ts @@ -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 { + 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); + }); +}); diff --git a/tests/unit/rulesByIdDeleteRoute.test.ts b/tests/unit/rulesByIdDeleteRoute.test.ts index bb43e16..c2ec4bc 100644 --- a/tests/unit/rulesByIdDeleteRoute.test.ts +++ b/tests/unit/rulesByIdDeleteRoute.test.ts @@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); +vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({ + deleteUploadsForRule: vi.fn().mockResolvedValue(undefined), +})); + import { DELETE } from "../../app/api/rules/[id]/route"; function makeContext(id: string) { diff --git a/tests/unit/rulesByIdPatchRoute.test.ts b/tests/unit/rulesByIdPatchRoute.test.ts index 01155d7..f98d566 100644 --- a/tests/unit/rulesByIdPatchRoute.test.ts +++ b/tests/unit/rulesByIdPatchRoute.test.ts @@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); +vi.mock("../../lib/server/uploads/linkUploads", () => ({ + linkUploadsToRule: vi.fn().mockResolvedValue(undefined), +})); + import { PATCH } from "../../app/api/rules/[id]/route"; function makeContext(id: string) { diff --git a/tests/unit/rulesByIdRoute.test.ts b/tests/unit/rulesByIdRoute.test.ts index db9d85f..ef983e2 100644 --- a/tests/unit/rulesByIdRoute.test.ts +++ b/tests/unit/rulesByIdRoute.test.ts @@ -4,6 +4,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const isDatabaseConfiguredMock = vi.fn(); const findUniqueMock = vi.fn(); const getSessionUserMock = vi.fn(); +const browserHoldsClaimForHashMock = vi.fn(); +const isRuleAdminEmailMock = vi.fn(); +const logAdminRuleReadMock = vi.fn(); vi.mock("../../lib/server/env", () => ({ isDatabaseConfigured: () => isDatabaseConfiguredMock(), @@ -21,17 +24,54 @@ vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); +vi.mock("../../lib/server/guestRuleClaim", () => ({ + browserHoldsClaimForHash: (...args: unknown[]) => + browserHoldsClaimForHashMock(...args), +})); + +vi.mock("../../lib/server/ruleAdmins", () => ({ + isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args), +})); + +vi.mock("../../lib/server/adminRuleReadLog", () => ({ + logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args), +})); + import { GET } from "../../app/api/rules/[id]/route"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; function makeContext(id: string) { return { params: Promise.resolve({ id }) }; } +function row(overrides: Record = {}) { + return { + id: "rule-1", + title: "Mutual Aid Mondays", + summary: "A grassroots community in Denver.", + document: { sections: [] }, + createdAt: new Date("2026-01-01T00:00:00Z"), + updatedAt: new Date("2026-01-02T00:00:00Z"), + userId: "user-1", + claimTokenHash: null, + visibility: RULE_VISIBILITY.private, + shareSlug: null, + stakeholders: [], + ...overrides, + }; +} + beforeEach(() => { isDatabaseConfiguredMock.mockReset(); findUniqueMock.mockReset(); getSessionUserMock.mockReset(); + browserHoldsClaimForHashMock.mockReset(); + isRuleAdminEmailMock.mockReset(); + logAdminRuleReadMock.mockReset(); getSessionUserMock.mockResolvedValue(null); + browserHoldsClaimForHashMock.mockResolvedValue(false); + isRuleAdminEmailMock.mockReturnValue(false); + logAdminRuleReadMock.mockResolvedValue(undefined); }); describe("GET /api/rules/[id]", () => { @@ -86,80 +126,39 @@ describe("GET /api/rules/[id]", () => { expect(res.status).toBe(404); }); - it("returns 200 with { rule, viewerIsOwner: false } when a published rule exists and the viewer is anonymous", async () => { + it("returns 404 for a private Rule when the viewer is anonymous", async () => { isDatabaseConfiguredMock.mockReturnValue(true); - const row = { - id: "rule-1", - title: "Mutual Aid Mondays", - summary: "A grassroots community in Denver.", - document: { sections: [] }, - createdAt: new Date("2026-01-01T00:00:00Z"), - updatedAt: new Date("2026-01-02T00:00:00Z"), - userId: "user-1", - claimTokenHash: null, - }; - findUniqueMock.mockResolvedValueOnce(row); + findUniqueMock.mockResolvedValueOnce(row()); + const res = await GET( + new NextRequest("https://x.test/api/rules/rule-1"), + makeContext("rule-1"), + ); + expect(res.status).toBe(404); + }); + + it("returns 200 for a public and featured Rule when the viewer is anonymous", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockResolvedValueOnce( + row({ visibility: RULE_VISIBILITY.public_and_featured }), + ); const res = await GET( new NextRequest("https://x.test/api/rules/rule-1"), makeContext("rule-1"), ); expect(res.status).toBe(200); const body = (await res.json()) as { - rule: { - id: string; - title: string; - summary: string | null; - isListed: boolean; - }; + rule: { id: string; isListed: boolean }; viewerIsOwner: boolean; }; expect(body.rule.id).toBe("rule-1"); - expect(body.rule.title).toBe("Mutual Aid Mondays"); - expect(body.rule.summary).toBe("A grassroots community in Denver."); expect(body.rule.isListed).toBe(true); expect(body.viewerIsOwner).toBe(false); - expect(findUniqueMock).toHaveBeenCalledTimes(1); - }); - - it("marks guest-claim rules as unlisted without exposing the claim token", async () => { - isDatabaseConfiguredMock.mockReturnValue(true); - findUniqueMock.mockResolvedValueOnce({ - id: "guest-1", - title: "Unlisted", - summary: null, - document: {}, - createdAt: new Date("2026-01-01T00:00:00Z"), - updatedAt: new Date("2026-01-02T00:00:00Z"), - userId: null, - claimTokenHash: "secret-hash", - }); - const res = await GET( - new NextRequest("https://x.test/api/rules/guest-1"), - makeContext("guest-1"), - ); - expect(res.status).toBe(200); - const body = (await res.json()) as { - rule: { isListed: boolean; claimTokenHash?: unknown; userId?: unknown }; - }; - expect(body.rule.isListed).toBe(false); - expect(body.rule).not.toHaveProperty("claimTokenHash"); - expect(body.rule).not.toHaveProperty("userId"); }); it("returns viewerIsOwner true when the signed-in user owns the rule", async () => { isDatabaseConfiguredMock.mockReturnValue(true); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); - const row = { - id: "rule-1", - title: "Mutual Aid Mondays", - summary: "A grassroots community in Denver.", - document: { sections: [] }, - createdAt: new Date("2026-01-01T00:00:00Z"), - updatedAt: new Date("2026-01-02T00:00:00Z"), - }; - findUniqueMock - .mockResolvedValueOnce(row) - .mockResolvedValueOnce({ userId: "user-1" }); + findUniqueMock.mockResolvedValueOnce(row()); const res = await GET( new NextRequest("https://x.test/api/rules/rule-1"), makeContext("rule-1"), @@ -167,23 +166,70 @@ describe("GET /api/rules/[id]", () => { expect(res.status).toBe(200); const body = (await res.json()) as { viewerIsOwner: boolean }; expect(body.viewerIsOwner).toBe(true); - expect(findUniqueMock).toHaveBeenCalledTimes(2); + expect(findUniqueMock).toHaveBeenCalledTimes(1); }); - it("returns viewerIsOwner false when the signed-in user does not own the rule", async () => { + it("returns 404 for a shared-by-link Rule at the internal id", async () => { isDatabaseConfiguredMock.mockReturnValue(true); - getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); - const row = { - id: "rule-1", - title: "Mutual Aid Mondays", - summary: "A grassroots community in Denver.", - document: { sections: [] }, - createdAt: new Date("2026-01-01T00:00:00Z"), - updatedAt: new Date("2026-01-02T00:00:00Z"), - }; - findUniqueMock - .mockResolvedValueOnce(row) - .mockResolvedValueOnce({ userId: "other" }); + findUniqueMock.mockResolvedValueOnce( + row({ + visibility: RULE_VISIBILITY.shared_by_link, + shareSlug: "k7f2-9qxm", + }), + ); + const res = await GET( + new NextRequest("https://x.test/api/rules/rule-1"), + makeContext("rule-1"), + ); + expect(res.status).toBe(404); + }); + + it("returns 200 when the browser holds the guest claim", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + browserHoldsClaimForHashMock.mockResolvedValue(true); + findUniqueMock.mockResolvedValueOnce( + row({ userId: null, claimTokenHash: "claim-hash" }), + ); + const res = await GET( + new NextRequest("https://x.test/api/rules/rule-1"), + makeContext("rule-1"), + ); + expect(res.status).toBe(200); + }); + + it("logs named-admin reads of a private Rule", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + isRuleAdminEmailMock.mockReturnValue(true); + getSessionUserMock.mockResolvedValue({ + id: "admin-1", + email: "ops@example.org", + }); + findUniqueMock.mockResolvedValueOnce(row()); + const res = await GET( + new NextRequest("https://x.test/api/rules/rule-1"), + makeContext("rule-1"), + ); + expect(res.status).toBe(200); + expect(logAdminRuleReadMock).toHaveBeenCalledWith( + expect.objectContaining({ + ruleId: "rule-1", + adminEmail: "ops@example.org", + path: "/api/rules/rule-1", + }), + ); + }); + + it("returns 200 for an invited reader of a private Rule", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + getSessionUserMock.mockResolvedValue({ + id: "reader-1", + email: "rosa@example.org", + }); + findUniqueMock.mockResolvedValueOnce( + row({ + stakeholders: [{ email: "rosa@example.org", userId: "reader-1" }], + }), + ); const res = await GET( new NextRequest("https://x.test/api/rules/rule-1"), makeContext("rule-1"), diff --git a/tests/unit/rulesPublishPostRoute.test.ts b/tests/unit/rulesPublishPostRoute.test.ts index 8af7e13..7ebacf1 100644 --- a/tests/unit/rulesPublishPostRoute.test.ts +++ b/tests/unit/rulesPublishPostRoute.test.ts @@ -44,6 +44,10 @@ vi.mock("../../lib/server/guestRuleClaim", () => ({ issueGuestRuleClaimCookieMock(...args), })); +vi.mock("../../lib/server/uploads/linkUploads", () => ({ + linkUploadsToRule: vi.fn().mockResolvedValue(undefined), +})); + vi.mock("../../lib/server/db", () => ({ prisma: { $transaction: (fn: (tx: unknown) => Promise) => diff --git a/tests/unit/rulesShareRoute.test.ts b/tests/unit/rulesShareRoute.test.ts new file mode 100644 index 0000000..333eab8 --- /dev/null +++ b/tests/unit/rulesShareRoute.test.ts @@ -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); + }); +}); diff --git a/tests/unit/saveCreateFlowUpload.test.ts b/tests/unit/saveCreateFlowUpload.test.ts index 6644712..74bc4c7 100644 --- a/tests/unit/saveCreateFlowUpload.test.ts +++ b/tests/unit/saveCreateFlowUpload.test.ts @@ -16,6 +16,14 @@ vi.mock("../../lib/server/uploads/uploadRoot", async () => { }; }); +vi.mock("../../lib/server/db", () => ({ + prisma: { + upload: { + create: vi.fn().mockResolvedValue({}), + }, + }, +})); + import { saveCreateFlowUpload } from "../../lib/server/uploads/saveCreateFlowUpload"; const PNG_1X1 = Buffer.from( diff --git a/tests/unit/sharePaths.test.ts b/tests/unit/sharePaths.test.ts new file mode 100644 index 0000000..1752a7d --- /dev/null +++ b/tests/unit/sharePaths.test.ts @@ -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"); + }); +}); diff --git a/tests/unit/shareSlug.test.ts b/tests/unit/shareSlug.test.ts new file mode 100644 index 0000000..af874dc --- /dev/null +++ b/tests/unit/shareSlug.test.ts @@ -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); + } + }); +}); diff --git a/tests/unit/siteMetadata.test.ts b/tests/unit/siteMetadata.test.ts index eade5a2..320a47e 100644 --- a/tests/unit/siteMetadata.test.ts +++ b/tests/unit/siteMetadata.test.ts @@ -227,7 +227,7 @@ describe("buildRobots", () => { }); describe("robotsForPublishedRule", () => { - it("leaves listed rules indexable and noindexes unlisted guest-claim pages", () => { + it("leaves public-and-featured Rules indexable and noindexes private and shared-by-link pages", () => { expect(robotsForPublishedRule(true)).toBeUndefined(); expect(robotsForPublishedRule(false)).toEqual(NO_INDEX_ROBOTS); }); diff --git a/tests/unit/stripImageMetadata.test.ts b/tests/unit/stripImageMetadata.test.ts new file mode 100644 index 0000000..f447686 --- /dev/null +++ b/tests/unit/stripImageMetadata.test.ts @@ -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); + }); +}); diff --git a/tests/unit/uploadsByIdRoute.test.ts b/tests/unit/uploadsByIdRoute.test.ts index 37d62e4..3851f6c 100644 --- a/tests/unit/uploadsByIdRoute.test.ts +++ b/tests/unit/uploadsByIdRoute.test.ts @@ -5,18 +5,61 @@ import { NextRequest } from "next/server"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const getUploadRootFromEnvMock = vi.fn(); +const isDatabaseConfiguredMock = vi.fn(); +const findUniqueMock = vi.fn(); +const getSessionUserMock = vi.fn(); +const getReadablePublishedRuleMock = vi.fn(); +const browserHoldsUploadGrantMock = vi.fn(); let uploadRoot: string | null = null; vi.mock("../../lib/server/uploads/uploadRoot", () => ({ getUploadRootFromEnv: () => getUploadRootFromEnvMock(), })); +vi.mock("../../lib/server/env", () => ({ + isDatabaseConfigured: () => isDatabaseConfiguredMock(), +})); + +vi.mock("../../lib/server/db", () => ({ + prisma: { + upload: { + findUnique: (...args: unknown[]) => findUniqueMock(...args), + }, + }, +})); + +vi.mock("../../lib/server/session", () => ({ + getSessionUser: () => getSessionUserMock(), +})); + +vi.mock("../../lib/server/publishedRules", () => ({ + getReadablePublishedRule: (...args: unknown[]) => + getReadablePublishedRuleMock(...args), +})); + +vi.mock("../../lib/server/uploads/uploadGrantCookie", () => ({ + browserHoldsUploadGrant: (...args: unknown[]) => + browserHoldsUploadGrantMock(...args), +})); + import { GET } from "../../app/api/uploads/[id]/route"; +import { RULE_VISIBILITY } from "../../lib/ruleVisibility"; + +const FEATURED_ID = "550e8400-e29b-41d4-a716-446655440000"; +const PRIVATE_ID = "550e8400-e29b-41d4-a716-446655440001"; beforeEach(async () => { uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-test-")); getUploadRootFromEnvMock.mockReset(); getUploadRootFromEnvMock.mockImplementation(() => uploadRoot); + isDatabaseConfiguredMock.mockReset(); + isDatabaseConfiguredMock.mockReturnValue(true); + findUniqueMock.mockReset(); + getSessionUserMock.mockReset(); + getSessionUserMock.mockResolvedValue(null); + getReadablePublishedRuleMock.mockReset(); + browserHoldsUploadGrantMock.mockReset(); + browserHoldsUploadGrantMock.mockResolvedValue(false); }); afterEach(() => { @@ -34,6 +77,7 @@ describe("GET /api/uploads/[id]", () => { }); it("returns 404 when the upload is not found", async () => { + findUniqueMock.mockResolvedValueOnce(null); const res = await GET( new NextRequest( "https://x.test/api/uploads/550e8400-e29b-41d4-a716-446655440000", @@ -47,16 +91,93 @@ describe("GET /api/uploads/[id]", () => { expect(res.status).toBe(404); }); - it("returns the file bytes with content type", async () => { - const id = "550e8400-e29b-41d4-a716-446655440000"; - await writeFile(path.join(uploadRoot!, `${id}.png`), "png-bytes"); + it("returns featured file bytes with a short public cache", async () => { + await writeFile(path.join(uploadRoot!, `${FEATURED_ID}.png`), "png-bytes"); + findUniqueMock.mockResolvedValueOnce({ + id: FEATURED_ID, + userId: null, + draftId: null, + ruleId: "rule-1", + rule: { visibility: RULE_VISIBILITY.public_and_featured }, + draft: null, + }); + getReadablePublishedRuleMock.mockResolvedValueOnce({ + visibility: RULE_VISIBILITY.public_and_featured, + rule: { isListed: true }, + }); const res = await GET( - new NextRequest(`https://x.test/api/uploads/${id}`), - { params: Promise.resolve({ id }) }, + new NextRequest(`https://x.test/api/uploads/${FEATURED_ID}`), + { params: Promise.resolve({ id: FEATURED_ID }) }, ); expect(res.status).toBe(200); expect(res.headers.get("Content-Type")).toBe("image/png"); - expect(res.headers.get("Cache-Control")).toContain("immutable"); + expect(res.headers.get("Cache-Control")).toBe("public, max-age=3600"); expect(await res.text()).toBe("png-bytes"); }); + + it("returns 404 for a private file the viewer cannot read", async () => { + findUniqueMock.mockResolvedValueOnce({ + id: PRIVATE_ID, + userId: null, + draftId: null, + ruleId: "rule-private", + rule: { visibility: RULE_VISIBILITY.private }, + draft: null, + }); + getReadablePublishedRuleMock.mockResolvedValueOnce(null); + const res = await GET( + new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`), + { params: Promise.resolve({ id: PRIVATE_ID }) }, + ); + expect(res.status).toBe(404); + expect(res.headers.get("Cache-Control")).toBeNull(); + }); + + it("serves a shared-by-link file to an anonymous viewer without a public cache", async () => { + await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "shared"); + findUniqueMock.mockResolvedValueOnce({ + id: PRIVATE_ID, + userId: null, + draftId: null, + ruleId: "rule-shared", + rule: { visibility: RULE_VISIBILITY.shared_by_link }, + draft: null, + }); + getReadablePublishedRuleMock.mockResolvedValueOnce({ + visibility: RULE_VISIBILITY.shared_by_link, + rule: { isListed: false }, + }); + const res = await GET( + new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`), + { params: Promise.resolve({ id: PRIVATE_ID }) }, + ); + expect(res.status).toBe(200); + expect(getReadablePublishedRuleMock).toHaveBeenCalledWith( + expect.objectContaining({ viaShareSlug: true }), + ); + expect(res.headers.get("Cache-Control")).toBe("private, no-store"); + }); + + it("serves a private file to a permitted reader without a public cache", async () => { + await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "private"); + findUniqueMock.mockResolvedValueOnce({ + id: PRIVATE_ID, + userId: "user-1", + draftId: null, + ruleId: "rule-private", + rule: { visibility: RULE_VISIBILITY.private }, + draft: null, + }); + getReadablePublishedRuleMock.mockResolvedValueOnce({ + visibility: RULE_VISIBILITY.private, + rule: { isListed: false }, + }); + const res = await GET( + new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`), + { params: Promise.resolve({ id: PRIVATE_ID }) }, + ); + expect(res.status).toBe(200); + expect(res.headers.get("Cache-Control")).toBe("private, no-store"); + expect(await res.text()).toBe("private"); + }); }); diff --git a/tests/unit/userMeDeleteRoute.test.ts b/tests/unit/userMeDeleteRoute.test.ts index 47edb83..4d72134 100644 --- a/tests/unit/userMeDeleteRoute.test.ts +++ b/tests/unit/userMeDeleteRoute.test.ts @@ -22,6 +22,10 @@ vi.mock("../../lib/server/session", () => ({ clearSessionCookie: vi.fn(), })); +vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({ + deleteUploadsForUser: vi.fn().mockResolvedValue(undefined), +})); + import { DELETE } from "../../app/api/user/me/route"; beforeEach(() => { -- 2.53.0 From b6795c1f181bde0b17de9bb35b6a5aa623c146c7 Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:54:09 -0700 Subject: [PATCH 2/3] Rebuild Share and Delete Account from the privacy designs. Share asks the person who holds the pen to confirm their community agreed before a link turns on, and deleting an account lists each owned Rule with PDF and RULE.md export. Case-study Share copies the page link instead of opening the privacy modal, and the sign-in banner stays below the header so Share remains clickable. --- app/(app)/create/CreateFlowLayoutClient.tsx | 26 +- app/(app)/profile/ProfilePageClient.tsx | 74 +++- .../profile/_components/ProfilePage.view.tsx | 42 +- .../UseCaseCompletedRule.container.tsx | 18 +- .../_components/UseCaseCompletedRule.types.ts | 6 +- .../_components/UseCaseCompletedRule.view.tsx | 18 +- .../modals/Create/CreateModalFrame.view.tsx | 20 +- .../DeleteAccount/DeleteAccount.container.tsx | 60 +++ .../DeleteAccount/DeleteAccount.types.ts | 50 +++ .../DeleteAccount/DeleteAccount.view.tsx | 139 ++++++ app/components/modals/DeleteAccount/index.tsx | 5 + .../modals/Share/Share.container.tsx | 333 +++++++++++++-- app/components/modals/Share/Share.types.ts | 100 +++-- app/components/modals/Share/Share.view.tsx | 395 ++++++++++++------ lib/assetUtils.ts | 2 + lib/create/api.ts | 104 +++++ messages/en/index.ts | 2 + messages/en/modals/deleteAccount.json | 13 + messages/en/modals/share.json | 34 +- public/assets/share/language.svg | 5 + public/assets/share/lock.svg | 5 + stories/modals/DeleteAccount.stories.js | 47 +++ stories/modals/Share.stories.js | 45 +- .../components/modals/DeleteAccount.test.tsx | 53 +++ tests/components/modals/Share.test.tsx | 210 ++++++---- tests/pages/profile.test.tsx | 15 +- tests/pages/use-cases-completed-rule.test.jsx | 21 + tests/unit/createFlowLayoutTokens.test.ts | 2 +- 28 files changed, 1467 insertions(+), 377 deletions(-) create mode 100644 app/components/modals/DeleteAccount/DeleteAccount.container.tsx create mode 100644 app/components/modals/DeleteAccount/DeleteAccount.types.ts create mode 100644 app/components/modals/DeleteAccount/DeleteAccount.view.tsx create mode 100644 app/components/modals/DeleteAccount/index.tsx create mode 100644 messages/en/modals/deleteAccount.json create mode 100644 public/assets/share/language.svg create mode 100644 public/assets/share/lock.svg create mode 100644 stories/modals/DeleteAccount.stories.js create mode 100644 tests/components/modals/DeleteAccount.test.tsx diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index 89e0d01..7bee008 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -253,16 +253,10 @@ function CreateFlowLayoutContent({ resolve?.(choice); }, []); - const { - copyPublishedRuleLink, - mailtoPublishedRule, - sharePublishedRuleViaSignal, - sharePublishedRuleViaSlack, - sharePublishedRuleViaDiscord, - onSelectExportFormat: onCompletedExportFormat, - } = useCompletedRuleShareExport({ - setActionBanner: setCompletedFlowBanner, - }); + const { onSelectExportFormat: onCompletedExportFormat } = + useCompletedRuleShareExport({ + setActionBanner: setCompletedFlowBanner, + }); const handleOpenCompletedShareModal = () => { if (!readLastPublishedRule()) { @@ -862,11 +856,13 @@ function CreateFlowLayoutContent({ setShareModalOpen(false)} - onCopyLink={() => void copyPublishedRuleLink()} - onEmailShare={mailtoPublishedRule} - onSignalShare={() => void sharePublishedRuleViaSignal()} - onSlackShare={() => void sharePublishedRuleViaSlack()} - onDiscordShare={() => void sharePublishedRuleViaDiscord()} + ruleId={readLastPublishedRule()?.id ?? null} + onRequestLogin={() => + openLogin({ + nextPath: pathname, + backdropVariant: "blurredYellow", + }) + } /> { + 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, + }; + }, + [], + ); + + 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 () => { setActionError(null); setAccountDeleteBusy(true); @@ -409,6 +479,8 @@ export default function ProfilePageClient() { }} onCloseDeleteAccount={() => setAccountDeleteOpen(false)} onConfirmDeleteAccount={handleConfirmDeleteAccount} + onExportRulePdf={(id) => void handleExportRulePdf(id)} + onExportRuleMarkdown={(id) => void handleExportRuleMarkdown(id)} onStartNewCustomRule={handleStartNewCustomRule} /> ); diff --git a/app/(app)/profile/_components/ProfilePage.view.tsx b/app/(app)/profile/_components/ProfilePage.view.tsx index 239cd11..5bc399c 100644 --- a/app/(app)/profile/_components/ProfilePage.view.tsx +++ b/app/(app)/profile/_components/ProfilePage.view.tsx @@ -9,6 +9,7 @@ import type { ListItem, ListSize } from "../../../components/layout/List"; import ListEntry from "../../../components/layout/ListEntry"; import Icon from "../../../components/asset/icon"; import Dialog from "../../../components/modals/Dialog"; +import DeleteAccount from "../../../components/modals/DeleteAccount"; import Alert from "../../../components/modals/Alert"; import HeaderLockup from "../../../components/type/HeaderLockup"; import { useTranslation } from "../../../contexts/MessagesContext"; @@ -71,6 +72,8 @@ export type ProfilePageViewProps = { onOpenDeleteAccount: () => void; onCloseDeleteAccount: () => void; onConfirmDeleteAccount: () => void; + onExportRulePdf: (id: string) => void; + onExportRuleMarkdown: (id: string) => void; onDismissProfileSuccess: () => void; onDismissActionError: () => void; onDismissRulesError: () => void; @@ -194,6 +197,8 @@ export function ProfilePageView({ onOpenDeleteAccount, onCloseDeleteAccount, onConfirmDeleteAccount, + onExportRulePdf, + onExportRuleMarkdown, onDismissProfileSuccess, onDismissActionError, onDismissRulesError, @@ -489,39 +494,18 @@ export function ProfilePageView({ } /> - { if (!accountDeleteBusy) onCloseDeleteAccount(); }} - backdropVariant="blurredYellow" - title={t("deleteAccountModalTitle")} - description={t("deleteAccountModalBody")} - footer={ - <> - - - - } + onConfirm={onConfirmDeleteAccount} + busy={accountDeleteBusy} + rules={rules + .filter((rule) => rule.role === "owner") + .map((rule) => ({ id: rule.id, title: rule.title }))} + onExportPdf={onExportRulePdf} + onExportMarkdown={onExportRuleMarkdown} /> (null); - const { copyPageLink, mailtoPageLink, handleDuplicate } = - useUseCaseCompletedRuleActions({ - slug, - fixture, - setActionBanner, - }); + const { copyPageLink, handleDuplicate } = useUseCaseCompletedRuleActions({ + slug, + fixture, + setActionBanner, + }); return ( setShareModalOpen(true)} - onShareClose={() => setShareModalOpen(false)} - onCopyLink={() => void copyPageLink()} - onEmailShare={mailtoPageLink} + onShare={() => void copyPageLink()} onDuplicate={() => void handleDuplicate()} onExit={() => router.push(`/use-cases/${slug}`)} actionBanner={actionBanner} diff --git a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts index d0796fd..03339a8 100644 --- a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts +++ b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.types.ts @@ -14,11 +14,7 @@ export type UseCaseCompletedRuleViewProps = UseCaseCompletedRuleProps & { duplicateLabel: string; duplicateAriaLabel: string; exitLabel: string; - shareModalOpen: boolean; - onShareOpen: () => void; - onShareClose: () => void; - onCopyLink: () => void; - onEmailShare: () => void; + onShare: () => void; onDuplicate: () => void; onExit: () => void; actionBanner: UseCaseCompletedRuleActionBanner | null; diff --git a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx index b306095..9268c92 100644 --- a/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx +++ b/app/(marketing-case-study)/use-cases/[slug]/rule/_components/UseCaseCompletedRule.view.tsx @@ -2,7 +2,6 @@ import CommunityRule from "../../../../../components/type/CommunityRule"; import CreateFlowTopNav from "../../../../../components/navigation/CreateFlowTopNav"; -import Share from "../../../../../components/modals/Share"; import Alert from "../../../../../components/modals/Alert"; import { CreateFlowHeaderLockup } from "../../../../../(app)/create/components/CreateFlowHeaderLockup"; import { @@ -19,11 +18,7 @@ export function UseCaseCompletedRuleView({ duplicateLabel, duplicateAriaLabel, exitLabel, - shareModalOpen, - onShareOpen, - onShareClose, - onCopyLink, - onEmailShare, + onShare, onDuplicate, onExit, actionBanner, @@ -59,15 +54,6 @@ export function UseCaseCompletedRuleView({ ) : null} - diff --git a/app/components/modals/Create/CreateModalFrame.view.tsx b/app/components/modals/Create/CreateModalFrame.view.tsx index c18e0b2..55b35b3 100644 --- a/app/components/modals/Create/CreateModalFrame.view.tsx +++ b/app/components/modals/Create/CreateModalFrame.view.tsx @@ -12,6 +12,8 @@ const backdropOverlayClasses: Record = { "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 = { isOpen: boolean; onOverlayClick: () => void; @@ -24,6 +26,11 @@ export type CreateModalFrameViewProps = { children: ReactNode; /** Rendered below the dialog card on the backdrop (e.g. “Back to home”). */ 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, children, belowCard, + presentation = "dialog", }: CreateModalFrameViewProps) { 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 = (
@@ -56,7 +72,7 @@ export function CreateModalFrameView({ aria-modal="true" aria-label={ariaLabel} 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()} > {children} diff --git a/app/components/modals/DeleteAccount/DeleteAccount.container.tsx b/app/components/modals/DeleteAccount/DeleteAccount.container.tsx new file mode 100644 index 0000000..b44fd85 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.container.tsx @@ -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((props) => { + const { + isOpen, + onClose, + onConfirm, + busy = false, + rules, + onExportPdf, + onExportMarkdown, + className = "", + backdropVariant = "blurredYellow", + } = props; + const dialogRef = useRef(null); + const overlayRef = useRef(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 ( + + ); +}); + +DeleteAccountContainer.displayName = "DeleteAccount"; + +export default DeleteAccountContainer; diff --git a/app/components/modals/DeleteAccount/DeleteAccount.types.ts b/app/components/modals/DeleteAccount/DeleteAccount.types.ts new file mode 100644 index 0000000..28f35f9 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.types.ts @@ -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; + overlayRef: RefObject; + titleId: string; + copy: DeleteAccountCopy; + understood: boolean; + onUnderstoodChange: (_checked: boolean) => void; +}; diff --git a/app/components/modals/DeleteAccount/DeleteAccount.view.tsx b/app/components/modals/DeleteAccount/DeleteAccount.view.tsx new file mode 100644 index 0000000..000ef82 --- /dev/null +++ b/app/components/modals/DeleteAccount/DeleteAccount.view.tsx @@ -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 ( + undefined : onClose} + backdropVariant={backdropVariant} + presentation="sheet" + className={className} + ariaLabel={copy.title} + ariaLabelledBy={titleId} + overlayRef={overlayRef} + dialogRef={dialogRef} + > + + +
+ +
+ +
+

+ {copy.yourRules} +

+ {rules.map((rule) => ( +
+ +

+ {rule.title} +

+
+ + +
+
+ ))} + onUnderstoodChange(data.checked)} + /> +
+ +
+ + +
+
+ ); +}); + +DeleteAccountView.displayName = "DeleteAccountView"; diff --git a/app/components/modals/DeleteAccount/index.tsx b/app/components/modals/DeleteAccount/index.tsx new file mode 100644 index 0000000..5692653 --- /dev/null +++ b/app/components/modals/DeleteAccount/index.tsx @@ -0,0 +1,5 @@ +export { default } from "./DeleteAccount.container"; +export type { + DeleteAccountProps, + DeleteAccountRule, +} from "./DeleteAccount.types"; diff --git a/app/components/modals/Share/Share.container.tsx b/app/components/modals/Share/Share.container.tsx index fcf2f55..2a309f0 100644 --- a/app/components/modals/Share/Share.container.tsx +++ b/app/components/modals/Share/Share.container.tsx @@ -1,62 +1,335 @@ "use client"; /** - * Figma: Community Rule System — "Modal / Share" - * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=22073-30884 - * Copy-link hover / Copied! : 23769:27494 / 23769:27443 + * Figma: Overlay / Modal / Share (24972:2094) + * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=24972-2094 */ 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 { 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((props) => { + const { + isOpen, + onClose, + ruleId = null, + previewSettings, + onRequestLogin, + className = "", + backdropVariant = "blurredYellow", + } = props; const dialogRef = useRef(null); const overlayRef = useRef(null); const titleId = useId(); - const t = useTranslation("modals.share"); + const copy = useMessages().modals.share; + + const [settings, setSettings] = useState( + previewSettings ?? null, + ); + const [phase, setPhase] = useState("idle"); + const [communityAgreed, setCommunityAgreed] = useState(false); + const [inviteValue, setInviteValue] = useState(""); + const [inviteBusy, setInviteBusy] = useState(false); + const [inviteError, setInviteError] = useState(null); + const [turnOnBusy, setTurnOnBusy] = useState(false); const [linkCopied, setLinkCopied] = useState(false); - useCreateModalA11y(props.isOpen, props.onClose, dialogRef); + useCreateModalA11y(isOpen, onClose, dialogRef); useEffect(() => { - if (!props.isOpen) { + if (!isOpen) { + setPhase("idle"); + setCommunityAgreed(false); + setInviteValue(""); + setInviteError(null); setLinkCopied(false); + setTurnOnBusy(false); + if (!previewSettings) setSettings(null); + return; } - }, [props.isOpen]); - - const onCopyLinkClick = useCallback(async () => { - try { - const result = await props.onCopyLink(); - if (result !== false) { - setLinkCopied(true); + 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 applySettings = useCallback((next: RuleShareSettings) => { + setSettings(next); + setPhase("idle"); + setCommunityAgreed(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; + } + 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); + } + }, + [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); + }, [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 { setLinkCopied(false); } - }, [props.onCopyLink]); + }, [settings]); + + if (!settings) { + return ( + 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} + 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 ( { + 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"} + copyEnabled={copyEnabled} linkCopied={linkCopied} - onCopyLinkClick={onCopyLinkClick} - signalLabel={t("signal")} - slackLabel={t("slack")} - discordLabel={t("discord")} - emailLabel={t("email")} - doneLabel={t("done")} - closeDialogAriaLabel={t("closeDialogAriaLabel")} - moreOptionsAriaLabel={t("moreOptionsAriaLabel")} + onCopyLink={() => void handleCopyLink()} /> ); }); diff --git a/app/components/modals/Share/Share.types.ts b/app/components/modals/Share/Share.types.ts index e8d35c5..3407aa3 100644 --- a/app/components/modals/Share/Share.types.ts +++ b/app/components/modals/Share/Share.types.ts @@ -1,43 +1,85 @@ -import type { ReactNode, RefObject } from "react"; +import type { RefObject } from "react"; import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view"; +import type { + RuleShareSettings, + SharePerson, +} from "../../../../lib/ruleShareTypes"; + +export type SharePhase = "idle" | "confirm" | "error"; export type ShareProps = { isOpen: boolean; onClose: () => void; - /** Return `false` when the clipboard write did not succeed. */ - onCopyLink: () => void | boolean | Promise; - onEmailShare: () => void; - onSignalShare: () => void | Promise; - onSlackShare: () => void | Promise; - onDiscordShare: () => void | Promise; + ruleId?: string | null; + /** Story / test seed. Skips the share API when set. */ + previewSettings?: RuleShareSettings; + onRequestLogin?: () => void; className?: string; 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; + closeDialogAriaLabel: string; + accessSelectAriaLabel: string; +}; + +export type ShareViewProps = { + isOpen: boolean; + onClose: () => void; + className: string; + backdropVariant: CreateModalBackdropVariant; dialogRef: RefObject; overlayRef: RefObject; titleId: string; - title: string; - description: string; - copyLinkLabel: string; - copiedLabel: string; - copiedLive: string; + copy: ShareCopy; + communityName: string; + inviteValue: string; + onInviteValueChange: (_value: string) => void; + 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; + copyEnabled: boolean; linkCopied: boolean; - onCopyLinkClick: () => void | Promise; - signalLabel: string; - slackLabel: string; - discordLabel: string; - emailLabel: string; - doneLabel: string; - closeDialogAriaLabel: string; - moreOptionsAriaLabel: string; -}; - -export type ShareChannelTileProps = { - label: string; - onClick: () => void | Promise; - circleClassName: string; - icon: ReactNode; - copied?: boolean; + onCopyLink: () => void; }; diff --git a/app/components/modals/Share/Share.view.tsx b/app/components/modals/Share/Share.view.tsx index 4e40d40..7a4a25b 100644 --- a/app/components/modals/Share/Share.view.tsx +++ b/app/components/modals/Share/Share.view.tsx @@ -7,26 +7,26 @@ import { shareIconPath, type ShareIconName, } from "../../../../lib/assetUtils"; -import ContentLockup from "../../type/ContentLockup"; +import Avatar from "../../asset/Avatar"; import Button from "../../buttons/Button"; -import ModalHeader from "../ModalHeader"; -import ModalFooter from "../ModalFooter"; +import Checkbox from "../../controls/Checkbox"; +import SelectInput from "../../controls/SelectInput"; +import TextInput from "../../controls/TextInput"; +import Alert from "../Alert"; 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 ShareAssetIcon(props: { - name: ShareIconName; - width: number; - height: number; -}) { - const { name, width, height } = props; +function ShareGlyph(props: { name: ShareIconName; size?: number }) { + const size = props.size ?? 24; return ( void onClick()} - aria-pressed={copied || undefined} - 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)]" - > -
- {icon} +
+ +
+

+ {props.title} +

+ {props.subtitle ? ( +

+ {props.subtitle} +

+ ) : null}
- - {label} - - +

+ {props.roleLabel} +

+
+ ); +} + +function ReaderRow({ reader, roleLabel }: { reader: SharePerson; roleLabel: string }) { + return ( + ); } export const ShareView = memo(function ShareView({ isOpen, onClose, - onEmailShare, - onSignalShare, - onSlackShare, - onDiscordShare, - className = "", - backdropVariant = "blurredYellow", + className, + backdropVariant, dialogRef, overlayRef, titleId, - title, - description, - copyLinkLabel, - copiedLabel, - copiedLive, + copy, + communityName, + inviteValue, + onInviteValueChange, + onInvite, + inviteBusy, + inviteError, + ownerEmail, + ownerInitials, + shownReaders, + overflowLabel, + selectValue, + onSelectValue, + showLinkField, + shareUrlDisplay, + onTurnOffLink, + showConfirm, + communityAgreed, + onCommunityAgreedChange, + onTurnOnLink, + turnOnDisabled, + turnOnBusy, + showError, + copyEnabled, linkCopied, - onCopyLinkClick, - signalLabel, - slackLabel, - discordLabel, - emailLabel, - doneLabel, - closeDialogAriaLabel, - moreOptionsAriaLabel, + onCopyLink, }: ShareViewProps) { + const linkOn = selectValue === "shared_by_link"; + return ( -
+
-
- {/* Channel circle hexes are third-party brand colors (copy/link, Signal, Slack, Discord), not DS tokens. */} -
- - } - /> - } - /> - } - /> - } - /> - } - /> +
+
+
+ onInviteValueChange(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + onInvite(); + } + }} + /> +
+
-

- {linkCopied ? copiedLive : ""} -

-
+ {inviteError ? ( +

+ {inviteError} +

+ ) : null} - +
+

+ {copy.peopleWithAccess} +

+ + {shownReaders.map((reader) => ( + + ))} + {overflowLabel ? ( +

+ {overflowLabel} +

+ ) : null} +
+ +
+

+ {copy.whoCanRead} +

+
+ +
+ onSelectValue(data.target.value)} + options={[ + { value: "private", label: copy.inviteOnly }, + { value: "shared_by_link", label: copy.anyoneWithLink }, + ]} + /> +
+
+ {!showConfirm && !showError ? ( +

+ {linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint} +

+ ) : null} +
+ + {showLinkField ? ( +
+
- } - /> + ) : null} + + {showConfirm || showError ? ( +
+ {showError ? ( + + ) : null} +

+ {copy.confirmBody} +

+ onCommunityAgreedChange(data.checked)} + /> + +
+ ) : null} + + {linkCopied ? ( + + ) : null} +
+ +
+ + +
); }); diff --git a/lib/assetUtils.ts b/lib/assetUtils.ts index d4df3c3..731c95a 100644 --- a/lib/assetUtils.ts +++ b/lib/assetUtils.ts @@ -89,7 +89,9 @@ export function partnerLogoPath(slug: string): string { export type ShareIconName = | "check" | "discord" + | "language" | "link" + | "lock" | "mail" | "signal" | "slack"; diff --git a/lib/create/api.ts b/lib/create/api.ts index 760e6ec..928f337 100644 --- a/lib/create/api.ts +++ b/lib/create/api.ts @@ -1,4 +1,6 @@ import type { CreateFlowState } from "../../app/(app)/create/types"; +import type { RuleShareSettings } from "../ruleShareTypes"; +import { isRuleVisibility } from "../ruleVisibility"; import { migrateLegacyCreateFlowState } from "./migrateLegacyCreateFlowState"; 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; + 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 { + 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 { + 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 }; /** diff --git a/messages/en/index.ts b/messages/en/index.ts index faa971c..e079c12 100644 --- a/messages/en/index.ts +++ b/messages/en/index.ts @@ -38,6 +38,7 @@ import invite from "./pages/invite.json"; import navigation from "./navigation.json"; import metadata from "./metadata.json"; import modalsShare from "./modals/share.json"; +import modalsDeleteAccount from "./modals/deleteAccount.json"; import modalsPopoverExport from "./modals/popoverExport.json"; import modalsAskOrganizerInquiry from "./modals/askOrganizerInquiry.json"; @@ -159,6 +160,7 @@ export default { metadata, modals: { share: modalsShare, + deleteAccount: modalsDeleteAccount, popoverExport: modalsPopoverExport, askOrganizerInquiry: modalsAskOrganizerInquiry, }, diff --git a/messages/en/modals/deleteAccount.json b/messages/en/modals/deleteAccount.json new file mode 100644 index 0000000..5984d49 --- /dev/null +++ b/messages/en/modals/deleteAccount.json @@ -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" +} diff --git a/messages/en/modals/share.json b/messages/en/modals/share.json index ea7af0b..93c767c 100644 --- a/messages/en/modals/share.json +++ b/messages/en/modals/share.json @@ -1,14 +1,30 @@ { - "title": "Share this CommunityRule", - "description": "Anyone with the link can view this rule.", + "_comment": "Overlay / Modal / Share 24972:2094", + "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", - "copied": "Copied!", - "copiedLive": "Link copied to clipboard", - "signal": "Signal", - "slack": "Slack", - "discord": "Discord", - "email": "Email", + "copied": "Copied", + "copiedLive": "Link copied", "done": "Done", + "errorTitle": "The link didn’t turn on", + "errorDescription": "Check your connection and try again.", "closeDialogAriaLabel": "Close", - "moreOptionsAriaLabel": "More share options" + "accessSelectAriaLabel": "Who can read this Rule" } diff --git a/public/assets/share/language.svg b/public/assets/share/language.svg new file mode 100644 index 0000000..2a32bfa --- /dev/null +++ b/public/assets/share/language.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/assets/share/lock.svg b/public/assets/share/lock.svg new file mode 100644 index 0000000..3ff65a3 --- /dev/null +++ b/public/assets/share/lock.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/stories/modals/DeleteAccount.stories.js b/stories/modals/DeleteAccount.stories.js new file mode 100644 index 0000000..be90d8d --- /dev/null +++ b/stories/modals/DeleteAccount.stories.js @@ -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 ( +
+ + 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} + /> +
+ ); +} + +export const Default = { + render: () => , +}; diff --git a/stories/modals/Share.stories.js b/stories/modals/Share.stories.js index 231d459..e1cf1bd 100644 --- a/stories/modals/Share.stories.js +++ b/stories/modals/Share.stories.js @@ -1,7 +1,7 @@ import React, { useState } from "react"; 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 { title: "Components/Modals/Share", component: Share, @@ -10,12 +10,31 @@ export default { docs: { description: { 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() { const [open, setOpen] = useState(true); return ( @@ -30,11 +49,7 @@ function ShareStoryHost() { setOpen(false)} - onCopyLink={() => {}} - onEmailShare={() => {}} - onSignalShare={() => {}} - onSlackShare={() => {}} - onDiscordShare={() => {}} + previewSettings={previewSettings} />
); @@ -43,3 +58,19 @@ function ShareStoryHost() { export const Default = { render: () => , }; + +export const AnyoneWithTheLink = { + render: () => ( + undefined} + previewSettings={{ + ...previewSettings, + visibility: "shared_by_link", + shareSlug: "k7f2-9qxm", + shareUrl: "https://communityrule.info/r/k7f2-9qxm", + shareUrlDisplay: "communityrule.info/r/k7f2-9qxm", + }} + /> + ), +}; diff --git a/tests/components/modals/DeleteAccount.test.tsx b/tests/components/modals/DeleteAccount.test.tsx new file mode 100644 index 0000000..47d26e9 --- /dev/null +++ b/tests/components/modals/DeleteAccount.test.tsx @@ -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( + , + ); + 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( + , + ); + 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); + }); +}); diff --git a/tests/components/modals/Share.test.tsx b/tests/components/modals/Share.test.tsx index 1da950d..8410458 100644 --- a/tests/components/modals/Share.test.tsx +++ b/tests/components/modals/Share.test.tsx @@ -1,117 +1,149 @@ -import { describe, it, expect, vi } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; 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 Share from "../../../app/components/modals/Share"; +import type { RuleShareSettings } from "../../../lib/ruleShareTypes"; -const noopHandlers = { - onCopyLink: vi.fn(), - onEmailShare: vi.fn(), - onSignalShare: 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 = {}) { + return render( + , + ); +} + +const writeText = vi.fn().mockResolvedValue(undefined); + +beforeEach(() => { + writeText.mockReset(); + writeText.mockResolvedValue(undefined); + Object.defineProperty(window.navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); +}); + describe("Share modal", () => { it("does not render dialog when closed", () => { render( - , + , ); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); - it("renders localized heading and copy link action when open", async () => { - const user = userEvent.setup(); - const onCopyLink = vi.fn(); - render( - , - ); + it("renders invite-only copy and people with access", () => { + openShare(); expect(screen.getByRole("dialog")).toBeInTheDocument(); expect( - screen.getByRole("heading", { level: 1, name: /Share this CommunityRule/ }), + screen.getByRole("heading", { level: 1, name: "Share this Rule" }), ).toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Copy link" })); - expect(onCopyLink).toHaveBeenCalledTimes(1); + expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument(); + 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 () => { - const user = userEvent.setup(); - const onSignalShare = vi.fn(); - const onSlackShare = vi.fn(); - const onDiscordShare = vi.fn(); - render( - , + 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", ); - await user.click(screen.getByRole("button", { name: "Signal" })); - await user.click(screen.getByRole("button", { name: "Slack" })); - await user.click(screen.getByRole("button", { name: "Discord" })); - expect(onSignalShare).toHaveBeenCalledTimes(1); - expect(onSlackShare).toHaveBeenCalledTimes(1); - expect(onDiscordShare).toHaveBeenCalledTimes(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("calls onClose when Done is clicked", async () => { const user = userEvent.setup(); const onClose = vi.fn(); - render(); + render( + , + ); await user.click(screen.getByRole("button", { name: "Done" })); 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( - , - ); - 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( - , - ); - 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(); - await user.click(screen.getByRole("button", { name: "More share options" })); - expect(onClose).toHaveBeenCalledTimes(1); - }); }); diff --git a/tests/pages/profile.test.tsx b/tests/pages/profile.test.tsx index 88ffb34..f4cd53e 100644 --- a/tests/pages/profile.test.tsx +++ b/tests/pages/profile.test.tsx @@ -61,6 +61,8 @@ function viewProps( onOpenDeleteAccount: vi.fn(), onCloseDeleteAccount: vi.fn(), onConfirmDeleteAccount: vi.fn(), + onExportRulePdf: vi.fn(), + onExportRuleMarkdown: vi.fn(), onDismissProfileSuccess: vi.fn(), onDismissActionError: vi.fn(), onDismissRulesError: vi.fn(), @@ -127,12 +129,13 @@ describe("ProfilePageView", () => { ); 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", { - name: copy.deleteAccountConfirm, + name: messages.modals.deleteAccount.confirm, }); + expect(confirm).toBeDisabled(); expect(confirm.className).toContain( "border-[var(--color-border-default-negative-primary)]", ); @@ -140,6 +143,12 @@ describe("ProfilePageView", () => { "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); expect(onConfirmDeleteAccount).toHaveBeenCalledTimes(1); }); diff --git a/tests/pages/use-cases-completed-rule.test.jsx b/tests/pages/use-cases-completed-rule.test.jsx index fc1cf1b..e6e28a4 100644 --- a/tests/pages/use-cases-completed-rule.test.jsx +++ b/tests/pages/use-cases-completed-rule.test.jsx @@ -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 () => { rtlRender( diff --git a/tests/unit/createFlowLayoutTokens.test.ts b/tests/unit/createFlowLayoutTokens.test.ts index 8f13473..e624d21 100644 --- a/tests/unit/createFlowLayoutTokens.test.ts +++ b/tests/unit/createFlowLayoutTokens.test.ts @@ -31,7 +31,7 @@ describe("createFlowLayoutTokens", () => { 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"); }); -- 2.53.0 From 63ba21c61448607f2e12e5ade5250b4e91a1cdfd Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:05:06 -0700 Subject: [PATCH 3/3] Keep shared Rule files reachable, and say when a privacy change does not save. --- app/api/uploads/[id]/route.ts | 1 + .../modals/Share/Share.container.tsx | 18 ++++- app/components/modals/Share/Share.types.ts | 3 + app/components/modals/Share/Share.view.tsx | 14 ++++ lib/server/publishedRules.ts | 31 +++++---- messages/en/modals/share.json | 2 + tests/components/modals/Share.test.tsx | 68 +++++++++++++++++++ tests/unit/publishedRules.test.ts | 21 ++++++ tests/unit/uploadsByIdRoute.test.ts | 6 +- 9 files changed, 148 insertions(+), 16 deletions(-) diff --git a/app/api/uploads/[id]/route.ts b/app/api/uploads/[id]/route.ts index 413d7eb..a972cdd 100644 --- a/app/api/uploads/[id]/route.ts +++ b/app/api/uploads/[id]/route.ts @@ -69,6 +69,7 @@ export const GET = apiRoute( idOrSlug: row.ruleId, user, viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link, + lookup: "id", requestPath: request.nextUrl.pathname, }); allowed = resolved != null; diff --git a/app/components/modals/Share/Share.container.tsx b/app/components/modals/Share/Share.container.tsx index 2a309f0..625add6 100644 --- a/app/components/modals/Share/Share.container.tsx +++ b/app/components/modals/Share/Share.container.tsx @@ -65,6 +65,7 @@ const ShareContainer = memo((props) => { const [inviteError, setInviteError] = useState(null); const [turnOnBusy, setTurnOnBusy] = useState(false); const [linkCopied, setLinkCopied] = useState(false); + const [saveFailed, setSaveFailed] = useState(false); useCreateModalA11y(isOpen, onClose, dialogRef); @@ -76,6 +77,7 @@ const ShareContainer = memo((props) => { setInviteError(null); setLinkCopied(false); setTurnOnBusy(false); + setSaveFailed(false); if (!previewSettings) setSettings(null); return; } @@ -106,6 +108,7 @@ const ShareContainer = memo((props) => { setSettings(next); setPhase("idle"); setCommunityAgreed(false); + setSaveFailed(false); }, []); const handleSelectValue = useCallback( @@ -132,7 +135,11 @@ const ShareContainer = memo((props) => { } void (async () => { const res = await patchRuleShare(ruleId, "private"); - if (res.ok) applySettings(res.share); + if (res.ok) { + applySettings(res.share); + return; + } + setSaveFailed(true); })(); return; } @@ -146,6 +153,7 @@ const ShareContainer = memo((props) => { } setPhase("confirm"); setCommunityAgreed(false); + setSaveFailed(false); } }, [applySettings, phase, ruleId, settings], @@ -185,7 +193,11 @@ const ShareContainer = memo((props) => { return; } const res = await patchRuleShare(ruleId, "private"); - if (res.ok) applySettings(res.share); + if (res.ok) { + applySettings(res.share); + return; + } + setSaveFailed(true); }, [applySettings, ruleId, settings]); const handleInvite = useCallback(async () => { @@ -274,6 +286,7 @@ const ShareContainer = memo((props) => { turnOnDisabled turnOnBusy={false} showError={false} + showSaveError={false} copyEnabled={false} linkCopied={false} onCopyLink={() => undefined} @@ -327,6 +340,7 @@ const ShareContainer = memo((props) => { turnOnDisabled={!communityAgreed} turnOnBusy={turnOnBusy} showError={phase === "error"} + showSaveError={saveFailed} copyEnabled={copyEnabled} linkCopied={linkCopied} onCopyLink={() => void handleCopyLink()} diff --git a/app/components/modals/Share/Share.types.ts b/app/components/modals/Share/Share.types.ts index 3407aa3..3d0d5d2 100644 --- a/app/components/modals/Share/Share.types.ts +++ b/app/components/modals/Share/Share.types.ts @@ -44,6 +44,8 @@ export type ShareCopy = { done: string; errorTitle: string; errorDescription: string; + saveErrorTitle: string; + saveErrorDescription: string; closeDialogAriaLabel: string; accessSelectAriaLabel: string; }; @@ -79,6 +81,7 @@ export type ShareViewProps = { turnOnDisabled: boolean; turnOnBusy: boolean; showError: boolean; + showSaveError: boolean; copyEnabled: boolean; linkCopied: boolean; onCopyLink: () => void; diff --git a/app/components/modals/Share/Share.view.tsx b/app/components/modals/Share/Share.view.tsx index 7a4a25b..9df3aad 100644 --- a/app/components/modals/Share/Share.view.tsx +++ b/app/components/modals/Share/Share.view.tsx @@ -107,6 +107,7 @@ export const ShareView = memo(function ShareView({ turnOnDisabled, turnOnBusy, showError, + showSaveError, copyEnabled, linkCopied, onCopyLink, @@ -229,6 +230,19 @@ export const ShareView = memo(function ShareView({ {linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint}

) : null} + {showSaveError ? ( + + ) : null}
{showLinkField ? ( diff --git a/lib/server/publishedRules.ts b/lib/server/publishedRules.ts index 6c547b2..0a8e6cc 100644 --- a/lib/server/publishedRules.ts +++ b/lib/server/publishedRules.ts @@ -133,30 +133,35 @@ async function resolveAccessForRow(opts: { /** * Fetch a published rule the viewer is allowed to read. * - * Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link - * strangers must use the rotating slug so turning the link off invalidates it. - * Returns `null` for missing rows, denied readers, and DB failures — callers - * render the same 404 as a missing Rule. + * 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 { 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 = opts.viaShareSlug - ? await prisma.publishedRule.findUnique({ - where: { shareSlug: idOrSlug }, - select: RULE_ACCESS_SELECT, - }) - : await prisma.publishedRule.findUnique({ - where: { id: idOrSlug }, - select: RULE_ACCESS_SELECT, - }); + 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, diff --git a/messages/en/modals/share.json b/messages/en/modals/share.json index 93c767c..627089f 100644 --- a/messages/en/modals/share.json +++ b/messages/en/modals/share.json @@ -25,6 +25,8 @@ "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", "accessSelectAriaLabel": "Who can read this Rule" } diff --git a/tests/components/modals/Share.test.tsx b/tests/components/modals/Share.test.tsx index 8410458..1938294 100644 --- a/tests/components/modals/Share.test.tsx +++ b/tests/components/modals/Share.test.tsx @@ -8,8 +8,15 @@ import { } from "../../utils/test-utils"; import "@testing-library/jest-dom/vitest"; import Share from "../../../app/components/modals/Share"; +import { patchRuleShare } from "../../../lib/create/api"; import type { RuleShareSettings } from "../../../lib/ruleShareTypes"; +vi.mock("../../../lib/create/api", () => ({ + patchRuleShare: vi.fn(), + fetchRuleShare: vi.fn(), + addRuleStakeholder: vi.fn(), +})); + const previewSettings: RuleShareSettings = { visibility: "private", shareSlug: null, @@ -41,9 +48,18 @@ function openShare(overrides: Partial = {}) { 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 }, @@ -133,6 +149,58 @@ describe("Share modal", () => { ).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(); + render( + , + ); + await user.click( + screen.getByRole("button", { name: /Anyone with the link/i }), + ); + await user.click( + await screen.findByRole("option", { name: "Only people you invite" }), + ); + 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( + , + ); + 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 () => { const user = userEvent.setup(); const onClose = vi.fn(); diff --git a/tests/unit/publishedRules.test.ts b/tests/unit/publishedRules.test.ts index d851e4f..df04d83 100644 --- a/tests/unit/publishedRules.test.ts +++ b/tests/unit/publishedRules.test.ts @@ -153,6 +153,27 @@ describe("getReadablePublishedRule", () => { ).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( diff --git a/tests/unit/uploadsByIdRoute.test.ts b/tests/unit/uploadsByIdRoute.test.ts index 3851f6c..1f88f9d 100644 --- a/tests/unit/uploadsByIdRoute.test.ts +++ b/tests/unit/uploadsByIdRoute.test.ts @@ -153,7 +153,11 @@ describe("GET /api/uploads/[id]", () => { ); expect(res.status).toBe(200); expect(getReadablePublishedRuleMock).toHaveBeenCalledWith( - expect.objectContaining({ viaShareSlug: true }), + expect.objectContaining({ + idOrSlug: "rule-shared", + viaShareSlug: true, + lookup: "id", + }), ); expect(res.headers.get("Cache-Control")).toBe("private, no-store"); }); -- 2.53.0