This commit is contained in:
Tom Moor committed 2026-08-14 21:36:44 -04:00
1 parent 3995befdd6
commit 41eac87e24
23 files changed
+698 -55

No files matched your search

+17 -3
View File
@@ -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) {
@@ -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<boolean>(false);
const [selectedPath, selectPath] = useState<NavigationNode | null>(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<string>([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"));
@@ -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 ? (
<Placeholder />
) : (
<DocumentMemberList
document={document}
invitedInSession={invitedInSession}
/>
)}
<ListItem
image={
<Squircle color={theme.accent} size={AvatarSize.Medium}>
<PadlockIcon color={theme.accentText} size={16} />
</Squircle>
}
title={t("Private")}
subtitle={t("Only people invited to this document have access")}
/>
</>
) : (
<>
{showLoading ? (
@@ -52,7 +52,11 @@ function PrivateDocs() {
}, [error, t]);
useEffect(() => {
if (!ui.activeDocumentId || locationSidebarContext === "private") {
if (
!ui.activeDocumentId ||
locationSidebarContext === "private" ||
locationSidebarContext?.startsWith("starred")
) {
return;
}
@@ -54,7 +54,11 @@ function SharedWithMe() {
locationSidebarContext === "shared" ||
locationSidebarContext?.startsWith("group");
if (!ui.activeDocumentId || isContextInSharedSection) {
if (
!ui.activeDocumentId ||
isContextInSharedSection ||
locationSidebarContext?.startsWith("starred")
) {
return;
}
+93
View File
@@ -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]);
}
+1
View File
@@ -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?: {
+20 -9
View File
@@ -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<NavigationNode | null>(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;
+13
View File
@@ -512,20 +512,25 @@ export default class DocumentsStore extends Store<Document> {
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<Document> {
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;
}
+5 -5
View File
@@ -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,
+33 -1
View File
@@ -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, {
+10 -6
View File
@@ -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);
+7 -6
View File
@@ -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;
+2 -2
View File
@@ -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;
+1 -1
View File
@@ -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)
)
);
@@ -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);
});
});
@@ -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);
});
}
@@ -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);
});
});
+6 -2
View File
@@ -1460,7 +1460,7 @@ router.post(
transaction(),
async (ctx: APIContext<T.DocumentsMoveReq>) => {
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,
});
+17 -3
View File
@@ -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<typeof DocumentsMoveSchema>;
+100
View File
@@ -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();
});
});
+65 -4
View File
@@ -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;
+2 -1
View File
@@ -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",