diff --git a/app/api/uploads/[id]/route.ts b/app/api/uploads/[id]/route.ts index 413d7eb..a972cdd 100644 --- a/app/api/uploads/[id]/route.ts +++ b/app/api/uploads/[id]/route.ts @@ -69,6 +69,7 @@ export const GET = apiRoute( idOrSlug: row.ruleId, user, viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link, + lookup: "id", requestPath: request.nextUrl.pathname, }); allowed = resolved != null; diff --git a/app/components/modals/Share/Share.container.tsx b/app/components/modals/Share/Share.container.tsx index 2a309f0..625add6 100644 --- a/app/components/modals/Share/Share.container.tsx +++ b/app/components/modals/Share/Share.container.tsx @@ -65,6 +65,7 @@ const ShareContainer = memo((props) => { const [inviteError, setInviteError] = useState(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((props) => { setInviteError(null); setLinkCopied(false); setTurnOnBusy(false); + setSaveFailed(false); if (!previewSettings) setSettings(null); return; } @@ -106,6 +108,7 @@ const ShareContainer = memo((props) => { setSettings(next); setPhase("idle"); setCommunityAgreed(false); + setSaveFailed(false); }, []); const handleSelectValue = useCallback( @@ -132,7 +135,11 @@ const ShareContainer = memo((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((props) => { } setPhase("confirm"); setCommunityAgreed(false); + setSaveFailed(false); } }, [applySettings, phase, ruleId, settings], @@ -185,7 +193,11 @@ const ShareContainer = memo((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((props) => { turnOnDisabled turnOnBusy={false} showError={false} + showSaveError={false} copyEnabled={false} linkCopied={false} onCopyLink={() => undefined} @@ -327,6 +340,7 @@ const ShareContainer = memo((props) => { turnOnDisabled={!communityAgreed} turnOnBusy={turnOnBusy} showError={phase === "error"} + showSaveError={saveFailed} copyEnabled={copyEnabled} linkCopied={linkCopied} onCopyLink={() => void handleCopyLink()} diff --git a/app/components/modals/Share/Share.types.ts b/app/components/modals/Share/Share.types.ts index 3407aa3..3d0d5d2 100644 --- a/app/components/modals/Share/Share.types.ts +++ b/app/components/modals/Share/Share.types.ts @@ -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; diff --git a/app/components/modals/Share/Share.view.tsx b/app/components/modals/Share/Share.view.tsx index 7a4a25b..9df3aad 100644 --- a/app/components/modals/Share/Share.view.tsx +++ b/app/components/modals/Share/Share.view.tsx @@ -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}

) : null} + {showSaveError ? ( + + ) : null} {showLinkField ? ( diff --git a/lib/server/publishedRules.ts b/lib/server/publishedRules.ts index 6c547b2..0a8e6cc 100644 --- a/lib/server/publishedRules.ts +++ b/lib/server/publishedRules.ts @@ -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 { 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, diff --git a/messages/en/modals/share.json b/messages/en/modals/share.json index 93c767c..627089f 100644 --- a/messages/en/modals/share.json +++ b/messages/en/modals/share.json @@ -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" } diff --git a/tests/components/modals/Share.test.tsx b/tests/components/modals/Share.test.tsx index 8410458..1938294 100644 --- a/tests/components/modals/Share.test.tsx +++ b/tests/components/modals/Share.test.tsx @@ -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 = {}) { 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( + , + ); + 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( + , + ); + 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(); diff --git a/tests/unit/publishedRules.test.ts b/tests/unit/publishedRules.test.ts index d851e4f..df04d83 100644 --- a/tests/unit/publishedRules.test.ts +++ b/tests/unit/publishedRules.test.ts @@ -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( diff --git a/tests/unit/uploadsByIdRoute.test.ts b/tests/unit/uploadsByIdRoute.test.ts index 3851f6c..1f88f9d 100644 --- a/tests/unit/uploadsByIdRoute.test.ts +++ b/tests/unit/uploadsByIdRoute.test.ts @@ -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"); });