From d30f86a214b36ff5896ba2080b7f6c5a5ff14221 Mon Sep 17 00:00:00 2001 From: Lorenzo Corallo Date: Mon, 23 Nov 2026 20:32:41 +0100 Subject: [PATCH] feat(regulations): secret drafts in the dashboard "Nuova bozza" asks who sees the draft: visible (regulations:read and the members) or secret, seen only by its creator and the members they add, whatever their permissions. The procedure page explains it, keeps the steps disabled and offers "Rendi visibile" to the creator (drafts.reveal, for good); lists and headers mark it "Segreta", and the members dialog keeps the creator as editor. Agent mode serves the same rules and two secret samples. Needs PoliNetworkOrg/backend#155 (contract copy). --- AGENTS.md | 3 +- docs/regulations/README.md | 10 ++- src/features/regulations/document-page.tsx | 3 +- src/features/regulations/drafts-page.tsx | 3 +- .../regulations/editor/editor-page.tsx | 3 +- src/features/regulations/members-dialog.tsx | 72 +++++++++------- src/features/regulations/new-draft-dialog.tsx | 29 ++++++- src/features/regulations/procedure-page.tsx | 66 +++++++++++--- .../regulations-draft.functions.ts | 6 ++ src/features/regulations/regulations-ui.tsx | 13 +++ .../regulations/regulations.api.server.ts | 3 + .../regulations/regulations.contract.ts | 16 +++- .../regulations/regulations.fake.server.ts | 86 +++++++++++++++++-- tests/server-security.test.mjs | 1 + 14 files changed, 258 insertions(+), 56 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 37613de..64dfa16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,7 +52,8 @@ What the app is and how to run it: [`README.md`](README.md). UI rules: [`docs/de PDFs, `regulations:rectify` rettifiche and Deleghe. Per-draft access (viewer, commenter, editor) and deleghe are backend data: `regulations.me.get` admits an account without `admin:access` to Regolamenti › Bozze only, draft-scoped server functions use `regulationsAssigneeMiddleware`, and pages act on the document's `editable` and the draft's `can` - from the backend. Every PDF opens in `PdfDialog`. The editor connects to the collab service with a single-use ticket + from the backend. A secret draft (`secret`) is seen only by its creator and the members they add, permissions + notwithstanding, and its procedure stays closed until the creator makes it visible (`drafts.reveal`, for good). Every PDF opens in `PdfDialog`. The editor connects to the collab service with a single-use ticket from a server function, never a token. UI copy is Italian. Details: `docs/regulations/README.md`. - **Shared UI**: `src/components/shell`, `src/components/primitives`, `src/components/ui`. diff --git a/docs/regulations/README.md b/docs/regulations/README.md index d1d2e1e..2d607d3 100644 --- a/docs/regulations/README.md +++ b/docs/regulations/README.md @@ -61,6 +61,13 @@ Every section but Bozze also needs `admin:access`, like the rest of the dashboar editor, and a delega lets anyone rectify. `loadAccess` admits a user without `admin:access` or `people:self` when `regulations.me.get` reports an assignment or a delega; `/dashboard` then shows them only Regolamenti › Bozze (`peopleRoles.regulations`, the `regulations` section role in `nav.ts`), and the logo leads there. +- **Secret drafts.** "Nuova bozza" asks who sees it: "Visibile" (`regulations:read` and the members) or "Segreta" + (`secret: true`): only its creator and the members they add, whatever their IdP permissions, with the role given in + the members dialog (a Direttivo member too); not even `regulations:write` or `:manage` see it, in lists or counts. + Only the creator manages members, deletes it and makes it visible ("Rendi visibile" on the procedure page, + `drafts.reveal`, for good). Until then its procedure is closed: the steps show disabled with the backend's reason, and + the page says why once. A draft from a secret draft is secret too. Lists and headers mark it "Segreta" + (`DraftSecretMark`). - **Middleware** (`src/server/auth.middleware.ts`): `regulationsReadMiddleware`, `regulationsWriteMiddleware`, `regulationsManageMiddleware` and `regulationsRectifyMiddleware` check the permission; draft-scoped calls (collab ticket, comments, snapshots, rename and delete, rettifiche) use `regulationsAssigneeMiddleware`, which admits any @@ -71,7 +78,7 @@ Every section but Bozze also needs `admin:access`, like the rest of the dashboar `src/features/regulations/regulations.contract.ts` is a verbatim copy of the backend's `src/regulations/contract.ts` (PoliNetworkOrg/backend#110); `regulations.api.server.ts` maps one method to each procedure and parses every response. -Procedures: `me.get`, `documents.list|get|sync|create|upload`, `templates.list`, `versions.list|pdf|upload`, `drafts.list|get|files|create|rename|delete|transition`, +Procedures: `me.get`, `documents.list|get|sync|create|upload`, `templates.list`, `versions.list|pdf|upload`, `drafts.list|get|files|create|rename|delete|reveal|transition`, `assignments.list|set|remove`, `users.search`, `collabTicket`, `compile.status|pdf`, `snapshots.list|get|create|restore`, `comments.list|create|reply|resolve|reopen|delete`, `merge.preview|execute`, `diff.get|regenerate|pdf`, `emanation.get|start|retry`, `deleghe.list|create|revoke`. Files (PDFs) come back as `{ fileName, contentType, base64 }` @@ -110,6 +117,7 @@ one. Logic: `editor/draft-files.ts`. `regulations.fixtures.server.ts`: the RRI with three drafts, two versions, the older one an untagged import labelled as the backend labels it, `import d08cb57`, a delega, a comment; the Guida della Matricola, a documento generale with a published draft and an open one; a private document from the generale template; an uploaded PDF with two versions; +two secret RRI drafts, the agent's (shared with one Socio) and the Presidente's, which the agent never sees; Statuto and Regolamento Elettorale, sola consultazione; a repository document "In creazione" and one whose pull request was closed). A repository document created in agent mode turns active 20 s later, as if its pull request merged; a private documento publishes at once. Version PDFs are compiled from their sources (stand-ins for the `polinetwork-regolamento` and `polinetwork` classes), diff --git a/src/features/regulations/document-page.tsx b/src/features/regulations/document-page.tsx index 42304b6..a8e390e 100644 --- a/src/features/regulations/document-page.tsx +++ b/src/features/regulations/document-page.tsx @@ -38,7 +38,7 @@ import { NewDraftDialog, type NewDraftTarget } from "./new-draft-dialog" import { downloadPdf, PdfDialog, usePdfDialog } from "./pdf-dialog" import { baseLabel, formatDay, versionOrigin } from "./regulations-format" import { failureMessage } from "./regulations-hooks" -import { DraftKindMark, DraftStateBadge } from "./regulations-ui" +import { DraftKindMark, DraftSecretMark, DraftStateBadge } from "./regulations-ui" import type { DocumentInfo, DraftSummary, VersionSummary } from "./regulations.contract" import { getVersionPdf } from "./regulations.functions" import { UploadVersionDialog } from "./upload-version-dialog" @@ -165,6 +165,7 @@ export function DocumentPage({ {draft.title} + ), }, diff --git a/src/features/regulations/drafts-page.tsx b/src/features/regulations/drafts-page.tsx index c42b798..662a88e 100644 --- a/src/features/regulations/drafts-page.tsx +++ b/src/features/regulations/drafts-page.tsx @@ -17,7 +17,7 @@ import { Button } from "@/components/ui/button" import { NewDraftDialog, type NewDraftTarget } from "./new-draft-dialog" import { baseLabel, formatDay, isFinalState, ROLE_LABELS } from "./regulations-format" -import { DraftKindMark, DraftStateBadge } from "./regulations-ui" +import { DraftKindMark, DraftSecretMark, DraftStateBadge } from "./regulations-ui" import type { DocumentInfo, DraftSummary, Me } from "./regulations.contract" type Filter = "open" | "closed" @@ -57,6 +57,7 @@ export function DraftsPage({ drafts, me, documents }: { drafts: DraftSummary[]; {draft.title} + di {draft.createdBy.name} diff --git a/src/features/regulations/editor/editor-page.tsx b/src/features/regulations/editor/editor-page.tsx index 9d1796c..2779959 100644 --- a/src/features/regulations/editor/editor-page.tsx +++ b/src/features/regulations/editor/editor-page.tsx @@ -37,7 +37,7 @@ import { cn } from "@/lib/utils" import { parseDocument, type StructureNode } from "../latex-structure" import { MembersDialog } from "../members-dialog" import { downloadPdf, PdfDialog, usePdfDialog } from "../pdf-dialog" -import { DraftKindMark, DraftStateBadge } from "../regulations-ui" +import { DraftKindMark, DraftSecretMark, DraftStateBadge } from "../regulations-ui" import type { Assignment, CommentThread, @@ -431,6 +431,7 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme

{draft.title}

+ {collab.peers.length > 0 ? ( void - draft: { id: string; title: string } + draft: { id: string; title: string; secret: boolean; createdBy: { id: string } } members: Assignment[] }) { const search = useServerFn(searchRegulationUsers) @@ -161,10 +162,17 @@ export function MembersDialog({ size="lg" title="Membri della bozza" description={ - <> - Chi aggiungi vede «{draft.title}» in Regolamenti › Bozze, anche senza altro accesso alla dashboard. Il - Direttivo legge e modifica sempre ogni bozza. - + draft.secret ? ( + <> + «{draft.title}» è segreta: la vedono solo i membri, in Regolamenti › Bozze, con il ruolo che scegli qui, + anche se sono nel Direttivo. + + ) : ( + <> + Chi aggiungi vede «{draft.title}» in Regolamenti › Bozze, anche senza altro accesso alla dashboard. Il + Direttivo legge e modifica sempre ogni bozza. + + ) } noun="membri" dirty={false} @@ -247,31 +255,35 @@ export function MembersDialog({ {members.map((member) => (
  • - - {busy === `role:${member.user.id}` ? : null} -
    - - changeRole(member, role)} + {draft.secret && member.user.id === draft.createdBy.id ? ( + Editor, l'ha creata + ) : ( + + {busy === `role:${member.user.id}` ? : null} +
    + + changeRole(member, role)} + /> +
    + { + setRemoving(member) + setRemoveOpen(true) + }} /> -
    - { - setRemoving(member) - setRemoveOpen(true) - }} - /> -
    + + )}
  • ))} diff --git a/src/features/regulations/new-draft-dialog.tsx b/src/features/regulations/new-draft-dialog.tsx index 624b6f3..3534fae 100644 --- a/src/features/regulations/new-draft-dialog.tsx +++ b/src/features/regulations/new-draft-dialog.tsx @@ -66,6 +66,7 @@ export function NewDraftDialog({ target.kind === "modifica" && target.from ? `${target.from.kind}:${target.from.id}` : null ) const [title, setTitle] = useState(rettifica ? `Rettifica del ${formatDay(todayInRome())}` : "") + const [secret, setSecret] = useState(false) const [submitted, setSubmitted] = useState(false) // A rettifica starts from the latest version, which `me.rectifiable` names; a modifica lists versions and drafts. @@ -98,6 +99,8 @@ export function NewDraftDialog({ ? `version:${latest.latestVersionId}` : null : (from ?? bases[0]?.value ?? null) + // A draft from a secret draft carries its text: the backend makes it secret too. + const fromSecret = !rettifica && data?.drafts.some((draft) => chosen === `draft:${draft.id}` && draft.secret) const titleError = submitted && !title.trim() ? "Scrivi un titolo." : undefined async function submit() { @@ -108,7 +111,7 @@ export function NewDraftDialog({ const base = kind === "draft" ? { kind: "draft" as const, id } : { kind: "version" as const, id } let created: { id: string } try { - const input = { documentKey, title: title.trim(), from: base } + const input = { documentKey, title: title.trim(), from: base, secret: secret || fromSecret === true } created = rettifica ? await rectify({ data: { ...input, kind: "rettifica" } }) : await create({ data: { ...input, kind: "modifica" } }) @@ -117,7 +120,7 @@ export function NewDraftDialog({ throw new Error(failureMessage(caught, "Non è stato possibile creare la bozza. Riprova."), { cause: caught }) } onOpenChange(false) - appToast.success(rettifica ? "Rettifica creata." : "Bozza creata.") + appToast.success(rettifica ? "Rettifica creata." : secret || fromSecret ? "Bozza segreta creata." : "Bozza creata.") await navigate({ to: "/dashboard/regulations/drafts/$draftId", params: { draftId: created.id } }) } @@ -183,6 +186,28 @@ export function NewDraftDialog({ ))} )} + {fromSecret ? ( +

    + Parte da una bozza segreta, quindi è segreta anche lei: la vedete solo tu e i membri che aggiungi. +

    + ) : ( + setSecret(value === "secret")} + > + + + + )} ) diff --git a/src/features/regulations/procedure-page.tsx b/src/features/regulations/procedure-page.tsx index ea2fbdc..7ccb2a4 100644 --- a/src/features/regulations/procedure-page.tsx +++ b/src/features/regulations/procedure-page.tsx @@ -1,6 +1,6 @@ import { Link, useRouter } from "@tanstack/react-router" import { useServerFn } from "@tanstack/react-start" -import { Check, FileCheck2, FileDiff, GitMerge, Landmark, PenLine, Send, Undo2, Users } from "lucide-react" +import { Check, Eye, FileCheck2, FileDiff, GitMerge, Landmark, PenLine, Send, Undo2, Users } from "lucide-react" import { cloneElement, type ReactElement, type ReactNode, useEffect, useState } from "react" import { @@ -24,7 +24,7 @@ import { ApproveDialog } from "./approve-dialog" import { DraftActions } from "./draft-actions" import { MembersDialog } from "./members-dialog" import { EmanationCard } from "./procedure-emanation" -import { emanateRectification, retryEmanation } from "./regulations-draft.functions" +import { emanateRectification, retryEmanation, revealDraft } from "./regulations-draft.functions" import { BODY_LABELS, baseLabel, @@ -38,7 +38,7 @@ import { } from "./regulations-format" import { failureMessage, useRefreshAfter } from "./regulations-hooks" import { emanateDraft, withdrawApproval } from "./regulations-manage.functions" -import { DraftKindMark, DraftStateBadge } from "./regulations-ui" +import { DraftKindMark, DraftSecretMark, DraftStateBadge } from "./regulations-ui" import { transitionDraft } from "./regulations-write.functions" import type { Assignment, DocumentInfo, Draft, Emanation, StateKey } from "./regulations.contract" import { getEmanation } from "./regulations.functions" @@ -190,12 +190,14 @@ export function ProcedurePage({ const emanate = useServerFn(emanateDraft) const emanateRettifica = useServerFn(emanateRectification) const retry = useServerFn(retryEmanation) + const reveal = useServerFn(revealDraft) const fetchEmanation = useServerFn(getEmanation) const [pendingTransition, setPendingTransition] = useState(null) const [transitionOpen, setTransitionOpen] = useState(false) const [approveOpen, setApproveOpen] = useState(false) const [emanateOpen, setEmanateOpen] = useState(false) + const [revealOpen, setRevealOpen] = useState(false) const [membersOpen, setMembersOpen] = useState(false) const [emanation, setEmanation] = useState(loadedEmanation) const [retrying, setRetrying] = useState(false) @@ -255,6 +257,18 @@ export function ProcedurePage({ await refresh((transitionText(draft.state, to) ?? TRANSITION_TEXT[to]).done) } + async function runReveal() { + try { + await reveal({ data: { draftId: draft.id } }) + } catch (caught) { + console.error(caught) + throw new Error(failureMessage(caught, "Non è stato possibile rendere visibile la bozza. Riprova."), { + cause: caught, + }) + } + await refresh("Bozza resa visibile.") + } + async function runEmanation() { try { await (rettifica ? emanateRettifica : emanate)({ data: { draftId: draft.id } }) @@ -350,13 +364,21 @@ export function ProcedurePage({ <> + } meta={`${KIND_LABELS[draft.kind]} da ${baseLabel(draft.base)} · creata da ${draft.createdBy.name} il ${formatDay(draft.createdAt)}`} /> - {draft.deadlines.length || draft.parses === false ? ( + {draft.deadlines.length || draft.parses === false || draft.secret ? (
    + {draft.secret ? ( + + {draft.can.reveal + ? "Bozza segreta: la vedete solo tu e i membri che aggiungi, non chi ha accesso ai Regolamenti. La procedura parte quando la rendi visibile." + : `Bozza segreta: la vedono solo ${draft.createdBy.name} e i membri che aggiunge, non chi ha accesso ai Regolamenti. La procedura parte quando la rende visibile.`} + + ) : null} {draft.parses === false && draft.state === "bozza" ? ( {documento @@ -388,9 +410,15 @@ export function ProcedurePage({
    - {plain.length || approval || draft.can.emanate || draft.can.emanateBlockedBy ? ( + {plain.length || approval || draft.can.emanate || draft.can.emanateBlockedBy || draft.can.reveal ? (
    + {draft.can.reveal ? ( + + ) : null} {draft.can.emanate ? ( @@ -409,7 +441,7 @@ export function ProcedurePage({ {approval ? ( setApproveOpen(true)} /> ) : null} @@ -417,7 +449,7 @@ export function ProcedurePage({ { setPendingTransition(option) setTransitionOpen(true) @@ -425,14 +457,15 @@ export function ProcedurePage({ /> ))}
    - {draft.can.emanateBlockedBy ? ( + {/* A secret draft's reason is the alert above; the buttons keep it as their hint. */} + {draft.can.emanateBlockedBy && !draft.secret ? (

    {emanateLabel}:{" "} {draft.can.emanateBlockedBy}

    ) : null} {[approval, ...plain].map((option) => - option?.blockedBy ? ( + option?.blockedBy && !draft.secret ? (

    {option.label}: {option.blockedBy}

    @@ -562,6 +595,19 @@ export function ProcedurePage({ icon={EmanateIcon} onConfirm={runEmanation} /> + {draft.can.reveal ? ( + + ) : null} {draft.can.assign ? ( diff --git a/src/features/regulations/regulations-draft.functions.ts b/src/features/regulations/regulations-draft.functions.ts index 7ba4584..6dff2a2 100644 --- a/src/features/regulations/regulations-draft.functions.ts +++ b/src/features/regulations/regulations-draft.functions.ts @@ -44,3 +44,9 @@ export const retryEmanation = createServerFn({ method: "POST" }) .middleware([regulationsAssigneeMiddleware]) .validator(draftRefInputSchema) .handler(async ({ data, context }) => (await regulationsApi(context)).retryEmanation(data)) + +/** "Rendi visibile": a secret draft opens to `regulations:read` and its procedure, for good. Its creator only. */ +export const revealDraft = createServerFn({ method: "POST" }) + .middleware([regulationsAssigneeMiddleware]) + .validator(draftRefInputSchema) + .handler(async ({ data, context }) => (await regulationsApi(context)).revealDraft(data)) diff --git a/src/features/regulations/regulations-ui.tsx b/src/features/regulations/regulations-ui.tsx index 39015bf..370e8be 100644 --- a/src/features/regulations/regulations-ui.tsx +++ b/src/features/regulations/regulations-ui.tsx @@ -1,3 +1,5 @@ +import { EyeOff } from "lucide-react" + import { StatusBadge } from "@/components/primitives" import { KIND_LABELS, STATE_LABELS, STATE_TONES } from "./regulations-format" @@ -17,3 +19,14 @@ export function DraftKindMark({ kind }: { kind: DraftKind }) { ) } + +/** "Segreta" next to a title: only its creator and their members see the draft. */ +export function DraftSecretMark({ secret }: { secret: boolean }) { + if (!secret) return null + return ( + + + Segreta + + ) +} diff --git a/src/features/regulations/regulations.api.server.ts b/src/features/regulations/regulations.api.server.ts index ee1de94..c6acff1 100644 --- a/src/features/regulations/regulations.api.server.ts +++ b/src/features/regulations/regulations.api.server.ts @@ -92,6 +92,8 @@ export type RegulationsApi = { createDraft: (input: In) => Promise<{ id: string }> renameDraft: (input: In) => Promise deleteDraft: (input: DraftRef) => Promise + /** A secret draft becomes visible to `regulations:read`, for good: its creator only. */ + revealDraft: (input: DraftRef) => Promise transition: (input: In) => Promise listAssignments: (input: DraftRef) => Promise setAssignment: (input: In) => Promise @@ -166,6 +168,7 @@ export function backendRegulationsApi(accessToken: string | null): RegulationsAp createDraft: async (input) => createdSchema.parse(await client.mutation("regulations.drafts.create", input)), renameDraft: (input) => mutate("drafts.rename", input), deleteDraft: (input) => mutate("drafts.delete", input), + revealDraft: (input) => mutate("drafts.reveal", input), transition: (input) => mutate("drafts.transition", input), listAssignments: (input) => query("assignments.list", input, assignmentSchema.array()), setAssignment: (input) => mutate("assignments.set", input), diff --git a/src/features/regulations/regulations.contract.ts b/src/features/regulations/regulations.contract.ts index 8b6ff4d..b44c79b 100644 --- a/src/features/regulations/regulations.contract.ts +++ b/src/features/regulations/regulations.contract.ts @@ -2,7 +2,7 @@ import { z } from "zod" /** * The `regulations.*` backend contract (docs/regulations/README.md), a verbatim copy of the backend's - * `src/regulations/contract.ts` (PoliNetworkOrg/backend#153, 2744322). Agent mode answers from + * `src/regulations/contract.ts` (PoliNetworkOrg/backend#155). Agent mode answers from * `regulations.fake.server.ts`; real responses are parsed with these schemas before they reach a page. Keep both * copies in step. * @@ -397,8 +397,16 @@ export const draftSummarySchema = z.object({ kind: draftKindSchema, state: stateKeySchema, base: draftBaseSchema, - /** The caller's effective role: `regulations:write` is always `editor`, `regulations:read` at least `viewer`. */ + /** + * The caller's effective role: `regulations:write` is always `editor`, `regulations:read` at least `viewer`. In a + * secret draft only the creator (`editor`) and the members they add, with the role they were given. + */ myRole: draftRoleSchema, + /** + * A secret draft: only its creator and the members they add see it, and its procedure is closed until the creator + * makes it visible to `regulations:read` (`drafts.reveal`), for good. + */ + secret: z.boolean(), createdBy: personRefSchema, createdAt: z.string(), updatedAt: z.string(), @@ -455,6 +463,8 @@ export const capabilitiesSchema = z.object({ rename: z.boolean(), snapshot: z.boolean(), restore: z.boolean(), + /** Make the secret draft visible (`drafts.reveal`): its creator only. */ + reveal: z.boolean(), }) export type Capabilities = z.infer @@ -485,6 +495,8 @@ export const createDraftInputSchema = z.object({ z.object({ kind: z.literal("draft"), id: draftIdSchema }), ]), kind: draftKindSchema.default("modifica"), + /** Start it secret. A draft from a secret draft is always secret. */ + secret: z.boolean().default(false), }) export const renameDraftInputSchema = z.object({ draftId: draftIdSchema, title: z.string().trim().min(1).max(120) }) export const listDraftsInputSchema = z.object({ diff --git a/src/features/regulations/regulations.fake.server.ts b/src/features/regulations/regulations.fake.server.ts index 0ea4556..b2b0f1c 100644 --- a/src/features/regulations/regulations.fake.server.ts +++ b/src/features/regulations/regulations.fake.server.ts @@ -65,6 +65,8 @@ const DOCUMENT_KEY = "rri" /** How long a repository document created here waits for its (imaginary) pull request to merge. */ const CREATION_MS = 20_000 const AGENT_ID = "agent-preview-user" +const SECRET_BLOCK = "La bozza è segreta: rendila visibile prima di avviare la procedura." +const CREATOR_STAYS = "Chi ha creato la bozza segreta ne resta editor." const STEP_MS = 2500 const DIFF_DELAY_MS = 2500 const AUTO_SNAPSHOT_MS = 5 * 60_000 @@ -236,6 +238,7 @@ function buildStore(): Store { kind: "modifica", state: "bozza", base: versionBase, + secret: false, createdBy: direttivo, createdAt: daysAgo(9), updatedAt: daysAgo(1), @@ -316,7 +319,29 @@ function buildStore(): Store { diff: { generation: 1, requestedAt: Date.parse("2026-03-10T10:00:00.000Z"), by: null }, emanation: { startedAt: Date.parse("2026-03-13T09:10:00.000Z"), startedBy: segretario, delegaId: null }, }) - for (const stored of [fondamentale, condotta, emanated]) + // Secret: the agent's, shared with one Socio, and the Presidente's, which nobody else sees. + const riservata = draft({ + id: "quote-riservata", + title: "Quote associative: proposta riservata", + secret: true, + createdBy: agent, + createdAt: daysAgo(3), + updatedAt: daysAgo(2), + stateChangedAt: daysAgo(3), + files: edit(PUBLISHED_FILES, "regolamenti/fondamentale.tex", (text) => + text.replace("entro \\textbf{trenta giorni}", "entro \\textbf{sessanta giorni}") + ), + assignments: [assign(agent, "editor", agent), assign(user("u-socio-1"), "commenter", agent)], + }) + const presidenza = draft({ + id: "presidenza-segreta", + title: "Riorganizzazione della Presidenza", + secret: true, + createdBy: presidente, + files: PUBLISHED_FILES, + assignments: [assign(presidente, "editor", presidente)], + }) + for (const stored of [fondamentale, condotta, emanated, riservata, presidenza]) stored.snapshots.push({ id: newId(), draftId: stored.id, @@ -367,7 +392,7 @@ function buildStore(): Store { ...others.documents, ], versions: [latest, old, ...others.versions], - drafts: [fondamentale, condotta, emanated, ...others.drafts], + drafts: [fondamentale, condotta, riservata, presidenza, emanated, ...others.drafts], deleghe: [ { id: newId(), @@ -915,7 +940,14 @@ function api(viewer: RegulationsViewer): RegulationsApi { ) ?? null const mayRectify = (documentKey: string) => can("regulations:rectify") || delegaFor(documentKey) !== null + const isCreator = (draft: StoredDraft) => draft.createdBy.id === me.id + function roleOf(draft: StoredDraft): DraftRole | null { + // A secret draft: its creator and the members they added, whatever their permissions. + if (draft.secret) + return isCreator(draft) + ? "editor" + : (draft.assignments.find((assignment) => assignment.user.id === me.id)?.role ?? null) if (can("regulations:write")) return "editor" const assigned = draft.assignments.find((assignment) => assignment.user.id === me.id)?.role if (assigned) return assigned @@ -942,7 +974,26 @@ function api(viewer: RegulationsViewer): RegulationsApi { ) } + /** As the backend: a secret draft's procedure stays closed, and only its creator manages it. */ function capabilities(draft: StoredDraft, role: DraftRole): Capabilities { + const open = procedureCapabilities(draft, role) + if (!draft.secret) return { ...open, reveal: false } + return { + ...open, + assign: isCreator(draft) && !isFinal(draft.state), + merge: open.merge && role === "editor", + transitions: open.transitions.map((transition) => ({ ...transition, blockedBy: SECRET_BLOCK })), + approve: false, + emanate: false, + emanateBlockedBy: open.emanate || open.emanateBlockedBy ? SECRET_BLOCK : null, + regenerateDiff: false, + delete: isCreator(draft) && draft.state === "bozza" && draft.emanation === null, + rename: role === "editor" && !isFinal(draft.state), + reveal: isCreator(draft), + } + } + + function procedureCapabilities(draft: StoredDraft, role: DraftRole): Omit { const procedure = procedureOf(draft.documentKey) const editable = procedure.states.find((state) => state.key === draft.state)?.editable ?? false const emanating = draft.emanation !== null && !isFinal(draft.state) @@ -1030,6 +1081,13 @@ function api(viewer: RegulationsViewer): RegulationsApi { } } + /** Its members may not be this draft's. */ + function secretBase(base: DraftBase): DraftBase { + if (base.kind !== "draft") return base + const parent = store().drafts.find((candidate) => candidate.id === base.id) + return parent?.secret ? { ...base, title: "Bozza segreta" } : base + } + function summary(draft: StoredDraft, role: DraftRole): DraftSummary { return { id: draft.id, @@ -1037,8 +1095,9 @@ function api(viewer: RegulationsViewer): RegulationsApi { title: draft.title, kind: draft.kind, state: draft.state, - base: draft.base, + base: secretBase(draft.base), myRole: role, + secret: draft.secret, createdBy: draft.createdBy, createdAt: draft.createdAt, updatedAt: draft.updatedAt, @@ -1405,7 +1464,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { const { draft } = visible(draftId) return { files: draft.files, structure: draftStructure(draft), sources: sourcesOf(draft.documentKey) } }, - async createDraft({ documentKey, title, from, kind = "modifica" }) { + async createDraft({ documentKey, title, from, kind = "modifica", secret = false }) { const document = documentOf(documentKey) const blocked = notEditableReason(document) if (blocked) refuse(blocked) @@ -1415,7 +1474,9 @@ function api(viewer: RegulationsViewer): RegulationsApi { const source = from.kind === "version" ? store().versions.find((version) => version.id === from.id && version.documentKey === documentKey) - : store().drafts.find((draft) => draft.id === from.id && !draft.deleted && draft.documentKey === documentKey) + : store().drafts.find( + (draft) => draft.id === from.id && !draft.deleted && draft.documentKey === documentKey && roleOf(draft) + ) if (!source) return refuse("La base scelta non esiste.") const [latest] = versionsOf(documentKey) if (kind === "rettifica" && from.id !== latest?.id) refuse("Una rettifica parte dall'ultima versione emanata.") @@ -1430,6 +1491,8 @@ function api(viewer: RegulationsViewer): RegulationsApi { from.kind === "version" ? { kind: "version", id: from.id, label: "label" in source ? source.label : from.id } : { kind: "draft", id: from.id, title: "title" in source ? source.title : from.id }, + // A draft from a secret draft would show its text: it is secret too. + secret: secret || ("secret" in source && source.secret), createdBy: me, createdAt: now(), updatedAt: now(), @@ -1438,7 +1501,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { entry: document.entry, files: source.files, baseFiles: source.files, - assignments: [], + assignments: [{ user: me, role: "editor", assignedBy: me, assignedAt: now() }], comments: [], seedComments: [], snapshots: [], @@ -1468,6 +1531,13 @@ function api(viewer: RegulationsViewer): RegulationsApi { if (!capabilities(draft, role).rename) refuse("Non puoi rinominare questa bozza.") draft.title = title }, + async revealDraft({ draftId }) { + const { draft } = visible(draftId) + if (!draft.secret) refuse("La bozza è già visibile.") + if (!isCreator(draft)) refuse("Solo chi ha creato la bozza segreta la rende visibile.") + draft.secret = false + draft.updatedAt = now() + }, async deleteDraft({ draftId }) { const { draft, role } = visible(draftId) if (!capabilities(draft, role).delete) refuse("Solo una bozza può essere eliminata.") @@ -1504,6 +1574,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { async setAssignment({ draftId, userId, role: assigned }) { const { draft, role } = visible(draftId) if (!capabilities(draft, role).assign) refuse("Non puoi assegnare questa bozza.") + if (draft.secret && userId === draft.createdBy.id) refuse(CREATOR_STAYS) const target = [...FAKE_USERS, { id: AGENT_ID, name: "Preview Agent", email: "agent@polinetwork.org" }].find( (candidate) => candidate.id === userId ) @@ -1515,6 +1586,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { async removeAssignment({ draftId, userId }) { const { draft, role } = visible(draftId) if (!capabilities(draft, role).assign) refuse("Non puoi assegnare questa bozza.") + if (draft.secret && userId === draft.createdBy.id) refuse(CREATOR_STAYS) draft.assignments = draft.assignments.filter((assignment) => assignment.user.id !== userId) }, async searchUsers({ q }) { @@ -1778,7 +1850,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { procedure: document.procedureKey ? PROCEDURES[document.procedureKey] : null, editable: notEditableReason(document) === null, latestVersion: latest ? versionSummary(latest) : null, - openDrafts: drafts.filter((draft) => !isFinal(draft.state)).length, + openDrafts: drafts.filter((draft) => !draft.secret && !isFinal(draft.state)).length, inApproval: current ? { id: current.id, title: current.title } : null, } } diff --git a/tests/server-security.test.mjs b/tests/server-security.test.mjs index dc5fcb4..209cee8 100644 --- a/tests/server-security.test.mjs +++ b/tests/server-security.test.mjs @@ -500,6 +500,7 @@ test("event handlers integrate protected server-function redirects with the rout "emanateDraft", "emanateRectification", "retryEmanation", + "revealDraft", ], "src/features/regulations/approve-dialog.tsx": ["approveDraft"], "src/features/regulations/diff-page.tsx": ["regenerateDiff"],