Hold /privacy behind a flag until counsel reads it, and fix leftover legal and email copy.

This commit is contained in:
adilallo committed 2026-11-20 15:36:06 -07:00
1 parent ead6c8f716
commit 072e5362f5
40 files changed
+530 -173

No files matched your search

+6
View File
@@ -15,6 +15,12 @@ SESSION_SECRET="dev-only-change-me-16chars-min"
# Leave mail vars unset in dev to log the magic-link verify URL to the server console instead of sending email.
SMTP_FROM="CommunityRule <noreply@localhost>"
# /privacy. Unset or any value other than `true` is off (404, no footer/login/email links).
# Staging: `true`. Production stays off until university counsel has read the policy.
# ENABLE_PRIVACY_POLICY is the Cloudron runtime switch. The NEXT_PUBLIC_ alias bakes at image build.
# ENABLE_PRIVACY_POLICY=true
# NEXT_PUBLIC_ENABLE_PRIVACY_POLICY=true
# CR-107: inbox for Ask an organizer form submissions (requires CLOUDRON_MAIL_SMTP_* in production).
ORGANIZER_INQUIRY_TO=
+2 -1
View File
@@ -6,6 +6,7 @@ import { MessagesProvider } from "../contexts/MessagesContext";
import { AuthModalProvider } from "../contexts/AuthModalContext";
import messages from "../../messages/en/index";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { isPrivacyPolicyEnabled } from "../../lib/privacyPolicyEnabled";
import { NO_INDEX_ROBOTS } from "../../lib/siteMetadata";
export const metadata: Metadata = {
@@ -21,7 +22,7 @@ export const metadata: Metadata = {
export default function AdminLayout({ children }: { children: ReactNode }) {
return (
<MessagesProvider messages={messages}>
<AuthModalProvider>
<AuthModalProvider privacyEnabled={isPrivacyPolicyEnabled()}>
<SkipToContent />
<Suspense fallback={null}>
<ConditionalNavigation />
+2 -1
View File
@@ -6,6 +6,7 @@ import { MessagesProvider } from "../contexts/MessagesContext";
import { AuthModalProvider } from "../contexts/AuthModalContext";
import messages from "../../messages/en/index";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { isPrivacyPolicyEnabled } from "../../lib/privacyPolicyEnabled";
import { NO_INDEX_ROBOTS } from "../../lib/siteMetadata";
export const metadata: Metadata = {
@@ -28,7 +29,7 @@ export const metadata: Metadata = {
export default function AppLayout({ children }: { children: ReactNode }) {
return (
<MessagesProvider messages={messages}>
<AuthModalProvider>
<AuthModalProvider privacyEnabled={isPrivacyPolicyEnabled()}>
<SkipToContent />
<Suspense fallback={null}>
<ConditionalNavigation />
+72
View File
@@ -0,0 +1,72 @@
"use client";
import { Suspense } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslation } from "../../contexts/MessagesContext";
import Login from "../../components/modals/Login";
import LoginForm from "../../components/modals/Login/LoginForm";
const loginPageBgClass =
"min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)]";
function LoginLoadingFallback() {
const t = useTranslation("pages.login");
return (
<div className={`${loginPageBgClass} flex items-center justify-center`}>
<p className="text-[14px] text-[var(--color-content-default-primary)]">
{t("loadingFallback")}
</p>
</div>
);
}
function LoginWithSearchParams({
privacyEnabled,
}: {
privacyEnabled: boolean;
}) {
const router = useRouter();
const t = useTranslation("pages.login");
const closeToHome = () => {
router.push("/");
};
return (
<div className={loginPageBgClass}>
<Login
isOpen
usePortal={false}
backdropVariant="solid"
onClose={closeToHome}
ariaLabelledBy="login-modal-heading"
belowCard={
<Link
href="/"
className="text-small-paragraph text-[var(--color-content-invert-tertiary,#2d2d2d)] text-center hover:opacity-90"
>
{t("backToHome")}
</Link>
}
>
<LoginForm privacyEnabled={privacyEnabled} onClose={closeToHome} />
</Login>
</div>
);
}
/**
* Full-page login shell for magic-link **error redirects** (`?error=*`) and direct `/login` visits.
* Header **Log in** uses `AuthModalProvider` instead; this route stays for verify failures and bookmarks.
*/
export default function LoginPageClient({
privacyEnabled,
}: {
privacyEnabled: boolean;
}) {
return (
<Suspense fallback={<LoginLoadingFallback />}>
<LoginWithSearchParams privacyEnabled={privacyEnabled} />
</Suspense>
);
}
+3 -61
View File
@@ -1,64 +1,6 @@
"use client";
import { Suspense } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslation } from "../../contexts/MessagesContext";
import Login from "../../components/modals/Login";
import LoginForm from "../../components/modals/Login/LoginForm";
const loginPageBgClass =
"min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)]";
function LoginLoadingFallback() {
const t = useTranslation("pages.login");
return (
<div className={`${loginPageBgClass} flex items-center justify-center`}>
<p className="text-[14px] text-[var(--color-content-default-primary)]">
{t("loadingFallback")}
</p>
</div>
);
}
/**
* Full-page login shell for magic-link **error redirects** (`?error=*`) and direct `/login` visits.
* Header **Log in** uses `AuthModalProvider` instead; this route stays for verify failures and bookmarks.
*/
function LoginWithSearchParams() {
const router = useRouter();
const t = useTranslation("pages.login");
const closeToHome = () => {
router.push("/");
};
return (
<div className={loginPageBgClass}>
<Login
isOpen
usePortal={false}
backdropVariant="solid"
onClose={closeToHome}
ariaLabelledBy="login-modal-heading"
belowCard={
<Link
href="/"
className="text-small-paragraph text-[var(--color-content-invert-tertiary,#2d2d2d)] text-center hover:opacity-90"
>
{t("backToHome")}
</Link>
}
>
<LoginForm onClose={closeToHome} />
</Login>
</div>
);
}
import { isPrivacyPolicyEnabled } from "../../../lib/privacyPolicyEnabled";
import LoginPageClient from "./LoginPageClient";
export default function LoginPage() {
return (
<Suspense fallback={<LoginLoadingFallback />}>
<LoginWithSearchParams />
</Suspense>
);
return <LoginPageClient privacyEnabled={isPrivacyPolicyEnabled()} />;
}
+2 -1
View File
@@ -5,6 +5,7 @@ import { MessagesProvider } from "../contexts/MessagesContext";
import { AuthModalProvider } from "../contexts/AuthModalContext";
import messages from "../../messages/en/index";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { isPrivacyPolicyEnabled } from "../../lib/privacyPolicyEnabled";
import { NO_INDEX_ROBOTS } from "../../lib/siteMetadata";
export const metadata: Metadata = {
@@ -18,7 +19,7 @@ export default function DevLayout({ children }: { children: ReactNode }) {
}
return (
<MessagesProvider messages={messages}>
<AuthModalProvider>
<AuthModalProvider privacyEnabled={isPrivacyPolicyEnabled()}>
<main
id={MAIN_CONTENT_ID}
tabIndex={-1}
@@ -8,6 +8,7 @@ import {
} from "../../../lib/legalSyntheticPost";
import { getRequestSiteOrigin } from "../../../lib/requestSiteOrigin";
import { absoluteSiteUrl } from "../../../lib/siteMetadata";
import { isPrivacyPolicyEnabled } from "../../../lib/privacyPolicyEnabled";
import ContentBanner from "../../components/sections/ContentBanner";
type LegalDocumentPageProps = {
@@ -45,7 +46,9 @@ function LegalInlineText({ text }: { text: string }) {
const label = match[1];
const href = match[2];
if (isSafeHref(href)) {
if (href === "/privacy" && !isPrivacyPolicyEnabled()) {
nodes.push(label);
} else if (isSafeHref(href)) {
const isInternal = href.startsWith("/") && !href.startsWith("//");
nodes.push(
isInternal ? (
+2 -1
View File
@@ -5,12 +5,13 @@ import SkipToContent from "../components/navigation/SkipToContent";
import { MessagesProvider } from "../contexts/MessagesContext";
import { AuthModalProvider } from "../contexts/AuthModalContext";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { isPrivacyPolicyEnabled } from "../../lib/privacyPolicyEnabled";
import marketingMessages from "../../messages/en/marketing";
export default function MarketingLayout({ children }: { children: ReactNode }) {
return (
<MessagesProvider messages={marketingMessages}>
<AuthModalProvider>
<AuthModalProvider privacyEnabled={isPrivacyPolicyEnabled()}>
{/*
* Same session-aware shell as `(app)` / `(admin)`: `ConditionalNavigation`
* reads the cookie behind Suspense so the static page shell can prerender
+4
View File
@@ -3,8 +3,10 @@
* https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=19003-23305
*/
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import messages from "../../../messages/en/index";
import { legalPathForSlug } from "../../../lib/legalSyntheticPost";
import { isPrivacyPolicyEnabled } from "../../../lib/privacyPolicyEnabled";
import { routeMetadata } from "../../../lib/siteMetadata";
import LegalDocumentPage, {
legalPageMetadata,
@@ -14,6 +16,7 @@ const SLUG = "privacy" as const;
const PATH = legalPathForSlug(SLUG);
export function generateMetadata(): Metadata {
if (!isPrivacyPolicyEnabled()) notFound();
return routeMetadata(
PATH,
legalPageMetadata(messages.metadata.privacy, messages.pages.privacy),
@@ -21,6 +24,7 @@ export function generateMetadata(): Metadata {
}
export default function PrivacyPage() {
if (!isPrivacyPolicyEnabled()) notFound();
return (
<LegalDocumentPage
slug={SLUG}
+2 -1
View File
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { MessagesProvider } from "../contexts/MessagesContext";
import { AuthModalProvider } from "../contexts/AuthModalContext";
import { MAIN_CONTENT_ID } from "../../lib/mainContent";
import { isPrivacyPolicyEnabled } from "../../lib/privacyPolicyEnabled";
import marketingMessages from "../../messages/en/marketing";
/** Full-viewport case-study surfaces (completed rule demos) — no marketing footer. */
@@ -12,7 +13,7 @@ export default function MarketingCaseStudyLayout({
}) {
return (
<MessagesProvider messages={marketingMessages}>
<AuthModalProvider>
<AuthModalProvider privacyEnabled={isPrivacyPolicyEnabled()}>
<main
id={MAIN_CONTENT_ID}
tabIndex={-1}
+5 -2
View File
@@ -1,5 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { sendOrganizerInquiryNotification } from "../../../lib/server/mail";
import {
resolveMailFrom,
sendOrganizerInquiryNotification,
} from "../../../lib/server/mail";
import { rateLimitKey } from "../../../lib/server/rateLimit";
import {
errorJson,
@@ -66,7 +69,7 @@ export const POST = apiRoute(SCOPE, async (request: NextRequest, _ctx, { request
return serverMisconfigured("ORGANIZER_INQUIRY_TO is not configured");
}
const from = process.env.SMTP_FROM ?? "noreply@localhost";
const from = resolveMailFrom();
try {
await sendOrganizerInquiryNotification({
+1 -1
View File
@@ -120,7 +120,7 @@ export const POST = apiRoute(SCOPE, async (request: NextRequest, _ctx, { request
const verifyUrl = `${origin}/api/user/email-change/verify?token=${encodeURIComponent(token)}`;
try {
await sendEmailChangeEmail(newEmail, verifyUrl);
await sendEmailChangeEmail(newEmail, verifyUrl, origin);
} catch (err) {
logRouteError(SCOPE, requestId, err, { phase: "sendEmailChangeEmail" });
await prisma.emailChangeToken.deleteMany({ where: { userId: user.id } });
@@ -111,6 +111,8 @@ export type LoginFormProps = {
variant?: LoginFormVariant;
/** Overrides URL `next` for `requestMagicLink` (e.g. create-flow exit modal). */
magicLinkNextPath?: string;
/** When false, the login legal line links terms only. */
privacyEnabled?: boolean;
/** `keepRule`: Continue without saving. */
onDismiss?: () => void;
/** Sent-state Close, and the dialog chrome close. */
@@ -120,6 +122,7 @@ export type LoginFormProps = {
export default function LoginForm({
variant = "default",
magicLinkNextPath,
privacyEnabled = false,
onDismiss,
onClose,
}: LoginFormProps) {
@@ -365,6 +368,8 @@ export default function LoginForm({
>
{tFooter("legal.termsOfService")}
</Link>
{privacyEnabled ? (
<>
{t("legalAnd")}
<Link
href={tFooter("legal.privacyPolicyHref")}
@@ -372,6 +377,8 @@ export default function LoginForm({
>
{tFooter("legal.privacyPolicy")}
</Link>
</>
) : null}
{t("legalSuffix")}
</p>
</>
+9 -1
View File
@@ -13,7 +13,13 @@ import { PRODUCTION_SITE_ORIGIN } from "../../../lib/siteMetadata";
* Tiers: smallest viewports (below `md`), `md` through `lg`, `lg` and up.
* Matches `--breakpoint-md: 640px`, `--breakpoint-lg: 1024px` in `app/tailwind.css`.
*/
const Footer = memo(({ siteOrigin = PRODUCTION_SITE_ORIGIN }: { siteOrigin?: string }) => {
const Footer = memo(({
siteOrigin = PRODUCTION_SITE_ORIGIN,
privacyEnabled = false,
}: {
siteOrigin?: string;
privacyEnabled?: boolean;
}) => {
const t = useTranslation("footer");
const tChrome = useTranslation("controlsChrome");
@@ -213,9 +219,11 @@ const Footer = memo(({ siteOrigin = PRODUCTION_SITE_ORIGIN }: { siteOrigin?: str
<Link href={t("takeawayHref")} className={legalLinkClass}>
{t("takeaway")}
</Link>
{privacyEnabled ? (
<Link href={t("legal.privacyPolicyHref")} className={legalLinkClass}>
{t("legal.privacyPolicy")}
</Link>
) : null}
<Link href={t("legal.termsOfServiceHref")} className={legalLinkClass}>
{t("legal.termsOfService")}
</Link>
@@ -1,8 +1,14 @@
import Footer from "./Footer";
import { isPrivacyPolicyEnabled } from "../../../lib/privacyPolicyEnabled";
import { getRequestSiteOrigin } from "../../../lib/requestSiteOrigin";
/** Footer JSON-LD uses the request origin, same host as the page canonical. */
export default async function FooterWithOrigin() {
const siteOrigin = await getRequestSiteOrigin();
return <Footer siteOrigin={siteOrigin} />;
return (
<Footer
siteOrigin={siteOrigin}
privacyEnabled={isPrivacyPolicyEnabled()}
/>
);
}
+8 -1
View File
@@ -39,7 +39,13 @@ type AuthModalContextValue = {
const AuthModalContext = createContext<AuthModalContextValue | null>(null);
export function AuthModalProvider({ children }: { children: ReactNode }) {
export function AuthModalProvider({
children,
privacyEnabled = false,
}: {
children: ReactNode;
privacyEnabled?: boolean;
}) {
const tLogin = useTranslation("pages.login");
const [open, setOpen] = useState(false);
const [opts, setOpts] = useState<OpenLoginOptions>({});
@@ -93,6 +99,7 @@ export function AuthModalProvider({ children }: { children: ReactNode }) {
<LoginForm
variant={opts.variant ?? "default"}
magicLinkNextPath={opts.nextPath}
privacyEnabled={privacyEnabled}
onDismiss={keepRuleDismiss}
onClose={closeLogin}
/>
+9 -2
View File
@@ -75,8 +75,14 @@ per-app in the manifest and provisioned at install time.
- `SESSION_SECRET` — long random (`openssl rand -hex 32`). Required,
≥ 16 chars. Rotating it logs everyone out.
- `SMTP_FROM` — visible "From:" address on sign-in emails. Cloudron
does not inject this. Use `hello@communityrule.info` (continuity
with the legacy service; SES relay accepts it).
does not inject this. Use `CommunityRule <hello@communityrule.info>`
(continuity with the legacy service; SES relay accepts it). A leftover
`Community Rule` display name is rewritten to one word.
- `ENABLE_PRIVACY_POLICY=true` — turns on `/privacy` at runtime. Staging
keeps this on so counsel can read the page. Leave unset in production
until that review is done (the route 404s and public chrome does not
link to it). `NEXT_PUBLIC_ENABLE_PRIVACY_POLICY` is the same switch
baked at image build; prefer the runtime name on Cloudron.
- `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true` — turns on Postgres draft
persistence for signed-in users. Required in production.
- `UPLOAD_ROOT` — absolute path to a writable directory on the Cloudron
@@ -445,6 +451,7 @@ production env vars, and verify the vertical slice before apex cutover
cloudron env set --app staging.communityrule.info \
SESSION_SECRET="$(openssl rand -hex 32)" \
SMTP_FROM="CommunityRule <hello@communityrule.info>" \
ENABLE_PRIVACY_POLICY=true \
NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true \
UPLOAD_ROOT=/app/data/uploads
```
+2 -1
View File
@@ -246,7 +246,8 @@ persist across image updates unless changed:
| Variable | Purpose |
| -------- | ------- |
| `SESSION_SECRET` | Session cookie signing (≥ 16 chars). Rotating logs everyone out. |
| `SMTP_FROM` | Visible From on sign-in emails (e.g. `Community Rule <hello@communityrule.info>`). |
| `SMTP_FROM` | Visible From on sign-in emails (e.g. `CommunityRule <hello@communityrule.info>`). The app rewrites a leftover `Community Rule` display name to one word. |
| `ENABLE_PRIVACY_POLICY` | `true` on staging so `/privacy` is reachable. Unset in production until counsel has read the policy (404, no public links). |
| `NEXT_PUBLIC_ENABLE_BACKEND_SYNC` | `true` in staging/production — Postgres draft persistence. |
| `UPLOAD_ROOT` | `/app/data/uploads` on Cloudron — required for file uploads. |
| `OPS_PRUNE_TOKEN` | Bearer token for `POST /api/ops/prune`. Unset hides the route. Optional; the daily scheduler runs the prune inside the container without it. |
+4 -3
View File
@@ -1,8 +1,8 @@
# Privacy policy facts
Numbers and hosting details the new privacy policy leaves in brackets.
Live `/privacy` stays on the current page until university counsel has
read this text. Do not switch the route on from this file.
Live `/privacy` stays behind `ENABLE_PRIVACY_POLICY` until university
counsel has read this text. Do not switch the route on from this file.
## How long things are kept
@@ -53,6 +53,7 @@ See [`docs/guides/ops-runbook.md`](guides/ops-runbook.md) §9.3.
- `/privacy` can show the new policy only after university counsel has
read it, including the Colorado Open Records Act line, Terms, Cookies,
the legal cards, and CC0 for cards and templates.
the legal cards, and CC0 for cards and templates. Flipping
`ENABLE_PRIVACY_POLICY=true` on production is that switch.
- An email to every account holder before a change to who can read Rules
is after launch. Nothing about who can read Rules changes at launch.
+17
View File
@@ -0,0 +1,17 @@
/**
* `/privacy` stays off in production until university counsel has read the
* policy. Staging sets `ENABLE_PRIVACY_POLICY=true` (or the public alias).
* Unset or any other value is off.
*/
export function isPrivacyPolicyEnabled(): boolean {
return (
process.env.ENABLE_PRIVACY_POLICY === "true" ||
process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY === "true"
);
}
/** Absolute /privacy URL, or null while the flag is off. */
export function privacyPolicyUrl(origin: string): string | null {
if (!isPrivacyPolicyEnabled()) return null;
return `${origin.replace(/\/$/, "")}/privacy`;
}
+4 -1
View File
@@ -1,5 +1,6 @@
import type { MetadataRoute } from "next";
import { getAllBlogPosts } from "./content";
import { isPrivacyPolicyEnabled } from "./privacyPolicyEnabled";
import { sitemapUrl } from "./siteMetadata";
import { USE_CASE_DETAIL_SLUGS } from "./useCaseSyntheticPost";
@@ -26,7 +27,9 @@ const STATIC_PUBLIC_PATHS = [
export function buildPublicSitemap(
listedRules: ReadonlyArray<{ id: string; updatedAt: Date }> = [],
): MetadataRoute.Sitemap {
const entries: MetadataRoute.Sitemap = STATIC_PUBLIC_PATHS.map((path) => ({
const entries: MetadataRoute.Sitemap = STATIC_PUBLIC_PATHS.filter(
(path) => path !== "/privacy" || isPrivacyPolicyEnabled(),
).map((path) => ({
url: sitemapUrl(path),
}));
+75 -30
View File
@@ -1,5 +1,6 @@
import { ASSETS, getAssetPath } from "../assetUtils";
import { MAGIC_LINK_TTL_MINUTES } from "../privacyRetention";
import { mailLegalFooterHtml, mailLegalFooterUrls } from "./mailLegalFooter";
export const MAGIC_LINK_LOGO_PATH = getAssetPath(ASSETS.LOGO_MARK);
@@ -31,51 +32,54 @@ function originHost(origin: string): string {
}
}
export function buildMagicLinkMail(
input: MagicLinkMailInput,
type BrandedVerifyMailCopy = {
verifyUrl: string;
origin: string;
subject: string;
previewText: string;
heading: string;
intro: string;
buttonLabel: string;
ignore: string;
why: string;
};
function buildBrandedVerifyMail(
copy: BrandedVerifyMailCopy,
): MagicLinkMailContent {
const origin = input.origin.replace(/\/$/, "");
const minutes = MAGIC_LINK_TTL_MINUTES;
const subject = "Your login link for CommunityRule";
const previewText = `It works once, for ${minutes} minutes.`;
const heading = "Log in to CommunityRule";
const intro = `Use the button to log in. It works once, for ${minutes} minutes.`;
const ignore =
"If you did not ask to log in, ignore this email. Nobody can log in without the link.";
const origin = copy.origin.replace(/\/$/, "");
const { aboutUrl, privacyUrl } = mailLegalFooterUrls(origin);
const madeBy =
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
const privacyUrl = `${origin}/privacy`;
const aboutUrl = `${origin}/about`;
const logoUrl = `${origin}${MAGIC_LINK_LOGO_PATH}`;
const host = originHost(origin);
const href = escapeHtml(copy.verifyUrl);
const text = [
heading,
copy.heading,
"",
intro,
copy.intro,
"",
`Log in: ${input.verifyUrl}`,
`${copy.buttonLabel}: ${copy.verifyUrl}`,
"",
ignore,
copy.ignore,
"",
madeBy,
`Privacy ${privacyUrl}`,
...(privacyUrl ? [`Privacy ${privacyUrl}`] : []),
`About CommunityRule ${aboutUrl}`,
"",
`Sent because you asked to log in at ${host}.`,
copy.why,
].join("\n");
const href = escapeHtml(input.verifyUrl);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${escapeHtml(subject)}</title>
<title>${escapeHtml(copy.subject)}</title>
</head>
<body style="margin:0;padding:0;background:#e4e4e4;">
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(
previewText,
copy.previewText,
)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#e4e4e4;">
<tr>
@@ -95,19 +99,17 @@ export function buildMagicLinkMail(
</tr>
<tr>
<td style="padding:40px 32px 56px;">
<h1 style="margin:0 0 16px;font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:36px;line-height:44px;font-weight:700;color:#000000;">${escapeHtml(heading)}</h1>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:18px;line-height:24px;color:#303030;">${escapeHtml(intro)}</p>
<h1 style="margin:0 0 16px;font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:36px;line-height:44px;font-weight:700;color:#000000;">${escapeHtml(copy.heading)}</h1>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:18px;line-height:24px;color:#303030;">${escapeHtml(copy.intro)}</p>
<p style="margin:0 0 32px;">
<a href="${href}" style="display:inline-block;background:#141414;color:#ffffff;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:20px;font-weight:500;text-decoration:none;border-radius:9999px;padding:12px 16px;">Log in</a>
<a href="${href}" style="display:inline-block;background:#141414;color:#ffffff;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:20px;font-weight:500;text-decoration:none;border-radius:9999px;padding:12px 16px;">${escapeHtml(copy.buttonLabel)}</a>
</p>
<div style="height:1px;background:#e4e4e4;margin:0 0 32px;"></div>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(ignore)}</p>
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(copy.ignore)}</p>
<div style="border-top:1px solid #e4e4e4;padding-top:24px;">
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(madeBy)}</p>
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
<a href="${escapeHtml(privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
&nbsp;&nbsp;
<a href="${escapeHtml(aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
${mailLegalFooterHtml(origin)}
</p>
</div>
</td>
@@ -119,5 +121,48 @@ export function buildMagicLinkMail(
</body>
</html>`;
return { subject, previewText, text, html };
return {
subject: copy.subject,
previewText: copy.previewText,
text,
html,
};
}
export function buildMagicLinkMail(
input: MagicLinkMailInput,
): MagicLinkMailContent {
const minutes = MAGIC_LINK_TTL_MINUTES;
const origin = input.origin.replace(/\/$/, "");
return buildBrandedVerifyMail({
verifyUrl: input.verifyUrl,
origin,
subject: "Your login link for CommunityRule",
previewText: `It works once, for ${minutes} minutes.`,
heading: "Log in to CommunityRule",
intro: `Use the button to log in. It works once, for ${minutes} minutes.`,
buttonLabel: "Log in",
ignore:
"If you did not ask to log in, ignore this email. Nobody can log in without the link.",
why: `Sent because you asked to log in at ${originHost(origin)}.`,
});
}
export function buildEmailChangeMail(
input: MagicLinkMailInput,
): MagicLinkMailContent {
const minutes = MAGIC_LINK_TTL_MINUTES;
const origin = input.origin.replace(/\/$/, "");
return buildBrandedVerifyMail({
verifyUrl: input.verifyUrl,
origin,
subject: "Confirm your new CommunityRule email",
previewText: `It works once, for ${minutes} minutes.`,
heading: "Confirm your new email",
intro: `Use the button to confirm the new address on your CommunityRule account. It works once, for ${minutes} minutes.`,
buttonLabel: "Confirm email",
ignore:
"If you did not request this change, ignore this email. Your current login is unchanged until you confirm.",
why: `Sent because you asked to change the email on your CommunityRule account at ${originHost(origin)}.`,
});
}
+17 -12
View File
@@ -5,8 +5,7 @@ import {
buildWorkshopInboxMail,
type WorkshopInquiryMailInput,
} from "../workshopSignupMail";
import { MAGIC_LINK_TTL_MINUTES } from "../privacyRetention";
import { buildMagicLinkMail } from "./magicLinkMail";
import { buildEmailChangeMail, buildMagicLinkMail } from "./magicLinkMail";
import { getSmtpUrl } from "./env";
import {
buildRuleStakeholderInviteMail,
@@ -26,12 +25,22 @@ function escapeHtml(value: string): string {
.replace(/"/g, "&quot;");
}
/** Display name is CommunityRule, one word, even if SMTP_FROM still has a space. */
function formatMailFrom(from: string): string {
const trimmed = from
.trim()
.replace(/^"?Community Rule"?(\s*<)/, "CommunityRule$1");
if (trimmed.includes("<")) return trimmed;
if (trimmed.includes("@")) return `CommunityRule <${trimmed}>`;
return trimmed;
}
export function resolveMailFrom(): string {
return (
const raw =
process.env.SMTP_FROM?.trim() ||
process.env.CLOUDRON_MAIL_FROM?.trim() ||
"noreply@localhost"
);
"noreply@localhost";
return formatMailFrom(raw);
}
/** Avoid quoted-printable `token=3D` wrapping that some webmail clients do not decode. */
@@ -187,16 +196,12 @@ export async function sendWorkshopInquiryConfirmation(input: {
export async function sendEmailChangeEmail(
to: string,
verifyUrl: string,
origin: string,
): Promise<void> {
const { text, html } = buildVerifyLinkParts(
verifyUrl,
`You asked to change the email on your Community Rule account.\n\nOpen this link to confirm the new address (it expires in ${MAGIC_LINK_TTL_MINUTES} minutes):`,
"If you did not request this change, you can ignore this email. Your current login is unchanged until you confirm.",
"Confirm email",
);
const { subject, text, html } = buildEmailChangeMail({ verifyUrl, origin });
await sendHtmlMail({
to,
subject: "Confirm your new Community Rule email",
subject,
text,
html,
devLog: `[dev] Email change verify for ${to}: ${verifyUrl}`,
+30
View File
@@ -0,0 +1,30 @@
import { privacyPolicyUrl } from "../privacyPolicyEnabled";
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
export function mailLegalFooterUrls(origin: string): {
aboutUrl: string;
privacyUrl: string | null;
} {
const base = origin.replace(/\/$/, "");
return {
aboutUrl: `${base}/about`,
privacyUrl: privacyPolicyUrl(base),
};
}
/** HTML Privacy + About links. Omits Privacy while the policy flag is off. */
export function mailLegalFooterHtml(origin: string): string {
const { aboutUrl, privacyUrl } = mailLegalFooterUrls(origin);
const about = `<a href="${escapeHtml(aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>`;
if (!privacyUrl) return about;
return `<a href="${escapeHtml(privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
&nbsp;&nbsp;
${about}`;
}
+6 -10
View File
@@ -1,6 +1,7 @@
import { ASSETS, getAssetPath } from "../assetUtils";
import { communityPossessive } from "../create/ruleInviteCardMeta";
import { RULE_MD_FILENAME } from "../create/ruleExportModel";
import { mailLegalFooterHtml, mailLegalFooterUrls } from "./mailLegalFooter";
export const RULE_FOLLOW_UP_LOGO_PATH = getAssetPath(ASSETS.LOGO_MARK);
@@ -55,8 +56,7 @@ export function buildRuleFollowUpMail(
const why = `Sent because you finished a Rule at ${host}.`;
const madeBy =
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
const privacyUrl = `${origin}/privacy`;
const aboutUrl = `${origin}/about`;
const { privacyUrl } = mailLegalFooterUrls(origin);
const logoUrl = `${origin}${RULE_FOLLOW_UP_LOGO_PATH}`;
const text = [
@@ -82,7 +82,7 @@ export function buildRuleFollowUpMail(
why,
"",
madeBy,
`Privacy ${privacyUrl}`,
...(privacyUrl ? [`Privacy ${privacyUrl}`] : []),
].join("\n");
const html = followUpHtml({
@@ -98,8 +98,7 @@ export function buildRuleFollowUpMail(
signOff,
why,
madeBy,
privacyUrl,
aboutUrl,
origin,
logoUrl,
kitHostPath: `${host}/kit`,
});
@@ -120,8 +119,7 @@ function followUpHtml(opts: {
signOff: string;
why: string;
madeBy: string;
privacyUrl: string;
aboutUrl: string;
origin: string;
logoUrl: string;
kitHostPath: string;
}): string {
@@ -180,9 +178,7 @@ function followUpHtml(opts: {
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.why)}</p>
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.madeBy)}</p>
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
<a href="${escapeHtml(opts.privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
&nbsp;&nbsp;
<a href="${escapeHtml(opts.aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
${mailLegalFooterHtml(opts.origin)}
</p>
</div>
</td>
+6 -12
View File
@@ -1,4 +1,5 @@
import { ASSETS, getAssetPath } from "../assetUtils";
import { mailLegalFooterHtml, mailLegalFooterUrls } from "./mailLegalFooter";
import {
clipCommunityInviteDescription,
communityInviteInitials,
@@ -84,8 +85,7 @@ export function buildRuleStakeholderInviteMail(
const why = `You got this email because ${inviterEmail} added your address to ${possessive} Rule on CommunityRule. If you do not know the community, you can ignore this email.`;
const madeBy =
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
const privacyUrl = `${origin}/privacy`;
const aboutUrl = `${origin}/about`;
const { privacyUrl } = mailLegalFooterUrls(origin);
const logoUrl = `${origin}${RULE_STAKEHOLDER_INVITE_LOGO_PATH}`;
const text = [
@@ -106,7 +106,7 @@ export function buildRuleStakeholderInviteMail(
why,
"",
madeBy,
`Privacy ${privacyUrl}`,
...(privacyUrl ? [`Privacy ${privacyUrl}`] : []),
].join("\n");
const html = inviteHtml({
@@ -123,8 +123,7 @@ export function buildRuleStakeholderInviteMail(
copyLead,
why,
madeBy,
privacyUrl,
aboutUrl,
origin,
logoUrl,
});
@@ -145,8 +144,7 @@ function inviteHtml(opts: {
copyLead: string;
why: string;
madeBy: string;
privacyUrl: string;
aboutUrl: string;
origin: string;
logoUrl: string;
}): string {
const heading = escapeHtml(opts.subject);
@@ -165,8 +163,6 @@ function inviteHtml(opts: {
` of this one and change what does not fit.`;
const why = escapeHtml(opts.why);
const madeBy = escapeHtml(opts.madeBy);
const privacyUrl = escapeHtml(opts.privacyUrl);
const aboutUrl = escapeHtml(opts.aboutUrl);
const logoUrl = escapeHtml(opts.logoUrl);
const cardBody = description
? `<p style="margin:16px 0 0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:18px;font-weight:500;color:#000000;">${description}</p>`
@@ -236,9 +232,7 @@ function inviteHtml(opts: {
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${why}</p>
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${madeBy}</p>
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
<a href="${privacyUrl}" style="color:#464646;text-decoration:underline;">Privacy</a>
&nbsp;&nbsp;
<a href="${aboutUrl}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
${mailLegalFooterHtml(opts.origin)}
</p>
</div>
</td>
+9 -9
View File
@@ -40,7 +40,7 @@
},
"create": {
"title": "Create",
"description": "This flow will give you recommendations to improve your community and help you put together a proposal for your group to consider."
"description": "Start a Rule for your community. CommunityRule recommends templates from the details you enter, then you put a proposal together for your group."
},
"blog": {
"title": "Blog",
@@ -63,7 +63,7 @@
},
"profile": {
"title": "Profile",
"description": "Manage your CommunityRules, saved progress, and account."
"description": "Manage the Rules you have finished, saved progress, and your account."
},
"monitor": {
"title": "Monitor",
@@ -117,8 +117,8 @@
},
"useCasesCompletedRule": {
"mutualAidColorado": {
"title": "Mutual Aid Colorado community rule",
"description": "Read the completed community rule Mutual Aid Colorado built with CommunityRule.",
"title": "Mutual Aid Colorado CommunityRule",
"description": "Read the completed Rule Mutual Aid Colorado built with CommunityRule.",
"keywords": [
"mutual aid",
"community rule",
@@ -127,8 +127,8 @@
]
},
"foodNotBombs": {
"title": "Food Not Bombs Boulder community rule",
"description": "Read the completed community rule Food Not Bombs Boulder built with CommunityRule.",
"title": "Food Not Bombs Boulder CommunityRule",
"description": "Read the completed Rule Food Not Bombs Boulder built with CommunityRule.",
"keywords": [
"food not bombs",
"community rule",
@@ -137,8 +137,8 @@
]
},
"boulderCountyStreetMedics": {
"title": "Boulder Street Medics community rule",
"description": "Read the completed community rule Boulder Street Medics built with CommunityRule.",
"title": "Boulder Street Medics CommunityRule",
"description": "Read the completed Rule Boulder Street Medics built with CommunityRule.",
"keywords": [
"street medics",
"community rule",
@@ -179,7 +179,7 @@
},
"cookies": {
"title": "Cookies",
"description": "CommunityRule uses cookies to keep you logged in and to let you claim a rule you finished without logging in.",
"description": "CommunityRule uses cookies to keep you logged in and to let you claim a Rule you finished without logging in.",
"keywords": ["cookies", "session", "privacy", "communityrule"]
}
}
+9 -4
View File
@@ -2,20 +2,25 @@
"_comment": "Cookies. Figma Content page Template (19003:23305): banner + labeled body stacks. There are no optional cookies to toggle. The footer does not link here.",
"banner": {
"title": "Cookies",
"description": "CommunityRule uses cookies to keep you logged in and to let you claim a rule you finished without logging in.",
"description": "CommunityRule uses cookies to keep you logged in and to let you claim a Rule you finished without logging in.",
"author": "Media Economies Design Lab",
"date": "2026-08-15"
},
"updated": "Last updated August 15, 2026.",
"intro": [
"CommunityRule sets a cookie named cr_session after you log in with a magic link. It keeps you logged in for up to 30 days. Set when you finish a Rule without logging in: we also set cr_rule_claim so that logging in later on this browser can attach that rule to your account. There are no advertising or analytics cookies to turn off."
"CommunityRule sets a cookie named cr_session after you log in. It keeps you logged in for up to 30 days. When you finish a Rule without logging in, we also set cr_rule_claim so that logging in later on this browser can attach that Rule to your account. There are no advertising or analytics cookies to turn off."
],
"sections": [
{
"heading": "The session cookie",
"paragraphs": [
"Log out to clear the session cookie on this browser. Blocking it will log you out and keep you from staying logged in. Browsing templates does not set this cookie.",
"Set when you finish a Rule without logging in. It is httpOnly, lasts up to 30 days, and is cleared after a successful login claim. Clearing this site’s cookies means you cannot attach that guest-finished rule to an account from this browser."
"Log out to clear the session cookie on this browser. Blocking it will log you out and keep you from staying logged in. Browsing templates does not set this cookie."
]
},
{
"heading": "The claim cookie",
"paragraphs": [
"Set when you finish a Rule without logging in. It is httpOnly, lasts up to 30 days, and is cleared after a successful login claim. Clearing this site’s cookies means you cannot attach that guest-finished Rule to an account from this browser."
]
},
{
+3 -3
View File
@@ -1,5 +1,5 @@
{
"_comment": "Privacy policy currently on /privacy. Owns personal data, hosting, and how ranking works. API usage and licenses live on Terms. Grounded in MEDLab Cloudron + SES mail relay + facet-matrix recommendations. Periods and hosting facts for the new policy live in docs/privacy-policy-facts.md. Do not switch /privacy to that text until university counsel has read it.",
"_comment": "Privacy policy currently on /privacy, behind ENABLE_PRIVACY_POLICY. Owns personal data, hosting, and how ranking works. API usage and licenses live on Terms. Grounded in MEDLab Cloudron + SES mail relay + facet-matrix recommendations. Periods and hosting facts for the new policy live in docs/privacy-policy-facts.md. Do not switch /privacy to that text until university counsel has read it.",
"banner": {
"title": "Privacy Policy",
"description": "What we collect, where it is stored, and how template recommendations work.",
@@ -14,7 +14,7 @@
{
"heading": "What we collect",
"paragraphs": [
"Your email, to log you in, change your email, or invite a stakeholder. In-progress drafts in your browser and, after you save, on our servers. Files you attach to a Rule. Messages you send through the organizer form, which go to MEDLab by email. Page performance metrics (URL, timing, and browser), which are written to our server logs and are not tied to your account. If you finish a Rule without logging in, a claim cookie on this browser so a later login can attach that Rule to your account. We count page views with Umami, self-hosted beside this app. It sets no cookies and stores aggregate counts only.",
"Your email, to log you in, change your email, or invite the people in your community. In-progress drafts in your browser and, after you save, on our servers. Files you attach to a Rule. Messages you send through the organizer form, which go to MEDLab by email. Page performance metrics (URL, timing, and browser), which are written to our server logs and are not tied to your account. If you finish a Rule without logging in, a claim cookie on this browser so a later login can attach that Rule to your account. We count page views with Umami, self-hosted beside this app. It sets no cookies and stores aggregate counts only.",
"We do not sell this information or use it for advertising. As a public university project, some records may be subject to the Colorado Open Records Act."
]
},
@@ -28,7 +28,7 @@
{
"heading": "Recommendations",
"paragraphs": [
"When you choose community details in the wizard (such as size or organization type), we use those answers to reorder templates and methods. The same ranking is available when those filters are sent to the templates API.",
"Your answers about your community’s size, kind, scale and stage reorder the templates and methods you see. The same ranking is available when those filters are sent to the templates API.",
"Ranking is a matching table we maintain. It is not an AI or machine-learning model, it does not train on your drafts, and we do not send your data to an AI service."
]
},
+11 -1
View File
@@ -118,7 +118,7 @@ describe("Footer (behavioral tests)", () => {
});
it("renders legal links to privacy and terms pages", () => {
render(<Footer />);
render(<Footer privacyEnabled />);
expect(
screen.getAllByRole("link", { name: "Privacy Policy" })[0],
).toHaveAttribute("href", "/privacy");
@@ -129,4 +129,14 @@ describe("Footer (behavioral tests)", () => {
screen.queryByRole("link", { name: "Cookies Settings" }),
).not.toBeInTheDocument();
});
it("omits the privacy link when the policy is off", () => {
render(<Footer privacyEnabled={false} />);
expect(
screen.queryByRole("link", { name: "Privacy Policy" }),
).not.toBeInTheDocument();
expect(
screen.getAllByRole("link", { name: "Terms of Service" })[0],
).toHaveAttribute("href", "/terms");
});
});
+15 -1
View File
@@ -78,7 +78,11 @@ describe("LoginForm", () => {
});
it("links terms and privacy to the legal pages", () => {
renderLoginForm();
renderWithProviders(
<Suspense fallback={null}>
<LoginForm privacyEnabled />
</Suspense>,
);
expect(
screen.getByRole("link", { name: "Terms of Service" }),
).toHaveAttribute("href", "/terms");
@@ -87,6 +91,16 @@ describe("LoginForm", () => {
).toHaveAttribute("href", "/privacy");
});
it("links terms only when the privacy policy is off", () => {
renderLoginForm();
expect(
screen.getByRole("link", { name: "Terms of Service" }),
).toHaveAttribute("href", "/terms");
expect(
screen.queryByRole("link", { name: "Privacy Policy" }),
).not.toBeInTheDocument();
});
it("shows validation error when email is invalid", async () => {
const user = userEvent.setup();
renderLoginForm();
+3
View File
@@ -17,4 +17,7 @@ vi.mock("next/navigation", () => ({
useRouter: () => testRouter,
usePathname: () => testPathname(),
useSearchParams: vi.fn(() => new URLSearchParams()),
notFound: () => {
throw new Error("NEXT_NOT_FOUND");
},
}));
+52 -8
View File
@@ -2,10 +2,14 @@ import { describe, expect, test, vi } from "vitest";
import { screen } from "@testing-library/react";
import { renderWithProviders as render } from "../utils/test-utils";
import PrivacyPage from "../../app/(marketing)/privacy/page";
import TermsPage from "../../app/(marketing)/terms/page";
import CookiesPage from "../../app/(marketing)/cookies/page";
import LegalDocumentPage from "../../app/(marketing)/_components/LegalDocumentPage";
import { legalPathForSlug } from "../../lib/legalSyntheticPost";
import messages from "../../messages/en/index";
vi.mock("../../lib/requestSiteOrigin", () => ({
getRequestSiteOrigin: async () => "https://communityrule.info",
}));
vi.mock("../../app/components/sections/ContentBanner", () => ({
default: ({ post, variant, updatedLabel }) => (
<section data-testid="content-banner" data-variant={variant}>
@@ -21,6 +25,18 @@ vi.mock("../../app/components/sections/ContentBanner", () => ({
),
}));
async function renderLegalPage(
slug: "privacy" | "terms" | "cookies",
page: (typeof messages.pages)[typeof slug],
) {
const ui = await LegalDocumentPage({
slug,
path: legalPathForSlug(slug),
page,
});
return render(ui);
}
describe("legal document pages", () => {
test("privacy copy names Umami and cookieless counts", () => {
const collect = messages.pages.privacy.sections.find(
@@ -30,8 +46,32 @@ describe("legal document pages", () => {
expect(collect?.paragraphs.join(" ")).toMatch(/sets no cookies/);
});
test("privacy page covers hosting, recommendations, and campus privacy", () => {
render(<PrivacyPage />);
test("privacy copy does not say stakeholder or wizard", () => {
const text = JSON.stringify(messages.pages.privacy);
expect(text).not.toMatch(/stakeholder/i);
expect(text).not.toMatch(/wizard/i);
});
test("privacy page 404s while the flag is off", () => {
const previous = process.env.ENABLE_PRIVACY_POLICY;
const previousPublic = process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
delete process.env.ENABLE_PRIVACY_POLICY;
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
try {
expect(() => PrivacyPage()).toThrow("NEXT_NOT_FOUND");
} finally {
if (previous === undefined) delete process.env.ENABLE_PRIVACY_POLICY;
else process.env.ENABLE_PRIVACY_POLICY = previous;
if (previousPublic === undefined) {
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
} else {
process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY = previousPublic;
}
}
});
test("privacy page covers hosting, recommendations, and campus privacy", async () => {
await renderLegalPage("privacy", messages.pages.privacy);
const page = messages.pages.privacy;
expect(screen.getByTestId("content-banner")).toHaveAttribute(
@@ -71,8 +111,8 @@ describe("legal document pages", () => {
);
});
test("terms page covers licenses and the templates API, not ranking", () => {
render(<TermsPage />);
test("terms page covers licenses and the templates API, not ranking", async () => {
await renderLegalPage("terms", messages.pages.terms);
const page = messages.pages.terms;
expect(
@@ -105,8 +145,8 @@ describe("legal document pages", () => {
).toHaveAttribute("href", "/api/templates");
});
test("cookies settings page explains there are no optional cookies", () => {
render(<CookiesPage />);
test("cookies settings page explains there are no optional cookies", async () => {
await renderLegalPage("cookies", messages.pages.cookies);
const page = messages.pages.cookies;
expect(
@@ -115,11 +155,15 @@ describe("legal document pages", () => {
expect(
screen.getByRole("heading", { level: 2, name: "The session cookie" }),
).toBeInTheDocument();
expect(
screen.getByRole("heading", { level: 2, name: "The claim cookie" }),
).toBeInTheDocument();
expect(
screen.getByText(/There are no advertising or analytics cookies to turn off/),
).toBeInTheDocument();
expect(screen.getByText(/cr_session/)).toBeInTheDocument();
expect(screen.getByText(/cr_rule_claim/)).toBeInTheDocument();
expect(JSON.stringify(page)).not.toMatch(/magic link/i);
expect(
screen.getAllByRole("link", { name: "Privacy Policy" })[0],
).toHaveAttribute("href", "/privacy");
+46 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { MAGIC_LINK_TTL_MINUTES } from "../../lib/privacyRetention";
import { buildMagicLinkMail } from "../../lib/server/magicLinkMail";
import {
buildEmailChangeMail,
buildMagicLinkMail,
} from "../../lib/server/magicLinkMail";
const VERIFY_URL =
"https://communityrule.info/api/auth/magic-link/verify?token=abc";
@@ -32,4 +35,46 @@ describe("buildMagicLinkMail", () => {
expect(mail.html).not.toContain("Hi ");
expect(mail.text).not.toContain("Hi ");
});
it("omits the privacy link while the policy flag is off", () => {
const previous = process.env.ENABLE_PRIVACY_POLICY;
const previousPublic = process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
delete process.env.ENABLE_PRIVACY_POLICY;
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
try {
const off = buildMagicLinkMail({
verifyUrl: VERIFY_URL,
origin: "https://communityrule.info",
});
expect(off.html).not.toContain("/privacy");
expect(off.text).not.toContain("/privacy");
expect(off.html).toContain("/about");
} finally {
if (previous === undefined) delete process.env.ENABLE_PRIVACY_POLICY;
else process.env.ENABLE_PRIVACY_POLICY = previous;
if (previousPublic === undefined) {
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
} else {
process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY = previousPublic;
}
}
});
});
describe("buildEmailChangeMail", () => {
const mail = buildEmailChangeMail({
verifyUrl: "https://communityrule.info/api/user/email-change/verify?token=abc",
origin: "https://communityrule.info",
});
it("matches the login email chrome with CommunityRule copy", () => {
expect(mail.subject).toBe("Confirm your new CommunityRule email");
expect(mail.html).toContain("background:#000000");
expect(mail.html).toContain(">Confirm email</a>");
expect(mail.html).toContain("CommunityRule account");
expect(mail.text).toContain("CommunityRule account");
expect(mail.subject).not.toMatch(/Community Rule/);
expect(mail.html).not.toMatch(/Community Rule/);
expect(mail.text).not.toMatch(/Community Rule/);
});
});
+10 -2
View File
@@ -100,14 +100,22 @@ describe("resolveMailFrom", () => {
it("prefers SMTP_FROM, then CLOUDRON_MAIL_FROM", () => {
delete process.env.SMTP_FROM;
delete process.env.CLOUDRON_MAIL_FROM;
expect(resolveMailFrom()).toBe("noreply@localhost");
expect(resolveMailFrom()).toBe("CommunityRule <noreply@localhost>");
process.env.CLOUDRON_MAIL_FROM = "staging.app@communityrule.info";
expect(resolveMailFrom()).toBe("staging.app@communityrule.info");
expect(resolveMailFrom()).toBe(
"CommunityRule <staging.app@communityrule.info>",
);
process.env.SMTP_FROM = "Community Rule <hello@communityrule.info>";
expect(resolveMailFrom()).toBe(
"CommunityRule <hello@communityrule.info>",
);
});
it("puts CommunityRule on a bare mailbox", () => {
delete process.env.SMTP_FROM;
process.env.CLOUDRON_MAIL_FROM = "hello@communityrule.info";
expect(resolveMailFrom()).toBe("CommunityRule <hello@communityrule.info>");
});
});
@@ -6,6 +6,7 @@ const sendOrganizerInquiryNotificationMock = vi.fn();
vi.mock("../../lib/server/mail", () => ({
sendOrganizerInquiryNotification: (...args: unknown[]) =>
sendOrganizerInquiryNotificationMock(...args),
resolveMailFrom: () => "CommunityRule <noreply@localhost>",
}));
const rateLimitKeyMock = vi.hoisted(() =>
@@ -54,6 +55,7 @@ describe("POST /api/organizer-inquiry", () => {
expect(body).toEqual({ ok: true });
expect(sendOrganizerInquiryNotificationMock).toHaveBeenCalledTimes(1);
const arg = sendOrganizerInquiryNotificationMock.mock.calls[0][0];
expect(arg.fromEmail).toBe("CommunityRule <noreply@localhost>");
expect(arg.visitorEmail).toBe("visitor@example.com");
expect(arg.message).toBe("How do we run consensus meetings?");
});
+40
View File
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, it } from "vitest";
import {
isPrivacyPolicyEnabled,
privacyPolicyUrl,
} from "../../lib/privacyPolicyEnabled";
const KEYS = ["ENABLE_PRIVACY_POLICY", "NEXT_PUBLIC_ENABLE_PRIVACY_POLICY"] as const;
const ORIGINAL = Object.fromEntries(
KEYS.map((key) => [key, process.env[key]]),
) as Record<(typeof KEYS)[number], string | undefined>;
afterEach(() => {
for (const key of KEYS) {
const original = ORIGINAL[key];
if (original === undefined) delete process.env[key];
else process.env[key] = original;
}
});
describe("isPrivacyPolicyEnabled", () => {
it("is off unless a flag is the string true", () => {
delete process.env.ENABLE_PRIVACY_POLICY;
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
expect(isPrivacyPolicyEnabled()).toBe(false);
expect(privacyPolicyUrl("https://communityrule.info")).toBeNull();
process.env.ENABLE_PRIVACY_POLICY = "yes";
expect(isPrivacyPolicyEnabled()).toBe(false);
process.env.ENABLE_PRIVACY_POLICY = "true";
expect(isPrivacyPolicyEnabled()).toBe(true);
expect(privacyPolicyUrl("https://communityrule.info/")).toBe(
"https://communityrule.info/privacy",
);
delete process.env.ENABLE_PRIVACY_POLICY;
process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY = "true";
expect(isPrivacyPolicyEnabled()).toBe(true);
});
});
+20
View File
@@ -55,4 +55,24 @@ describe("buildPublicSitemap", () => {
lastModified: updatedAt,
});
});
it("omits /privacy while the policy flag is off", () => {
const previous = process.env.ENABLE_PRIVACY_POLICY;
const previousPublic = process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
delete process.env.ENABLE_PRIVACY_POLICY;
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
try {
const urls = buildPublicSitemap().map((entry) => entry.url);
expect(urls).not.toContain(sitemapUrl("/privacy"));
expect(urls).toContain(sitemapUrl("/terms"));
} finally {
if (previous === undefined) delete process.env.ENABLE_PRIVACY_POLICY;
else process.env.ENABLE_PRIVACY_POLICY = previous;
if (previousPublic === undefined) {
delete process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY;
} else {
process.env.NEXT_PUBLIC_ENABLE_PRIVACY_POLICY = previousPublic;
}
}
});
});
@@ -153,6 +153,7 @@ describe("POST /api/user/email-change/request", () => {
expect(sendEmailChangeEmailMock).toHaveBeenCalledWith(
"new@x.com",
expect.stringContaining("/api/user/email-change/verify?token="),
"https://x.test",
);
});
+3
View File
@@ -1,4 +1,7 @@
import "@testing-library/jest-dom/vitest";
// Tests exercise the policy as staging will: on. Production leaves this unset.
process.env.ENABLE_PRIVACY_POLICY ??= "true";
import "./tests/mocks/navigation";
import React from "react";
import { afterAll, afterEach, beforeAll, vi } from "vitest";