Fix Share access, initials, copy confirm, and mailed export links #112
No files matched your search
@@ -1,8 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { notFound } from "next/navigation";
|
||||
import messages from "../../../../messages/en/index";
|
||||
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 { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
||||
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
|
||||
@@ -13,14 +18,32 @@ interface PageProps {
|
||||
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) {
|
||||
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();
|
||||
return getReadablePublishedRule({
|
||||
idOrSlug: shareSlug,
|
||||
user,
|
||||
viaShareSlug: true,
|
||||
requestPath: `/r/${shareSlug}`,
|
||||
failedLookupKey: ip,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -30,10 +53,7 @@ export async function generateMetadata({
|
||||
const { shareSlug } = await params;
|
||||
const resolved = await loadSharedRule(shareSlug);
|
||||
if (!resolved) {
|
||||
return {
|
||||
title: messages.pages.ruleDetail.notFoundTitle,
|
||||
description: "The requested CommunityRule could not be found.",
|
||||
};
|
||||
notFound();
|
||||
}
|
||||
const { rule } = resolved;
|
||||
const description =
|
||||
|
||||
@@ -52,6 +52,7 @@ export const GET = apiRoute<RouteContext>(
|
||||
document: true,
|
||||
createdAt: true,
|
||||
userId: true,
|
||||
exportTokenVersion: true,
|
||||
},
|
||||
});
|
||||
if (!row) return notFound();
|
||||
@@ -60,7 +61,12 @@ export const GET = apiRoute<RouteContext>(
|
||||
let tokenOk = false;
|
||||
if (token.length > 0) {
|
||||
try {
|
||||
tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper());
|
||||
tokenOk = ruleExportTokenMatches(
|
||||
row.id,
|
||||
token,
|
||||
getSessionPepper(),
|
||||
row.exportTokenVersion,
|
||||
);
|
||||
} catch {
|
||||
tokenOk = false;
|
||||
}
|
||||
|
||||
@@ -42,6 +42,10 @@ export const DELETE = apiRoute<RouteContext>(
|
||||
}
|
||||
|
||||
await prisma.ruleStakeholder.delete({ where: { id: row.id } });
|
||||
await prisma.publishedRule.update({
|
||||
where: { id: ruleId },
|
||||
data: { exportTokenVersion: { increment: 1 } },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
},
|
||||
|
||||
@@ -97,7 +97,7 @@ const Avatar = memo<AvatarProps>(
|
||||
const fallbackChrome =
|
||||
variant === "outlined"
|
||||
? "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).
|
||||
const smallImageBorder =
|
||||
size === "small" && showImage && loaded
|
||||
|
||||
@@ -16,8 +16,8 @@ const SelectDropdown = forwardRef<HTMLDivElement, SelectDropdownProps>(
|
||||
rounded-[var(--radius-400)]
|
||||
shadow-lg
|
||||
p-[4px]
|
||||
w-full
|
||||
min-w-[200px]
|
||||
max-w-[300px]
|
||||
${className}
|
||||
`
|
||||
.trim()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import React, {
|
||||
Children,
|
||||
type CSSProperties,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
forwardRef,
|
||||
@@ -12,11 +13,13 @@ import React, {
|
||||
memo,
|
||||
useImperativeHandle,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
} from "react";
|
||||
import { useClickOutside } from "../../../hooks";
|
||||
import { useTranslation } from "../../../contexts/MessagesContext";
|
||||
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
|
||||
@@ -70,11 +73,31 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
const generatedId = useId();
|
||||
const selectId = id || `select-input-${generatedId}`;
|
||||
const labelId = `${selectId}-label`;
|
||||
const listboxId = `${selectId}-listbox`;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [selectedValue, setSelectedValue] = useState(value || "");
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0);
|
||||
const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null);
|
||||
const selectRef = useRef<HTMLButtonElement>(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)
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const [focusMethod, setFocusMethod] = useState<"mouse" | "keyboard" | null>(
|
||||
@@ -99,14 +122,69 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
() => selectRef.current as HTMLButtonElement | null,
|
||||
);
|
||||
|
||||
const closeMenu = useCallback(() => {
|
||||
setIsOpen(false);
|
||||
setMenuStyle(null);
|
||||
}, []);
|
||||
|
||||
// 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
|
||||
const handleOptionSelect = useCallback(
|
||||
(optionValue: string, optionText: string) => {
|
||||
setSelectedValue(optionValue);
|
||||
setIsOpen(false);
|
||||
closeMenu();
|
||||
if (onChange) {
|
||||
onChange({ target: { value: optionValue, text: optionText } });
|
||||
}
|
||||
@@ -114,7 +192,7 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
selectRef.current.focus();
|
||||
}
|
||||
},
|
||||
[onChange],
|
||||
[closeMenu, onChange],
|
||||
);
|
||||
|
||||
// Handle mouse down to detect mouse clicks
|
||||
@@ -126,24 +204,77 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
|
||||
// Handle select button click
|
||||
const handleSelectClick = useCallback(() => {
|
||||
if (!disabled) {
|
||||
setIsOpen(!isOpen);
|
||||
if (disabled) return;
|
||||
if (isOpen) {
|
||||
closeMenu();
|
||||
return;
|
||||
}
|
||||
}, [disabled, isOpen]);
|
||||
openMenu();
|
||||
}, [closeMenu, disabled, isOpen, openMenu]);
|
||||
|
||||
// Handle keyboard navigation
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
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 === " ") {
|
||||
e.preventDefault();
|
||||
setIsOpen(!isOpen);
|
||||
} else if (e.key === "Escape") {
|
||||
setIsOpen(false);
|
||||
if (!isOpen) {
|
||||
openMenu();
|
||||
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
|
||||
@@ -159,14 +290,23 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
}
|
||||
}, [disabled, shouldAutoManageFocus]);
|
||||
|
||||
// Handle blur
|
||||
const handleBlur = useCallback(() => {
|
||||
if (shouldAutoManageFocus) {
|
||||
setIsFocused(false);
|
||||
setFocusMethod(null);
|
||||
wasMouseDownRef.current = false;
|
||||
}
|
||||
}, [shouldAutoManageFocus]);
|
||||
const handleMenuMouseDown = useCallback((event: React.MouseEvent) => {
|
||||
event.preventDefault();
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback(
|
||||
(event: React.FocusEvent<HTMLButtonElement>) => {
|
||||
if (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:
|
||||
// - Active: when clicked (mouse focus) or when dropdown is open
|
||||
@@ -234,9 +374,13 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
||||
onButtonMouseDown={handleMouseDown}
|
||||
onButtonFocus={handleFocus}
|
||||
onButtonBlur={handleBlur}
|
||||
onMenuMouseDown={handleMenuMouseDown}
|
||||
onOptionClick={handleOptionSelect}
|
||||
selectRef={selectRef}
|
||||
menuRef={menuRef}
|
||||
listboxId={listboxId}
|
||||
highlightedIndex={highlightedIndex}
|
||||
menuStyle={menuStyle}
|
||||
ariaLabelledby={shouldShowLabel ? labelId : undefined}
|
||||
ariaInvalid={error}
|
||||
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 SelectDropdown from "./SelectDropdown";
|
||||
import SelectOption from "../SelectOption";
|
||||
@@ -25,11 +26,15 @@ export interface SelectInputViewProps {
|
||||
onButtonKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
|
||||
onButtonMouseDown?: () => void;
|
||||
onButtonFocus?: () => void;
|
||||
onButtonBlur?: () => void;
|
||||
onButtonBlur?: (_event: React.FocusEvent<HTMLButtonElement>) => void;
|
||||
onMenuMouseDown?: (_event: React.MouseEvent<HTMLDivElement>) => void;
|
||||
onOptionClick: (_value: string, _text: string) => void;
|
||||
// Refs
|
||||
selectRef: React.RefObject<HTMLButtonElement>;
|
||||
menuRef: React.RefObject<HTMLDivElement>;
|
||||
listboxId: string;
|
||||
highlightedIndex: number;
|
||||
menuStyle: CSSProperties | null;
|
||||
// Additional props
|
||||
ariaLabelledby?: string;
|
||||
ariaInvalid?: boolean;
|
||||
@@ -63,9 +68,13 @@ export function SelectInputView({
|
||||
onButtonMouseDown,
|
||||
onButtonFocus,
|
||||
onButtonBlur,
|
||||
onMenuMouseDown,
|
||||
onOptionClick,
|
||||
selectRef,
|
||||
menuRef,
|
||||
listboxId,
|
||||
highlightedIndex,
|
||||
menuStyle,
|
||||
ariaLabelledby,
|
||||
ariaInvalid,
|
||||
asterisk = false,
|
||||
@@ -132,6 +141,29 @@ export function SelectInputView({
|
||||
|
||||
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
|
||||
const textColorClass = isFilled
|
||||
? "text-[var(--color-content-default-primary)]"
|
||||
@@ -183,6 +215,8 @@ export function SelectInputView({
|
||||
aria-invalid={ariaInvalid}
|
||||
aria-expanded={isOpen}
|
||||
aria-haspopup="listbox"
|
||||
aria-controls={isOpen ? listboxId : undefined}
|
||||
aria-activedescendant={isOpen ? activeOptionId : undefined}
|
||||
onClick={onButtonClick}
|
||||
onKeyDown={onButtonKeyDown}
|
||||
onMouseDown={onButtonMouseDown}
|
||||
@@ -219,53 +253,32 @@ export function SelectInputView({
|
||||
/>
|
||||
)}
|
||||
|
||||
{isOpen && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="absolute top-full left-0 right-0 z-50 mt-1"
|
||||
>
|
||||
<SelectDropdown ariaLabel={selectAriaLabel}>
|
||||
{options && Array.isArray(options)
|
||||
? options.map((option) => (
|
||||
{isOpen && menuStyle && typeof document !== "undefined"
|
||||
? createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed z-[10050]"
|
||||
style={menuStyle}
|
||||
onMouseDown={onMenuMouseDown}
|
||||
>
|
||||
<SelectDropdown id={listboxId} ariaLabel={selectAriaLabel}>
|
||||
{optionEntries.map((option, index) => (
|
||||
<SelectOption
|
||||
key={option.value}
|
||||
id={`${listboxId}-option-${index}`}
|
||||
selected={option.value === selectedValue}
|
||||
highlighted={index === highlightedIndex}
|
||||
size="medium"
|
||||
onClick={() => onOptionClick(option.value, option.label)}
|
||||
>
|
||||
{option.label}
|
||||
</SelectOption>
|
||||
))
|
||||
: Children.map(children, (child) => {
|
||||
if (
|
||||
React.isValidElement(child) &&
|
||||
child.type === "option"
|
||||
) {
|
||||
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>
|
||||
)}
|
||||
))}
|
||||
</SelectDropdown>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
{textHint && (
|
||||
<div className="flex items-start relative shrink-0 w-full">
|
||||
|
||||
@@ -13,8 +13,10 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
|
||||
{
|
||||
children,
|
||||
selected = false,
|
||||
highlighted = false,
|
||||
disabled = false,
|
||||
className = "",
|
||||
id,
|
||||
onClick,
|
||||
size: sizeProp = "medium",
|
||||
...props
|
||||
@@ -35,15 +37,17 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
|
||||
}
|
||||
};
|
||||
|
||||
const active = selected || highlighted;
|
||||
const itemClasses = `
|
||||
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)]
|
||||
${getTextSize()}
|
||||
cursor-pointer
|
||||
transition-colors duration-150
|
||||
${
|
||||
selected
|
||||
active
|
||||
? "bg-[var(--color-surface-default-secondary)] rounded-[var(--radius-300)]"
|
||||
: ""
|
||||
}
|
||||
@@ -85,6 +89,7 @@ const SelectOptionContainer = forwardRef<HTMLDivElement, SelectOptionProps>(
|
||||
disabled={disabled}
|
||||
className={className}
|
||||
itemClasses={itemClasses}
|
||||
optionId={id}
|
||||
handleClick={handleClick}
|
||||
handleKeyDown={handleKeyDown}
|
||||
{...props}
|
||||
|
||||
@@ -3,8 +3,11 @@ export type SelectOptionSizeValue = "small" | "medium" | "large";
|
||||
export interface SelectOptionProps {
|
||||
children?: React.ReactNode;
|
||||
selected?: boolean;
|
||||
/** Keyboard highlight in a listbox; distinct from the selected value. */
|
||||
highlighted?: boolean;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
id?: string;
|
||||
onClick?: (
|
||||
_e: React.MouseEvent<HTMLDivElement> | React.KeyboardEvent<HTMLDivElement>,
|
||||
) => void;
|
||||
@@ -20,6 +23,7 @@ export interface SelectOptionViewProps {
|
||||
disabled: boolean;
|
||||
className: string;
|
||||
itemClasses: string;
|
||||
optionId?: string;
|
||||
handleClick: (_e: React.MouseEvent<HTMLDivElement>) => void;
|
||||
handleKeyDown: (_e: React.KeyboardEvent<HTMLDivElement>) => void;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export const SelectOptionView = forwardRef<
|
||||
selected,
|
||||
disabled,
|
||||
itemClasses,
|
||||
optionId,
|
||||
handleClick,
|
||||
handleKeyDown,
|
||||
...props
|
||||
@@ -20,9 +21,10 @@ export const SelectOptionView = forwardRef<
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
id={optionId}
|
||||
className={itemClasses}
|
||||
role="option"
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
tabIndex={-1}
|
||||
aria-selected={selected}
|
||||
aria-disabled={disabled}
|
||||
onClick={handleClick}
|
||||
|
||||
@@ -16,6 +16,7 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
|
||||
state: externalStateProp = "default",
|
||||
inputSize: inputSizeProp = "medium",
|
||||
disabled = false,
|
||||
readOnly = false,
|
||||
error = false,
|
||||
label,
|
||||
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) {
|
||||
const filledStyles = isFilled
|
||||
? "font-medium leading-[20px]"
|
||||
@@ -231,6 +242,7 @@ const TextInputContainer = forwardRef<HTMLInputElement, TextInputProps>(
|
||||
labelId={labelId}
|
||||
state={actualState}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
error={error}
|
||||
label={label}
|
||||
placeholder={placeholder}
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface TextInputProps extends Omit<
|
||||
*/
|
||||
inputSize?: TextInputSizeValue;
|
||||
disabled?: boolean;
|
||||
readOnly?: boolean;
|
||||
error?: boolean;
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
@@ -43,6 +44,7 @@ export interface TextInputViewProps {
|
||||
labelId: string;
|
||||
state: "default" | "active" | "hover" | "focus";
|
||||
disabled: boolean;
|
||||
readOnly: boolean;
|
||||
error: boolean;
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
|
||||
@@ -13,6 +13,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
|
||||
name,
|
||||
type,
|
||||
disabled,
|
||||
readOnly = false,
|
||||
error = false,
|
||||
className: _className,
|
||||
containerClasses,
|
||||
@@ -90,6 +91,7 @@ export const TextInputView = forwardRef<HTMLInputElement, TextInputViewProps>(
|
||||
onKeyDown={onKeyDown}
|
||||
onMouseDown={handleMouseDown}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
maxLength={maxLength}
|
||||
autoComplete={autoComplete}
|
||||
inputMode={inputMode}
|
||||
|
||||
@@ -245,9 +245,25 @@ const ShareContainer = memo<ShareProps>((props) => {
|
||||
|
||||
const handleCopyLink = useCallback(async () => {
|
||||
if (!settings) return;
|
||||
const text = settings.shareUrl;
|
||||
try {
|
||||
await navigator.clipboard.writeText(settings.shareUrl);
|
||||
await navigator.clipboard.writeText(text);
|
||||
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 {
|
||||
setLinkCopied(false);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ function PersonRow(props: {
|
||||
roleLabel: string;
|
||||
}) {
|
||||
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
|
||||
alt=""
|
||||
initials={props.initials}
|
||||
@@ -142,7 +142,8 @@ export const ShareView = memo(function ShareView({
|
||||
/>
|
||||
</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="min-w-0 flex-1">
|
||||
<TextInput
|
||||
@@ -170,7 +171,7 @@ export const ShareView = memo(function ShareView({
|
||||
buttonType="outline"
|
||||
palette="default"
|
||||
size="small"
|
||||
disabled={inviteBusy || inviteValue.trim().length === 0}
|
||||
disabled={inviteBusy}
|
||||
onClick={onInvite}
|
||||
>
|
||||
{copy.invite}
|
||||
@@ -182,7 +183,7 @@ export const ShareView = memo(function ShareView({
|
||||
</p>
|
||||
) : 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)]">
|
||||
{copy.peopleWithAccess}
|
||||
</p>
|
||||
@@ -206,7 +207,7 @@ export const ShareView = memo(function ShareView({
|
||||
) : null}
|
||||
</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)]">
|
||||
{copy.whoCanRead}
|
||||
</p>
|
||||
@@ -252,7 +253,7 @@ export const ShareView = memo(function ShareView({
|
||||
showHelpIcon={false}
|
||||
label={copy.anyoneWithLink}
|
||||
value={shareUrlDisplay}
|
||||
disabled
|
||||
readOnly
|
||||
textHint={copy.linkHint}
|
||||
/>
|
||||
<Button
|
||||
@@ -303,7 +304,11 @@ export const ShareView = memo(function ShareView({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{linkCopied ? (
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{linkCopied ? (
|
||||
<div className="shrink-0 px-6 pb-2">
|
||||
<Alert
|
||||
type="toast"
|
||||
status="positive"
|
||||
@@ -314,8 +319,8 @@ export const ShareView = memo(function ShareView({
|
||||
hasTrailingIcon={false}
|
||||
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">
|
||||
<Button
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../publishedRuleAccess";
|
||||
import { prisma } from "./db";
|
||||
import { isDatabaseConfigured } from "./env";
|
||||
import { rateLimitCoolingDown, rateLimitKey } from "./rateLimit";
|
||||
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
||||
import { isRuleAdminEmail } from "./ruleAdmins";
|
||||
import { logAdminRuleRead } from "./adminRuleReadLog";
|
||||
@@ -140,17 +141,31 @@ async function resolveAccessForRow(opts: {
|
||||
* invalidates it. Returns `null` for missing rows, denied readers, and DB
|
||||
* failures — callers render the same 404 as a missing Rule.
|
||||
*/
|
||||
export const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
|
||||
|
||||
export async function getReadablePublishedRule(opts: {
|
||||
idOrSlug: string;
|
||||
user: User | null;
|
||||
viaShareSlug: boolean;
|
||||
requestPath: string;
|
||||
lookup?: "id" | "shareSlug";
|
||||
/** Client IP (or similar) used to slow failed `/r/{slug}` guesses. */
|
||||
failedLookupKey?: string;
|
||||
}): Promise<ReadablePublishedRule | null> {
|
||||
if (!isDatabaseConfigured()) return null;
|
||||
const idOrSlug = opts.idOrSlug.trim();
|
||||
if (idOrSlug.length === 0) return null;
|
||||
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
|
||||
const missKey =
|
||||
lookup === "shareSlug" && opts.failedLookupKey
|
||||
? `share-lookup-miss:${opts.failedLookupKey}`
|
||||
: null;
|
||||
if (
|
||||
missKey &&
|
||||
rateLimitCoolingDown(missKey, SHARE_LOOKUP_MISS_INTERVAL_MS)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const row =
|
||||
lookup === "shareSlug"
|
||||
@@ -162,7 +177,13 @@ export async function getReadablePublishedRule(opts: {
|
||||
where: { id: idOrSlug },
|
||||
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({
|
||||
row,
|
||||
viaShareSlug: opts.viaShareSlug,
|
||||
|
||||
@@ -18,3 +18,12 @@ export function rateLimitKey(
|
||||
windows.set(key, now);
|
||||
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;
|
||||
}
|
||||
@@ -1,19 +1,55 @@
|
||||
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)
|
||||
.update(`rule-export:${ruleId}`)
|
||||
.update(`rule-export:${ruleId}:${version}:${exp}`)
|
||||
.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(
|
||||
ruleId: string,
|
||||
token: string,
|
||||
pepper: string,
|
||||
version: number,
|
||||
now = new Date(),
|
||||
): boolean {
|
||||
if (token.length === 0) return false;
|
||||
const expected = Buffer.from(ruleExportToken(ruleId, pepper));
|
||||
const actual = Buffer.from(token);
|
||||
if (expected.length !== actual.length) return false;
|
||||
return timingSafeEqual(expected, actual);
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 3) return false;
|
||||
const exp = Number(parts[0]);
|
||||
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);
|
||||
}
|
||||
@@ -46,6 +46,7 @@ export async function sendDueRuleFollowUpEmails(
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
exportTokenVersion: true,
|
||||
user: { select: { email: true } },
|
||||
},
|
||||
});
|
||||
@@ -66,7 +67,7 @@ export async function sendDueRuleFollowUpEmails(
|
||||
continue;
|
||||
}
|
||||
|
||||
const token = ruleExportToken(row.id, pepper);
|
||||
const token = ruleExportToken(row.id, pepper, row.exportTokenVersion);
|
||||
try {
|
||||
await sendRuleFollowUpEmail({
|
||||
to: email,
|
||||
|
||||
@@ -147,11 +147,18 @@ export async function patchOwnedRuleShare(opts: {
|
||||
shareSlug = await allocateShareSlug();
|
||||
}
|
||||
|
||||
const turningLinkOff =
|
||||
opts.visibility === RULE_VISIBILITY.private &&
|
||||
row.visibility !== RULE_VISIBILITY.private;
|
||||
|
||||
await prisma.publishedRule.update({
|
||||
where: { id: row.id },
|
||||
data: {
|
||||
visibility: opts.visibility,
|
||||
shareSlug,
|
||||
...(turningLinkOff
|
||||
? { exportTokenVersion: { increment: 1 } }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -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} */
|
||||
const nextConfig = {
|
||||
output: "standalone",
|
||||
poweredByHeader: false,
|
||||
serverExternalPackages: ["@prisma/client"],
|
||||
// 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
|
||||
@@ -102,6 +134,18 @@ const nextConfig = {
|
||||
key: "X-XSS-Protection",
|
||||
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;
|
||||
@@ -101,6 +101,9 @@ model PublishedRule {
|
||||
/// 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.
|
||||
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[]
|
||||
uploads Upload[]
|
||||
|
||||
@@ -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", () => {
|
||||
const onClick = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
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 { componentTestSuite } from "../utils/componentTestSuite";
|
||||
import { renderWithProviders, screen } from "../utils/test-utils";
|
||||
|
||||
type SelectInputProps = React.ComponentProps<typeof SelectInput>;
|
||||
|
||||
@@ -31,3 +35,108 @@ componentTestSuite<SelectInputProps>({
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -81,4 +81,19 @@ describe("TextInput (size tests)", () => {
|
||||
expect(input).toBeRequired();
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -86,11 +86,33 @@ describe("Share modal", () => {
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("Juniper Street Food Share")).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("Five more people can read 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 () => {
|
||||
openShare();
|
||||
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" }));
|
||||
expect(
|
||||
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"),
|
||||
).toBeInTheDocument();
|
||||
const linkField = screen.getByDisplayValue(
|
||||
"communityrule.info/r/k7f2-9qxm",
|
||||
);
|
||||
expect(linkField).toHaveAttribute("readonly");
|
||||
expect(linkField).not.toBeDisabled();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Turn off link" }),
|
||||
).toBeInTheDocument();
|
||||
@@ -201,6 +225,28 @@ describe("Share modal", () => {
|
||||
).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 () => {
|
||||
const user = userEvent.setup();
|
||||
const onClose = vi.fn();
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const rateLimitKeyMock = vi.fn();
|
||||
const rateLimitCoolingDownMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const stakeholderFindManyMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
@@ -12,6 +14,12 @@ vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/rateLimit", () => ({
|
||||
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
||||
rateLimitCoolingDown: (...args: unknown[]) =>
|
||||
rateLimitCoolingDownMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
@@ -71,9 +79,13 @@ beforeEach(() => {
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
rateLimitKeyMock.mockReset();
|
||||
rateLimitCoolingDownMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
rateLimitKeyMock.mockReturnValue({ ok: true });
|
||||
rateLimitCoolingDownMock.mockReturnValue(false);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
RULE_EXPORT_TOKEN_TTL_MS,
|
||||
ruleExportToken,
|
||||
ruleExportTokenMatches,
|
||||
} from "../../lib/server/ruleExportToken";
|
||||
|
||||
describe("ruleExportToken", () => {
|
||||
it("accepts the matching token and rejects another rule or token", () => {
|
||||
const pepper = "test-pepper-16chars";
|
||||
const token = ruleExportToken("rule-1", pepper);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true);
|
||||
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false);
|
||||
const pepper = "test-pepper-16chars";
|
||||
const now = new Date("2026-11-21T12:00:00.000Z");
|
||||
|
||||
it("accepts the matching token and rejects another rule, version, or token", () => {
|
||||
const token = ruleExportToken("rule-1", pepper, 0, now);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper, 0, now)).toBe(true);
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-1",
|
||||
title: "Garden Norms",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
@@ -85,7 +86,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
|
||||
it("skips rows with no mailbox and does not mark them sent", async () => {
|
||||
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);
|
||||
expect(result.skipped).toBe(1);
|
||||
@@ -98,6 +99,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-4",
|
||||
title: "Race",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
@@ -112,6 +114,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-3",
|
||||
title: "Retry",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => {
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
exportTokenVersion: { increment: 1 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -52,6 +52,7 @@ function row() {
|
||||
},
|
||||
createdAt: new Date("2026-11-08T00:00:00.000Z"),
|
||||
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 () => {
|
||||
const token = ruleExportToken("rule-1", PEPPER);
|
||||
const token = ruleExportToken("rule-1", PEPPER, 0);
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
`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("## 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";
|
||||
|
||||
const findFirstRuleMock = vi.fn();
|
||||
const publishedRuleUpdateMock = vi.fn();
|
||||
const findFirstStakeholderMock = vi.fn();
|
||||
const countMock = vi.fn();
|
||||
const deleteMock = vi.fn();
|
||||
@@ -20,6 +21,7 @@ vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
|
||||
update: (...args: unknown[]) => publishedRuleUpdateMock(...args),
|
||||
},
|
||||
ruleStakeholder: {
|
||||
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
|
||||
@@ -67,6 +69,7 @@ const memberCtx = {
|
||||
|
||||
beforeEach(() => {
|
||||
findFirstRuleMock.mockReset();
|
||||
publishedRuleUpdateMock.mockReset();
|
||||
findFirstStakeholderMock.mockReset();
|
||||
countMock.mockReset();
|
||||
deleteMock.mockReset();
|
||||
@@ -177,6 +180,10 @@ describe("DELETE /api/rules/[id]/stakeholders/[stakeholderId]", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
|
||||
expect(publishedRuleUpdateMock).toHaveBeenCalledWith({
|
||||
where: { id: "rule-1" },
|
||||
data: { exportTokenVersion: { increment: 1 } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user