From 2644023b5acaa86688bdf942f4ae5ab550f07a9b Mon Sep 17 00:00:00 2001 From: adilallo <39313955+adilallo@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:59:46 -0700 Subject: [PATCH] Save a guest edit on the published Rule, and publish a new one when that update is refused. A leftover editing id was treated as a successful finish in this browser only, so the public Rule stayed stale and a later Finish could skip creating a new Rule. --- app/(app)/create/CreateFlowLayoutClient.tsx | 5 +- .../create/hooks/useCreateFlowFinalize.ts | 62 ++++++------ app/api/rules/[id]/route.ts | 22 +++-- docs/create-flow.md | 2 +- .../unit/hooks/useCreateFlowFinalize.test.tsx | 99 ++++++++++++++++++- tests/unit/rulesByIdPatchRoute.test.ts | 61 ++++++++++++ 6 files changed, 207 insertions(+), 44 deletions(-) diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index 1d6a9f1..5b73d0f 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -485,10 +485,13 @@ function CreateFlowLayoutContent({ * Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections * may already match draft state while compact CardStack pins stayed false * (pins are normally set only on facet **Confirm**). + * + * An empty id with that same content is a finished edit. Writing the id + * back would make the next Finish update the old Rule. */ if ( titleOk && - editingId === last.id && + (editingId === last.id || editingId.length === 0) && sectionsClear && !isPublishedRuleHydratePatchIncomplete(state, patch) ) { diff --git a/app/(app)/create/hooks/useCreateFlowFinalize.ts b/app/(app)/create/hooks/useCreateFlowFinalize.ts index 0fccb5b..64b476f 100644 --- a/app/(app)/create/hooks/useCreateFlowFinalize.ts +++ b/app/(app)/create/hooks/useCreateFlowFinalize.ts @@ -132,28 +132,14 @@ export function useCreateFlowFinalize({ ? state.editingPublishedRuleId.trim() : ""; - if (editingId.length > 0 && sessionUser === null) { - setIsPublishing(false); - writeLastPublishedRule({ - id: editingId, - title, - summary: summary ?? null, - document: ruleDocument, - }); - updateState({ editingPublishedRuleId: undefined }); - onGuestPublished?.({ skippedInvites: false }); - router.push(createFlowStepPath("completed")); - return; - } - if (editingId.length > 0) { const updateResult = await updatePublishedRule(editingId, { title, summary: summary ?? null, document: ruleDocument, }); - setIsPublishing(false); if (updateResult.ok === true) { + setIsPublishing(false); writeLastPublishedRule({ id: editingId, title, @@ -161,28 +147,39 @@ export function useCreateFlowFinalize({ document: ruleDocument, }); updateState({ editingPublishedRuleId: undefined }); - void deleteServerDraftAfterPublish(); + if (sessionUser === null) { + onGuestPublished?.({ skippedInvites: false }); + } else { + void deleteServerDraftAfterPublish(); + } router.push(createFlowStepPath("completed")); return; } - if (updateResult.status === 401) { - openLogin({ - variant: sessionUser === null ? "keepRule" : "default", - nextPath: - sessionUser === null - ? createFlowStepPath("completed") - : loginReturnPath, - backdropVariant: "blurredYellow", - }); + // A leftover id must not block a new Rule. This browser cannot update + // that id, so publish a new one instead of pretending the edit saved. + const guestCannotUpdate = + sessionUser === null && + (updateResult.status === 401 || + updateResult.status === 403 || + updateResult.status === 404); + if (!guestCannotUpdate) { + setIsPublishing(false); + if (updateResult.status === 401) { + openLogin({ + variant: "default", + nextPath: loginReturnPath, + backdropVariant: "blurredYellow", + }); + return; + } + showFailedBanner( + updateResult.error.trim() !== "" + ? updateResult.error + : messages.create.reviewAndComplete.publish.genericPublishFailed, + false, + ); return; } - showFailedBanner( - updateResult.error.trim() !== "" - ? updateResult.error - : messages.create.reviewAndComplete.publish.genericPublishFailed, - false, - ); - return; } const isGuest = sessionUser === null; @@ -212,6 +209,7 @@ export function useCreateFlowFinalize({ ? { finishedAt: publishResult.createdAt } : {}), }); + updateState({ editingPublishedRuleId: undefined }); if (isGuest) { onGuestPublished?.({ skippedInvites: skippedGuestInvites }); } else { diff --git a/app/api/rules/[id]/route.ts b/app/api/rules/[id]/route.ts index 36a3403..68ff74a 100644 --- a/app/api/rules/[id]/route.ts +++ b/app/api/rules/[id]/route.ts @@ -8,6 +8,7 @@ import { notFound, unauthorized, } from "../../../../lib/server/responses"; +import { browserHoldsClaimForHash } from "../../../../lib/server/guestRuleClaim"; import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import { getSessionUser } from "../../../../lib/server/session"; import { apiRoute } from "../../../../lib/server/apiRoute"; @@ -54,20 +55,25 @@ export const PATCH = apiRoute( } const user = await getSessionUser(); - if (!user) { - return unauthorized(); - } - const { id } = await context.params; const row = await prisma.publishedRule.findUnique({ where: { id }, - select: { id: true, userId: true }, + select: { id: true, userId: true, claimTokenHash: true }, }); + // This browser published the Rule and nobody has claimed it yet. + const claimUpdate = + row != null && + row.userId == null && + (await browserHoldsClaimForHash(row.claimTokenHash)); + if (!row) { - return notFound(); + return user ? notFound() : unauthorized(); } - if (row.userId !== user.id) { + if (!user && !claimUpdate) { + return unauthorized(); + } + if (user && row.userId !== user.id && !claimUpdate) { return forbidden("You do not have permission to update this rule"); } @@ -95,7 +101,7 @@ export const PATCH = apiRoute( await linkUploadsToRule({ ruleId: row.id, document, - userId: user.id, + userId: user?.id ?? null, }); return NextResponse.json({ ok: true }); diff --git a/docs/create-flow.md b/docs/create-flow.md index 5852700..9da20ec 100644 --- a/docs/create-flow.md +++ b/docs/create-flow.md @@ -111,7 +111,7 @@ Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog cl | Mode | Where progress lives | Save & Exit / publish | | --- | --- | --- | -| **Anonymous** | `localStorage` key **`create-flow-anonymous`** | Header is **Exit**. **Save your progress** (`community-save`) is optional (**Skip for now** never comes back as a required step). **Publish** `POST`s `/api/rules` without a session (`userId` null) and sets httpOnly **`cr_rule_claim`**. Completed is **Exit** with no login or email prompt; Print, PDF, and RULE.md work from that Rule. Signing in later on the same browser attaches `userId` (profile, edit, invites). **Send invitations** opens the invite login and returns to Invite your members after the link is followed. | +| **Anonymous** | `localStorage` key **`create-flow-anonymous`** | Header is **Exit**. **Save your progress** (`community-save`) is optional (**Skip for now** never comes back as a required step). **Publish** `POST`s `/api/rules` without a session (`userId` null) and sets httpOnly **`cr_rule_claim`**. Finishing changes to a Rule this browser published `PATCH`es that Rule while it is still unclaimed. If that update is refused, Finish publishes a new Rule. Completed is **Exit** with no login or email prompt; Print, PDF, and RULE.md work from that Rule. Signing in later on the same browser attaches `userId` (profile, invites, and later edits). **Send invitations** opens the invite login and returns to Invite your members after the link is followed. | | **Signed-in** | In-memory React state in **`CreateFlowContext`** | **Save and exit** from **`community-save`** onward (and `edit-rule`) may **PUT** `/api/drafts/me` when sync is on. **Completed** is **Exit**. **Publish** stores the rule with **`userId`**. **Sign out** is on profile, not in the create top nav. | Details and edge cases (conflict confirm, banners, `?syncDraft=1`) match **Ticket 4**, **Ticket 5**, and [`docs/guides/backend-roadmap.md`](guides/backend-roadmap.md) ยง12. diff --git a/tests/unit/hooks/useCreateFlowFinalize.test.tsx b/tests/unit/hooks/useCreateFlowFinalize.test.tsx index 886544d..b95fb6c 100644 --- a/tests/unit/hooks/useCreateFlowFinalize.test.tsx +++ b/tests/unit/hooks/useCreateFlowFinalize.test.tsx @@ -109,6 +109,9 @@ describe("useCreateFlowFinalize", () => { sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY), ).toBeNull(); expect(deleteServerDraft).toHaveBeenCalledTimes(1); + expect(updateState).toHaveBeenCalledWith({ + editingPublishedRuleId: undefined, + }); }); it("retries clearing the server draft when the first delete fails", async () => { @@ -450,7 +453,9 @@ describe("useCreateFlowFinalize", () => { }); }); - it("does not PATCH when a guest publishes an already-published rule", async () => { + it("PATCHes when a guest finishes an edit of a rule this browser published", async () => { + vi.mocked(updatePublishedRule).mockResolvedValue({ ok: true }); + const { result } = renderHook(() => useCreateFlowFinalize({ state: { @@ -470,8 +475,16 @@ describe("useCreateFlowFinalize", () => { await result.current.finalize(); }); - expect(updatePublishedRule).not.toHaveBeenCalled(); + expect(updatePublishedRule).toHaveBeenCalledWith( + "guest-rule-1", + expect.objectContaining({ + title: "Published title", + summary: "Published summary", + document: {}, + }), + ); expect(publishRule).not.toHaveBeenCalled(); + expect(deleteServerDraft).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled(); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); expect(writeLastPublishedRule).toHaveBeenCalledWith({ @@ -480,10 +493,92 @@ describe("useCreateFlowFinalize", () => { summary: "Published summary", document: {}, }); + expect(updateState).toHaveBeenCalledWith({ + editingPublishedRuleId: undefined, + }); expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull(); expect(router.push).toHaveBeenCalledWith("/create/completed"); }); + it("publishes a new rule when a guest cannot update the leftover id", async () => { + vi.mocked(updatePublishedRule).mockResolvedValue({ + ok: false, + error: "Unauthorized", + status: 401, + }); + vi.mocked(publishRule).mockResolvedValue({ + ok: true, + id: "new-guest-rule", + title: "Published title", + }); + + const { result } = renderHook(() => + useCreateFlowFinalize({ + state: { + ...emptyState, + editingPublishedRuleId: "stale-rule", + }, + router, + openLogin, + updateState, + loginReturnPath: "/create/final-review?syncDraft=1", + sessionUser: null, + onGuestPublished, + }), + ); + + await act(async () => { + await result.current.finalize(); + }); + + expect(updatePublishedRule).toHaveBeenCalledWith( + "stale-rule", + expect.anything(), + ); + expect(publishRule).toHaveBeenCalled(); + expect(openLogin).not.toHaveBeenCalled(); + expect(writeLastPublishedRule).toHaveBeenCalledWith( + expect.objectContaining({ id: "new-guest-rule" }), + ); + expect(updateState).toHaveBeenCalledWith({ + editingPublishedRuleId: undefined, + }); + expect(router.push).toHaveBeenCalledWith( + `/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`, + ); + }); + + it("does not publish a second rule when a guest update fails on the server", async () => { + vi.mocked(updatePublishedRule).mockResolvedValue({ + ok: false, + error: "Database unavailable", + status: 500, + }); + + const { result } = renderHook(() => + useCreateFlowFinalize({ + state: { + ...emptyState, + editingPublishedRuleId: "guest-rule-1", + }, + router, + openLogin, + updateState, + loginReturnPath: "/create/final-review?syncDraft=1", + sessionUser: null, + onGuestPublished, + }), + ); + + await act(async () => { + await result.current.finalize(); + }); + + expect(publishRule).not.toHaveBeenCalled(); + expect(router.push).not.toHaveBeenCalled(); + expect(result.current.publishBannerMessage).toBe("Database unavailable"); + }); + it("opens keepRule login when a guest publish is unauthorized", async () => { vi.mocked(publishRule).mockResolvedValue({ ok: false, diff --git a/tests/unit/rulesByIdPatchRoute.test.ts b/tests/unit/rulesByIdPatchRoute.test.ts index ac543d2..91e7e8e 100644 --- a/tests/unit/rulesByIdPatchRoute.test.ts +++ b/tests/unit/rulesByIdPatchRoute.test.ts @@ -5,6 +5,7 @@ const isDatabaseConfiguredMock = vi.fn(); const findUniqueMock = vi.fn(); const updateMock = vi.fn(); const getSessionUserMock = vi.fn(); +const browserHoldsClaimForHashMock = vi.fn(); vi.mock("../../lib/server/env", () => ({ isDatabaseConfigured: () => isDatabaseConfiguredMock(), @@ -23,22 +24,37 @@ vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); +vi.mock("../../lib/server/guestRuleClaim", () => ({ + browserHoldsClaimForHash: (...args: unknown[]) => + browserHoldsClaimForHashMock(...args), +})); + vi.mock("../../lib/server/uploads/linkUploads", () => ({ linkUploadsToRule: vi.fn().mockResolvedValue(undefined), })); import { PATCH } from "../../app/api/rules/[id]/route"; +import { linkUploadsToRule } from "../../lib/server/uploads/linkUploads"; function makeContext(id: string) { return { params: Promise.resolve({ id }) }; } +const patchBody = { + title: "Updated", + summary: "Context", + document: { sections: [], coreValues: [] }, +}; + beforeEach(() => { isDatabaseConfiguredMock.mockReset(); findUniqueMock.mockReset(); updateMock.mockReset(); getSessionUserMock.mockReset(); + browserHoldsClaimForHashMock.mockReset(); + vi.mocked(linkUploadsToRule).mockClear(); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); + browserHoldsClaimForHashMock.mockResolvedValue(false); }); describe("PATCH /api/rules/[id]", () => { @@ -114,4 +130,49 @@ describe("PATCH /api/rules/[id]", () => { }), ); }); + + it("updates an unclaimed rule when this browser holds the claim", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + getSessionUserMock.mockResolvedValueOnce(null); + browserHoldsClaimForHashMock.mockResolvedValueOnce(true); + findUniqueMock.mockResolvedValueOnce({ + id: "r1", + userId: null, + claimTokenHash: "claim-hash", + }); + updateMock.mockResolvedValueOnce({}); + const res = await PATCH( + new NextRequest("https://x.test/api/rules/r1", { + method: "PATCH", + body: JSON.stringify(patchBody), + }), + makeContext("r1"), + ); + expect(res.status).toBe(200); + expect(browserHoldsClaimForHashMock).toHaveBeenCalledWith("claim-hash"); + expect(updateMock).toHaveBeenCalled(); + expect(linkUploadsToRule).toHaveBeenCalledWith( + expect.objectContaining({ ruleId: "r1", userId: null }), + ); + }); + + it("returns 401 when a guest does not hold the claim", async () => { + isDatabaseConfiguredMock.mockReturnValue(true); + getSessionUserMock.mockResolvedValueOnce(null); + browserHoldsClaimForHashMock.mockResolvedValueOnce(false); + findUniqueMock.mockResolvedValueOnce({ + id: "r1", + userId: null, + claimTokenHash: "claim-hash", + }); + const res = await PATCH( + new NextRequest("https://x.test/api/rules/r1", { + method: "PATCH", + body: JSON.stringify(patchBody), + }), + makeContext("r1"), + ); + expect(res.status).toBe(401); + expect(updateMock).not.toHaveBeenCalled(); + }); });