Merge pull request 'Fix Share access, initials, copy confirm, and mailed export links' (#112) from adilallo/fix/share-dialog into main

Reviewed-on: #112
This commit was merged in pull request #112.
This commit is contained in:
an.di committed 2026-11-22 23:35:10 +00:00
commit 600056499c
35 files changed
+833 -102

No files matched your search

+26 -6
View File
@@ -1,8 +1,13 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { headers } from "next/headers";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import messages from "../../../../messages/en/index"; import messages from "../../../../messages/en/index";
import { isShareSlug } from "../../../../lib/sharePaths"; import { isShareSlug } from "../../../../lib/sharePaths";
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import {
SHARE_LOOKUP_MISS_INTERVAL_MS,
getReadablePublishedRule,
} from "../../../../lib/server/publishedRules";
import { rateLimitKey } from "../../../../lib/server/rateLimit";
import { getSessionUser } from "../../../../lib/server/session"; import { getSessionUser } from "../../../../lib/server/session";
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections"; import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata"; import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
@@ -13,14 +18,32 @@ interface PageProps {
params: Promise<{ shareSlug: string }>; params: Promise<{ shareSlug: string }>;
} }
async function clientIp(): Promise<string> {
const headerStore = await headers();
return (
headerStore.get("x-forwarded-for")?.split(",")[0]?.trim() ||
headerStore.get("x-real-ip") ||
"unknown"
);
}
async function loadSharedRule(shareSlug: string) { async function loadSharedRule(shareSlug: string) {
if (!isShareSlug(shareSlug)) return null; const ip = await clientIp();
if (!isShareSlug(shareSlug)) {
const limited = rateLimitKey(
`share-lookup-miss:${ip}`,
SHARE_LOOKUP_MISS_INTERVAL_MS,
);
if (!limited.ok) return null;
return null;
}
const user = await getSessionUser(); const user = await getSessionUser();
return getReadablePublishedRule({ return getReadablePublishedRule({
idOrSlug: shareSlug, idOrSlug: shareSlug,
user, user,
viaShareSlug: true, viaShareSlug: true,
requestPath: `/r/${shareSlug}`, requestPath: `/r/${shareSlug}`,
failedLookupKey: ip,
}); });
} }
@@ -30,10 +53,7 @@ export async function generateMetadata({
const { shareSlug } = await params; const { shareSlug } = await params;
const resolved = await loadSharedRule(shareSlug); const resolved = await loadSharedRule(shareSlug);
if (!resolved) { if (!resolved) {
return { notFound();
title: messages.pages.ruleDetail.notFoundTitle,
description: "The requested CommunityRule could not be found.",
};
} }
const { rule } = resolved; const { rule } = resolved;
const description = const description =
+7 -1
View File
@@ -52,6 +52,7 @@ export const GET = apiRoute<RouteContext>(
document: true, document: true,
createdAt: true, createdAt: true,
userId: true, userId: true,
exportTokenVersion: true,
}, },
}); });
if (!row) return notFound(); if (!row) return notFound();
@@ -60,7 +61,12 @@ export const GET = apiRoute<RouteContext>(
let tokenOk = false; let tokenOk = false;
if (token.length > 0) { if (token.length > 0) {
try { try {
tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper()); tokenOk = ruleExportTokenMatches(
row.id,
token,
getSessionPepper(),
row.exportTokenVersion,
);
} catch { } catch {
tokenOk = false; tokenOk = false;
} }
@@ -42,6 +42,10 @@ export const DELETE = apiRoute<RouteContext>(
} }
await prisma.ruleStakeholder.delete({ where: { id: row.id } }); await prisma.ruleStakeholder.delete({ where: { id: row.id } });
await prisma.publishedRule.update({
where: { id: ruleId },
data: { exportTokenVersion: { increment: 1 } },
});
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
}, },
+1 -1
View File
@@ -97,7 +97,7 @@ const Avatar = memo<AvatarProps>(
const fallbackChrome = const fallbackChrome =
variant === "outlined" variant === "outlined"
? "border-[1.5px] border-solid border-[var(--color-content-default-brand-primary)] bg-transparent text-[var(--color-content-default-brand-primary)]" ? "border-[1.5px] border-solid border-[var(--color-content-default-brand-primary)] bg-transparent text-[var(--color-content-default-brand-primary)]"
: "bg-[var(--color-surface-invert-brand-primary)] text-[var(--color-content-default-primary)]"; : "bg-[var(--color-surface-invert-brand-primary)] text-[var(--color-content-invert-primary)]";
// White 30% ring on small photos: no DS token (opacity scale is black-alpha). // White 30% ring on small photos: no DS token (opacity scale is black-alpha).
const smallImageBorder = const smallImageBorder =
size === "small" && showImage && loaded size === "small" && showImage && loaded
@@ -16,8 +16,8 @@ const SelectDropdown = forwardRef<HTMLDivElement, SelectDropdownProps>(
rounded-[var(--radius-400)] rounded-[var(--radius-400)]
shadow-lg shadow-lg
p-[4px] p-[4px]
w-full
min-w-[200px] min-w-[200px]
max-w-[300px]
${className} ${className}
` `
.trim() .trim()
@@ -2,6 +2,7 @@
import React, { import React, {
Children, Children,
type CSSProperties,
type ReactElement, type ReactElement,
type ReactNode, type ReactNode,
forwardRef, forwardRef,
@@ -12,11 +13,13 @@ import React, {
memo, memo,
useImperativeHandle, useImperativeHandle,
useEffect, useEffect,
useLayoutEffect,
useMemo,
} from "react"; } from "react";
import { useClickOutside } from "../../../hooks"; import { useClickOutside } from "../../../hooks";
import { useTranslation } from "../../../contexts/MessagesContext"; import { useTranslation } from "../../../contexts/MessagesContext";
import { SelectInputView } from "./SelectInput.view"; import { SelectInputView } from "./SelectInput.view";
import type { SelectInputProps } from "./SelectInput.types"; import type { SelectInputProps, SelectOptionData } from "./SelectInput.types";
/** /**
* Figma: "Control / SelectInput". Custom-styled select dropdown * Figma: "Control / SelectInput". Custom-styled select dropdown
@@ -70,11 +73,31 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
const generatedId = useId(); const generatedId = useId();
const selectId = id || `select-input-${generatedId}`; const selectId = id || `select-input-${generatedId}`;
const labelId = `${selectId}-label`; const labelId = `${selectId}-label`;
const listboxId = `${selectId}-listbox`;
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [selectedValue, setSelectedValue] = useState(value || ""); const [selectedValue, setSelectedValue] = useState(value || "");
const [highlightedIndex, setHighlightedIndex] = useState(0);
const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null);
const selectRef = useRef<HTMLButtonElement>(null); const selectRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null); const menuRef = useRef<HTMLDivElement>(null);
const optionItems = useMemo((): SelectOptionData[] => {
if (options && Array.isArray(options)) return options;
return Children.toArray(children).flatMap((child) => {
if (!React.isValidElement(child) || child.type !== "option") return [];
const optionProps = child.props as {
value: string;
children: ReactNode;
};
return [
{
value: optionProps.value,
label: String(optionProps.children),
},
];
});
}, [options, children]);
// Internal state management: track if focused and how (mouse vs keyboard) // Internal state management: track if focused and how (mouse vs keyboard)
const [isFocused, setIsFocused] = useState(false); const [isFocused, setIsFocused] = useState(false);
const [focusMethod, setFocusMethod] = useState<"mouse" | "keyboard" | null>( const [focusMethod, setFocusMethod] = useState<"mouse" | "keyboard" | null>(
@@ -99,14 +122,69 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
() => selectRef.current as HTMLButtonElement | null, () => selectRef.current as HTMLButtonElement | null,
); );
const closeMenu = useCallback(() => {
setIsOpen(false);
setMenuStyle(null);
}, []);
// Handle click outside to close menu // Handle click outside to close menu
useClickOutside([menuRef, selectRef], () => setIsOpen(false), isOpen); useClickOutside([menuRef, selectRef], closeMenu, isOpen);
const indexForValue = useCallback(
(current: string) => {
const index = optionItems.findIndex((option) => option.value === current);
return index >= 0 ? index : 0;
},
[optionItems],
);
const openMenu = useCallback(() => {
const trigger = selectRef.current?.getBoundingClientRect();
setMenuStyle({
top: (trigger?.bottom ?? 0) + 4,
left: trigger?.left ?? 0,
width: Math.max(trigger?.width ?? 0, 200),
});
setHighlightedIndex(indexForValue(selectedValue));
setIsOpen(true);
}, [indexForValue, selectedValue]);
useLayoutEffect(() => {
if (!isOpen) {
setMenuStyle(null);
return;
}
const update = () => {
const trigger = selectRef.current;
if (!trigger) return;
const rect = trigger.getBoundingClientRect();
const menuHeight = menuRef.current?.offsetHeight ?? optionItems.length * 44 + 8;
const gap = 4;
const openUp =
rect.bottom + gap + menuHeight > window.innerHeight &&
rect.top > menuHeight + gap;
setMenuStyle({
top: openUp
? Math.max(8, rect.top - menuHeight - gap)
: rect.bottom + gap,
left: rect.left,
width: Math.max(rect.width, 200),
});
};
update();
window.addEventListener("resize", update);
window.addEventListener("scroll", update, true);
return () => {
window.removeEventListener("resize", update);
window.removeEventListener("scroll", update, true);
};
}, [isOpen, optionItems.length, highlightedIndex]);
// Handle option selection // Handle option selection
const handleOptionSelect = useCallback( const handleOptionSelect = useCallback(
(optionValue: string, optionText: string) => { (optionValue: string, optionText: string) => {
setSelectedValue(optionValue); setSelectedValue(optionValue);
setIsOpen(false); closeMenu();
if (onChange) { if (onChange) {
onChange({ target: { value: optionValue, text: optionText } }); onChange({ target: { value: optionValue, text: optionText } });
} }
@@ -114,7 +192,7 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
selectRef.current.focus(); selectRef.current.focus();
} }
}, },
[onChange], [closeMenu, onChange],
); );
// Handle mouse down to detect mouse clicks // Handle mouse down to detect mouse clicks
@@ -126,24 +204,77 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
// Handle select button click // Handle select button click
const handleSelectClick = useCallback(() => { const handleSelectClick = useCallback(() => {
if (!disabled) { if (disabled) return;
setIsOpen(!isOpen); if (isOpen) {
closeMenu();
return;
} }
}, [disabled, isOpen]); openMenu();
}, [closeMenu, disabled, isOpen, openMenu]);
// Handle keyboard navigation // Handle keyboard navigation
const handleKeyDown = useCallback( const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => { (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (disabled) return; if (disabled) return;
if (e.key === "ArrowDown") {
e.preventDefault();
if (!isOpen) {
openMenu();
return;
}
setHighlightedIndex((index) =>
Math.min(index + 1, Math.max(optionItems.length - 1, 0)),
);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
if (!isOpen) {
openMenu();
return;
}
setHighlightedIndex((index) => Math.max(index - 1, 0));
return;
}
if (e.key === "Home" && isOpen) {
e.preventDefault();
setHighlightedIndex(0);
return;
}
if (e.key === "End" && isOpen) {
e.preventDefault();
setHighlightedIndex(Math.max(optionItems.length - 1, 0));
return;
}
if (e.key === "Enter" || e.key === " ") { if (e.key === "Enter" || e.key === " ") {
e.preventDefault(); e.preventDefault();
setIsOpen(!isOpen); if (!isOpen) {
} else if (e.key === "Escape") { openMenu();
setIsOpen(false); return;
}
const option = optionItems[highlightedIndex];
if (option) {
handleOptionSelect(option.value, option.label);
}
return;
}
if (e.key === "Escape") {
if (!isOpen) return;
e.preventDefault();
e.stopPropagation();
closeMenu();
} }
}, },
[disabled, isOpen], [
closeMenu,
disabled,
handleOptionSelect,
highlightedIndex,
isOpen,
openMenu,
optionItems,
],
); );
// Handle focus to detect mouse vs keyboard // Handle focus to detect mouse vs keyboard
@@ -159,14 +290,23 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
} }
}, [disabled, shouldAutoManageFocus]); }, [disabled, shouldAutoManageFocus]);
// Handle blur const handleMenuMouseDown = useCallback((event: React.MouseEvent) => {
const handleBlur = useCallback(() => { event.preventDefault();
if (shouldAutoManageFocus) { }, []);
setIsFocused(false);
setFocusMethod(null); const handleBlur = useCallback(
wasMouseDownRef.current = false; (event: React.FocusEvent<HTMLButtonElement>) => {
} if (shouldAutoManageFocus) {
}, [shouldAutoManageFocus]); setIsFocused(false);
setFocusMethod(null);
wasMouseDownRef.current = false;
}
const next = event.relatedTarget;
if (next instanceof Node && menuRef.current?.contains(next)) return;
closeMenu();
},
[closeMenu, shouldAutoManageFocus],
);
// Determine actual state: // Determine actual state:
// - Active: when clicked (mouse focus) or when dropdown is open // - Active: when clicked (mouse focus) or when dropdown is open
@@ -234,9 +374,13 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
onButtonMouseDown={handleMouseDown} onButtonMouseDown={handleMouseDown}
onButtonFocus={handleFocus} onButtonFocus={handleFocus}
onButtonBlur={handleBlur} onButtonBlur={handleBlur}
onMenuMouseDown={handleMenuMouseDown}
onOptionClick={handleOptionSelect} onOptionClick={handleOptionSelect}
selectRef={selectRef} selectRef={selectRef}
menuRef={menuRef} menuRef={menuRef}
listboxId={listboxId}
highlightedIndex={highlightedIndex}
menuStyle={menuStyle}
ariaLabelledby={shouldShowLabel ? labelId : undefined} ariaLabelledby={shouldShowLabel ? labelId : undefined}
ariaInvalid={error} ariaInvalid={error}
asterisk={asterisk} asterisk={asterisk}
@@ -1,4 +1,5 @@
import React, { Children, type ReactNode } from "react"; import React, { Children, type CSSProperties, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils"; import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
import SelectDropdown from "./SelectDropdown"; import SelectDropdown from "./SelectDropdown";
import SelectOption from "../SelectOption"; import SelectOption from "../SelectOption";
@@ -25,11 +26,15 @@ export interface SelectInputViewProps {
onButtonKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void; onButtonKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
onButtonMouseDown?: () => void; onButtonMouseDown?: () => void;
onButtonFocus?: () => void; onButtonFocus?: () => void;
onButtonBlur?: () => void; onButtonBlur?: (_event: React.FocusEvent<HTMLButtonElement>) => void;
onMenuMouseDown?: (_event: React.MouseEvent<HTMLDivElement>) => void;
onOptionClick: (_value: string, _text: string) => void; onOptionClick: (_value: string, _text: string) => void;
// Refs // Refs
selectRef: React.RefObject<HTMLButtonElement>; selectRef: React.RefObject<HTMLButtonElement>;
menuRef: React.RefObject<HTMLDivElement>; menuRef: React.RefObject<HTMLDivElement>;
listboxId: string;
highlightedIndex: number;
menuStyle: CSSProperties | null;
// Additional props // Additional props
ariaLabelledby?: string; ariaLabelledby?: string;
ariaInvalid?: boolean; ariaInvalid?: boolean;
@@ -63,9 +68,13 @@ export function SelectInputView({
onButtonMouseDown, onButtonMouseDown,
onButtonFocus, onButtonFocus,
onButtonBlur, onButtonBlur,
onMenuMouseDown,
onOptionClick, onOptionClick,
selectRef, selectRef,
menuRef, menuRef,
listboxId,
highlightedIndex,
menuStyle,
ariaLabelledby, ariaLabelledby,
ariaInvalid, ariaInvalid,
asterisk = false, asterisk = false,
@@ -132,6 +141,29 @@ export function SelectInputView({
const buttonClasses = getButtonClasses(); const buttonClasses = getButtonClasses();
const optionEntries: SelectOptionData[] =
options && Array.isArray(options)
? options
: Children.toArray(children).flatMap((child) => {
if (!React.isValidElement(child) || child.type !== "option") {
return [];
}
const optionProps = child.props as {
value: string;
children: ReactNode;
};
return [
{
value: optionProps.value,
label: String(optionProps.children),
},
];
});
const highlightedValue = optionEntries[highlightedIndex]?.value;
const activeOptionId =
highlightedValue != null ? `${listboxId}-option-${highlightedIndex}` : undefined;
// Text color based on filled state // Text color based on filled state
const textColorClass = isFilled const textColorClass = isFilled
? "text-[var(--color-content-default-primary)]" ? "text-[var(--color-content-default-primary)]"
@@ -183,6 +215,8 @@ export function SelectInputView({
aria-invalid={ariaInvalid} aria-invalid={ariaInvalid}
aria-expanded={isOpen} aria-expanded={isOpen}
aria-haspopup="listbox" aria-haspopup="listbox"
aria-controls={isOpen ? listboxId : undefined}
aria-activedescendant={isOpen ? activeOptionId : undefined}
onClick={onButtonClick} onClick={onButtonClick}
onKeyDown={onButtonKeyDown} onKeyDown={onButtonKeyDown}
onMouseDown={onButtonMouseDown} onMouseDown={onButtonMouseDown}
@@ -219,53 +253,32 @@ export function SelectInputView({
/> />
)} )}
{isOpen && ( {isOpen && menuStyle && typeof document !== "undefined"
<div ? createPortal(
ref={menuRef} <div
className="absolute top-full left-0 right-0 z-50 mt-1" ref={menuRef}
> className="fixed z-[10050]"
<SelectDropdown ariaLabel={selectAriaLabel}> style={menuStyle}
{options && Array.isArray(options) onMouseDown={onMenuMouseDown}
? options.map((option) => ( >
<SelectDropdown id={listboxId} ariaLabel={selectAriaLabel}>
{optionEntries.map((option, index) => (
<SelectOption <SelectOption
key={option.value} key={option.value}
id={`${listboxId}-option-${index}`}
selected={option.value === selectedValue} selected={option.value === selectedValue}
highlighted={index === highlightedIndex}
size="medium" size="medium"
onClick={() => onOptionClick(option.value, option.label)} onClick={() => onOptionClick(option.value, option.label)}
> >
{option.label} {option.label}
</SelectOption> </SelectOption>
)) ))}
: Children.map(children, (child) => { </SelectDropdown>
if ( </div>,
React.isValidElement(child) && document.body,
child.type === "option" )
) { : null}
const optionProps = child.props as {
value: string;
children: ReactNode;
};
return (
<SelectOption
key={optionProps.value}
selected={optionProps.value === selectedValue}
size="medium"
onClick={() =>
onOptionClick(
optionProps.value,
String(optionProps.children),
)
}
>
{optionProps.children}
</SelectOption>
);
}
return child;
})}
</SelectDropdown>
</div>
)}
</div> </div>
{textHint && ( {textHint && (
<div className="flex items-start relative shrink-0 w-full"> <div className="flex items-start relative shrink-0 w-full">
@@ -13,8 +13,10 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
{ {
children, children,
selected = false, selected = false,
highlighted = false,
disabled = false, disabled = false,
className = "", className = "",
id,
onClick, onClick,
size: sizeProp = "medium", size: sizeProp = "medium",
...props ...props
@@ -35,15 +37,17 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
} }
}; };
const active = selected || highlighted;
const itemClasses = ` const itemClasses = `
flex items-center justify-between flex items-center justify-between
px-[8px] py-[4px] min-h-11 px-[8px] py-2
md:min-h-0 md:py-[4px]
text-[var(--color-content-default-brand-primary)] text-[var(--color-content-default-brand-primary)]
${getTextSize()} ${getTextSize()}
cursor-pointer cursor-pointer
transition-colors duration-150 transition-colors duration-150
${ ${
selected active
? "bg-[var(--color-surface-default-secondary)] rounded-[var(--radius-300)]" ? "bg-[var(--color-surface-default-secondary)] rounded-[var(--radius-300)]"
: "" : ""
} }
@@ -85,6 +89,7 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
disabled={disabled} disabled={disabled}
className={className} className={className}
itemClasses={itemClasses} itemClasses={itemClasses}
optionId={id}
handleClick={handleClick} handleClick={handleClick}
handleKeyDown={handleKeyDown} handleKeyDown={handleKeyDown}
{...props} {...props}
@@ -3,8 +3,11 @@ export type SelectOptionSizeValue = "small" | "medium" | "large";
export interface SelectOptionProps { export interface SelectOptionProps {
children?: React.ReactNode; children?: React.ReactNode;
selected?: boolean; selected?: boolean;
/** Keyboard highlight in a listbox; distinct from the selected value. */
highlighted?: boolean;
disabled?: boolean; disabled?: boolean;
className?: string; className?: string;
id?: string;
onClick?: ( onClick?: (
_e: React.MouseEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>, _e: React.MouseEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>,
) => void; ) => void;
@@ -20,6 +23,7 @@ export interface SelectOptionViewProps {
disabled: boolean; disabled: boolean;
className: string; className: string;
itemClasses: string; itemClasses: string;
optionId?: string;
handleClick: (_e: React.MouseEvent<HTMLDivElement>) => void; handleClick: (_e: React.MouseEvent<HTMLDivElement>) => void;
handleKeyDown: (_e: React.KeyboardEvent<HTMLDivElement>) => void; handleKeyDown: (_e: React.KeyboardEvent<HTMLDivElement>) => void;
} }
@@ -11,6 +11,7 @@ export const SelectOptionView = forwardRef<
selected, selected,
disabled, disabled,
itemClasses, itemClasses,
optionId,
handleClick, handleClick,
handleKeyDown, handleKeyDown,
...props ...props
@@ -20,9 +21,10 @@ export const SelectOptionView = forwardRef<
return ( return (
<div <div
ref={ref} ref={ref}
id={optionId}
className={itemClasses} className={itemClasses}
role="option" role="option"
tabIndex={disabled ? -1 : 0} tabIndex={-1}
aria-selected={selected} aria-selected={selected}
aria-disabled={disabled} aria-disabled={disabled}
onClick={handleClick} onClick={handleClick}
@@ -16,6 +16,7 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
state: externalStateProp = "default", state: externalStateProp = "default",
inputSize: inputSizeProp = "medium", inputSize: inputSizeProp = "medium",
disabled = false, disabled = false,
readOnly = false,
error = false, error = false,
label, label,
placeholder, placeholder,
@@ -109,6 +110,16 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
}; };
} }
if (readOnly) {
return {
input:
"bg-[var(--color-surface-default-secondary)] text-[var(--color-content-default-primary)] border border-solid border-[var(--color-border-default-primary)] cursor-default",
label: "text-[var(--color-content-default-secondary)]",
inputWrapper: "relative",
focusRing: "",
};
}
if (error) { if (error) {
const filledStyles = isFilled const filledStyles = isFilled
? "font-medium leading-[20px]" ? "font-medium leading-[20px]"
@@ -231,6 +242,7 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
labelId={labelId} labelId={labelId}
state={actualState} state={actualState}
disabled={disabled} disabled={disabled}
readOnly={readOnly}
error={error} error={error}
label={label} label={label}
placeholder={placeholder} placeholder={placeholder}
@@ -16,6 +16,7 @@ export interface TextInputProps extends Omit<
*/ */
inputSize?: TextInputSizeValue; inputSize?: TextInputSizeValue;
disabled?: boolean; disabled?: boolean;
readOnly?: boolean;
error?: boolean; error?: boolean;
label?: string; label?: string;
placeholder?: string; placeholder?: string;
@@ -43,6 +44,7 @@ export interface TextInputViewProps {
labelId: string; labelId: string;
state: "default" | "active" | "hover" | "focus"; state: "default" | "active" | "hover" | "focus";
disabled: boolean; disabled: boolean;
readOnly: boolean;
error: boolean; error: boolean;
label?: string; label?: string;
placeholder?: string; placeholder?: string;
@@ -13,6 +13,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
name, name,
type, type,
disabled, disabled,
readOnly = false,
error = false, error = false,
className: _className, className: _className,
containerClasses, containerClasses,
@@ -90,6 +91,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
onKeyDown={onKeyDown} onKeyDown={onKeyDown}
onMouseDown={handleMouseDown} onMouseDown={handleMouseDown}
disabled={disabled} disabled={disabled}
readOnly={readOnly}
maxLength={maxLength} maxLength={maxLength}
autoComplete={autoComplete} autoComplete={autoComplete}
inputMode={inputMode} inputMode={inputMode}
@@ -245,9 +245,25 @@ const ShareContainer = memo<ShareProps>((props) => {
const handleCopyLink = useCallback(async () => { const handleCopyLink = useCallback(async () => {
if (!settings) return; if (!settings) return;
const text = settings.shareUrl;
try { try {
await navigator.clipboard.writeText(settings.shareUrl); await navigator.clipboard.writeText(text);
setLinkCopied(true); setLinkCopied(true);
return;
} catch {
// Some browsers deny clipboard without a secure context; fall back.
}
try {
const field = document.createElement("textarea");
field.value = text;
field.setAttribute("readonly", "");
field.style.position = "fixed";
field.style.left = "-9999px";
document.body.appendChild(field);
field.select();
const copied = document.execCommand("copy");
field.remove();
setLinkCopied(copied);
} catch { } catch {
setLinkCopied(false); setLinkCopied(false);
} }
+14 -9
View File
@@ -41,7 +41,7 @@ function PersonRow(props: {
roleLabel: string; roleLabel: string;
}) { }) {
return ( return (
<div className="flex w-full items-center gap-3 overflow-hidden"> <div className="flex w-full shrink-0 items-center gap-3 overflow-hidden">
<Avatar <Avatar
alt="" alt=""
initials={props.initials} initials={props.initials}
@@ -142,7 +142,8 @@ export const ShareView = memo(function ShareView({
/> />
</div> </div>
<div className="flex min-h-0 flex-1 flex-col gap-5 overflow-x-clip overflow-y-auto px-6 pb-6 pt-6"> <div className="scrollbar-design min-h-0 flex-1 overflow-x-clip overflow-y-auto">
<div className="flex flex-col gap-5 px-6 pb-6 pt-6">
<div className="flex w-full items-center gap-2"> <div className="flex w-full items-center gap-2">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<TextInput <TextInput
@@ -170,7 +171,7 @@ export const ShareView = memo(function ShareView({
buttonType="outline" buttonType="outline"
palette="default" palette="default"
size="small" size="small"
disabled={inviteBusy || inviteValue.trim().length === 0} disabled={inviteBusy}
onClick={onInvite} onClick={onInvite}
> >
{copy.invite} {copy.invite}
@@ -182,7 +183,7 @@ export const ShareView = memo(function ShareView({
</p> </p>
) : null} ) : null}
<div className="flex w-full flex-col items-start gap-3 overflow-hidden"> <div className="flex w-full shrink-0 flex-col items-start gap-3">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]"> <p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.peopleWithAccess} {copy.peopleWithAccess}
</p> </p>
@@ -206,7 +207,7 @@ export const ShareView = memo(function ShareView({
) : null} ) : null}
</div> </div>
<div className="flex w-full flex-col items-start gap-2 overflow-hidden"> <div className="flex w-full flex-col items-start gap-2 overflow-visible">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]"> <p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.whoCanRead} {copy.whoCanRead}
</p> </p>
@@ -252,7 +253,7 @@ export const ShareView = memo(function ShareView({
showHelpIcon={false} showHelpIcon={false}
label={copy.anyoneWithLink} label={copy.anyoneWithLink}
value={shareUrlDisplay} value={shareUrlDisplay}
disabled readOnly
textHint={copy.linkHint} textHint={copy.linkHint}
/> />
<Button <Button
@@ -303,7 +304,11 @@ export const ShareView = memo(function ShareView({
</div> </div>
) : null} ) : null}
{linkCopied ? ( </div>
</div>
{linkCopied ? (
<div className="shrink-0 px-6 pb-2">
<Alert <Alert
type="toast" type="toast"
status="positive" status="positive"
@@ -314,8 +319,8 @@ export const ShareView = memo(function ShareView({
hasTrailingIcon={false} hasTrailingIcon={false}
className="w-full" className="w-full"
/> />
) : null} </div>
</div> ) : null}
<div className="flex shrink-0 items-center justify-between border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4"> <div className="flex shrink-0 items-center justify-between border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4">
<Button <Button
+22 -1
View File
@@ -8,6 +8,7 @@ import {
} from "../publishedRuleAccess"; } from "../publishedRuleAccess";
import { prisma } from "./db"; import { prisma } from "./db";
import { isDatabaseConfigured } from "./env"; import { isDatabaseConfigured } from "./env";
import { rateLimitCoolingDown, rateLimitKey } from "./rateLimit";
import { browserHoldsClaimForHash } from "./guestRuleClaim"; import { browserHoldsClaimForHash } from "./guestRuleClaim";
import { isRuleAdminEmail } from "./ruleAdmins"; import { isRuleAdminEmail } from "./ruleAdmins";
import { logAdminRuleRead } from "./adminRuleReadLog"; import { logAdminRuleRead } from "./adminRuleReadLog";
@@ -140,17 +141,31 @@ async function resolveAccessForRow(opts: {
* invalidates it. Returns `null` for missing rows, denied readers, and DB * invalidates it. Returns `null` for missing rows, denied readers, and DB
* failures — callers render the same 404 as a missing Rule. * failures — callers render the same 404 as a missing Rule.
*/ */
export const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
export async function getReadablePublishedRule(opts: { export async function getReadablePublishedRule(opts: {
idOrSlug: string; idOrSlug: string;
user: User | null; user: User | null;
viaShareSlug: boolean; viaShareSlug: boolean;
requestPath: string; requestPath: string;
lookup?: "id" | "shareSlug"; lookup?: "id" | "shareSlug";
/** Client IP (or similar) used to slow failed `/r/{slug}` guesses. */
failedLookupKey?: string;
}): Promise<ReadablePublishedRule | null> { }): Promise<ReadablePublishedRule | null> {
if (!isDatabaseConfigured()) return null; if (!isDatabaseConfigured()) return null;
const idOrSlug = opts.idOrSlug.trim(); const idOrSlug = opts.idOrSlug.trim();
if (idOrSlug.length === 0) return null; if (idOrSlug.length === 0) return null;
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id"); const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
const missKey =
lookup === "shareSlug" && opts.failedLookupKey
? `share-lookup-miss:${opts.failedLookupKey}`
: null;
if (
missKey &&
rateLimitCoolingDown(missKey, SHARE_LOOKUP_MISS_INTERVAL_MS)
) {
return null;
}
try { try {
const row = const row =
lookup === "shareSlug" lookup === "shareSlug"
@@ -162,7 +177,13 @@ export async function getReadablePublishedRule(opts: {
where: { id: idOrSlug }, where: { id: idOrSlug },
select: RULE_ACCESS_SELECT, select: RULE_ACCESS_SELECT,
}); });
if (!row) return null; if (!row) {
if (missKey) {
const limited = rateLimitKey(missKey, SHARE_LOOKUP_MISS_INTERVAL_MS);
if (!limited.ok) return null;
}
return null;
}
return resolveAccessForRow({ return resolveAccessForRow({
row, row,
viaShareSlug: opts.viaShareSlug, viaShareSlug: opts.viaShareSlug,
+9
View File
@@ -18,3 +18,12 @@ export function rateLimitKey(
windows.set(key, now); windows.set(key, now);
return { ok: true }; return { ok: true };
} }
/** True when `key` is still inside the interval started by the last allowed call. */
export function rateLimitCoolingDown(
key: string,
minIntervalMs: number,
): boolean {
const last = windows.get(key) ?? 0;
return Date.now() - last < minIntervalMs;
}
+42 -6
View File
@@ -1,19 +1,55 @@
import { createHmac, timingSafeEqual } from "crypto"; import { createHmac, timingSafeEqual } from "crypto";
export function ruleExportToken(ruleId: string, pepper: string): string { /** How long a mailed export link stays valid after it is issued. */
export const RULE_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
function signExportMac(
ruleId: string,
version: number,
exp: number,
pepper: string,
): string {
return createHmac("sha256", pepper) return createHmac("sha256", pepper)
.update(`rule-export:${ruleId}`) .update(`rule-export:${ruleId}:${version}:${exp}`)
.digest("base64url"); .digest("base64url");
} }
function timingSafeStringEqual(left: string, right: string): boolean {
const expected = Buffer.from(left);
const actual = Buffer.from(right);
if (expected.length !== actual.length) return false;
return timingSafeEqual(expected, actual);
}
export function ruleExportToken(
ruleId: string,
pepper: string,
version: number,
now = new Date(),
): string {
const exp = Math.floor((now.getTime() + RULE_EXPORT_TOKEN_TTL_MS) / 1000);
const mac = signExportMac(ruleId, version, exp, pepper);
return `${exp}.${version}.${mac}`;
}
export function ruleExportTokenMatches( export function ruleExportTokenMatches(
ruleId: string, ruleId: string,
token: string, token: string,
pepper: string, pepper: string,
version: number,
now = new Date(),
): boolean { ): boolean {
if (token.length === 0) return false; if (token.length === 0) return false;
const expected = Buffer.from(ruleExportToken(ruleId, pepper)); const parts = token.split(".");
const actual = Buffer.from(token); if (parts.length !== 3) return false;
if (expected.length !== actual.length) return false; const exp = Number(parts[0]);
return timingSafeEqual(expected, actual); const tokenVersion = Number(parts[1]);
const mac = parts[2] ?? "";
if (!Number.isFinite(exp) || !Number.isInteger(tokenVersion) || mac.length === 0) {
return false;
}
if (tokenVersion !== version) return false;
if (exp * 1000 <= now.getTime()) return false;
const expected = signExportMac(ruleId, version, exp, pepper);
return timingSafeStringEqual(expected, mac);
} }
+2 -1
View File
@@ -46,6 +46,7 @@ export async function sendDueRuleFollowUpEmails(
select: { select: {
id: true, id: true,
title: true, title: true,
exportTokenVersion: true,
user: { select: { email: true } }, user: { select: { email: true } },
}, },
}); });
@@ -66,7 +67,7 @@ export async function sendDueRuleFollowUpEmails(
continue; continue;
} }
const token = ruleExportToken(row.id, pepper); const token = ruleExportToken(row.id, pepper, row.exportTokenVersion);
try { try {
await sendRuleFollowUpEmail({ await sendRuleFollowUpEmail({
to: email, to: email,
+7
View File
@@ -147,11 +147,18 @@ export async function patchOwnedRuleShare(opts: {
shareSlug = await allocateShareSlug(); shareSlug = await allocateShareSlug();
} }
const turningLinkOff =
opts.visibility === RULE_VISIBILITY.private &&
row.visibility !== RULE_VISIBILITY.private;
await prisma.publishedRule.update({ await prisma.publishedRule.update({
where: { id: row.id }, where: { id: row.id },
data: { data: {
visibility: opts.visibility, visibility: opts.visibility,
shareSlug, shareSlug,
...(turningLinkOff
? { exportTokenVersion: { increment: 1 } }
: {}),
}, },
}); });
+44
View File
@@ -24,9 +24,41 @@ const svgrLoaderOptions = {
}, },
}; };
function umamiOrigin() {
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
if (!src) return "";
try {
return new URL(src).origin;
} catch {
return "";
}
}
function contentSecurityPolicy() {
const umami = umamiOrigin();
const scriptSrc = umami
? `'self' 'unsafe-inline' ${umami}`
: `'self' 'unsafe-inline'`;
const connectSrc = umami ? `'self' ${umami}` : `'self'`;
return [
"default-src 'self'",
`script-src ${scriptSrc}`,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob:",
"font-src 'self'",
`connect-src ${connectSrc}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"upgrade-insecure-requests",
].join("; ");
}
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
output: "standalone", output: "standalone",
poweredByHeader: false,
serverExternalPackages: ["@prisma/client"], serverExternalPackages: ["@prisma/client"],
// React Compiler — annotation mode: opt-in via the `"use memo"` directive at // React Compiler — annotation mode: opt-in via the `"use memo"` directive at
// the top of a component/hook. With no annotations in the codebase yet, this // the top of a component/hook. With no annotations in the codebase yet, this
@@ -102,6 +134,18 @@ const nextConfig = {
key: "X-XSS-Protection", key: "X-XSS-Protection",
value: "1; mode=block", value: "1; mode=block",
}, },
{
key: "Referrer-Policy",
value: "same-origin",
},
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=()",
},
{
key: "Content-Security-Policy",
value: contentSecurityPolicy(),
},
], ],
}, },
{ {
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "PublishedRule" ADD COLUMN "exportTokenVersion" INTEGER NOT NULL DEFAULT 0;
+3
View File
@@ -101,6 +101,9 @@ model PublishedRule {
/// Set when the 48-hour print follow-up has been sent, or when a Rule /// Set when the 48-hour print follow-up has been sent, or when a Rule
/// finished more than seven days before this mail existed and will not be sent. /// finished more than seven days before this mail existed and will not be sent.
followUpEmailSentAt DateTime? followUpEmailSentAt DateTime?
/// Bumped when a share link is turned off or a reader is removed so mailed
/// export links stop working.
exportTokenVersion Int @default(0)
stakeholders RuleStakeholder[] stakeholders RuleStakeholder[]
uploads Upload[] uploads Upload[]
+9
View File
@@ -117,6 +117,15 @@ describe("Avatar (behavioral tests)", () => {
); );
}); });
it("paints filled initials in invert ink on the yellow field", () => {
render(
<Avatar alt="Ada Lovelace" initials="N" variant="filled" />,
);
expect(screen.getByText("N")).toHaveClass(
"text-[var(--color-content-invert-primary)]",
);
});
it("renders a button with hover treatment when onClick is set", () => { it("renders a button with hover treatment when onClick is set", () => {
const onClick = vi.fn(); const onClick = vi.fn();
render( render(
+109
View File
@@ -1,6 +1,10 @@
import "@testing-library/jest-dom/vitest";
import React from "react"; import React from "react";
import { describe, expect, it, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import SelectInput from "../../app/components/controls/SelectInput"; import SelectInput from "../../app/components/controls/SelectInput";
import { componentTestSuite } from "../utils/componentTestSuite"; import { componentTestSuite } from "../utils/componentTestSuite";
import { renderWithProviders, screen } from "../utils/test-utils";
type SelectInputProps = React.ComponentProps<typeof SelectInput>; type SelectInputProps = React.ComponentProps<typeof SelectInput>;
@@ -31,3 +35,108 @@ componentTestSuite<SelectInputProps>({
errorProps: { error: true }, errorProps: { error: true },
}, },
}); });
describe("SelectInput listbox keyboard", () => {
it("moves between options with arrows and picks with Enter", async () => {
const onChange = vi.fn();
const user = userEvent.setup();
renderWithProviders(
<SelectInput
labelText="Who can read"
showLabel
value="option1"
onChange={onChange}
options={[
{ value: "option1", label: "Option 1" },
{ value: "option2", label: "Option 2" },
]}
/>,
);
const trigger = screen.getByRole("button", { name: /Who can read/i });
trigger.focus();
await user.keyboard("{ArrowDown}");
expect(await screen.findByRole("option", { name: "Option 1" })).toBeVisible();
expect(screen.getByRole("option", { name: "Option 2" })).toBeVisible();
await user.keyboard("{ArrowDown}{Enter}");
expect(onChange).toHaveBeenCalledWith({
target: { value: "option2", text: "Option 2" },
});
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
});
it("closes the listbox when focus leaves the trigger", async () => {
const user = userEvent.setup();
renderWithProviders(
<>
<SelectInput
labelText="Who can read"
showLabel
value="option1"
options={[
{ value: "option1", label: "Option 1" },
{ value: "option2", label: "Option 2" },
]}
/>
<button type="button">Next</button>
</>,
);
const trigger = screen.getByRole("button", { name: /Who can read/i });
await user.click(trigger);
expect(await screen.findByRole("listbox")).toBeVisible();
await user.click(screen.getByRole("button", { name: "Next" }));
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
});
it("Escape closes the listbox and does not reach document listeners", async () => {
const user = userEvent.setup();
const onDocumentKeyDown = vi.fn();
document.addEventListener("keydown", onDocumentKeyDown);
renderWithProviders(
<SelectInput
labelText="Who can read"
showLabel
value="option1"
options={[
{ value: "option1", label: "Option 1" },
{ value: "option2", label: "Option 2" },
]}
/>,
);
const trigger = screen.getByRole("button", { name: /Who can read/i });
trigger.focus();
await user.keyboard("{ArrowDown}");
expect(await screen.findByRole("listbox")).toBeVisible();
onDocumentKeyDown.mockClear();
await user.keyboard("{Escape}");
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
expect(onDocumentKeyDown).not.toHaveBeenCalled();
document.removeEventListener("keydown", onDocumentKeyDown);
});
it("selects an option that is clicked", async () => {
const onChange = vi.fn();
const user = userEvent.setup();
renderWithProviders(
<SelectInput
labelText="Who can read"
showLabel
value="option1"
onChange={onChange}
options={[
{ value: "option1", label: "Option 1" },
{ value: "option2", label: "Option 2" },
]}
/>,
);
await user.click(screen.getByRole("button", { name: /Who can read/i }));
await user.click(await screen.findByRole("option", { name: "Option 2" }));
expect(onChange).toHaveBeenCalledWith({
target: { value: "option2", text: "Option 2" },
});
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
});
});
+15
View File
@@ -81,4 +81,19 @@ describe("TextInput (size tests)", () => {
expect(input).toBeRequired(); expect(input).toBeRequired();
expect(input).toHaveAttribute("form", "create-flow-community-save"); expect(input).toHaveAttribute("form", "create-flow-community-save");
}); });
it("keeps read-only values at full contrast", () => {
const { container } = render(
<TextInput
label="Share link"
value="communityrule.info/r/k7f2-9qxm"
readOnly
/>,
);
const input = container.querySelector("input");
expect(input).toHaveAttribute("readonly");
expect(input).not.toBeDisabled();
expect(input).toHaveClass("text-[var(--color-content-default-primary)]");
expect(container.querySelector(".opacity-40")).not.toBeInTheDocument();
});
}); });
+49 -3
View File
@@ -86,11 +86,33 @@ describe("Share modal", () => {
).toBeInTheDocument(); ).toBeInTheDocument();
expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument(); expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument();
expect(screen.getByText("You")).toBeInTheDocument(); expect(screen.getByText("You")).toBeInTheDocument();
const people = screen.getByText("People with access").parentElement;
expect(people).not.toHaveClass("overflow-hidden");
expect(people?.parentElement?.parentElement).toHaveClass("scrollbar-design");
expect(screen.getByText("N")).toBeInTheDocument();
expect(screen.getByText("R")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Invite" })).toBeEnabled();
expect(screen.getByText("rosa@example.org")).toBeInTheDocument(); expect(screen.getByText("rosa@example.org")).toBeInTheDocument();
expect(screen.getByText("Five more people can read it")).toBeInTheDocument(); expect(screen.getByText("Five more people can read it")).toBeInTheDocument();
expect(screen.getByText("Only people you invite can open it.")).toBeInTheDocument(); expect(screen.getByText("Only people you invite can open it.")).toBeInTheDocument();
}); });
it("confirms a copy when the clipboard API is denied", async () => {
writeText.mockRejectedValueOnce(new Error("denied"));
const exec = vi.fn().mockReturnValue(true);
Object.defineProperty(document, "execCommand", {
configurable: true,
value: exec,
});
openShare();
fireEvent.click(screen.getByRole("button", { name: /Copy link/i }));
await waitFor(() => {
expect(screen.getByText("Link copied")).toBeInTheDocument();
});
expect(screen.getByRole("button", { name: /Copied/i })).toBeInTheDocument();
expect(exec).toHaveBeenCalledWith("copy");
});
it("copies the private Rule URL", async () => { it("copies the private Rule URL", async () => {
openShare(); openShare();
fireEvent.click(screen.getByRole("button", { name: /Copy link/i })); fireEvent.click(screen.getByRole("button", { name: /Copy link/i }));
@@ -141,9 +163,11 @@ describe("Share modal", () => {
}), }),
); );
await user.click(screen.getByRole("button", { name: "Turn on link" })); await user.click(screen.getByRole("button", { name: "Turn on link" }));
expect( const linkField = screen.getByDisplayValue(
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"), "communityrule.info/r/k7f2-9qxm",
).toBeInTheDocument(); );
expect(linkField).toHaveAttribute("readonly");
expect(linkField).not.toBeDisabled();
expect( expect(
screen.getByRole("button", { name: "Turn off link" }), screen.getByRole("button", { name: "Turn off link" }),
).toBeInTheDocument(); ).toBeInTheDocument();
@@ -201,6 +225,28 @@ describe("Share modal", () => {
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("shows both access options and picks one with arrow keys", async () => {
const user = userEvent.setup();
openShare();
const trigger = screen.getByRole("button", {
name: /Only people you invite/i,
});
trigger.focus();
await user.keyboard("{ArrowDown}");
const inviteOnly = await screen.findByRole("option", {
name: "Only people you invite",
});
const anyone = screen.getByRole("option", { name: "Anyone with the link" });
expect(inviteOnly).toBeVisible();
expect(anyone).toBeVisible();
await user.keyboard("{ArrowDown}{Enter}");
expect(
screen.getByText(
"Anyone with the link can read it without logging in and pass it on. Check with your community first.",
),
).toBeInTheDocument();
});
it("calls onClose when Done is clicked", async () => { it("calls onClose when Done is clicked", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onClose = vi.fn(); const onClose = vi.fn();
+68
View File
@@ -0,0 +1,68 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const getReadablePublishedRuleMock = vi.fn();
const getSessionUserMock = vi.fn();
const rateLimitKeyMock = vi.fn();
const notFoundMock = vi.fn(() => {
throw new Error("NEXT_NOT_FOUND");
});
vi.mock("next/navigation", () => ({
notFound: () => notFoundMock(),
}));
vi.mock("next/headers", () => ({
headers: async () =>
new Headers({ "x-forwarded-for": "203.0.113.8" }),
}));
vi.mock("../../lib/server/rateLimit", () => ({
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
}));
vi.mock("../../lib/server/publishedRules", () => ({
SHARE_LOOKUP_MISS_INTERVAL_MS: 1_000,
getReadablePublishedRule: (...args: unknown[]) =>
getReadablePublishedRuleMock(...args),
}));
vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(),
}));
import { generateMetadata } from "../../app/(marketing)/r/[shareSlug]/page";
describe("shared Rule page", () => {
beforeEach(() => {
getReadablePublishedRuleMock.mockReset();
getSessionUserMock.mockReset();
rateLimitKeyMock.mockReset();
rateLimitKeyMock.mockReturnValue({ ok: true });
notFoundMock.mockClear();
getSessionUserMock.mockResolvedValue(null);
});
it("returns 404 when the share link is off or unknown", async () => {
getReadablePublishedRuleMock.mockResolvedValue(null);
await expect(
generateMetadata({
params: Promise.resolve({ shareSlug: "k7f2-9qxm" }),
}),
).rejects.toThrow("NEXT_NOT_FOUND");
expect(notFoundMock).toHaveBeenCalled();
});
it("does not look up a malformed slug when the miss limit refuses", async () => {
rateLimitKeyMock.mockReturnValue({ ok: false, retryAfterMs: 1_000 });
await expect(
generateMetadata({
params: Promise.resolve({ shareSlug: "not-a-slug" }),
}),
).rejects.toThrow("NEXT_NOT_FOUND");
expect(rateLimitKeyMock).toHaveBeenCalledWith(
"share-lookup-miss:203.0.113.8",
1_000,
);
expect(getReadablePublishedRuleMock).not.toHaveBeenCalled();
});
});
+62
View File
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const isDatabaseConfiguredMock = vi.fn(); const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn(); const findUniqueMock = vi.fn();
const rateLimitKeyMock = vi.fn();
const rateLimitCoolingDownMock = vi.fn();
const findManyMock = vi.fn(); const findManyMock = vi.fn();
const stakeholderFindManyMock = vi.fn(); const stakeholderFindManyMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn(); const browserHoldsClaimForHashMock = vi.fn();
@@ -12,6 +14,12 @@ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(), isDatabaseConfigured: () => isDatabaseConfiguredMock(),
})); }));
vi.mock("../../lib/server/rateLimit", () => ({
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
rateLimitCoolingDown: (...args: unknown[]) =>
rateLimitCoolingDownMock(...args),
}));
vi.mock("../../lib/server/db", () => ({ vi.mock("../../lib/server/db", () => ({
prisma: { prisma: {
publishedRule: { publishedRule: {
@@ -71,9 +79,13 @@ beforeEach(() => {
browserHoldsClaimForHashMock.mockReset(); browserHoldsClaimForHashMock.mockReset();
isRuleAdminEmailMock.mockReset(); isRuleAdminEmailMock.mockReset();
logAdminRuleReadMock.mockReset(); logAdminRuleReadMock.mockReset();
rateLimitKeyMock.mockReset();
rateLimitCoolingDownMock.mockReset();
browserHoldsClaimForHashMock.mockResolvedValue(false); browserHoldsClaimForHashMock.mockResolvedValue(false);
isRuleAdminEmailMock.mockReturnValue(false); isRuleAdminEmailMock.mockReturnValue(false);
logAdminRuleReadMock.mockResolvedValue(undefined); logAdminRuleReadMock.mockResolvedValue(undefined);
rateLimitKeyMock.mockReturnValue({ ok: true });
rateLimitCoolingDownMock.mockReturnValue(false);
}); });
describe("getReadablePublishedRule", () => { describe("getReadablePublishedRule", () => {
@@ -220,6 +232,56 @@ describe("getReadablePublishedRule", () => {
}), }),
); );
}); });
it("rate limits failed share-slug lookups", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(null);
expect(
await getReadablePublishedRule({
idOrSlug: "k7f2-9qxm",
user: null,
viaShareSlug: true,
requestPath: "/r/k7f2-9qxm",
failedLookupKey: "203.0.113.8",
}),
).toBeNull();
expect(rateLimitKeyMock).toHaveBeenCalledWith(
"share-lookup-miss:203.0.113.8",
1_000,
);
});
it("does not query when a share-slug miss is still cooling down", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
rateLimitCoolingDownMock.mockReturnValue(true);
expect(
await getReadablePublishedRule({
idOrSlug: "k7f2-9qxm",
user: null,
viaShareSlug: true,
requestPath: "/r/k7f2-9qxm",
failedLookupKey: "203.0.113.8",
}),
).toBeNull();
expect(findUniqueMock).not.toHaveBeenCalled();
expect(rateLimitKeyMock).not.toHaveBeenCalled();
});
it("returns null when the miss limit refuses after a lookup", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(null);
rateLimitKeyMock.mockReturnValue({ ok: false, retryAfterMs: 400 });
expect(
await getReadablePublishedRule({
idOrSlug: "k7f2-9qxm",
user: null,
viaShareSlug: true,
requestPath: "/r/k7f2-9qxm",
failedLookupKey: "203.0.113.8",
}),
).toBeNull();
expect(findUniqueMock).toHaveBeenCalledTimes(1);
});
}); });
describe("listListedPublishedRules", () => { describe("listListedPublishedRules", () => {
+21 -7
View File
@@ -1,16 +1,30 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
RULE_EXPORT_TOKEN_TTL_MS,
ruleExportToken, ruleExportToken,
ruleExportTokenMatches, ruleExportTokenMatches,
} from "../../lib/server/ruleExportToken"; } from "../../lib/server/ruleExportToken";
describe("ruleExportToken", () => { describe("ruleExportToken", () => {
it("accepts the matching token and rejects another rule or token", () => { const pepper = "test-pepper-16chars";
const pepper = "test-pepper-16chars"; const now = new Date("2026-11-21T12:00:00.000Z");
const token = ruleExportToken("rule-1", pepper);
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true); it("accepts the matching token and rejects another rule, version, or token", () => {
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false); const token = ruleExportToken("rule-1", pepper, 0, now);
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false); expect(ruleExportTokenMatches("rule-1", token, pepper, 0, now)).toBe(true);
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false); expect(ruleExportTokenMatches("rule-2", token, pepper, 0, now)).toBe(false);
expect(ruleExportTokenMatches("rule-1", token, pepper, 1, now)).toBe(false);
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper, 0, now)).toBe(
false,
);
expect(ruleExportTokenMatches("rule-1", "", pepper, 0, now)).toBe(false);
});
it("rejects a token after it expires", () => {
const token = ruleExportToken("rule-1", pepper, 0, now);
const afterExpiry = new Date(now.getTime() + RULE_EXPORT_TOKEN_TTL_MS + 1);
expect(
ruleExportTokenMatches("rule-1", token, pepper, 0, afterExpiry),
).toBe(false);
}); });
}); });
+4 -1
View File
@@ -49,6 +49,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{ {
id: "rule-1", id: "rule-1",
title: "Garden Norms", title: "Garden Norms",
exportTokenVersion: 0,
user: { email: "pen@example.com" }, user: { email: "pen@example.com" },
}, },
]); ]);
@@ -85,7 +86,7 @@ describe("sendDueRuleFollowUpEmails", () => {
it("skips rows with no mailbox and does not mark them sent", async () => { it("skips rows with no mailbox and does not mark them sent", async () => {
findManyMock.mockResolvedValueOnce([ findManyMock.mockResolvedValueOnce([
{ id: "rule-2", title: "Guest", user: { email: "" } }, { id: "rule-2", title: "Guest", exportTokenVersion: 0, user: { email: "" } },
]); ]);
const result = await sendDueRuleFollowUpEmails(db as never); const result = await sendDueRuleFollowUpEmails(db as never);
expect(result.skipped).toBe(1); expect(result.skipped).toBe(1);
@@ -98,6 +99,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{ {
id: "rule-4", id: "rule-4",
title: "Race", title: "Race",
exportTokenVersion: 0,
user: { email: "pen@example.com" }, user: { email: "pen@example.com" },
}, },
]); ]);
@@ -112,6 +114,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{ {
id: "rule-3", id: "rule-3",
title: "Retry", title: "Retry",
exportTokenVersion: 0,
user: { email: "pen@example.com" }, user: { email: "pen@example.com" },
}, },
]); ]);
+1
View File
@@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => {
data: { data: {
visibility: RULE_VISIBILITY.private, visibility: RULE_VISIBILITY.private,
shareSlug: null, shareSlug: null,
exportTokenVersion: { increment: 1 },
}, },
}), }),
); );
+17 -1
View File
@@ -52,6 +52,7 @@ function row() {
}, },
createdAt: new Date("2026-11-08T00:00:00.000Z"), createdAt: new Date("2026-11-08T00:00:00.000Z"),
userId: "user-1", userId: "user-1",
exportTokenVersion: 0,
}; };
} }
@@ -86,7 +87,7 @@ describe("GET /api/rules/[id]/export/[format]", () => {
}); });
it("returns a PDF attachment when the export token matches", async () => { it("returns a PDF attachment when the export token matches", async () => {
const token = ruleExportToken("rule-1", PEPPER); const token = ruleExportToken("rule-1", PEPPER, 0);
const res = await GET( const res = await GET(
new NextRequest( new NextRequest(
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`, `https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
@@ -117,4 +118,19 @@ describe("GET /api/rules/[id]/export/[format]", () => {
expect(text).toContain("# Garden Norms"); expect(text).toContain("# Garden Norms");
expect(text).toContain("## Shared terms"); expect(text).toContain("## Shared terms");
}); });
it("rejects a mailed token after the share link is turned off", async () => {
const token = ruleExportToken("rule-1", PEPPER, 0);
findUniqueMock.mockResolvedValueOnce({
...row(),
exportTokenVersion: 1,
});
const res = await GET(
new NextRequest(
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
),
makeContext("rule-1", "pdf"),
);
expect(res.status).toBe(401);
});
}); });
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
const findFirstRuleMock = vi.fn(); const findFirstRuleMock = vi.fn();
const publishedRuleUpdateMock = vi.fn();
const findFirstStakeholderMock = vi.fn(); const findFirstStakeholderMock = vi.fn();
const countMock = vi.fn(); const countMock = vi.fn();
const deleteMock = vi.fn(); const deleteMock = vi.fn();
@@ -20,6 +21,7 @@ vi.mock("../../lib/server/db", () => ({
prisma: { prisma: {
publishedRule: { publishedRule: {
findFirst: (...args: unknown[]) => findFirstRuleMock(...args), findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
update: (...args: unknown[]) => publishedRuleUpdateMock(...args),
}, },
ruleStakeholder: { ruleStakeholder: {
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args), findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
@@ -67,6 +69,7 @@ const memberCtx = {
beforeEach(() => { beforeEach(() => {
findFirstRuleMock.mockReset(); findFirstRuleMock.mockReset();
publishedRuleUpdateMock.mockReset();
findFirstStakeholderMock.mockReset(); findFirstStakeholderMock.mockReset();
countMock.mockReset(); countMock.mockReset();
deleteMock.mockReset(); deleteMock.mockReset();
@@ -177,6 +180,10 @@ describe("DELETE /api/rules/[id]/stakeholders/[stakeholderId]", () => {
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true }); expect(await res.json()).toEqual({ ok: true });
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } }); expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
expect(publishedRuleUpdateMock).toHaveBeenCalledWith({
where: { id: "rule-1" },
data: { exportTokenVersion: { increment: 1 } },
});
}); });
}); });
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import nextConfig from "../../next.config.mjs";
describe("security headers", () => {
it("drops X-Powered-By and sends a same-origin CSP", async () => {
expect(nextConfig.poweredByHeader).toBe(false);
const rows = await nextConfig.headers();
const globalHeaders = rows.find((row) => row.source === "/(.*)")?.headers;
expect(globalHeaders).toBeDefined();
const byKey = Object.fromEntries(
(globalHeaders ?? []).map((header) => [header.key, header.value]),
);
expect(byKey["Content-Security-Policy"]).toContain("default-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("script-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("style-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("font-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("img-src 'self'");
expect(byKey["Permissions-Policy"]).toBe(
"camera=(), microphone=(), geolocation=()",
);
expect(byKey["Referrer-Policy"]).toBe("same-origin");
});
});