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.
This commit is contained in:
adilallo committed 2026-11-23 14:59:46 -07:00
1 parent 0535f6f167
commit 2644023b5a
6 files changed
+207 -44

No files matched your search

+4 -1
View File
@@ -485,10 +485,13 @@ function CreateFlowLayoutContent({
* Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections * Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections
* may already match draft state while compact CardStack pins stayed false * may already match draft state while compact CardStack pins stayed false
* (pins are normally set only on facet **Confirm**). * (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 ( if (
titleOk && titleOk &&
editingId === last.id && (editingId === last.id || editingId.length === 0) &&
sectionsClear && sectionsClear &&
!isPublishedRuleHydratePatchIncomplete(state, patch) !isPublishedRuleHydratePatchIncomplete(state, patch)
) { ) {
+30 -32
View File
@@ -132,28 +132,14 @@ export function useCreateFlowFinalize({
? state.editingPublishedRuleId.trim() ? 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) { if (editingId.length > 0) {
const updateResult = await updatePublishedRule(editingId, { const updateResult = await updatePublishedRule(editingId, {
title, title,
summary: summary ?? null, summary: summary ?? null,
document: ruleDocument, document: ruleDocument,
}); });
setIsPublishing(false);
if (updateResult.ok === true) { if (updateResult.ok === true) {
setIsPublishing(false);
writeLastPublishedRule({ writeLastPublishedRule({
id: editingId, id: editingId,
title, title,
@@ -161,28 +147,39 @@ export function useCreateFlowFinalize({
document: ruleDocument, document: ruleDocument,
}); });
updateState({ editingPublishedRuleId: undefined }); updateState({ editingPublishedRuleId: undefined });
void deleteServerDraftAfterPublish(); if (sessionUser === null) {
onGuestPublished?.({ skippedInvites: false });
} else {
void deleteServerDraftAfterPublish();
}
router.push(createFlowStepPath("completed")); router.push(createFlowStepPath("completed"));
return; return;
} }
if (updateResult.status === 401) { // A leftover id must not block a new Rule. This browser cannot update
openLogin({ // that id, so publish a new one instead of pretending the edit saved.
variant: sessionUser === null ? "keepRule" : "default", const guestCannotUpdate =
nextPath: sessionUser === null &&
sessionUser === null (updateResult.status === 401 ||
? createFlowStepPath("completed") updateResult.status === 403 ||
: loginReturnPath, updateResult.status === 404);
backdropVariant: "blurredYellow", 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; return;
} }
showFailedBanner(
updateResult.error.trim() !== ""
? updateResult.error
: messages.create.reviewAndComplete.publish.genericPublishFailed,
false,
);
return;
} }
const isGuest = sessionUser === null; const isGuest = sessionUser === null;
@@ -212,6 +209,7 @@ export function useCreateFlowFinalize({
? { finishedAt: publishResult.createdAt } ? { finishedAt: publishResult.createdAt }
: {}), : {}),
}); });
updateState({ editingPublishedRuleId: undefined });
if (isGuest) { if (isGuest) {
onGuestPublished?.({ skippedInvites: skippedGuestInvites }); onGuestPublished?.({ skippedInvites: skippedGuestInvites });
} else { } else {
+14 -8
View File
@@ -8,6 +8,7 @@ import {
notFound, notFound,
unauthorized, unauthorized,
} from "../../../../lib/server/responses"; } from "../../../../lib/server/responses";
import { browserHoldsClaimForHash } from "../../../../lib/server/guestRuleClaim";
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
import { getSessionUser } from "../../../../lib/server/session"; import { getSessionUser } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute"; import { apiRoute } from "../../../../lib/server/apiRoute";
@@ -54,20 +55,25 @@ export const PATCH = apiRoute<RouteContext>(
} }
const user = await getSessionUser(); const user = await getSessionUser();
if (!user) {
return unauthorized();
}
const { id } = await context.params; const { id } = await context.params;
const row = await prisma.publishedRule.findUnique({ const row = await prisma.publishedRule.findUnique({
where: { id }, 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) { 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"); return forbidden("You do not have permission to update this rule");
} }
@@ -95,7 +101,7 @@ export const PATCH = apiRoute<RouteContext>(
await linkUploadsToRule({ await linkUploadsToRule({
ruleId: row.id, ruleId: row.id,
document, document,
userId: user.id, userId: user?.id ?? null,
}); });
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
+1 -1
View File
@@ -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 | | 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. | | **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. 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.
@@ -109,6 +109,9 @@ describe("useCreateFlowFinalize", () => {
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY), sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull(); ).toBeNull();
expect(deleteServerDraft).toHaveBeenCalledTimes(1); expect(deleteServerDraft).toHaveBeenCalledTimes(1);
expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
}); });
it("retries clearing the server draft when the first delete fails", async () => { 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(() => const { result } = renderHook(() =>
useCreateFlowFinalize({ useCreateFlowFinalize({
state: { state: {
@@ -470,8 +475,16 @@ describe("useCreateFlowFinalize", () => {
await result.current.finalize(); 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(publishRule).not.toHaveBeenCalled();
expect(deleteServerDraft).not.toHaveBeenCalled();
expect(openLogin).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled();
expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false });
expect(writeLastPublishedRule).toHaveBeenCalledWith({ expect(writeLastPublishedRule).toHaveBeenCalledWith({
@@ -480,10 +493,92 @@ describe("useCreateFlowFinalize", () => {
summary: "Published summary", summary: "Published summary",
document: {}, document: {},
}); });
expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull(); expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull();
expect(router.push).toHaveBeenCalledWith("/create/completed"); 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 () => { it("opens keepRule login when a guest publish is unauthorized", async () => {
vi.mocked(publishRule).mockResolvedValue({ vi.mocked(publishRule).mockResolvedValue({
ok: false, ok: false,
+61
View File
@@ -5,6 +5,7 @@ const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn(); const findUniqueMock = vi.fn();
const updateMock = vi.fn(); const updateMock = vi.fn();
const getSessionUserMock = vi.fn(); const getSessionUserMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn();
vi.mock("../../lib/server/env", () => ({ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(), isDatabaseConfigured: () => isDatabaseConfiguredMock(),
@@ -23,22 +24,37 @@ vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(), getSessionUser: () => getSessionUserMock(),
})); }));
vi.mock("../../lib/server/guestRuleClaim", () => ({
browserHoldsClaimForHash: (...args: unknown[]) =>
browserHoldsClaimForHashMock(...args),
}));
vi.mock("../../lib/server/uploads/linkUploads", () => ({ vi.mock("../../lib/server/uploads/linkUploads", () => ({
linkUploadsToRule: vi.fn().mockResolvedValue(undefined), linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
})); }));
import { PATCH } from "../../app/api/rules/[id]/route"; import { PATCH } from "../../app/api/rules/[id]/route";
import { linkUploadsToRule } from "../../lib/server/uploads/linkUploads";
function makeContext(id: string) { function makeContext(id: string) {
return { params: Promise.resolve({ id }) }; return { params: Promise.resolve({ id }) };
} }
const patchBody = {
title: "Updated",
summary: "Context",
document: { sections: [], coreValues: [] },
};
beforeEach(() => { beforeEach(() => {
isDatabaseConfiguredMock.mockReset(); isDatabaseConfiguredMock.mockReset();
findUniqueMock.mockReset(); findUniqueMock.mockReset();
updateMock.mockReset(); updateMock.mockReset();
getSessionUserMock.mockReset(); getSessionUserMock.mockReset();
browserHoldsClaimForHashMock.mockReset();
vi.mocked(linkUploadsToRule).mockClear();
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
browserHoldsClaimForHashMock.mockResolvedValue(false);
}); });
describe("PATCH /api/rules/[id]", () => { 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();
});
}); });