diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index cf351a39b9..00675e9f33 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -1430,7 +1430,12 @@ export const restoreDocument = createAction({ ? context.stores.collections.get(document.collectionId) : undefined; const can = context.stores.policies.abilities(document.id); - return !!collection?.isActive && !!(can.restore || can.unarchive); + // Documents outside any collection, such as private documents, are + // restored in place. + const collectionActive = document.collectionId + ? !!collection?.isActive + : true; + return collectionActive && !!(can.restore || can.unarchive); }), perform: (context) => performBatchOnActiveModels( @@ -1464,7 +1469,11 @@ export const restoreDocumentToCollection = createActionWithChildren({ ? stores.collections.get(document.collectionId) : undefined; - return !collection?.isActive && !!(can.restore || can.unarchive); + return ( + !!document.collectionId && + !collection?.isActive && + !!(can.restore || can.unarchive) + ); }, children: ({ t, activeDocumentId, stores }) => { const { collections, documents, policies } = stores; @@ -1742,8 +1751,13 @@ export const leaveDocument = createAction({ const membership = stores.userMemberships.orderedData.find( (m) => m.documentId === activeDocumentId && m.userId === currentUserId ); + if (!membership || !activeDocumentId) { + return false; + } - return !!membership; + // The creator cannot leave their own private document. + const document = stores.documents.get(activeDocumentId); + return !(document?.isPrivate && document.createdBy?.id === currentUserId); }, perform: async ({ t, location, currentUserId, activeDocumentId, stores }) => { if (!activeDocumentId) { diff --git a/app/components/DocumentExplorer/DocumentMove.tsx b/app/components/DocumentExplorer/DocumentMove.tsx index 80d9640a47..c90ee4c334 100644 --- a/app/components/DocumentExplorer/DocumentMove.tsx +++ b/app/components/DocumentExplorer/DocumentMove.tsx @@ -8,6 +8,9 @@ import type Document from "~/models/Document"; import Button from "~/components/Button"; import Text from "~/components/Text"; import useCollectionTrees from "~/hooks/useCollectionTrees"; +import usePrivateDocumentsTree, { + PRIVATE_TREE_ID, +} from "~/hooks/usePrivateDocumentsTree"; import useStores from "~/hooks/useStores"; import { FlexContainer, Footer } from "./Components"; import DocumentExplorer from "./DocumentExplorer"; @@ -20,14 +23,19 @@ function DocumentMove({ document }: Props) { const { dialogs, policies } = useStores(); const { t } = useTranslation(); const collectionTrees = useCollectionTrees(); + const privateTree = usePrivateDocumentsTree(); const [moving, setMoving] = useState(false); const [selectedPath, selectPath] = useState(null); const items = useMemo(() => { + const trees = privateTree + ? [...collectionTrees, privateTree] + : collectionTrees; + // Collect the IDs of the document itself and all of its descendants so they // can be excluded from the move targets (moving to self or a descendant // would create a cycle; moving to the exact same location is a no-op). - const allNodes = collectionTrees.flatMap(flattenTree); + const allNodes = trees.flatMap(flattenTree); const sourceNode = allNodes.find((node) => node.id === document.id); const excludedIds = new Set([document.id]); if (sourceNode) { @@ -44,7 +52,7 @@ function DocumentMove({ document }: Props) { .map(filterSourceDocument), }); - const nodes = collectionTrees + const nodes = trees .map(filterSourceDocument) // Filter out collections that we don't have permission to create documents in. .filter((node) => @@ -54,7 +62,7 @@ function DocumentMove({ document }: Props) { ); return nodes; - }, [policies, collectionTrees, document.id]); + }, [policies, collectionTrees, privateTree, document.id]); const move = async (path = selectedPath) => { if (!path) { @@ -64,14 +72,19 @@ function DocumentMove({ document }: Props) { try { setMoving(true); - const { type, id: parentDocumentId } = path; - const collectionId = path.collectionId as string; - - if (type === "document") { - await document.move({ collectionId, parentDocumentId }); + if (path.id === PRIVATE_TREE_ID) { + await document.move({ private: true }); } else { - await document.move({ collectionId }); + const { type, id: parentDocumentId } = path; + + const collectionId = path.collectionId as string; + + if (type === "document") { + await document.move({ collectionId, parentDocumentId }); + } else { + await document.move({ collectionId }); + } } toast.success(t("Document moved")); diff --git a/app/components/Sharing/Document/AccessControlList.tsx b/app/components/Sharing/Document/AccessControlList.tsx index 890f57ce1e..7856fce0ba 100644 --- a/app/components/Sharing/Document/AccessControlList.tsx +++ b/app/components/Sharing/Document/AccessControlList.tsx @@ -1,5 +1,10 @@ import { observer } from "mobx-react"; -import { MoreIcon, QuestionMarkIcon, UserIcon } from "outline-icons"; +import { + MoreIcon, + PadlockIcon, + QuestionMarkIcon, + UserIcon, +} from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled, { useTheme } from "styled-components"; @@ -158,6 +163,26 @@ export const AccessControlList = observer( /> )} + ) : document.isPrivate && !document.parentDocumentId ? ( + <> + {showLoading ? ( + + ) : ( + + )} + + + + } + title={t("Private")} + subtitle={t("Only people invited to this document have access")} + /> + ) : ( <> {showLoading ? ( diff --git a/app/components/Sidebar/components/PrivateDocs.tsx b/app/components/Sidebar/components/PrivateDocs.tsx index d19387093d..54d37afabe 100644 --- a/app/components/Sidebar/components/PrivateDocs.tsx +++ b/app/components/Sidebar/components/PrivateDocs.tsx @@ -52,7 +52,11 @@ function PrivateDocs() { }, [error, t]); useEffect(() => { - if (!ui.activeDocumentId || locationSidebarContext === "private") { + if ( + !ui.activeDocumentId || + locationSidebarContext === "private" || + locationSidebarContext?.startsWith("starred") + ) { return; } diff --git a/app/components/Sidebar/components/SharedWithMe.tsx b/app/components/Sidebar/components/SharedWithMe.tsx index ab8a686208..2085cbe6d7 100644 --- a/app/components/Sidebar/components/SharedWithMe.tsx +++ b/app/components/Sidebar/components/SharedWithMe.tsx @@ -54,7 +54,11 @@ function SharedWithMe() { locationSidebarContext === "shared" || locationSidebarContext?.startsWith("group"); - if (!ui.activeDocumentId || isContextInSharedSection) { + if ( + !ui.activeDocumentId || + isContextInSharedSection || + locationSidebarContext?.startsWith("starred") + ) { return; } diff --git a/app/hooks/usePrivateDocumentsTree.ts b/app/hooks/usePrivateDocumentsTree.ts new file mode 100644 index 0000000000..6baba43fe8 --- /dev/null +++ b/app/hooks/usePrivateDocumentsTree.ts @@ -0,0 +1,93 @@ +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import type { NavigationNode } from "@shared/types"; +import { NavigationNodeType } from "@shared/types"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; +import usePolicy from "~/hooks/usePolicy"; +import useStores from "~/hooks/useStores"; + +/** Sentinel id used for the private section root in document pickers. */ +export const PRIVATE_TREE_ID = "$private"; + +/** + * React hook that builds a synthetic navigation tree of the user's private + * documents, for use as a destination in document pickers. + * + * @returns the root node of the private tree, or null when the user cannot + * create private documents. + */ +export default function usePrivateDocumentsTree(): NavigationNode | null { + const { documents } = useStores(); + const { t } = useTranslation(); + const team = useCurrentTeam(); + const user = useCurrentUser(); + const can = usePolicy(team); + const memberships = user.privateDocumentMemberships; + + return useMemo(() => { + if (!can.createPrivateDocument) { + return null; + } + + // Collection trees are rooted at depth 1, see useCollectionTrees. + const root: NavigationNode = { + id: PRIVATE_TREE_ID, + title: t("Private"), + icon: "padlock", + url: "", + children: [], + depth: 1, + parent: null, + }; + + const buildNode = ( + node: NavigationNode, + parent: NavigationNode, + depth: number + ): NavigationNode => { + const doc = documents.get(node.id); + const built: NavigationNode = { + id: node.id, + title: doc?.title ?? node.title, + url: doc?.url ?? node.url, + icon: doc?.icon ?? node.icon, + color: doc?.color ?? node.color, + type: NavigationNodeType.Document, + depth, + parent, + children: [], + }; + built.children = (node.children ?? []).map((child) => + buildNode(child, built, depth + 1) + ); + return built; + }; + + root.children = memberships.flatMap((membership) => { + const doc = membership.documentId + ? documents.get(membership.documentId) + : undefined; + if (!doc) { + return []; + } + + return [ + buildNode( + { + id: doc.id, + title: doc.title, + url: doc.url, + icon: doc.icon ?? undefined, + color: doc.color ?? undefined, + children: membership.documents ?? [], + }, + root, + 2 + ), + ]; + }); + + return root; + }, [can.createPrivateDocument, memberships, documents, t]); +} diff --git a/app/models/Document.ts b/app/models/Document.ts index 88d77c10a9..f76c6caaad 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -603,6 +603,7 @@ export default class Document extends ArchivableModel implements Searchable { move = (options: { collectionId?: string | null; parentDocumentId?: string; + private?: boolean; }) => this.store.move({ documentId: this.id, ...options }); duplicate = (options?: { diff --git a/app/scenes/DocumentPublish.tsx b/app/scenes/DocumentPublish.tsx index a80fd18212..d92b85813f 100644 --- a/app/scenes/DocumentPublish.tsx +++ b/app/scenes/DocumentPublish.tsx @@ -11,6 +11,9 @@ import DocumentExplorer from "~/components/DocumentExplorer"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; import useCollectionTrees from "~/hooks/useCollectionTrees"; +import usePrivateDocumentsTree, { + PRIVATE_TREE_ID, +} from "~/hooks/usePrivateDocumentsTree"; import useStores from "~/hooks/useStores"; type Props = { @@ -22,16 +25,16 @@ function DocumentPublish({ document }: Props) { const { dialogs, policies } = useStores(); const { t } = useTranslation(); const collectionTrees = useCollectionTrees(); + const privateTree = usePrivateDocumentsTree(); const [selectedPath, selectPath] = useState(null); - const publishOptions = useMemo( - () => - collectionTrees.filter((node) => - node.collectionId - ? policies.get(node.collectionId)?.abilities.createDocument - : true - ), - [policies, collectionTrees] - ); + const publishOptions = useMemo(() => { + const nodes = collectionTrees.filter((node) => + node.collectionId + ? policies.get(node.collectionId)?.abilities.createDocument + : true + ); + return privateTree ? [...nodes, privateTree] : nodes; + }, [policies, collectionTrees, privateTree]); const publish = async (path = selectedPath) => { if (!path) { @@ -40,6 +43,14 @@ function DocumentPublish({ document }: Props) { } try { + if (path.id === PRIVATE_TREE_ID) { + await document.save(undefined, { publish: true, private: true }); + + toast.success(t("Document published")); + dialogs.closeAllModals(); + return; + } + const { type, id: parentDocumentId } = path; const collectionId = path.collectionId as string; diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index c35ea6d207..2938c2c66f 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -512,20 +512,25 @@ export default class DocumentsStore extends Store { documentId, collectionId, parentDocumentId, + private: isPrivate, index, }: { documentId: string; collectionId?: string | null; parentDocumentId?: string | null; + private?: boolean; index?: number | null; }) => { this.movingDocumentId = documentId; + const previousMembership = + this.rootStore.userMemberships.getByDocumentId(documentId); try { const res = await client.post("/documents.move", { id: documentId, collectionId, parentDocumentId, + private: isPrivate, index, }); invariant(res?.data, "Data not available"); @@ -548,6 +553,14 @@ export default class DocumentsStore extends Store { if (parentMembership && parentMembership.id !== membership?.id) { await parentMembership.fetchDocuments({ force: true }); } + + if ( + previousMembership && + previousMembership.id !== membership?.id && + previousMembership.id !== parentMembership?.id + ) { + await previousMembership.fetchDocuments({ force: true }); + } } finally { this.movingDocumentId = undefined; } diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts index f3a1f44c84..073c964f2a 100644 --- a/server/commands/documentCreator.ts +++ b/server/commands/documentCreator.ts @@ -138,6 +138,11 @@ export async function authorizeDocumentPublish( authorize(user, "publish", document); } + if (options?.private && !collectionId) { + authorize(user, "createPrivateDocument", user.team); + return null; + } + if (document.parentDocumentId) { if (!document.collectionId && collectionId) { collection = await Collection.findByPk(collectionId, { @@ -153,11 +158,6 @@ export async function authorizeDocumentPublish( return collection; } - if (options?.private && !document.collectionId && !collectionId) { - authorize(user, "createPrivateDocument", user.team); - return null; - } - if (!document.collectionId) { assertPresent( collectionId, diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 28c8284661..b424b7a5bd 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -1,6 +1,7 @@ import { Transaction } from "sequelize"; +import { createPrivateDocumentMembership } from "@server/commands/documentCreator"; import { traceFunction } from "@server/logging/tracing"; -import { Document, Collection, Pin } from "@server/models"; +import { Document, Collection, Pin, UserMembership } from "@server/models"; import type { APIContext } from "@server/types"; type Props = { @@ -10,6 +11,8 @@ type Props = { collectionId: string | null; /** ID of parent under which the document is moved */ parentDocumentId?: string | null; + /** Whether the document is being moved to be private, outside any collection */ + private?: boolean; /** Position of moved document within document structure */ index?: number; }; @@ -26,6 +29,7 @@ async function documentMover( document, collectionId, parentDocumentId = null, + private: isPrivate, // convert undefined to null so parentId comparison treats them as equal index, }: Props @@ -140,6 +144,19 @@ async function documentMover( }, } ); + } else if (isPrivate) { + // document stays published and keeps its tree, outside any collection + await Document.update( + { + collectionId: null, + }, + { + transaction, + where: { + id: childDocumentIds, + }, + } + ); } else { // document will be moved to drafts document.publishedAt = null; @@ -192,6 +209,21 @@ async function documentMover( await pin?.destroyWithCtx(ctx); } + // A private document is anchored to the mover through a root membership. + if (isPrivate) { + const existing = await UserMembership.findOne({ + where: { + documentId: document.id, + userId: user.id, + sourceId: null, + }, + transaction, + }); + if (!existing) { + await createPrivateDocumentMembership(ctx, document); + } + } + result.documents.push(document); await document.saveWithCtx(ctx, undefined, { diff --git a/server/commands/documentRestorer.ts b/server/commands/documentRestorer.ts index 390f0ca2ac..86ddecf027 100644 --- a/server/commands/documentRestorer.ts +++ b/server/commands/documentRestorer.ts @@ -53,13 +53,13 @@ async function documentRestorer( }) : undefined; - if (!destCollection?.isActive) { + if (destCollectionId && !destCollection?.isActive) { throw ValidationError( "Unable to restore, the collection may have been deleted or archived" ); } - if (sourceCollectionId && sourceCollectionId !== destCollection.id) { + if (sourceCollectionId && sourceCollectionId !== destCollection?.id) { authorize(user, "updateDocument", srcCollection); await srcCollection?.removeDocumentInStructure(document, { save: true, @@ -69,16 +69,20 @@ async function documentRestorer( if (document.deletedAt) { authorize(user, "restore", document); - authorize(user, "updateDocument", destCollection); + if (destCollection) { + authorize(user, "updateDocument", destCollection); + } // restore a previously deleted document - await document.restoreTo(ctx, { collectionId: destCollection.id }); + await document.restoreTo(ctx, { collectionId: destCollection?.id ?? null }); } else if (document.archivedAt) { authorize(user, "unarchive", document); - authorize(user, "updateDocument", destCollection); + if (destCollection) { + authorize(user, "updateDocument", destCollection); + } // restore a previously archived document - await document.restoreTo(ctx, { collectionId: destCollection.id }); + await document.restoreTo(ctx, { collectionId: destCollection?.id ?? null }); } else if (revisionId) { // restore a document to a specific revision authorize(user, "update", document); diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index 23ca006cb8..1aa93b10a1 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -136,16 +136,17 @@ export default async function documentUpdater( data: eventData, }; - if (publish && (cId || isPrivate || document.parentDocumentId)) { - const wasDraft = !document.publishedAt; + if (publish && isPrivate && !collectionId && !document.publishedAt) { + // publishing a draft privately detaches it from any collection or parent + document.collectionId = null; + document.parentDocumentId = null; + await document.publish(ctx, { collectionId: null, data: eventData }); + await createPrivateDocumentMembership(ctx, document); + } else if (publish && (cId || document.parentDocumentId)) { if (!document.collectionId && cId) { document.collectionId = cId; } await document.publish(ctx, { collectionId: cId ?? null, data: eventData }); - - if (isPrivate && !cId && wasDraft) { - await createPrivateDocumentMembership(ctx, document); - } } else if (changed) { document.lastModifiedById = user.id; document.updatedBy = user; diff --git a/server/models/Document.ts b/server/models/Document.ts index c96e81818d..e714513615 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -1348,7 +1348,7 @@ class Document extends ArchivableModel< // Restore an archived document back to being visible to the team restoreTo = async ( ctx: APIContext, - { collectionId }: { collectionId: string } + { collectionId }: { collectionId: string | null } ) => { const { transaction } = ctx.state; const collection = collectionId @@ -1498,7 +1498,7 @@ class Document extends ArchivableModel< private restoreArchivedWithChildren = async ( ctx: APIContext, - { collectionId }: { collectionId: string } + { collectionId }: { collectionId: string | null } ) => { const { user } = ctx.state.auth; const { transaction } = ctx.state; diff --git a/server/policies/document.ts b/server/policies/document.ts index 9dc82a5796..40575cf9c6 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -24,7 +24,7 @@ allow(User, "createPrivateDocument", Team, (actor, team) => !actor.isViewer, isTeamModel(actor, team), isTeamMutable(actor), - !!actor.team.getPreference(TeamPreference.PrivateDocs) + !!team?.getPreference(TeamPreference.PrivateDocs) ) ); diff --git a/server/queues/processors/DocumentMovedProcessor.test.ts b/server/queues/processors/DocumentMovedProcessor.test.ts index a62a9b3698..dd28d4f522 100644 --- a/server/queues/processors/DocumentMovedProcessor.test.ts +++ b/server/queues/processors/DocumentMovedProcessor.test.ts @@ -702,4 +702,52 @@ describe("DocumentMovedProcessor", () => { expect(parentMemberships.length).toBe(1); expect(parentMemberships[0].id).toBe(parentMembership.id); }); + + it("should recreate sourced memberships from the moved document's own root memberships", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + + const parent = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: null, + publishedAt: new Date(), + }); + const child = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: null, + parentDocumentId: parent.id, + publishedAt: new Date(), + }); + + // the root membership cascades a sourced membership to the child + const rootMembership = await UserMembership.create({ + userId: user.id, + documentId: parent.id, + permission: DocumentPermission.Admin, + index: "a", + createdById: user.id, + }); + + const processor = new DocumentMovedProcessor(); + await processor.perform({ + name: "documents.move", + documentId: parent.id, + collectionId: parent.collectionId!, + teamId: team.id, + actorId: user.id, + ip, + data: { + collectionIds: [], + documentIds: [parent.id], + }, + }); + + const childMemberships = await UserMembership.findAll({ + where: { documentId: child.id, userId: user.id }, + }); + expect(childMemberships.length).toBe(1); + expect(childMemberships[0].sourceId).toBe(rootMembership.id); + }); }); diff --git a/server/queues/processors/DocumentMovedProcessor.ts b/server/queues/processors/DocumentMovedProcessor.ts index cd1b2d8df1..ba3dfd0d7d 100644 --- a/server/queues/processors/DocumentMovedProcessor.ts +++ b/server/queues/processors/DocumentMovedProcessor.ts @@ -59,6 +59,22 @@ export default class DocumentMovedProcessor extends BaseProcessor { document.id ); + // Root memberships on the moved document itself cascade to its children, + // so they must be recreated as well. + const [ownUserMemberships, ownGroupMemberships] = await Promise.all([ + UserMembership.findAll({ + where: { documentId: document.id, sourceId: { [Op.eq]: null } }, + transaction, + }), + GroupMembership.findAll({ + where: { documentId: document.id, sourceId: { [Op.eq]: null } }, + transaction, + }), + ]); + + await this.recalculateUserMemberships(ownUserMemberships, transaction); + await this.recalculateGroupMemberships(ownGroupMemberships, transaction); + await this.destroyRedundantRootMemberships(document, event, transaction); }); } diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 0762226d2c..4f0930f7c2 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -6697,3 +6697,187 @@ describe("#documents.documents - private", () => { expect(treeBody.data.children[0].id).toEqual(childBody.data.id); }); }); + +describe("#documents.restore - private", () => { + it("should restore an archived private document in place", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.create", user, { + body: { + title: "Private notes", + private: true, + publish: true, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + + const archiveRes = await server.post("/api/documents.archive", user, { + body: { id: body.data.id }, + }); + expect(archiveRes.status).toEqual(200); + + const restoreRes = await server.post("/api/documents.restore", user, { + body: { id: body.data.id }, + }); + const restoreBody = await restoreRes.json(); + expect(restoreRes.status).toEqual(200); + expect(restoreBody.data.archivedAt).toBeNull(); + expect(restoreBody.data.collectionId).toBeNull(); + expect(restoreBody.data.publishedAt).toBeTruthy(); + }); + + it("should restore a deleted private document in place", async () => { + const user = await buildUser(); + const res = await server.post("/api/documents.create", user, { + body: { + title: "Private notes", + private: true, + publish: true, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + + const deleteRes = await server.post("/api/documents.delete", user, { + body: { id: body.data.id }, + }); + expect(deleteRes.status).toEqual(200); + + const restoreRes = await server.post("/api/documents.restore", user, { + body: { id: body.data.id }, + }); + const restoreBody = await restoreRes.json(); + expect(restoreRes.status).toEqual(200); + expect(restoreBody.data.deletedAt).toBeNull(); + expect(restoreBody.data.collectionId).toBeNull(); + }); +}); + +describe("#documents.move - private", () => { + it("should move a published document and its children to private", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const parent = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + const child = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + parentDocumentId: parent.id, + }); + + const res = await server.post("/api/documents.move", user, { + body: { + id: parent.id, + private: true, + }, + }); + expect(res.status).toEqual(200); + + await Promise.all([parent.reload(), child.reload()]); + expect(parent.collectionId).toBeNull(); + expect(parent.parentDocumentId).toBeNull(); + expect(parent.publishedAt).toBeTruthy(); + expect(child.collectionId).toBeNull(); + expect(child.parentDocumentId).toEqual(parent.id); + expect(child.publishedAt).toBeTruthy(); + + const membership = await UserMembership.findOne({ + where: { + documentId: parent.id, + userId: user.id, + }, + }); + expect(membership).not.toBeNull(); + expect(membership!.sourceId).toBeNull(); + expect(membership!.permission).toEqual(DocumentPermission.Admin); + }); + + it("should not allow private with a collectionId", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/documents.move", user, { + body: { + id: document.id, + private: true, + collectionId: collection.id, + }, + }); + expect(res.status).toEqual(400); + }); + + it("should not allow moving to private when the preference is disabled", async () => { + const team = await buildTeam(); + team.setPreference(TeamPreference.PrivateDocs, false); + await team.save(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/documents.move", user, { + body: { + id: document.id, + private: true, + }, + }); + expect(res.status).toEqual(403); + }); +}); + +describe("#documents.update - publish to private from collection", () => { + it("should detach a draft from its collection when publishing privately", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const draft = await buildDraftDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/documents.update", user, { + body: { + id: draft.id, + publish: true, + private: true, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.collectionId).toBeNull(); + expect(body.data.publishedAt).toBeTruthy(); + + const membership = await UserMembership.findOne({ + where: { + documentId: draft.id, + userId: user.id, + }, + }); + expect(membership).not.toBeNull(); + expect(membership!.permission).toEqual(DocumentPermission.Admin); + }); +}); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index ed03e3cf7a..40a06d08b1 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1460,7 +1460,7 @@ router.post( transaction(), async (ctx: APIContext) => { const { transaction } = ctx.state; - const { id, parentDocumentId, index } = ctx.input.body; + const { id, parentDocumentId, private: isPrivate, index } = ctx.input.body; let collectionId = ctx.input.body.collectionId; const { user } = ctx.state.auth; const document = await Document.findByPk(id, { @@ -1469,7 +1469,10 @@ router.post( }); authorize(user, "move", document); - if (parentDocumentId) { + if (isPrivate) { + authorize(user, "createPrivateDocument", user.team); + collectionId = null; + } else if (parentDocumentId) { const parent = await Document.findByPk(parentDocumentId, { userId: user.id, transaction, @@ -1494,6 +1497,7 @@ router.post( document, collectionId: collectionId ?? null, parentDocumentId, + private: isPrivate, index, }); diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 35770b04ac..61eaf056db 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -362,12 +362,26 @@ export const DocumentsMoveSchema = BaseSchema.extend({ /** Parent Id, in case if the doc is moved to a new parent */ parentDocumentId: z.uuid().nullish(), + /** Whether to move the doc to be private, outside any collection */ + private: z.boolean().optional(), + /** Helps evaluate the new index in collection structure upon move */ index: z.number().gte(0).optional(), }), -}).refine((req) => !(req.body.parentDocumentId === req.body.id), { - message: "infinite loop detected, cannot nest a document inside itself", -}); +}) + .refine((req) => !(req.body.parentDocumentId === req.body.id), { + message: "infinite loop detected, cannot nest a document inside itself", + }) + .refine( + (req) => + !( + req.body.private && + (req.body.collectionId || req.body.parentDocumentId) + ), + { + message: "collectionId and parentDocumentId cannot be used with private", + } + ); export type DocumentsMoveReq = z.infer; diff --git a/server/tools/documents.test.ts b/server/tools/documents.test.ts index 098905ae08..f322075032 100644 --- a/server/tools/documents.test.ts +++ b/server/tools/documents.test.ts @@ -4,6 +4,7 @@ import { buildViewer, buildCollection, buildDocument, + buildDraftDocument, buildTemplate, buildOAuthAuthentication, buildGroup, @@ -903,3 +904,102 @@ describe("restore_document", () => { expect(res?.result?.isError).toBe(true); }); }); + +describe("create_document - private", () => { + it("creates a private document with a creator membership", async () => { + const { user, accessToken } = await buildOAuthUser(); + + const res = await callMcpTool(server, accessToken, "create_document", { + title: "Private notes", + text: "Hello world", + private: true, + }); + const data = JSON.parse(res?.result?.content?.[0]?.text ?? "{}"); + + expect(res?.result?.isError).not.toBe(true); + expect(data.success).toBe(true); + + const document = await Document.findByPk(data.id, { rejectOnEmpty: true }); + expect(document.collectionId).toBeNull(); + expect(document.publishedAt).toBeTruthy(); + + const membership = await UserMembership.findOne({ + where: { documentId: document.id, userId: user.id }, + }); + expect(membership).not.toBeNull(); + expect(membership!.permission).toEqual(DocumentPermission.Admin); + }); + + it("rejects private combined with collectionId", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + + const res = await callMcpTool(server, accessToken, "create_document", { + title: "Private notes", + private: true, + collectionId: collection.id, + }); + expect(res?.result?.isError).toBe(true); + }); +}); + +describe("move_document - private", () => { + it("moves a published document to private", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "move_document", { + id: document.id, + private: true, + }); + expect(res?.result?.isError).not.toBe(true); + + await document.reload(); + expect(document.collectionId).toBeNull(); + expect(document.publishedAt).toBeTruthy(); + + const membership = await UserMembership.findOne({ + where: { documentId: document.id, userId: user.id }, + }); + expect(membership).not.toBeNull(); + expect(membership!.sourceId).toBeNull(); + }); +}); + +describe("update_document - private", () => { + it("publishes a draft privately", async () => { + const { user, accessToken } = await buildOAuthUser(); + const draft = await buildDraftDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: null, + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: draft.id, + publish: true, + private: true, + }); + expect(res?.result?.isError).not.toBe(true); + + await draft.reload(); + expect(draft.collectionId).toBeNull(); + expect(draft.publishedAt).toBeTruthy(); + + const membership = await UserMembership.findOne({ + where: { documentId: draft.id, userId: user.id }, + }); + expect(membership).not.toBeNull(); + }); +}); diff --git a/server/tools/documents.ts b/server/tools/documents.ts index 0b69913e4a..c65ce58d3b 100644 --- a/server/tools/documents.ts +++ b/server/tools/documents.ts @@ -331,7 +331,7 @@ export function documentTools(server: McpServer, scopes: string[]) { { title: "Create document", description: - "Creates a new document from markdown or HTML content. Requires a collectionId to place the document in a collection, or parentDocumentId to nest it under an existing document. Pass a templateId (from list_templates) to pre-fill the document from a template; the template's content is used unless text is also provided.", + "Creates a new document from markdown or HTML content. Requires a collectionId to place the document in a collection, parentDocumentId to nest it under an existing document, or private set to true to create a private document. Pass a templateId (from list_templates) to pre-fill the document from a template; the template's content is used unless text is also provided.", annotations: { idempotentHint: false, readOnlyHint: false, @@ -361,6 +361,12 @@ export function documentTools(server: McpServer, scopes: string[]) { parentDocumentId: optionalString().describe( "The parent document ID to nest this document under." ), + private: z + .boolean() + .optional() + .describe( + "Set to true to create a private document, outside any collection, visible only to the creator and the people they share it with. Cannot be combined with collectionId or parentDocumentId." + ), templateId: optionalString().describe( "The ID of a template to pre-fill the new document from. The template's title, content, icon, and color are used unless overridden by the corresponding parameters." ), @@ -386,13 +392,37 @@ export function documentTools(server: McpServer, scopes: string[]) { }, withTracing("create_document", async (input, context) => { try { - const { collectionId, parentDocumentId, templateId } = input; + const { + collectionId, + parentDocumentId, + private: isPrivate, + templateId, + } = input; const ctx = buildAPIContext(context); const { user } = ctx.state.auth; + if (isPrivate) { + if (collectionId || parentDocumentId) { + throw ValidationError( + "collectionId and parentDocumentId cannot be used with private" + ); + } + if (input.publish === false) { + throw ValidationError( + "Private documents cannot be created as drafts" + ); + } + if (input.format === "html") { + throw ValidationError( + "Private documents cannot be created from HTML content" + ); + } + } + const { collection } = await authorizeDocumentCreate(ctx, { collectionId, parentDocumentId, + private: isPrivate, }); let template: Template | null | undefined; @@ -437,6 +467,7 @@ export function documentTools(server: McpServer, scopes: string[]) { color: input.color, parentDocumentId, publish: input.publish !== false, + private: isPrivate, collectionId: collection?.id, template, fullWidth: input.fullWidth, @@ -487,6 +518,12 @@ export function documentTools(server: McpServer, scopes: string[]) { parentDocumentId: optionalString().describe( "The ID of the document to nest this document under. The document will be moved to the parent's collection." ), + private: z + .boolean() + .optional() + .describe( + "Set to true to move the document to the user's private documents, outside any collection. Cannot be combined with collectionId or parentDocumentId." + ), index: z .number() .int() @@ -516,7 +553,15 @@ export function documentTools(server: McpServer, scopes: string[]) { let collectionId = input.collectionId; - if (input.parentDocumentId) { + if (input.private) { + if (collectionId || input.parentDocumentId) { + throw ValidationError( + "collectionId and parentDocumentId cannot be used with private" + ); + } + authorize(user, "createPrivateDocument", user.team); + collectionId = undefined; + } else if (input.parentDocumentId) { if (input.parentDocumentId === input.id) { throw ValidationError("Cannot nest a document inside itself"); } @@ -550,6 +595,7 @@ export function documentTools(server: McpServer, scopes: string[]) { document, collectionId: collectionId ?? null, parentDocumentId: input.parentDocumentId ?? null, + private: input.private, index: input.index, }); @@ -628,6 +674,12 @@ export function documentTools(server: McpServer, scopes: string[]) { .describe( "Set to true to publish a draft document, or false to convert a published document back to a draft." ), + private: z + .boolean() + .optional() + .describe( + "When publishing a draft, set to true to publish it privately, outside any collection, visible only to the creator and the people they share it with. Cannot be combined with collectionId." + ), fullWidth: z .boolean() .optional() @@ -658,8 +710,17 @@ export function documentTools(server: McpServer, scopes: string[]) { } else { authorize(user, "update", document); + if (input.private && input.collectionId) { + throw ValidationError("collectionId cannot be used with private"); + } + if (input.publish) { - await authorizeDocumentPublish(ctx, document, input.collectionId); + await authorizeDocumentPublish( + ctx, + document, + input.collectionId, + { private: input.private } + ); } const { revisionCount } = document; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 004b78fbe0..ad7875ede6 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -581,6 +581,8 @@ "Can view": "Can view", "Everyone in the collection": "Everyone in the collection", "You have full access": "You have full access", + "Private": "Private", + "Only people invited to this document have access": "Only people invited to this document have access", "Other people": "Other people", "Other workspace members may have access": "Other workspace members may have access", "This document may be shared with more workspace members through a parent document or collection you do not have access to": "This document may be shared with more workspace members through a parent document or collection you do not have access to", @@ -614,7 +616,6 @@ "Go back": "Go back", "Go forward": "Go forward", "Could not load private documents": "Could not load private documents", - "Private": "Private", "Show more": "Show more", "Could not load shared documents": "Could not load shared documents", "Shared with me": "Shared with me",