Keep finished Rules private until a rotating share link is on, and delete files with the Rule #102

Merged
an.di merged 3 commits from adilallo/feature/CR-248-rule-visibility into main 2026-11-10 04:12:12 +00:00
9 changed files with 148 additions and 16 deletions
Showing only changes of commit 63ba21c614 - Show all commits

No files matched your search

+1
View File
@@ -69,6 +69,7 @@ export const GET = apiRoute<RouteContext>(
idOrSlug: row.ruleId,
user,
viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link,
lookup: "id",
requestPath: request.nextUrl.pathname,
});
allowed = resolved != null;
@@ -65,6 +65,7 @@ const ShareContainer = memo<ShareProps>((props) => {
const [inviteError, setInviteError] = useState<string | null>(null);
const [turnOnBusy, setTurnOnBusy] = useState(false);
const [linkCopied, setLinkCopied] = useState(false);
const [saveFailed, setSaveFailed] = useState(false);
useCreateModalA11y(isOpen, onClose, dialogRef);
@@ -76,6 +77,7 @@ const ShareContainer = memo<ShareProps>((props) => {
setInviteError(null);
setLinkCopied(false);
setTurnOnBusy(false);
setSaveFailed(false);
if (!previewSettings) setSettings(null);
return;
}
@@ -106,6 +108,7 @@ const ShareContainer = memo<ShareProps>((props) => {
setSettings(next);
setPhase("idle");
setCommunityAgreed(false);
setSaveFailed(false);
}, []);
const handleSelectValue = useCallback(
@@ -132,7 +135,11 @@ const ShareContainer = memo<ShareProps>((props) => {
}
void (async () => {
const res = await patchRuleShare(ruleId, "private");
if (res.ok) applySettings(res.share);
if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
})();
return;
}
@@ -146,6 +153,7 @@ const ShareContainer = memo<ShareProps>((props) => {
}
setPhase("confirm");
setCommunityAgreed(false);
setSaveFailed(false);
}
},
[applySettings, phase, ruleId, settings],
@@ -185,7 +193,11 @@ const ShareContainer = memo<ShareProps>((props) => {
return;
}
const res = await patchRuleShare(ruleId, "private");
if (res.ok) applySettings(res.share);
if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
}, [applySettings, ruleId, settings]);
const handleInvite = useCallback(async () => {
@@ -274,6 +286,7 @@ const ShareContainer = memo<ShareProps>((props) => {
turnOnDisabled
turnOnBusy={false}
showError={false}
showSaveError={false}
copyEnabled={false}
linkCopied={false}
onCopyLink={() => undefined}
@@ -327,6 +340,7 @@ const ShareContainer = memo<ShareProps>((props) => {
turnOnDisabled={!communityAgreed}
turnOnBusy={turnOnBusy}
showError={phase === "error"}
showSaveError={saveFailed}
copyEnabled={copyEnabled}
linkCopied={linkCopied}
onCopyLink={() => void handleCopyLink()}
@@ -44,6 +44,8 @@ export type ShareCopy = {
done: string;
errorTitle: string;
errorDescription: string;
saveErrorTitle: string;
saveErrorDescription: string;
closeDialogAriaLabel: string;
accessSelectAriaLabel: string;
};
@@ -79,6 +81,7 @@ export type ShareViewProps = {
turnOnDisabled: boolean;
turnOnBusy: boolean;
showError: boolean;
showSaveError: boolean;
copyEnabled: boolean;
linkCopied: boolean;
onCopyLink: () => void;
@@ -107,6 +107,7 @@ export const ShareView = memo(function ShareView({
turnOnDisabled,
turnOnBusy,
showError,
showSaveError,
copyEnabled,
linkCopied,
onCopyLink,
@@ -229,6 +230,19 @@ export const ShareView = memo(function ShareView({
{linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint}
</p>
) : null}
{showSaveError ? (
<Alert
type="banner"
status="danger"
size="s"
title={copy.saveErrorTitle}
description={copy.saveErrorDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
className="w-full"
/>
) : null}
</div>
{showLinkField ? (
+18 -13
View File
@@ -133,30 +133,35 @@ async function resolveAccessForRow(opts: {
/**
* Fetch a published rule the viewer is allowed to read.
*
* Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link
* strangers must use the rotating slug so turning the link off invalidates it.
* Returns `null` for missing rows, denied readers, and DB failures — callers
* render the same 404 as a missing Rule.
* Lookup is by internal id unless `viaShareSlug` is set. Pass `lookup: "id"`
* when the caller already has the Rule id but link visitors should still
* count as readers (file URLs on a shared Rule). Shared-by-link strangers
* opening the Rule itself must use the rotating slug so turning the link off
* invalidates it. Returns `null` for missing rows, denied readers, and DB
* failures — callers render the same 404 as a missing Rule.
*/
export async function getReadablePublishedRule(opts: {
idOrSlug: string;
user: User | null;
viaShareSlug: boolean;
requestPath: string;
lookup?: "id" | "shareSlug";
}): 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");
try {
const row = opts.viaShareSlug
? await prisma.publishedRule.findUnique({
where: { shareSlug: idOrSlug },
select: RULE_ACCESS_SELECT,
})
: await prisma.publishedRule.findUnique({
where: { id: idOrSlug },
select: RULE_ACCESS_SELECT,
});
const row =
lookup === "shareSlug"
? await prisma.publishedRule.findUnique({
where: { shareSlug: idOrSlug },
select: RULE_ACCESS_SELECT,
})
: await prisma.publishedRule.findUnique({
where: { id: idOrSlug },
select: RULE_ACCESS_SELECT,
});
if (!row) return null;
return resolveAccessForRow({
row,
+2
View File
@@ -25,6 +25,8 @@
"done": "Done",
"errorTitle": "The link didn’t turn on",
"errorDescription": "Check your connection and try again.",
"saveErrorTitle": "That change didn’t save",
"saveErrorDescription": "Check your connection and try again.",
"closeDialogAriaLabel": "Close",
"accessSelectAriaLabel": "Who can read this Rule"
}
+68
View File
@@ -8,8 +8,15 @@ import {
} from "../../utils/test-utils";
import "@testing-library/jest-dom/vitest";
import Share from "../../../app/components/modals/Share";
import { patchRuleShare } from "../../../lib/create/api";
import type { RuleShareSettings } from "../../../lib/ruleShareTypes";
vi.mock("../../../lib/create/api", () => ({
patchRuleShare: vi.fn(),
fetchRuleShare: vi.fn(),
addRuleStakeholder: vi.fn(),
}));
const previewSettings: RuleShareSettings = {
visibility: "private",
shareSlug: null,
@@ -41,9 +48,18 @@ function openShare(overrides: Partial<RuleShareSettings> = {}) {
const writeText = vi.fn().mockResolvedValue(undefined);
const sharedSettings: RuleShareSettings = {
...previewSettings,
visibility: "shared_by_link",
shareSlug: "k7f2-9qxm",
shareUrl: "https://communityrule.info/r/k7f2-9qxm",
shareUrlDisplay: "communityrule.info/r/k7f2-9qxm",
};
beforeEach(() => {
writeText.mockReset();
writeText.mockResolvedValue(undefined);
vi.mocked(patchRuleShare).mockReset();
Object.defineProperty(window.navigator, "clipboard", {
configurable: true,
value: { writeText },
@@ -133,6 +149,58 @@ describe("Share modal", () => {
).toBeInTheDocument();
});
it("keeps the link on and says so when turning the Rule private does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup();
render(
<Share
isOpen
onClose={vi.fn()}
ruleId="rule-1"
previewSettings={sharedSettings}
/>,
);
await user.click(
screen.getByRole("button", { name: /Anyone with the link/i }),
);
await user.click(
await screen.findByRole("option", { name: "Only people you invite" }),
);
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Turn off link" }),
).toBeInTheDocument();
expect(
screen.queryByText("Only people you invite can open it."),
).not.toBeInTheDocument();
});
it("keeps the link on and says so when turning the link off does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup();
render(
<Share
isOpen
onClose={vi.fn()}
ruleId="rule-1"
previewSettings={sharedSettings}
/>,
);
await user.click(screen.getByRole("button", { name: "Turn off link" }));
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"),
).toBeInTheDocument();
});
it("calls onClose when Done is clicked", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
+21
View File
@@ -153,6 +153,27 @@ describe("getReadablePublishedRule", () => {
).toBeNull();
});
it("lets anonymous readers of a shared Rule through when the caller already has the id", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(
row({
visibility: RULE_VISIBILITY.shared_by_link,
shareSlug: "k7f2-9qxm",
}),
);
const resolved = await getReadablePublishedRule({
idOrSlug: "owned-1",
user: null,
viaShareSlug: true,
lookup: "id",
requestPath: "/api/uploads/file-1",
});
expect(resolved?.rule.id).toBe("owned-1");
expect(findUniqueMock).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "owned-1" } }),
);
});
it("lets anonymous readers use the rotating slug", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(
+5 -1
View File
@@ -153,7 +153,11 @@ describe("GET /api/uploads/[id]", () => {
);
expect(res.status).toBe(200);
expect(getReadablePublishedRuleMock).toHaveBeenCalledWith(
expect.objectContaining({ viaShareSlug: true }),
expect.objectContaining({
idOrSlug: "rule-shared",
viaShareSlug: true,
lookup: "id",
}),
);
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
});