diff --git a/app/(marketing)/r/[shareSlug]/page.tsx b/app/(marketing)/r/[shareSlug]/page.tsx index 74dc1a0..5fb5bb0 100644 --- a/app/(marketing)/r/[shareSlug]/page.tsx +++ b/app/(marketing)/r/[shareSlug]/page.tsx @@ -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 { + 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 = diff --git a/app/api/rules/[id]/export/[format]/route.ts b/app/api/rules/[id]/export/[format]/route.ts index 11b00e5..2e00b7a 100644 --- a/app/api/rules/[id]/export/[format]/route.ts +++ b/app/api/rules/[id]/export/[format]/route.ts @@ -52,6 +52,7 @@ export const GET = apiRoute( document: true, createdAt: true, userId: true, + exportTokenVersion: true, }, }); if (!row) return notFound(); @@ -60,7 +61,12 @@ export const GET = apiRoute( 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; } diff --git a/app/api/rules/[id]/stakeholders/[stakeholderId]/route.ts b/app/api/rules/[id]/stakeholders/[stakeholderId]/route.ts index 51adcdd..e70c16f 100644 --- a/app/api/rules/[id]/stakeholders/[stakeholderId]/route.ts +++ b/app/api/rules/[id]/stakeholders/[stakeholderId]/route.ts @@ -42,6 +42,10 @@ export const DELETE = apiRoute( } await prisma.ruleStakeholder.delete({ where: { id: row.id } }); + await prisma.publishedRule.update({ + where: { id: ruleId }, + data: { exportTokenVersion: { increment: 1 } }, + }); return NextResponse.json({ ok: true }); }, diff --git a/app/components/asset/Avatar/Avatar.tsx b/app/components/asset/Avatar/Avatar.tsx index a37b590..d01153c 100644 --- a/app/components/asset/Avatar/Avatar.tsx +++ b/app/components/asset/Avatar/Avatar.tsx @@ -97,7 +97,7 @@ const Avatar = memo( 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 diff --git a/app/components/controls/SelectInput/SelectDropdown.tsx b/app/components/controls/SelectInput/SelectDropdown.tsx index 79237d0..c840771 100644 --- a/app/components/controls/SelectInput/SelectDropdown.tsx +++ b/app/components/controls/SelectInput/SelectDropdown.tsx @@ -16,8 +16,8 @@ const SelectDropdown = forwardRef( rounded-[var(--radius-400)] shadow-lg p-[4px] + w-full min-w-[200px] - max-w-[300px] ${className} ` .trim() diff --git a/app/components/controls/SelectInput/SelectInput.container.tsx b/app/components/controls/SelectInput/SelectInput.container.tsx index b23d0da..e19efe4 100644 --- a/app/components/controls/SelectInput/SelectInput.container.tsx +++ b/app/components/controls/SelectInput/SelectInput.container.tsx @@ -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( 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(null); const selectRef = useRef(null); const menuRef = useRef(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( () => 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( selectRef.current.focus(); } }, - [onChange], + [closeMenu, onChange], ); // Handle mouse down to detect mouse clicks @@ -126,24 +204,77 @@ const SelectInputContainer = forwardRef( // 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) => { 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( } }, [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) => { + 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( 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} diff --git a/app/components/controls/SelectInput/SelectInput.view.tsx b/app/components/controls/SelectInput/SelectInput.view.tsx index 0b40e89..2a64960 100644 --- a/app/components/controls/SelectInput/SelectInput.view.tsx +++ b/app/components/controls/SelectInput/SelectInput.view.tsx @@ -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) => void; onButtonMouseDown?: () => void; onButtonFocus?: () => void; - onButtonBlur?: () => void; + onButtonBlur?: (_event: React.FocusEvent) => void; + onMenuMouseDown?: (_event: React.MouseEvent) => void; onOptionClick: (_value: string, _text: string) => void; // Refs selectRef: React.RefObject; menuRef: React.RefObject; + 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 && ( -
- - {options && Array.isArray(options) - ? options.map((option) => ( + {isOpen && menuStyle && typeof document !== "undefined" + ? createPortal( +
+ + {optionEntries.map((option, index) => ( onOptionClick(option.value, option.label)} > {option.label} - )) - : Children.map(children, (child) => { - if ( - React.isValidElement(child) && - child.type === "option" - ) { - const optionProps = child.props as { - value: string; - children: ReactNode; - }; - return ( - - onOptionClick( - optionProps.value, - String(optionProps.children), - ) - } - > - {optionProps.children} - - ); - } - return child; - })} - -
- )} + ))} +
+
, + document.body, + ) + : null} {textHint && (
diff --git a/app/components/controls/SelectOption/SelectOption.container.tsx b/app/components/controls/SelectOption/SelectOption.container.tsx index 05d0a9b..28526db 100644 --- a/app/components/controls/SelectOption/SelectOption.container.tsx +++ b/app/components/controls/SelectOption/SelectOption.container.tsx @@ -13,8 +13,10 @@ const SelectOptionContainer = forwardRef( { children, selected = false, + highlighted = false, disabled = false, className = "", + id, onClick, size: sizeProp = "medium", ...props @@ -35,15 +37,17 @@ const SelectOptionContainer = forwardRef( } }; + 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( disabled={disabled} className={className} itemClasses={itemClasses} + optionId={id} handleClick={handleClick} handleKeyDown={handleKeyDown} {...props} diff --git a/app/components/controls/SelectOption/SelectOption.types.ts b/app/components/controls/SelectOption/SelectOption.types.ts index 4a86be4..41eb19d 100644 --- a/app/components/controls/SelectOption/SelectOption.types.ts +++ b/app/components/controls/SelectOption/SelectOption.types.ts @@ -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 | React.KeyboardEvent, ) => void; @@ -20,6 +23,7 @@ export interface SelectOptionViewProps { disabled: boolean; className: string; itemClasses: string; + optionId?: string; handleClick: (_e: React.MouseEvent) => void; handleKeyDown: (_e: React.KeyboardEvent) => void; } diff --git a/app/components/controls/SelectOption/SelectOption.view.tsx b/app/components/controls/SelectOption/SelectOption.view.tsx index 04c1a4a..d3e3be8 100644 --- a/app/components/controls/SelectOption/SelectOption.view.tsx +++ b/app/components/controls/SelectOption/SelectOption.view.tsx @@ -11,6 +11,7 @@ export const SelectOptionView = forwardRef< selected, disabled, itemClasses, + optionId, handleClick, handleKeyDown, ...props @@ -20,9 +21,10 @@ export const SelectOptionView = forwardRef< return (
( state: externalStateProp = "default", inputSize: inputSizeProp = "medium", disabled = false, + readOnly = false, error = false, label, placeholder, @@ -109,6 +110,16 @@ const TextInputContainer = forwardRef( }; } + 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( labelId={labelId} state={actualState} disabled={disabled} + readOnly={readOnly} error={error} label={label} placeholder={placeholder} diff --git a/app/components/controls/TextInput/TextInput.types.ts b/app/components/controls/TextInput/TextInput.types.ts index c445828..2ecc8f3 100644 --- a/app/components/controls/TextInput/TextInput.types.ts +++ b/app/components/controls/TextInput/TextInput.types.ts @@ -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; diff --git a/app/components/controls/TextInput/TextInput.view.tsx b/app/components/controls/TextInput/TextInput.view.tsx index 3b3b5a0..07687f1 100644 --- a/app/components/controls/TextInput/TextInput.view.tsx +++ b/app/components/controls/TextInput/TextInput.view.tsx @@ -13,6 +13,7 @@ export const TextInputView = forwardRef( name, type, disabled, + readOnly = false, error = false, className: _className, containerClasses, @@ -90,6 +91,7 @@ export const TextInputView = forwardRef( onKeyDown={onKeyDown} onMouseDown={handleMouseDown} disabled={disabled} + readOnly={readOnly} maxLength={maxLength} autoComplete={autoComplete} inputMode={inputMode} diff --git a/app/components/modals/Share/Share.container.tsx b/app/components/modals/Share/Share.container.tsx index 625add6..fbea707 100644 --- a/app/components/modals/Share/Share.container.tsx +++ b/app/components/modals/Share/Share.container.tsx @@ -245,9 +245,25 @@ const ShareContainer = memo((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); } diff --git a/app/components/modals/Share/Share.view.tsx b/app/components/modals/Share/Share.view.tsx index 9df3aad..dcb9363 100644 --- a/app/components/modals/Share/Share.view.tsx +++ b/app/components/modals/Share/Share.view.tsx @@ -41,7 +41,7 @@ function PersonRow(props: { roleLabel: string; }) { return ( -
+
-
+
+
{copy.invite} @@ -182,7 +183,7 @@ export const ShareView = memo(function ShareView({

) : null} -
+

{copy.peopleWithAccess}

@@ -206,7 +207,7 @@ export const ShareView = memo(function ShareView({ ) : null}
-
+

{copy.whoCanRead}

@@ -252,7 +253,7 @@ export const ShareView = memo(function ShareView({ showHelpIcon={false} label={copy.anyoneWithLink} value={shareUrlDisplay} - disabled + readOnly textHint={copy.linkHint} />
+
+ + {linkCopied ? ( +
- ) : null} -
+
+ ) : null}
+ , + ); + + 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( + , + ); + + 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( + , + ); + + 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(); + }); +}); diff --git a/tests/components/TextInput.test.tsx b/tests/components/TextInput.test.tsx index de9cc0a..3264034 100644 --- a/tests/components/TextInput.test.tsx +++ b/tests/components/TextInput.test.tsx @@ -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( + , + ); + 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(); + }); }); diff --git a/tests/components/modals/Share.test.tsx b/tests/components/modals/Share.test.tsx index 1938294..8302253 100644 --- a/tests/components/modals/Share.test.tsx +++ b/tests/components/modals/Share.test.tsx @@ -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(); diff --git a/tests/pages/shared-rule.test.ts b/tests/pages/shared-rule.test.ts new file mode 100644 index 0000000..2a7c1aa --- /dev/null +++ b/tests/pages/shared-rule.test.ts @@ -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(); + }); +}); diff --git a/tests/unit/publishedRules.test.ts b/tests/unit/publishedRules.test.ts index cbf95e7..9743fcf 100644 --- a/tests/unit/publishedRules.test.ts +++ b/tests/unit/publishedRules.test.ts @@ -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", () => { diff --git a/tests/unit/ruleExportToken.test.ts b/tests/unit/ruleExportToken.test.ts index 82b2a79..5aacf22 100644 --- a/tests/unit/ruleExportToken.test.ts +++ b/tests/unit/ruleExportToken.test.ts @@ -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); }); }); diff --git a/tests/unit/ruleFollowUp.test.ts b/tests/unit/ruleFollowUp.test.ts index 52ad272..2c1a5e5 100644 --- a/tests/unit/ruleFollowUp.test.ts +++ b/tests/unit/ruleFollowUp.test.ts @@ -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" }, }, ]); diff --git a/tests/unit/ruleShare.test.ts b/tests/unit/ruleShare.test.ts index a947b6b..3e4c6e3 100644 --- a/tests/unit/ruleShare.test.ts +++ b/tests/unit/ruleShare.test.ts @@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => { data: { visibility: RULE_VISIBILITY.private, shareSlug: null, + exportTokenVersion: { increment: 1 }, }, }), ); diff --git a/tests/unit/rulesExportRoute.test.ts b/tests/unit/rulesExportRoute.test.ts index 3effff6..fec8d58 100644 --- a/tests/unit/rulesExportRoute.test.ts +++ b/tests/unit/rulesExportRoute.test.ts @@ -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); + }); }); diff --git a/tests/unit/rulesStakeholderMutationsRoute.test.ts b/tests/unit/rulesStakeholderMutationsRoute.test.ts index 309b024..ca33386 100644 --- a/tests/unit/rulesStakeholderMutationsRoute.test.ts +++ b/tests/unit/rulesStakeholderMutationsRoute.test.ts @@ -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 } }, + }); }); }); diff --git a/tests/unit/securityHeaders.test.ts b/tests/unit/securityHeaders.test.ts new file mode 100644 index 0000000..1d338a3 --- /dev/null +++ b/tests/unit/securityHeaders.test.ts @@ -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"); + }); +});