Honor the share-link miss limit before querying, and keep Escape inside the access menu.
This commit is contained in:
1 parent
75649a9a42
commit
1b3d055c81
8 files changed
+189
-19
No files matched your search
@@ -3,7 +3,10 @@ import { headers } from "next/headers";
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import messages from "../../../../messages/en/index";
|
import messages from "../../../../messages/en/index";
|
||||||
import { isShareSlug } from "../../../../lib/sharePaths";
|
import { isShareSlug } from "../../../../lib/sharePaths";
|
||||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
import {
|
||||||
|
SHARE_LOOKUP_MISS_INTERVAL_MS,
|
||||||
|
getReadablePublishedRule,
|
||||||
|
} from "../../../../lib/server/publishedRules";
|
||||||
import { rateLimitKey } from "../../../../lib/server/rateLimit";
|
import { rateLimitKey } from "../../../../lib/server/rateLimit";
|
||||||
import { getSessionUser } from "../../../../lib/server/session";
|
import { getSessionUser } from "../../../../lib/server/session";
|
||||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
||||||
@@ -27,7 +30,11 @@ async function clientIp(): Promise<string> {
|
|||||||
async function loadSharedRule(shareSlug: string) {
|
async function loadSharedRule(shareSlug: string) {
|
||||||
const ip = await clientIp();
|
const ip = await clientIp();
|
||||||
if (!isShareSlug(shareSlug)) {
|
if (!isShareSlug(shareSlug)) {
|
||||||
rateLimitKey(`share-lookup-miss:${ip}`, 1_000);
|
const limited = rateLimitKey(
|
||||||
|
`share-lookup-miss:${ip}`,
|
||||||
|
SHARE_LOOKUP_MISS_INTERVAL_MS,
|
||||||
|
);
|
||||||
|
if (!limited.ok) return null;
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const user = await getSessionUser();
|
const user = await getSessionUser();
|
||||||
|
|||||||
@@ -260,6 +260,9 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === "Escape") {
|
if (e.key === "Escape") {
|
||||||
|
if (!isOpen) return;
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
closeMenu();
|
closeMenu();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -287,14 +290,23 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
|||||||
}
|
}
|
||||||
}, [disabled, shouldAutoManageFocus]);
|
}, [disabled, shouldAutoManageFocus]);
|
||||||
|
|
||||||
// Handle blur
|
const handleMenuMouseDown = useCallback((event: React.MouseEvent) => {
|
||||||
const handleBlur = useCallback(() => {
|
event.preventDefault();
|
||||||
if (shouldAutoManageFocus) {
|
}, []);
|
||||||
setIsFocused(false);
|
|
||||||
setFocusMethod(null);
|
const handleBlur = useCallback(
|
||||||
wasMouseDownRef.current = false;
|
(event: React.FocusEvent<HTMLButtonElement>) => {
|
||||||
}
|
if (shouldAutoManageFocus) {
|
||||||
}, [shouldAutoManageFocus]);
|
setIsFocused(false);
|
||||||
|
setFocusMethod(null);
|
||||||
|
wasMouseDownRef.current = false;
|
||||||
|
}
|
||||||
|
const next = event.relatedTarget;
|
||||||
|
if (next instanceof Node && menuRef.current?.contains(next)) return;
|
||||||
|
closeMenu();
|
||||||
|
},
|
||||||
|
[closeMenu, shouldAutoManageFocus],
|
||||||
|
);
|
||||||
|
|
||||||
// Determine actual state:
|
// Determine actual state:
|
||||||
// - Active: when clicked (mouse focus) or when dropdown is open
|
// - Active: when clicked (mouse focus) or when dropdown is open
|
||||||
@@ -362,6 +374,7 @@ const SelectInputContainer = forwardRef<HTMLButtonElement, SelectInputProps>(
|
|||||||
onButtonMouseDown={handleMouseDown}
|
onButtonMouseDown={handleMouseDown}
|
||||||
onButtonFocus={handleFocus}
|
onButtonFocus={handleFocus}
|
||||||
onButtonBlur={handleBlur}
|
onButtonBlur={handleBlur}
|
||||||
|
onMenuMouseDown={handleMenuMouseDown}
|
||||||
onOptionClick={handleOptionSelect}
|
onOptionClick={handleOptionSelect}
|
||||||
selectRef={selectRef}
|
selectRef={selectRef}
|
||||||
menuRef={menuRef}
|
menuRef={menuRef}
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ export interface SelectInputViewProps {
|
|||||||
onButtonKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
|
onButtonKeyDown: (_e: React.KeyboardEvent<HTMLButtonElement>) => void;
|
||||||
onButtonMouseDown?: () => void;
|
onButtonMouseDown?: () => void;
|
||||||
onButtonFocus?: () => void;
|
onButtonFocus?: () => void;
|
||||||
onButtonBlur?: () => void;
|
onButtonBlur?: (_event: React.FocusEvent<HTMLButtonElement>) => void;
|
||||||
|
onMenuMouseDown?: (_event: React.MouseEvent<HTMLDivElement>) => void;
|
||||||
onOptionClick: (_value: string, _text: string) => void;
|
onOptionClick: (_value: string, _text: string) => void;
|
||||||
// Refs
|
// Refs
|
||||||
selectRef: React.RefObject<HTMLButtonElement>;
|
selectRef: React.RefObject<HTMLButtonElement>;
|
||||||
@@ -67,6 +68,7 @@ export function SelectInputView({
|
|||||||
onButtonMouseDown,
|
onButtonMouseDown,
|
||||||
onButtonFocus,
|
onButtonFocus,
|
||||||
onButtonBlur,
|
onButtonBlur,
|
||||||
|
onMenuMouseDown,
|
||||||
onOptionClick,
|
onOptionClick,
|
||||||
selectRef,
|
selectRef,
|
||||||
menuRef,
|
menuRef,
|
||||||
@@ -257,6 +259,7 @@ export function SelectInputView({
|
|||||||
ref={menuRef}
|
ref={menuRef}
|
||||||
className="fixed z-[10050]"
|
className="fixed z-[10050]"
|
||||||
style={menuStyle}
|
style={menuStyle}
|
||||||
|
onMouseDown={onMenuMouseDown}
|
||||||
>
|
>
|
||||||
<SelectDropdown id={listboxId} ariaLabel={selectAriaLabel}>
|
<SelectDropdown id={listboxId} ariaLabel={selectAriaLabel}>
|
||||||
{optionEntries.map((option, index) => (
|
{optionEntries.map((option, index) => (
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
} from "../publishedRuleAccess";
|
} from "../publishedRuleAccess";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { isDatabaseConfigured } from "./env";
|
import { isDatabaseConfigured } from "./env";
|
||||||
import { rateLimitKey } from "./rateLimit";
|
import { rateLimitCoolingDown, rateLimitKey } from "./rateLimit";
|
||||||
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
||||||
import { isRuleAdminEmail } from "./ruleAdmins";
|
import { isRuleAdminEmail } from "./ruleAdmins";
|
||||||
import { logAdminRuleRead } from "./adminRuleReadLog";
|
import { logAdminRuleRead } from "./adminRuleReadLog";
|
||||||
@@ -141,7 +141,7 @@ async function resolveAccessForRow(opts: {
|
|||||||
* invalidates it. Returns `null` for missing rows, denied readers, and DB
|
* invalidates it. Returns `null` for missing rows, denied readers, and DB
|
||||||
* failures — callers render the same 404 as a missing Rule.
|
* failures — callers render the same 404 as a missing Rule.
|
||||||
*/
|
*/
|
||||||
const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
|
export const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
|
||||||
|
|
||||||
export async function getReadablePublishedRule(opts: {
|
export async function getReadablePublishedRule(opts: {
|
||||||
idOrSlug: string;
|
idOrSlug: string;
|
||||||
@@ -156,6 +156,16 @@ export async function getReadablePublishedRule(opts: {
|
|||||||
const idOrSlug = opts.idOrSlug.trim();
|
const idOrSlug = opts.idOrSlug.trim();
|
||||||
if (idOrSlug.length === 0) return null;
|
if (idOrSlug.length === 0) return null;
|
||||||
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
|
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
|
||||||
|
const missKey =
|
||||||
|
lookup === "shareSlug" && opts.failedLookupKey
|
||||||
|
? `share-lookup-miss:${opts.failedLookupKey}`
|
||||||
|
: null;
|
||||||
|
if (
|
||||||
|
missKey &&
|
||||||
|
rateLimitCoolingDown(missKey, SHARE_LOOKUP_MISS_INTERVAL_MS)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const row =
|
const row =
|
||||||
lookup === "shareSlug"
|
lookup === "shareSlug"
|
||||||
@@ -168,11 +178,9 @@ export async function getReadablePublishedRule(opts: {
|
|||||||
select: RULE_ACCESS_SELECT,
|
select: RULE_ACCESS_SELECT,
|
||||||
});
|
});
|
||||||
if (!row) {
|
if (!row) {
|
||||||
if (lookup === "shareSlug" && opts.failedLookupKey) {
|
if (missKey) {
|
||||||
rateLimitKey(
|
const limited = rateLimitKey(missKey, SHARE_LOOKUP_MISS_INTERVAL_MS);
|
||||||
`share-lookup-miss:${opts.failedLookupKey}`,
|
if (!limited.ok) return null;
|
||||||
SHARE_LOOKUP_MISS_INTERVAL_MS,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,3 +18,12 @@ export function rateLimitKey(
|
|||||||
windows.set(key, now);
|
windows.set(key, now);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True when `key` is still inside the interval started by the last allowed call. */
|
||||||
|
export function rateLimitCoolingDown(
|
||||||
|
key: string,
|
||||||
|
minIntervalMs: number,
|
||||||
|
): boolean {
|
||||||
|
const last = windows.get(key) ?? 0;
|
||||||
|
return Date.now() - last < minIntervalMs;
|
||||||
|
}
|
||||||
@@ -64,4 +64,79 @@ describe("SelectInput listbox keyboard", () => {
|
|||||||
});
|
});
|
||||||
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
const getReadablePublishedRuleMock = vi.fn();
|
const getReadablePublishedRuleMock = vi.fn();
|
||||||
const getSessionUserMock = vi.fn();
|
const getSessionUserMock = vi.fn();
|
||||||
|
const rateLimitKeyMock = vi.fn();
|
||||||
const notFoundMock = vi.fn(() => {
|
const notFoundMock = vi.fn(() => {
|
||||||
throw new Error("NEXT_NOT_FOUND");
|
throw new Error("NEXT_NOT_FOUND");
|
||||||
});
|
});
|
||||||
@@ -16,10 +17,11 @@ vi.mock("next/headers", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../../lib/server/rateLimit", () => ({
|
vi.mock("../../lib/server/rateLimit", () => ({
|
||||||
rateLimitKey: () => ({ ok: true }),
|
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../../lib/server/publishedRules", () => ({
|
vi.mock("../../lib/server/publishedRules", () => ({
|
||||||
|
SHARE_LOOKUP_MISS_INTERVAL_MS: 1_000,
|
||||||
getReadablePublishedRule: (...args: unknown[]) =>
|
getReadablePublishedRule: (...args: unknown[]) =>
|
||||||
getReadablePublishedRuleMock(...args),
|
getReadablePublishedRuleMock(...args),
|
||||||
}));
|
}));
|
||||||
@@ -34,6 +36,8 @@ describe("shared Rule page", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
getReadablePublishedRuleMock.mockReset();
|
getReadablePublishedRuleMock.mockReset();
|
||||||
getSessionUserMock.mockReset();
|
getSessionUserMock.mockReset();
|
||||||
|
rateLimitKeyMock.mockReset();
|
||||||
|
rateLimitKeyMock.mockReturnValue({ ok: true });
|
||||||
notFoundMock.mockClear();
|
notFoundMock.mockClear();
|
||||||
getSessionUserMock.mockResolvedValue(null);
|
getSessionUserMock.mockResolvedValue(null);
|
||||||
});
|
});
|
||||||
@@ -47,4 +51,18 @@ describe("shared Rule page", () => {
|
|||||||
).rejects.toThrow("NEXT_NOT_FOUND");
|
).rejects.toThrow("NEXT_NOT_FOUND");
|
||||||
expect(notFoundMock).toHaveBeenCalled();
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
const isDatabaseConfiguredMock = vi.fn();
|
const isDatabaseConfiguredMock = vi.fn();
|
||||||
const findUniqueMock = vi.fn();
|
const findUniqueMock = vi.fn();
|
||||||
const rateLimitKeyMock = vi.fn();
|
const rateLimitKeyMock = vi.fn();
|
||||||
|
const rateLimitCoolingDownMock = vi.fn();
|
||||||
const findManyMock = vi.fn();
|
const findManyMock = vi.fn();
|
||||||
const stakeholderFindManyMock = vi.fn();
|
const stakeholderFindManyMock = vi.fn();
|
||||||
const browserHoldsClaimForHashMock = vi.fn();
|
const browserHoldsClaimForHashMock = vi.fn();
|
||||||
@@ -15,6 +16,8 @@ vi.mock("../../lib/server/env", () => ({
|
|||||||
|
|
||||||
vi.mock("../../lib/server/rateLimit", () => ({
|
vi.mock("../../lib/server/rateLimit", () => ({
|
||||||
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
||||||
|
rateLimitCoolingDown: (...args: unknown[]) =>
|
||||||
|
rateLimitCoolingDownMock(...args),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../../lib/server/db", () => ({
|
vi.mock("../../lib/server/db", () => ({
|
||||||
@@ -77,10 +80,12 @@ beforeEach(() => {
|
|||||||
isRuleAdminEmailMock.mockReset();
|
isRuleAdminEmailMock.mockReset();
|
||||||
logAdminRuleReadMock.mockReset();
|
logAdminRuleReadMock.mockReset();
|
||||||
rateLimitKeyMock.mockReset();
|
rateLimitKeyMock.mockReset();
|
||||||
|
rateLimitCoolingDownMock.mockReset();
|
||||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||||
isRuleAdminEmailMock.mockReturnValue(false);
|
isRuleAdminEmailMock.mockReturnValue(false);
|
||||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||||
rateLimitKeyMock.mockReturnValue({ ok: true });
|
rateLimitKeyMock.mockReturnValue({ ok: true });
|
||||||
|
rateLimitCoolingDownMock.mockReturnValue(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getReadablePublishedRule", () => {
|
describe("getReadablePublishedRule", () => {
|
||||||
@@ -245,6 +250,38 @@ describe("getReadablePublishedRule", () => {
|
|||||||
1_000,
|
1_000,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not query when a share-slug miss is still cooling down", async () => {
|
||||||
|
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||||
|
rateLimitCoolingDownMock.mockReturnValue(true);
|
||||||
|
expect(
|
||||||
|
await getReadablePublishedRule({
|
||||||
|
idOrSlug: "k7f2-9qxm",
|
||||||
|
user: null,
|
||||||
|
viaShareSlug: true,
|
||||||
|
requestPath: "/r/k7f2-9qxm",
|
||||||
|
failedLookupKey: "203.0.113.8",
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
expect(findUniqueMock).not.toHaveBeenCalled();
|
||||||
|
expect(rateLimitKeyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when the miss limit refuses after a lookup", async () => {
|
||||||
|
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||||
|
findUniqueMock.mockResolvedValueOnce(null);
|
||||||
|
rateLimitKeyMock.mockReturnValue({ ok: false, retryAfterMs: 400 });
|
||||||
|
expect(
|
||||||
|
await getReadablePublishedRule({
|
||||||
|
idOrSlug: "k7f2-9qxm",
|
||||||
|
user: null,
|
||||||
|
viaShareSlug: true,
|
||||||
|
requestPath: "/r/k7f2-9qxm",
|
||||||
|
failedLookupKey: "203.0.113.8",
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
expect(findUniqueMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("listListedPublishedRules", () => {
|
describe("listListedPublishedRules", () => {
|
||||||
|
|||||||
Reference in new issue
Block a user