diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx
index 83eeb357f0..6fad915895 100644
--- a/app/actions/definitions/collections.tsx
+++ b/app/actions/definitions/collections.tsx
@@ -65,13 +65,15 @@ export const openCollection = createActionWithChildren({
shortcut: ["o", "c"],
icon: ,
children: ({ stores }) => {
- const collections = stores.collections.orderedData;
+ const collections = stores.collections.orderedData.filter(
+ (collection) => !collection.isPersonal
+ );
return collections.map((collection) =>
createInternalLinkAction({
// Note: using url which includes the slug rather than id here to bust
// cache if the collection is renamed
id: collection.path,
- name: collection.name,
+ name: collection.displayName,
icon: ,
section: CollectionSection,
to: collection.path,
@@ -125,7 +127,9 @@ export const editCollectionPermissions = createAction({
section: ActiveCollectionSection,
icon: ,
visible: ({ getActivePolicies }) =>
- getActivePolicies(Collection).some((policy) => policy.abilities.update),
+ getActivePolicies(Collection).some(
+ (policy) => policy.abilities.manageUsers
+ ),
perform: ({ t, getActiveModel, stores }) => {
const collection = getActiveModel(Collection);
if (!collection) {
diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx
index ca75893459..cdd1b468c4 100644
--- a/app/actions/definitions/documents.tsx
+++ b/app/actions/definitions/documents.tsx
@@ -1545,7 +1545,7 @@ export const restoreDocumentToCollection = createActionWithChildren({
const actions = collections.orderedData.map((collection) => {
const can = policies.abilities(collection.id);
return createAction({
- name: collection.name,
+ name: collection.displayName,
section: ActiveDocumentSection,
icon: ,
visible: can.createDocument,
diff --git a/app/actions/definitions/webmcp.ts b/app/actions/definitions/webmcp.ts
index fad4d68214..17ed0d6718 100644
--- a/app/actions/definitions/webmcp.ts
+++ b/app/actions/definitions/webmcp.ts
@@ -30,7 +30,11 @@ export const getCurrentContext = createAction({
}
: undefined,
collection: collection
- ? { id: collection.id, name: collection.name, path: collection.path }
+ ? {
+ id: collection.id,
+ name: collection.displayName,
+ path: collection.path,
+ }
: undefined,
});
},
diff --git a/app/actions/sections.ts b/app/actions/sections.ts
index b3499b46c6..6531dde2d4 100644
--- a/app/actions/sections.ts
+++ b/app/actions/sections.ts
@@ -6,7 +6,7 @@ export const CollectionsSection = ({ t }: ActionContext) => t("Collections");
export const ActiveCollectionSection = ({ t, stores }: ActionContext) => {
const activeCollection = stores.collections.active;
- return `${t("Collection")} · ${activeCollection?.name}`;
+ return `${t("Collection")} · ${activeCollection?.displayName}`;
};
ActiveCollectionSection.priority = 0.8;
diff --git a/app/components/Breadcrumb.tsx b/app/components/Breadcrumb.tsx
index 4a4b98aeb7..072b724651 100644
--- a/app/components/Breadcrumb.tsx
+++ b/app/components/Breadcrumb.tsx
@@ -2,7 +2,7 @@ import { GoToIcon } from "outline-icons";
import { observer } from "mobx-react";
import * as React from "react";
import { Link } from "react-router-dom";
-import styled from "styled-components";
+import styled, { css } from "styled-components";
import { s, ellipsis } from "@shared/styles";
import Flex from "~/components/Flex";
import BreadcrumbMenu from "~/menus/BreadcrumbMenu";
@@ -75,13 +75,20 @@ function Breadcrumb({
}
const item = actionToMenuItem(action, actionContext) as MenuInternalLink;
+ const highlight = !!highlightFirstItem && index === 0;
+
+ // Items without a destination are shown as plain text.
+ if (!item.to) {
+ return (
+
+ {item.icon}
+ {item.title}
+
+ );
+ }
return (
- -
+
-
{item.icon}
{item.title}
@@ -110,7 +117,7 @@ const Slash = styled(GoToIcon)`
fill: ${s("divider")};
`;
-const Item = styled(Link)<{ $highlight: boolean }>`
+const itemStyles = css<{ $highlight: boolean }>`
${undraggableOnDesktop()}
display: flex;
@@ -118,7 +125,6 @@ const Item = styled(Link)<{ $highlight: boolean }>`
gap: 4px;
flex-shrink: 1;
min-width: 0;
- cursor: var(--pointer);
color: ${s("text")};
font-size: 15px;
height: 32px;
@@ -131,6 +137,11 @@ const Item = styled(Link)<{ $highlight: boolean }>`
margin-inline-start: 0;
}
max-width: 460px;
+`;
+
+const Item = styled(Link)<{ $highlight: boolean }>`
+ ${itemStyles}
+ cursor: var(--pointer);
transition: background 100ms ease-in-out;
&:hover,
@@ -140,6 +151,11 @@ const Item = styled(Link)<{ $highlight: boolean }>`
}
`;
+const StaticItem = styled.span<{ $highlight: boolean }>`
+ ${itemStyles}
+ cursor: default;
+`;
+
const Title = styled.span`
${ellipsis()}
min-width: 0;
diff --git a/app/components/CollectionBreadcrumb.tsx b/app/components/CollectionBreadcrumb.tsx
index c5ebf3f08e..c95b563a75 100644
--- a/app/components/CollectionBreadcrumb.tsx
+++ b/app/components/CollectionBreadcrumb.tsx
@@ -25,7 +25,7 @@ export const CollectionBreadcrumb: React.FC = ({ collection }) => {
to: archivePath(),
}),
createInternalLinkAction({
- name: collection.name,
+ name: collection.displayName,
section: ActiveCollectionSection,
icon: ,
to: collectionPath(collection),
diff --git a/app/components/CollectionDeleteDialog.tsx b/app/components/CollectionDeleteDialog.tsx
index 337ccbde9a..e8d4d1a153 100644
--- a/app/components/CollectionDeleteDialog.tsx
+++ b/app/components/CollectionDeleteDialog.tsx
@@ -44,7 +44,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) {
,
@@ -56,7 +56,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) {
,
diff --git a/app/components/ConfirmMoveDialog.tsx b/app/components/ConfirmMoveDialog.tsx
index 55401670a8..c3d3f0d08d 100644
--- a/app/components/ConfirmMoveDialog.tsx
+++ b/app/components/ConfirmMoveDialog.tsx
@@ -46,7 +46,7 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
"You do not have permission to move {{ documentName }} to the {{ collectionName }} collection",
{
documentName: item.title,
- collectionName: collection.name,
+ collectionName: collection.displayName,
}
)
);
@@ -68,8 +68,8 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
defaults="Moving the document {{ title }} to the {{ newCollectionName }} collection will change permission for all workspace members from {{ prevPermission }} to {{ newPermission }}."
values={{
title: item.title,
- prevCollectionName: prevCollection?.name,
- newCollectionName: collection.name,
+ prevCollectionName: prevCollection?.displayName,
+ newCollectionName: collection.displayName,
prevPermission: accessMapping[prevCollection?.permission || "null"],
newPermission: accessMapping[collection.permission || "null"],
}}
diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx
index 79b4e76dc4..9016fc1ccb 100644
--- a/app/components/DefaultCollectionInputSelect.tsx
+++ b/app/components/DefaultCollectionInputSelect.tsx
@@ -84,7 +84,7 @@ const DefaultCollectionInputSelect = observer(
...acc,
{
type: "item" as const,
- label: collection.name,
+ label: collection.displayName,
value: collection.id,
icon,
},
diff --git a/app/components/DialogTitle.tsx b/app/components/DialogTitle.tsx
index 5e713a7a7f..0085d43bd3 100644
--- a/app/components/DialogTitle.tsx
+++ b/app/components/DialogTitle.tsx
@@ -60,7 +60,7 @@ export const DialogTitle = observer(function DialogTitle_({
{icon}
- {isDocument ? model.titleWithDefault : model.name}
+ {isDocument ? model.titleWithDefault : model.displayName}
diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx
index 9a9922440f..991eb7932d 100644
--- a/app/components/DocumentBreadcrumb.tsx
+++ b/app/components/DocumentBreadcrumb.tsx
@@ -38,8 +38,8 @@ export function documentBreadcrumbParts(
let collectionLabel: string | undefined;
if (document.isCollectionDeleted) {
collectionLabel = t("Deleted Collection");
- } else if (document.collection?.name) {
- collectionLabel = document.collection.name;
+ } else if (document.collection?.displayName) {
+ collectionLabel = document.collection.displayName;
}
return {
@@ -139,12 +139,14 @@ function DocumentBreadcrumb({
) : undefined,
section: ActiveDocumentSection,
visible: !!(collection && can.readDocument),
- to: collection
- ? {
- pathname: collection.path,
- state: { sidebarContext },
- }
- : "",
+ // A personal collection has no page to link to.
+ to:
+ collection && !collection.isPersonal
+ ? {
+ pathname: collection.path,
+ state: { sidebarContext },
+ }
+ : "",
}),
createInternalLinkAction({
name: t("Deleted Collection"),
@@ -262,7 +264,7 @@ const CollectionName = observer(function CollectionName_({
{icon}
- {collection.name}
+ {collection.displayName}
diff --git a/app/components/Icons/CollectionIcon.tsx b/app/components/Icons/CollectionIcon.tsx
index bfdbe651c0..5c13bf59c7 100644
--- a/app/components/Icons/CollectionIcon.tsx
+++ b/app/components/Icons/CollectionIcon.tsx
@@ -1,9 +1,12 @@
import { observer } from "mobx-react";
import { CollectionIcon, PrivateCollectionIcon } from "outline-icons";
+import styled from "styled-components";
import Icon from "@shared/components/Icon";
import { colorPalette } from "@shared/constants";
import useContrastColor from "@shared/hooks/useContrastColor";
+import Avatar from "~/components/Avatar/Avatar";
import type Collection from "~/models/Collection";
+import useStores from "~/hooks/useStores";
type Props = {
/** The collection to show an icon for */
@@ -25,6 +28,18 @@ function ResolvedCollectionIcon({
className,
}: Props) {
const contrastColor = useContrastColor();
+ const { users } = useStores();
+ const owner = collection.ownerId ? users.get(collection.ownerId) : undefined;
+
+ // A personal collection always shows the avatar of its owner.
+ if (owner) {
+ const iconSize = size ?? 24;
+ return (
+
+
+
+ );
+ }
if (!collection.icon || collection.icon === "collection") {
const color =
@@ -55,4 +70,13 @@ function ResolvedCollectionIcon({
);
}
+const AvatarWrapper = styled.span<{ $size: number }>`
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: ${(props) => props.$size}px;
+ height: ${(props) => props.$size}px;
+`;
+
export default observer(ResolvedCollectionIcon);
diff --git a/app/components/Notifications/NotificationListItem.tsx b/app/components/Notifications/NotificationListItem.tsx
index 7e6b09d534..0a6f5dcba7 100644
--- a/app/components/Notifications/NotificationListItem.tsx
+++ b/app/components/Notifications/NotificationListItem.tsx
@@ -84,7 +84,7 @@ function NotificationListItem({ notification, onNavigate }: Props) {
{" "}
- {collection && <>· {collection.name}>}
+ {collection && <>· {collection.displayName}>}
{commentData && (
diff --git a/app/components/Sharing/Collection/AccessControlList.tsx b/app/components/Sharing/Collection/AccessControlList.tsx
index d7c82e3c3e..18ccc833fb 100644
--- a/app/components/Sharing/Collection/AccessControlList.tsx
+++ b/app/components/Sharing/Collection/AccessControlList.tsx
@@ -124,7 +124,7 @@ export const AccessControlList = observer(
permission: value === EmptySelectValue ? null : value,
});
}}
- disabled={!can.update}
+ disabled={!can.manageUsers}
value={collection?.permission}
labelHidden
nude
@@ -192,7 +192,7 @@ export const AccessControlList = observer(
}
return true;
}}
- disabled={!can.update}
+ disabled={!can.manageUsers}
value={membership.permission}
/>
@@ -246,7 +246,7 @@ export const AccessControlList = observer(
}
return true;
}}
- disabled={!can.update}
+ disabled={!can.manageUsers}
value={membership.permission}
/>
diff --git a/app/components/Sharing/Collection/SharePopover.tsx b/app/components/Sharing/Collection/SharePopover.tsx
index 89c6d3427b..d498ad498b 100644
--- a/app/components/Sharing/Collection/SharePopover.tsx
+++ b/app/components/Sharing/Collection/SharePopover.tsx
@@ -364,7 +364,7 @@ function SharePopover({
return (
- {can.update && (
+ {can.manageUsers && (
{
+ if (ownerId && !owner) {
+ void users.fetch(ownerId);
+ }
+ }, [ownerId, owner, users]);
const containerRef = React.useRef(null);
const publicAccessRef = React.useRef(null);
@@ -137,7 +145,7 @@ export const AccessControlList = observer(
) : usersInCollection ? (
}
- title={collection.name}
+ title={collection.displayName}
subtitle={t("Everyone in the collection")}
actions={{t("Can view")}}
/>
@@ -160,6 +168,20 @@ export const AccessControlList = observer(
>
) : (
<>
+ {owner && (
+ }
+ title={owner.name}
+ subtitle={t("Owner")}
+ actions={
+
+ {t("Can edit")}
+
+ }
+ />
+ )}
{showLoading ? (
) : (
@@ -168,22 +190,24 @@ export const AccessControlList = observer(
invitedInSession={invitedInSession}
/>
)}
-
-
-
- }
- title={t("Other people")}
- subtitle={t("Other workspace members may have access")}
- actions={
-
- }
- />
+ {!ownerId && (
+
+
+
+ }
+ title={t("Other people")}
+ subtitle={t("Other workspace members may have access")}
+ actions={
+
+ }
+ />
+ )}
>
)}
diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx
index 92c8e0e6f1..c7b0b5c02c 100644
--- a/app/components/Sidebar/App.tsx
+++ b/app/components/Sidebar/App.tsx
@@ -32,6 +32,7 @@ import { DraftsLink } from "./components/DraftsLink";
import DragPlaceholder from "./components/DragPlaceholder";
import { DismissableSidebarAction } from "./components/DismissableSidebarAction";
import HistoryNavigation from "./components/HistoryNavigation";
+import { PersonalDocs } from "./components/PersonalDocs";
import Section from "./components/Section";
import SharedWithMe from "./components/SharedWithMe";
import SidebarButton from "./components/SidebarButton";
@@ -79,6 +80,7 @@ function AppSidebar() {
[SidebarSection.Starred]: ,
[SidebarSection.SharedWithMe]: ,
[SidebarSection.Collections]: ,
+ [SidebarSection.Personal]: ,
};
return (
diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx
index a07b8ae95a..75697700bf 100644
--- a/app/components/Sidebar/components/CollectionLink.tsx
+++ b/app/components/Sidebar/components/CollectionLink.tsx
@@ -117,7 +117,7 @@ const CollectionLink: React.FC = ({
onDisclosureClick={onDisclosureClick}
onExpand={handleExpand}
canEdit={can.update}
- labelText={collection.name}
+ labelText={collection.displayName}
onTitleChange={handleTitleChange}
editableTitleRef={editableTitleRef}
contextAction={contextMenuAction}
diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx
index 3ccbe06cdc..cbde050b87 100644
--- a/app/components/Sidebar/components/CollectionLinkChildren.tsx
+++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx
@@ -30,6 +30,8 @@ type Props = {
expanded: boolean;
/** Indentation depth of the parent collection. */
depth?: number;
+ /** Indentation depth of the child documents, defaults to below the collection. */
+ childDepth?: number;
/** Function to prefetch a document by ID. */
prefetchDocument?: (documentId: string) => Promise;
/** Element to display above the child documents */
@@ -40,12 +42,13 @@ function CollectionLinkChildren({
collection,
expanded,
depth = 0,
+ childDepth: childDepthProp,
prefetchDocument,
children,
}: Props) {
// Documents sit one level below the collection, with a minimum that leaves
// room for their own disclosure to the left of the label.
- const childDepth = Math.max(depth + 1, 2);
+ const childDepth = childDepthProp ?? Math.max(depth + 1, 2);
const { documents } = useStores();
const { t } = useTranslation();
// Scoped to this collection so that other collections do not re-render when
@@ -90,17 +93,19 @@ function CollectionLinkChildren({
prefetchDocument={prefetchDocument}
/>
)}
- {childDocuments?.length === 0 && !children && (
-
- {t("Empty")}
-
- }
- onClick={() => history.push(collection.url)}
- depth={childDepth}
- />
- )}
+ {childDocuments?.length === 0 &&
+ !children &&
+ !collection.isPersonal && (
+
+ {t("Empty")}
+
+ }
+ onClick={() => history.push(collection.url)}
+ depth={childDepth}
+ />
+ )}
diff --git a/app/components/Sidebar/components/CollectionRow.tsx b/app/components/Sidebar/components/CollectionRow.tsx
index 443dd3d27c..99a73f9fc8 100644
--- a/app/components/Sidebar/components/CollectionRow.tsx
+++ b/app/components/Sidebar/components/CollectionRow.tsx
@@ -165,7 +165,7 @@ function CollectionRow({
const labelElement = canEdit ? (
undefined)}
isEditing={isEditing}
onEditing={setIsEditing}
@@ -174,7 +174,7 @@ function CollectionRow({
ref={editableTitleRef}
/>
) : (
- collection.name
+ collection.displayName
);
const iconElement = icon ?? (
@@ -212,7 +212,7 @@ function CollectionRow({
{
id: collection.id,
url: collection.path,
- title: collection.name,
+ title: collection.displayName,
sidebarContext,
collapsedChildren: expanded ? undefined : collection.sortedDocuments,
},
diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx
index 37f35d2c7b..7f5d45a8c7 100644
--- a/app/components/Sidebar/components/DocumentLink.tsx
+++ b/app/components/Sidebar/components/DocumentLink.tsx
@@ -1,5 +1,6 @@
import type { Location } from "history";
import { observer } from "mobx-react";
+import { DocumentIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import type { match } from "react-router";
@@ -31,7 +32,7 @@ import {
import { useSidebarExpansion } from "./SidebarExpansionContext";
import DocumentRow from "./DocumentRow";
import DropCursor from "./DropCursor";
-import { indentForDepth } from "./SidebarLink";
+import { childDepthFor, indentForDepth } from "./SidebarLink";
import type { SidebarContextType } from "./SidebarContext";
import { useSidebarContext } from "./SidebarContext";
@@ -172,10 +173,16 @@ const DocumentLink = observer(function DocumentLink({
const color = document?.color || node.color;
const initial = document?.initial || node.title.charAt(0).toUpperCase();
+ // Rows at the top level of a section show the default icon, so that they
+ // align with the other rows in the sidebar.
const iconElement = React.useMemo(
() =>
- icon ? : undefined,
- [icon, color, initial]
+ icon ? (
+
+ ) : depth === 0 ? (
+
+ ) : undefined,
+ [icon, color, initial, depth, isDraft]
);
const [{ isDragging }, drag] = useDragDocument(
@@ -207,7 +214,9 @@ const DocumentLink = observer(function DocumentLink({
// dragged skips the position after itself, which would be a no-op.
const targetsBelow = React.useMemo(() => {
if (expanded && hasChildren) {
- return [{ parentDocumentId: node.id, index: 0, depth: depth + 1 }];
+ return [
+ { parentDocumentId: node.id, index: 0, depth: childDepthFor(depth) },
+ ];
}
const afterSelf = isDragging
? []
diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx
index 256575b1c6..8889543abd 100644
--- a/app/components/Sidebar/components/DocumentTree.tsx
+++ b/app/components/Sidebar/components/DocumentTree.tsx
@@ -6,7 +6,10 @@ import * as React from "react";
import scrollIntoView from "scroll-into-view-if-needed";
import type { NavigationNode } from "@shared/types";
import { sortNavigationNodes } from "@shared/utils/collections";
-import { flattenExpandedTree } from "@shared/utils/tree";
+import {
+ flattenExpandedTree,
+ type FlattenedTreeNode,
+} from "@shared/utils/tree";
import type Collection from "~/models/Collection";
import type Document from "~/models/Document";
import type GroupMembership from "~/models/GroupMembership";
@@ -79,27 +82,30 @@ export const DocumentTree = observer(function DocumentTree({
const rows = useComputed(
() =>
- flattenExpandedTree({
- nodes,
- depth,
- parentId,
- isExpanded: (nodeId) => expansion.isExpanded(nodeId),
- getChildren: (node) => {
- // Show an unpublished draft below its parent while it is open.
- if (
- collection &&
- activeDraft &&
- activeDraft.parentDocumentId === node.id
- ) {
- return sortNavigationNodes(
- [activeDraft.asNavigationNode, ...node.children],
- collection.sort,
- false
- );
- }
- return node.children;
- },
- }),
+ withChildDepth(
+ flattenExpandedTree({
+ nodes,
+ depth,
+ parentId,
+ isExpanded: (nodeId) => expansion.isExpanded(nodeId),
+ getChildren: (node) => {
+ // Show an unpublished draft below its parent while it is open.
+ if (
+ collection &&
+ activeDraft &&
+ activeDraft.parentDocumentId === node.id
+ ) {
+ return sortNavigationNodes(
+ [activeDraft.asNavigationNode, ...node.children],
+ collection.sort,
+ false
+ );
+ }
+ return node.children;
+ },
+ }),
+ depth
+ ),
[nodes, depth, parentId, collection, expansion, activeDraft]
);
@@ -273,3 +279,28 @@ export const DocumentTree = observer(function DocumentTree({
);
});
+
+/**
+ * Moves the descendants of root rows at depth 0 one level deeper, so that the
+ * rows match childDepthFor.
+ *
+ * @param rows The flattened rows of the tree.
+ * @param depth The depth of the root rows.
+ * @returns the rows with adjusted depths.
+ */
+function withChildDepth(
+ rows: FlattenedTreeNode[],
+ depth: number
+): FlattenedTreeNode[] {
+ if (depth !== 0) {
+ return rows;
+ }
+
+ const adjust = (row: FlattenedTreeNode): FlattenedTreeNode =>
+ row.depth === 0 ? row : { ...row, depth: row.depth + 1 };
+
+ return rows.map((row) => ({
+ ...adjust(row),
+ trailingAncestors: row.trailingAncestors.map(adjust),
+ }));
+}
diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx
index e46c9cad1c..dc3fc6b285 100644
--- a/app/components/Sidebar/components/DraggableCollectionLink.tsx
+++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx
@@ -83,7 +83,7 @@ function DraggableCollectionLink({ collection, belowCollection }: Props) {
type: "collection",
item: () => ({
id: collection.id,
- title: collection.name,
+ title: collection.displayName,
icon: ,
}),
collect: (monitor) => ({
diff --git a/app/components/Sidebar/components/DraggableSection.tsx b/app/components/Sidebar/components/DraggableSection.tsx
index 29577e158b..8ce612f44e 100644
--- a/app/components/Sidebar/components/DraggableSection.tsx
+++ b/app/components/Sidebar/components/DraggableSection.tsx
@@ -112,6 +112,7 @@ function DraggableSection({ section, children }: Props) {
[SidebarSection.Starred]: t("Starred"),
[SidebarSection.SharedWithMe]: t("Shared with me"),
[SidebarSection.Collections]: t("Collections"),
+ [SidebarSection.Personal]: t("Personal"),
};
const order = normalizeSidebarSectionOrder(
diff --git a/app/components/Sidebar/components/PersonalDocs.tsx b/app/components/Sidebar/components/PersonalDocs.tsx
new file mode 100644
index 0000000000..f16dc84c8b
--- /dev/null
+++ b/app/components/Sidebar/components/PersonalDocs.tsx
@@ -0,0 +1,172 @@
+import { observer } from "mobx-react";
+import { DocumentIcon, PlusIcon } from "outline-icons";
+import { useCallback, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { useHistory } from "react-router-dom";
+import { PersonalCollectionId } from "@shared/constants";
+import { UserPreference } from "@shared/types";
+import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
+import { DocumentValidation } from "@shared/validations";
+import { createAction } from "~/actions";
+import { DocumentSection } from "~/actions/sections";
+import EditableTitle, { type RefHandle } from "~/components/EditableTitle";
+import Flex from "~/components/Flex";
+import useBoolean from "~/hooks/useBoolean";
+import useCurrentTeam from "~/hooks/useCurrentTeam";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import usePolicy from "~/hooks/usePolicy";
+import useStores from "~/hooks/useStores";
+import { useSyncSidebarContext } from "~/hooks/useSyncSidebarContext";
+import { documentEditPath } from "~/utils/routeHelpers";
+import CollectionLinkChildren from "./CollectionLinkChildren";
+import Header from "./Header";
+import Relative from "./Relative";
+import SidebarAction from "./SidebarAction";
+import SidebarContext, { type SidebarContextType } from "./SidebarContext";
+import SidebarLink from "./SidebarLink";
+
+/**
+ * The sidebar section that shows the documents in the personal collection of
+ * the current user.
+ */
+export const PersonalDocs = observer(function PersonalDocs() {
+ const { collections, documents } = useStores();
+ const { t } = useTranslation();
+ const history = useHistory();
+ const user = useCurrentUser();
+ const team = useCurrentTeam();
+ const can = usePolicy(team);
+ const collection = collections.personal;
+ const canCollection = usePolicy(collection);
+ const canCreate = collection
+ ? !!canCollection.createDocument
+ : !!can.createPersonalCollection;
+ const [isAddingNew, setIsAddingNew, closeAddingNew] = useBoolean();
+ const newTitleRef = useRef(null);
+
+ // Opens a temporary row with an editable title, the document is only
+ // created once a title is submitted.
+ const newDocAction = useMemo(
+ () =>
+ createAction({
+ name: ({ t, isMenu }) => (isMenu ? t("New document") : t("New doc")),
+ analyticsName: "New personal document",
+ section: DocumentSection,
+ icon: ,
+ keywords: "create personal private",
+ visible: canCreate,
+ perform: setIsAddingNew,
+ }),
+ [canCreate, setIsAddingNew]
+ );
+ const headerActions = useMemo(() => [newDocAction], [newDocAction]);
+
+ const handleNewDoc = useCallback(
+ async (title: string) => {
+ // The personal collection is created with the first document.
+ const newDocument = await documents.create(
+ {
+ collectionId: collection?.id ?? PersonalCollectionId,
+ title,
+ fullWidth: user.getPreference(UserPreference.FullWidthDocuments),
+ data: ProsemirrorDataHelper.getEmpty(),
+ },
+ { publish: true }
+ );
+ if (newDocument.collectionId) {
+ const personal =
+ collection ?? (await collections.fetch(newDocument.collectionId));
+ personal.addDocument(newDocument);
+ }
+ history.push({
+ pathname: documentEditPath(newDocument),
+ state: { sidebarContext: "personal" },
+ });
+ },
+ [collection, collections, documents, user, history]
+ );
+
+ const handleNewDocSubmit = useCallback(
+ async (value: string) => {
+ try {
+ newTitleRef.current?.setIsEditing(false);
+ await handleNewDoc(value);
+ closeAddingNew();
+ } catch (_err) {
+ newTitleRef.current?.setIsEditing(true);
+ }
+ },
+ [handleNewDoc, closeAddingNew]
+ );
+
+ const collectionId = collection?.id;
+ useSyncSidebarContext(
+ useCallback(
+ (context: NonNullable) => context === "personal",
+ []
+ ),
+ useCallback(
+ (activeDocumentId: string) =>
+ collectionId &&
+ documents.get(activeDocumentId)?.collectionId === collectionId
+ ? "personal"
+ : undefined,
+ [documents, collectionId]
+ )
+ );
+
+ if (!collection && !canCreate) {
+ return null;
+ }
+
+ const newDocRow =
+ isAddingNew && canCreate ? (
+ true}
+ depth={0}
+ icon={}
+ ellipsis={false}
+ label={
+
+ }
+ />
+ ) : null;
+
+ return (
+
+
+
+
+ {collection ? (
+
+ {newDocRow}
+
+ ) : (
+ newDocRow
+ )}
+
+
+
+
+
+ );
+});
diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx
index 901faab02a..43b345eb86 100644
--- a/app/components/Sidebar/components/SharedWithMeLink.tsx
+++ b/app/components/Sidebar/components/SharedWithMeLink.tsx
@@ -227,6 +227,14 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
parentRef={parentRef}
dropToReparentRef={dropToReparent}
isActiveDropTarget={isOverReparent}
+ cursorAfter={
+ reorderProps.isDragging ? (
+
+ ) : undefined
+ }
menu={menu}
menuOpen={menuOpen}
isActiveOverride={isActive}
@@ -240,16 +248,13 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) {
parentId={document.id}
collection={collection}
membership={membership}
+ // Loads the document and its policies on hover, without which
+ // rows that were never opened cannot be dragged or dropped on.
+ prefetchDocument={documents.prefetchDocument}
/>
- {reorderProps.isDragging && (
-
- )}
);
}
diff --git a/app/components/Sidebar/components/SidebarContext.ts b/app/components/Sidebar/components/SidebarContext.ts
index 71a3833182..1c08ae9ff4 100644
--- a/app/components/Sidebar/components/SidebarContext.ts
+++ b/app/components/Sidebar/components/SidebarContext.ts
@@ -5,6 +5,7 @@ import type User from "~/models/User";
export type SidebarContextType =
| "collections"
| "shared"
+ | "personal"
| "archive"
| `group-${string}`
| `starred-${string}`
@@ -57,7 +58,10 @@ export const determineSidebarContext = ({
}
if (document.collection) {
- return document.collection.isArchived ? "archive" : "collections";
+ if (document.collection.isArchived) {
+ return "archive";
+ }
+ return document.collection.isPersonal ? "personal" : "collections";
} else if (
user.documentMemberships.find((m) => m.documentId === document.id)
) {
diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx
index 0689edb134..5793305a90 100644
--- a/app/components/Sidebar/components/SidebarLink.tsx
+++ b/app/components/Sidebar/components/SidebarLink.tsx
@@ -30,6 +30,17 @@ export function indentForDepth(depth: number): number {
return depth * 16 + 12;
}
+/**
+ * Returns the nesting depth of the children of a sidebar row. A row at depth 0
+ * shows an icon, so its children skip a level to start beyond the icon.
+ *
+ * @param depth The nesting depth of the row, 0-based.
+ * @returns the nesting depth of the children.
+ */
+export function childDepthFor(depth: number): number {
+ return depth === 0 ? 2 : depth + 1;
+}
+
/**
* Props for the SidebarLink component.
* Extends NavLink props with additional sidebar-specific functionality.
diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx
index ee8774bdb1..2de85b68fd 100644
--- a/app/components/Sidebar/components/StarredLink.tsx
+++ b/app/components/Sidebar/components/StarredLink.tsx
@@ -353,7 +353,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({
onExpand={handleExpand}
onClickIntent={handlePrefetch}
canEdit={can.update}
- labelText={collection.name}
+ labelText={collection.displayName}
onTitleChange={handleTitleChange}
editableTitleRef={editableTitleRef}
contextAction={contextMenuAction}
diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx
index 0f3ca5fb71..d49291efa8 100644
--- a/app/components/Sidebar/hooks/useDragAndDrop.tsx
+++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx
@@ -394,7 +394,7 @@ export function useDropToChangeCollection(
"You do not have permission to move {{ documentName }} to the {{ collectionName }} collection",
{
documentName: item.title,
- collectionName: collection.name,
+ collectionName: collection.displayName,
}
)
);
diff --git a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx
index 79c5071001..eff563fb43 100644
--- a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx
+++ b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx
@@ -33,7 +33,7 @@ export function useSidebarLabelAndIcon({
const initial = document?.initial;
const color = document?.color;
const isDraft = document?.isDraft;
- const collectionName = collection?.name;
+ const collectionName = collection?.displayName;
return React.useMemo(() => {
if (document) {
diff --git a/app/components/TemplatizeDialog/SelectLocation.tsx b/app/components/TemplatizeDialog/SelectLocation.tsx
index 1a293d3131..e3d5a17793 100644
--- a/app/components/TemplatizeDialog/SelectLocation.tsx
+++ b/app/components/TemplatizeDialog/SelectLocation.tsx
@@ -52,7 +52,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => {
if (canCollection.createTemplate) {
memo.push({
type: "item",
- label: collection.name,
+ label: collection.displayName,
value: collection.id,
icon: ,
});
diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx
index a1311c9356..92a268fc25 100644
--- a/app/editor/components/MentionMenu.tsx
+++ b/app/editor/components/MentionMenu.tsx
@@ -185,6 +185,8 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
.concat(
collections
.findByQuery(search, { maxResults: maxResultsInSection, weight })
+ // A personal collection has no page for a mention to link to.
+ .filter((collection) => !collection.isPersonal)
.map((collection) => collectionMentionItem(collection, actorId))
)
.concat(
diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx
index 557a76b1fa..14ac459653 100644
--- a/app/editor/extensions/PasteHandler.tsx
+++ b/app/editor/extensions/PasteHandler.tsx
@@ -197,7 +197,7 @@ export default class PasteHandler extends Extension {
state.schema.nodes.mention.create({
type: MentionType.Collection,
modelId: collection.id,
- label: collection.name,
+ label: collection.displayName,
id: uuidv4(),
})
)
@@ -209,7 +209,7 @@ export default class PasteHandler extends Extension {
IconType.Emoji;
const title = `${hasEmoji ? collection.icon + " " : ""}${
- collection.name
+ collection.displayName
}`;
this.insertLink(`${collection.path}${hash}`, title);
diff --git a/app/editor/menus/mention.tsx b/app/editor/menus/mention.tsx
index 22669bf984..1027c08384 100644
--- a/app/editor/menus/mention.tsx
+++ b/app/editor/menus/mention.tsx
@@ -128,7 +128,7 @@ export function collectionMentionItem(
) : (
),
- title: collection.name,
+ title: collection.displayName,
section: CollectionsSection,
appendSpace: true,
attrs: {
@@ -136,7 +136,7 @@ export function collectionMentionItem(
type: MentionType.Collection,
modelId: collection.id,
actorId,
- label: collection.name,
+ label: collection.displayName,
},
};
}
diff --git a/app/hooks/useCollectionTrees.ts b/app/hooks/useCollectionTrees.ts
index 829e50b6b7..a106ce8fa9 100644
--- a/app/hooks/useCollectionTrees.ts
+++ b/app/hooks/useCollectionTrees.ts
@@ -30,7 +30,7 @@ export default function useCollectionTrees(): NavigationNode[] {
function getCollectionTree(collection: Collection): NavigationNode {
const root: NavigationNode = {
id: collection.id,
- title: collection.name,
+ title: collection.displayName,
url: collection.path,
type: NavigationNodeType.Collection,
collectionId: collection.id,
diff --git a/app/hooks/useSyncSidebarContext.ts b/app/hooks/useSyncSidebarContext.ts
new file mode 100644
index 0000000000..5889700332
--- /dev/null
+++ b/app/hooks/useSyncSidebarContext.ts
@@ -0,0 +1,53 @@
+import { useEffect } from "react";
+import { useHistory } from "react-router-dom";
+import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext";
+import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
+import useStores from "~/hooks/useStores";
+import { patchLocation } from "~/utils/history";
+
+/**
+ * Writes the sidebar context of the active document into the location state, so
+ * that the section which contains the document is the one revealed in the
+ * sidebar. Sections the user is already looking at, and the starred section,
+ * are left alone.
+ *
+ * @param belongsToSection whether the given context is one of this section's own.
+ * @param resolve returns the context for the active document, or undefined when
+ * the document does not belong to this section.
+ */
+export function useSyncSidebarContext(
+ belongsToSection: (context: NonNullable) => boolean,
+ resolve: (activeDocumentId: string) => SidebarContextType | undefined
+) {
+ const { ui } = useStores();
+ const history = useHistory();
+ const locationSidebarContext = useLocationSidebarContext();
+
+ useEffect(() => {
+ if (
+ !ui.activeDocumentId ||
+ (locationSidebarContext &&
+ (belongsToSection(locationSidebarContext) ||
+ locationSidebarContext.startsWith("starred")))
+ ) {
+ return;
+ }
+
+ const sidebarContext = resolve(ui.activeDocumentId);
+ if (!sidebarContext) {
+ return;
+ }
+
+ history.push(
+ patchLocation(history.location, {
+ state: {
+ ...(history.location.state as Record),
+ sidebarContext,
+ },
+ })
+ );
+ // `history` is read imperatively, the sidebar context should only be
+ // recalculated when the active document or memberships change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ui.activeDocumentId, locationSidebarContext, belongsToSection, resolve]);
+}
diff --git a/app/menus/NewChildDocumentMenu.tsx b/app/menus/NewChildDocumentMenu.tsx
index b3264c26d5..81f351d827 100644
--- a/app/menus/NewChildDocumentMenu.tsx
+++ b/app/menus/NewChildDocumentMenu.tsx
@@ -25,7 +25,7 @@ function NewChildDocumentMenu({ document }: Props) {
const collection = document.collectionId
? collections.get(document.collectionId)
: undefined;
- const collectionName = collection ? collection.name : t("collection");
+ const collectionName = collection ? collection.displayName : t("collection");
const actions = React.useMemo(
() => [
diff --git a/app/menus/NewTemplateMenu.tsx b/app/menus/NewTemplateMenu.tsx
index dd7e7f3a6b..23a4e264c5 100644
--- a/app/menus/NewTemplateMenu.tsx
+++ b/app/menus/NewTemplateMenu.tsx
@@ -30,7 +30,7 @@ function NewTemplateMenu() {
collections.orderedData.map((collection) => {
const canCollection = policies.abilities(collection.id);
return createInternalLinkAction({
- name: collection.name,
+ name: collection.displayName,
section: DocumentSection,
icon: ,
visible: !!canCollection.createTemplate,
diff --git a/app/models/Collection.test.ts b/app/models/Collection.test.ts
index 6397b90444..c1edf365be 100644
--- a/app/models/Collection.test.ts
+++ b/app/models/Collection.test.ts
@@ -9,4 +9,16 @@ describe("Collection model", () => {
});
expect(collection.name).toBe("Engineering");
});
+
+ it("should show the translated name for a personal collection", () => {
+ const collection = stores.collections.add({
+ id: "456",
+ name: "Renamed",
+ ownerId: "user-id",
+ });
+ expect(collection.displayName).toBe("Personal");
+
+ const shared = stores.collections.add({ id: "789", name: "Design" });
+ expect(shared.displayName).toBe("Design");
+ });
});
diff --git a/app/models/Collection.ts b/app/models/Collection.ts
index 228cac21ff..44e936ac66 100644
--- a/app/models/Collection.ts
+++ b/app/models/Collection.ts
@@ -1,3 +1,4 @@
+import i18n from "i18next";
import invariant from "invariant";
import {
action,
@@ -60,6 +61,10 @@ export default class Collection extends ParanoidModel {
@Field
@observable
permission?: CollectionPermission = undefined;
+
+ /** The user that owns this collection, if it is a personal collection. */
+ @observable
+ ownerId: string | null;
/**
* Whether public sharing is enabled for the collection. Note this can also be disabled at the
* workspace level.
@@ -116,7 +121,18 @@ export default class Collection extends ParanoidModel {
archivedBy?: User = undefined;
@computed
get searchContent(): string {
- return this.name;
+ return this.displayName;
+ }
+
+ /**
+ * The name to show for the collection. A personal collection is always shown
+ * with a translated name, whatever name is stored.
+ *
+ * @returns the name to display.
+ */
+ @computed
+ get displayName(): string {
+ return this.isPersonal ? i18n.t("Personal") : this.name;
}
/** Returns whether the collection is empty, or undefined if not loaded. */
@@ -143,6 +159,15 @@ export default class Collection extends ParanoidModel {
return this.permission === null;
}
+ /**
+ * Whether this collection is the personal collection of a user.
+ *
+ * @returns boolean
+ */
+ get isPersonal(): boolean {
+ return !!this.ownerId;
+ }
+
@computed
get isStarred(): boolean {
return !!this.store.rootStore.stars.orderedData.find(
@@ -199,7 +224,7 @@ export default class Collection extends ParanoidModel {
/** The initial letter of the collection name as a string. */
@computed
get initial() {
- return (this.name?.charAt(0) ?? "?").toUpperCase();
+ return (this.displayName?.charAt(0) ?? "?").toUpperCase();
}
@computed
diff --git a/app/models/Document.ts b/app/models/Document.ts
index 8256c06742..2051baf53e 100644
--- a/app/models/Document.ts
+++ b/app/models/Document.ts
@@ -135,6 +135,12 @@ export default class Document extends ArchivableModel implements Searchable {
@Relation(() => Collection, { onDelete: "cascade" })
collection?: Collection;
+ /**
+ * The owner of the personal collection that this document is in, if any.
+ */
+ @observable
+ ownerId?: string | null;
+
/**
* The title of the document.
*/
diff --git a/app/models/Notification.ts b/app/models/Notification.ts
index 6fd4c29f49..e925f3193d 100644
--- a/app/models/Notification.ts
+++ b/app/models/Notification.ts
@@ -256,7 +256,7 @@ class Notification extends Model {
return this.document?.title ?? t("a document");
}
if (this.collectionId) {
- return this.collection?.name ?? t("a collection");
+ return this.collection?.displayName ?? t("a collection");
}
if (this.groupId) {
return this.group?.name ?? t("a group");
diff --git a/app/scenes/Collection/components/Actions.tsx b/app/scenes/Collection/components/Actions.tsx
index 8b638d9b59..5b6bc458f3 100644
--- a/app/scenes/Collection/components/Actions.tsx
+++ b/app/scenes/Collection/components/Actions.tsx
@@ -53,7 +53,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) {
return (
<>
- {(!isEditing || !user?.separateEditMode) && (
+ {(!isEditing || !user?.separateEditMode) && !collection.isPersonal && (
diff --git a/app/scenes/Collection/components/Empty.tsx b/app/scenes/Collection/components/Empty.tsx
index 3226725a0e..19cb5dbda7 100644
--- a/app/scenes/Collection/components/Empty.tsx
+++ b/app/scenes/Collection/components/Empty.tsx
@@ -12,7 +12,7 @@ type Props = {
};
function EmptyCollection({ collection }: Props) {
- const collectionName = collection ? collection.name : "";
+ const collectionName = collection ? collection.displayName : "";
return (
diff --git a/app/scenes/Collection/components/Header.tsx b/app/scenes/Collection/components/Header.tsx
index c9252fb53e..5236130477 100644
--- a/app/scenes/Collection/components/Header.tsx
+++ b/app/scenes/Collection/components/Header.tsx
@@ -49,7 +49,7 @@ export const Header = observer(function Header_({
) : null;
- const dir = isRTL(collection.name) ? "rtl" : "ltr";
+ const dir = isRTL(collection.displayName) ? "rtl" : "ltr";
return (
@@ -80,7 +80,7 @@ export const Header = observer(function Header_({
dir="auto"
/>
) : (
- collection.name
+ collection.displayName
)}
);
diff --git a/app/scenes/Collection/index.tsx b/app/scenes/Collection/index.tsx
index 9c067deacc..01ea0fcd1c 100644
--- a/app/scenes/Collection/index.tsx
+++ b/app/scenes/Collection/index.tsx
@@ -98,7 +98,7 @@ const CollectionScene = observer(function CollectionScene_() {
}, [collection, collection?.name, history, id, match.url]);
useEffect(() => {
- if (collection) {
+ if (collection && !collection.isPersonal) {
ui.setActiveCollection(collection.id);
}
@@ -140,12 +140,17 @@ const CollectionScene = observer(function CollectionScene_() {
return ;
}
+ // A personal collection is only shown in the sidebar, it has no page.
+ if (collection.isPersonal) {
+ return ;
+ }
+
const showOverview = can.update || hasDescription;
return (
@@ -161,12 +166,14 @@ const CollectionScene = observer(function CollectionScene_() {
title={
<>
- {collection.name}
+ {collection.displayName}
>
}
actions={
<>
-
+ {!collection.isPersonal && (
+
+ )}
{collections.nonPrivate.map((collection) => (
- {collection.name}
+ {collection.displayName}
))}
>
}
diff --git a/app/scenes/Search/components/CollectionFilter.tsx b/app/scenes/Search/components/CollectionFilter.tsx
index 18768b7bfc..f61c65ef6a 100644
--- a/app/scenes/Search/components/CollectionFilter.tsx
+++ b/app/scenes/Search/components/CollectionFilter.tsx
@@ -20,7 +20,7 @@ function CollectionFilter(props: Props) {
const options = useMemo(() => {
const collectionOptions = collections.orderedData.map((collection) => ({
key: collection.id,
- label: collection.name,
+ label: collection.displayName,
icon: ,
}));
return [
diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx
index 35ac63e6d0..e8ab25a5d7 100644
--- a/app/scenes/Settings/Security.tsx
+++ b/app/scenes/Settings/Security.tsx
@@ -164,6 +164,17 @@ function Security() {
[saveData, team.preferences]
);
+ const handlePersonalDocsChange = React.useCallback(
+ async (checked: boolean) => {
+ const preferences = {
+ ...team.preferences,
+ [TeamPreference.PersonalDocs]: checked,
+ };
+ await saveData({ preferences });
+ },
+ [saveData, team.preferences]
+ );
+
const handleViewersCanExportChange = React.useCallback(
async (checked: boolean) => {
const preferences = {
@@ -389,6 +400,19 @@ function Security() {
short
/>
+
+
+
,
to: collectionPath(collection),
diff --git a/app/scenes/Settings/components/TemplatesTable.tsx b/app/scenes/Settings/components/TemplatesTable.tsx
index 6c29e9167f..b46a3e7224 100644
--- a/app/scenes/Settings/components/TemplatesTable.tsx
+++ b/app/scenes/Settings/components/TemplatesTable.tsx
@@ -97,7 +97,7 @@ export function TemplatesTable(props: Props) {
type: "data",
id: "collectionId",
header: t("Visibility"),
- accessor: (template) => template.collection?.name,
+ accessor: (template) => template.collection?.displayName,
component: (template) => ,
width: "2fr",
},
@@ -198,7 +198,9 @@ const Permission = observer(({ template }: { template: Template }) => {
{template.collection ? (
) : null}
- {template.collectionId ? template.collection?.name : t("Workspace")}
+ {template.collectionId
+ ? template.collection?.displayName
+ : t("Workspace")}
);
});
diff --git a/app/scenes/Shared/Collection.tsx b/app/scenes/Shared/Collection.tsx
index 94b527aeec..7230c066aa 100644
--- a/app/scenes/Shared/Collection.tsx
+++ b/app/scenes/Shared/Collection.tsx
@@ -54,12 +54,12 @@ function SharedCollection({ collection }: Props) {
return (
}
title={
<>
- {collection.name}
+ {collection.displayName}
>
}
actions={
@@ -75,7 +75,7 @@ function SharedCollection({ collection }: Props) {
- {collection.name}
+ {collection.displayName}
{!!shareId && showLastUpdated && !!collection.updatedAt ? (
diff --git a/app/scenes/Shared/index.tsx b/app/scenes/Shared/index.tsx
index 7c7471a85b..b52d216929 100644
--- a/app/scenes/Shared/index.tsx
+++ b/app/scenes/Shared/index.tsx
@@ -138,7 +138,7 @@ function SharedScene() {
const pageTitle =
model instanceof Collection
- ? model.name
+ ? model.displayName
: model instanceof Document
? model.title
: undefined;
diff --git a/app/stores/CollectionsStore.ts b/app/stores/CollectionsStore.ts
index c431ca9671..674101bf46 100644
--- a/app/stores/CollectionsStore.ts
+++ b/app/stores/CollectionsStore.ts
@@ -31,9 +31,23 @@ export default class CollectionsStore extends IndexedStore {
: undefined;
}
+ /** Active collections, other than the personal collection. */
@computed
get allActive() {
- return this.orderedData.filter((c) => c.isActive);
+ return this.orderedData.filter((c) => c.isActive && !c.isPersonal);
+ }
+
+ /**
+ * Returns the personal collection of the current user, if it was loaded.
+ *
+ * @returns The personal Collection or undefined
+ */
+ @computed
+ get personal(): Collection | undefined {
+ const userId = this.rootStore.auth.user?.id;
+ return userId
+ ? this.orderedData.find((c) => c.ownerId === userId)
+ : undefined;
}
@override
@@ -73,7 +87,7 @@ export default class CollectionsStore extends IndexedStore {
get all(): Collection[] {
return sortBy(
Array.from(this.data.values()),
- (collection) => collection.name
+ (collection) => collection.displayName
);
}
diff --git a/plugins/webhooks/server/helpers/WebhookEventHelper.ts b/plugins/webhooks/server/helpers/WebhookEventHelper.ts
new file mode 100644
index 0000000000..3374b3d851
--- /dev/null
+++ b/plugins/webhooks/server/helpers/WebhookEventHelper.ts
@@ -0,0 +1,78 @@
+import { Op } from "sequelize";
+import {
+ Attachment,
+ Collection,
+ Document,
+ FileOperation,
+} from "@server/models";
+import type { Event } from "@server/types";
+
+export class WebhookEventHelper {
+ /**
+ * Whether an event relates to a personal collection, or to a document,
+ * attachment or file operation in one. Such events are never sent to workspace webhooks,
+ * as any admin can change where a webhook delivers to.
+ *
+ * @param event The event to check.
+ * @returns true if the event is in a personal collection.
+ */
+ public static async isInPersonalCollection(event: Event): Promise {
+ const modelId = "modelId" in event ? event.modelId : null;
+ const collectionIds: string[] = [];
+ let documentId = "documentId" in event ? event.documentId : null;
+
+ if ("collectionId" in event && event.collectionId) {
+ collectionIds.push(event.collectionId);
+ }
+ if (event.name.startsWith("collections.") && modelId) {
+ collectionIds.push(modelId);
+ }
+
+ if (event.name.startsWith("fileOperations.") && modelId) {
+ const fileOperation = await FileOperation.unscoped().findOne({
+ attributes: ["collectionId", "documentId"],
+ where: { id: modelId },
+ paranoid: false,
+ });
+ if (fileOperation?.collectionId) {
+ collectionIds.push(fileOperation.collectionId);
+ }
+ documentId = documentId ?? fileOperation?.documentId ?? null;
+ }
+
+ if (event.name.startsWith("attachments.") && modelId) {
+ const attachment = await Attachment.unscoped().findOne({
+ attributes: ["documentId"],
+ where: { id: modelId },
+ paranoid: false,
+ });
+ documentId = documentId ?? attachment?.documentId ?? null;
+ }
+
+ // The document may have moved since the event, so its current collection
+ // is checked as well.
+ if (documentId) {
+ const document = await Document.unscoped().findOne({
+ attributes: ["collectionId"],
+ where: { id: documentId },
+ paranoid: false,
+ });
+ if (document?.collectionId) {
+ collectionIds.push(document.collectionId);
+ }
+ }
+
+ if (!collectionIds.length) {
+ return false;
+ }
+
+ const count = await Collection.unscoped().count({
+ where: {
+ id: collectionIds,
+ ownerId: { [Op.ne]: null },
+ },
+ paranoid: false,
+ });
+ return count > 0;
+ }
+}
diff --git a/plugins/webhooks/server/processors/WebhookProcessor.test.ts b/plugins/webhooks/server/processors/WebhookProcessor.test.ts
index dae000d664..75f9758260 100644
--- a/plugins/webhooks/server/processors/WebhookProcessor.test.ts
+++ b/plugins/webhooks/server/processors/WebhookProcessor.test.ts
@@ -1,6 +1,13 @@
-import { buildUser, buildWebhookSubscription } from "@server/test/factories";
+import {
+ buildAdmin,
+ buildAttachment,
+ buildDocument,
+ buildPersonalCollection,
+ buildUser,
+ buildWebhookSubscription,
+} from "@server/test/factories";
import { mockTaskSchedule } from "@server/test/support";
-import type { UserEvent } from "@server/types";
+import type { AttachmentEvent, DocumentEvent, UserEvent } from "@server/types";
import WebhookProcessor from "./WebhookProcessor";
const ip = "127.0.0.1";
@@ -133,4 +140,72 @@ describe("WebhookProcessor", () => {
expect(await WebhookProcessor.shouldQueue(event)).toBe(false);
});
});
+
+ it("does not schedule events in a personal collection", async () => {
+ const owner = await buildUser();
+ const admin = await buildAdmin({ teamId: owner.teamId });
+ const personal = await buildPersonalCollection(owner);
+ const document = await buildDocument({
+ teamId: owner.teamId,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ for (const createdById of [admin.id, owner.id]) {
+ await buildWebhookSubscription({
+ teamId: owner.teamId,
+ createdById,
+ url: "http://example.com",
+ events: ["*"],
+ });
+ }
+ const processor = new WebhookProcessor();
+
+ const event: DocumentEvent = {
+ name: "documents.update",
+ documentId: document.id,
+ collectionId: personal.id,
+ teamId: owner.teamId,
+ actorId: owner.id,
+ ip,
+ createdAt: new Date().toISOString(),
+ data: { done: true },
+ };
+ schedule.mockClear();
+ await processor.perform(event);
+
+ expect(schedule).not.toHaveBeenCalled();
+ });
+
+ it("does not schedule attachment events in a personal collection", async () => {
+ const owner = await buildUser();
+ const personal = await buildPersonalCollection(owner);
+ const document = await buildDocument({
+ teamId: owner.teamId,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ const attachment = await buildAttachment({
+ teamId: owner.teamId,
+ userId: owner.id,
+ documentId: document.id,
+ });
+ await buildWebhookSubscription({
+ teamId: owner.teamId,
+ url: "http://example.com",
+ events: ["*"],
+ });
+
+ const event: AttachmentEvent = {
+ name: "attachments.create",
+ modelId: attachment.id,
+ teamId: owner.teamId,
+ actorId: owner.id,
+ ip,
+ data: { name: attachment.name },
+ };
+ schedule.mockClear();
+ await new WebhookProcessor().perform(event);
+
+ expect(schedule).not.toHaveBeenCalled();
+ });
});
diff --git a/plugins/webhooks/server/processors/WebhookProcessor.ts b/plugins/webhooks/server/processors/WebhookProcessor.ts
index 1a4b14097f..df2ad856d1 100644
--- a/plugins/webhooks/server/processors/WebhookProcessor.ts
+++ b/plugins/webhooks/server/processors/WebhookProcessor.ts
@@ -1,6 +1,7 @@
import { WebhookSubscription } from "@server/models";
import BaseProcessor from "@server/queues/processors/BaseProcessor";
import type { Event } from "@server/types";
+import { WebhookEventHelper } from "../helpers/WebhookEventHelper";
import DeliverWebhookTask from "../tasks/DeliverWebhookTask";
export default class WebhookProcessor extends BaseProcessor {
@@ -40,6 +41,12 @@ export default class WebhookProcessor extends BaseProcessor {
const applicableSubscriptions = subscriptions.filter((subscription) =>
WebhookSubscription.matchEvent(subscription.events, event.name)
);
+ if (
+ !applicableSubscriptions.length ||
+ (await WebhookEventHelper.isInPersonalCollection(event))
+ ) {
+ return;
+ }
await Promise.all(
applicableSubscriptions.map((subscription) =>
diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts
index 0b007ea601..ba21f0b824 100644
--- a/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts
+++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts
@@ -8,11 +8,14 @@ import {
import { server } from "@server/test/msw";
import { WebhookDelivery } from "@server/models";
import {
+ buildCollection,
+ buildDocument,
+ buildPersonalCollection,
buildUser,
buildWebhookDelivery,
buildWebhookSubscription,
} from "@server/test/factories";
-import type { UserEvent } from "@server/types";
+import type { DocumentEvent, UserEvent } from "@server/types";
import DeliverWebhookTask, {
isExpectedNetworkError,
} from "./DeliverWebhookTask";
@@ -40,6 +43,50 @@ const captureWebhook = (
};
describe("DeliverWebhookTask", () => {
+ test("should not deliver events in a personal collection", async () => {
+ const owner = await buildUser();
+ const subscription = await buildWebhookSubscription({
+ teamId: owner.teamId,
+ createdById: owner.id,
+ url: "http://example.com",
+ events: ["*"],
+ });
+ const previous = await buildCollection({
+ teamId: owner.teamId,
+ userId: owner.id,
+ });
+ const personal = await buildPersonalCollection(owner);
+ const document = await buildDocument({
+ teamId: owner.teamId,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ const captured = captureWebhook("http://example.com");
+
+ // The event was queued before the document moved to the personal collection.
+ const event: DocumentEvent = {
+ name: "documents.update",
+ documentId: document.id,
+ collectionId: previous.id,
+ teamId: owner.teamId,
+ actorId: owner.id,
+ ip,
+ createdAt: new Date().toISOString(),
+ data: { done: true },
+ };
+ await new DeliverWebhookTask().perform({
+ subscriptionId: subscription.id,
+ event,
+ });
+
+ expect(captured.length).toBe(0);
+ expect(
+ await WebhookDelivery.count({
+ where: { webhookSubscriptionId: subscription.id },
+ })
+ ).toBe(0);
+ });
+
test("should hit the subscription url and record a delivery", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts
index c9db826617..362b306ce7 100644
--- a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts
+++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts
@@ -71,6 +71,7 @@ import type {
WebhookSubscriptionEvent,
} from "@server/types";
import fetch from "@server/utils/fetch";
+import { WebhookEventHelper } from "../helpers/WebhookEventHelper";
import type { WebhookPayload } from "../presenters/webhook";
import presentWebhook from "../presenters/webhook";
import presentWebhookSubscription from "../presenters/webhookSubscription";
@@ -151,6 +152,16 @@ export default class DeliverWebhookTask extends BaseTask {
return;
}
+ // Checked again, as a document can move into a personal collection after
+ // the delivery was queued.
+ if (await WebhookEventHelper.isInPersonalCollection(event)) {
+ Logger.info("task", `Skipped webhook for personal collection event`, {
+ event: event.name,
+ subscriptionId: subscription.id,
+ });
+ return;
+ }
+
Logger.info("task", `DeliverWebhookTask: ${event.name}`, {
event: event.name,
subscriptionId: subscription.id,
diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts
index aa69671cd2..8b9103c48e 100644
--- a/server/commands/accountProvisioner.ts
+++ b/server/commands/accountProvisioner.ts
@@ -217,6 +217,7 @@ async function accountProvisioner(
const count = await Collection.count({
where: {
teamId: team.id,
+ ownerId: null,
},
});
provision = count === 0;
diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts
index dd0e09b388..8d4afaf09f 100644
--- a/server/commands/documentCreator.ts
+++ b/server/commands/documentCreator.ts
@@ -1,4 +1,5 @@
import type { Optional } from "utility-types";
+import { PersonalCollectionId } from "@shared/constants";
import { TextHelper } from "@shared/utils/TextHelper";
import { Collection, Document, type Template } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
@@ -6,6 +7,7 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import { authorize } from "@server/policies";
import type { APIContext } from "@server/types";
import { assertPresent } from "@server/validation";
+import personalCollectionLoader from "./personalCollectionLoader";
type Props = Optional<
Pick<
@@ -50,7 +52,9 @@ type CreateLocation = {
* the collection and parent document it will belong to. Shared by the
* documents.create API route and the MCP create_document tool so that both
* enforce identical permissions, including the team-level check that prevents
- * viewers and guests from creating drafts with no collection.
+ * viewers and guests from creating drafts with no collection. The collectionId
+ * "personal" refers to the personal collection of the user, which is created
+ * when it does not exist yet.
*
* @param ctx the API context containing the acting user.
* @param location the requested collection and/or parent document.
@@ -83,10 +87,13 @@ export async function authorizeDocumentCreate(
}
if (collectionId) {
- const collection = await Collection.findByPk(collectionId, {
- userId: user.id,
- transaction,
- });
+ const collection =
+ collectionId === PersonalCollectionId
+ ? await personalCollectionLoader(ctx)
+ : await Collection.findByPk(collectionId, {
+ userId: user.id,
+ transaction,
+ });
authorize(user, "createDocument", collection);
return { collection };
}
diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts
index 6530fbba68..0c51e48368 100644
--- a/server/commands/documentMover.test.ts
+++ b/server/commands/documentMover.test.ts
@@ -2,6 +2,7 @@ import Pin from "@server/models/Pin";
import {
buildDocument,
buildCollection,
+ buildPersonalCollection,
buildTeam,
buildUser,
} from "@server/test/factories";
@@ -205,6 +206,46 @@ describe("documentMover", () => {
expect(response.documents[0].updatedBy.id).toEqual(user.id);
});
+ it("should remove all pins if moved to a personal collection", async () => {
+ const team = await buildTeam();
+ const user = await buildUser({ teamId: team.id });
+ const collection = await buildCollection({
+ userId: user.id,
+ teamId: team.id,
+ });
+ const document = await buildDocument({
+ userId: user.id,
+ collectionId: collection.id,
+ teamId: team.id,
+ });
+ const child = await buildDocument({
+ userId: user.id,
+ collectionId: collection.id,
+ parentDocumentId: document.id,
+ teamId: team.id,
+ });
+ const personal = await buildPersonalCollection(user);
+ for (const documentId of [document.id, child.id]) {
+ await Pin.create({
+ createdById: user.id,
+ collectionId: null,
+ documentId,
+ teamId: team.id,
+ });
+ }
+
+ await withAPIContext(user, (ctx) =>
+ documentMover(ctx, {
+ document,
+ collectionId: personal.id,
+ parentDocumentId: undefined,
+ index: 0,
+ })
+ );
+
+ expect(await Pin.count({ where: { teamId: team.id } })).toBe(0);
+ });
+
it("should detach document from collection and move it to drafts", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts
index 28c8284661..4bf1c8107b 100644
--- a/server/commands/documentMover.ts
+++ b/server/commands/documentMover.ts
@@ -190,6 +190,21 @@ async function documentMover(
});
await pin?.destroyWithCtx(ctx);
+
+ // Pins are not shown for documents in a personal collection, so any pin of
+ // the moved documents, including pins to home, is removed.
+ if (newCollection?.isPersonal) {
+ const pins = await Pin.findAll({
+ where: {
+ documentId: [document.id, ...childDocumentIds],
+ },
+ transaction,
+ lock: Transaction.LOCK.UPDATE,
+ });
+ for (const personalPin of pins) {
+ await personalPin.destroyWithCtx(ctx);
+ }
+ }
}
result.documents.push(document);
diff --git a/server/commands/personalCollectionLoader.ts b/server/commands/personalCollectionLoader.ts
new file mode 100644
index 0000000000..692d7b9f40
--- /dev/null
+++ b/server/commands/personalCollectionLoader.ts
@@ -0,0 +1,64 @@
+import { PersonalCollectionId } from "@shared/constants";
+import { createContext } from "@server/context";
+import { Collection } from "@server/models";
+import { authorize } from "@server/policies";
+import { sequelize } from "@server/storage/database";
+import type { APIContext } from "@server/types";
+
+/**
+ * Loads the personal collection of the acting user, and creates it when the
+ * user does not have one yet.
+ *
+ * @param ctx the API context containing the acting user.
+ * @returns the personal collection, with the memberships of the user loaded.
+ * @throws AuthorizationError when the collection does not exist and the user
+ * may not create it.
+ */
+export default async function personalCollectionLoader(
+ ctx: APIContext
+): Promise {
+ const { user } = ctx.state.auth;
+ const { transaction } = ctx.state;
+
+ const existing = await Collection.findPersonal(user, { transaction });
+ if (existing) {
+ return existing;
+ }
+
+ authorize(user, "createPersonalCollection", user.team);
+
+ if (transaction) {
+ return Collection.findOrCreatePersonal(ctx);
+ }
+
+ // The creation lock is only held inside a transaction.
+ return sequelize.transaction((innerTransaction) =>
+ Collection.findOrCreatePersonal(
+ createContext({
+ user,
+ authType: ctx.state.auth.type,
+ ip: ctx.context.ip,
+ transaction: innerTransaction,
+ })
+ )
+ );
+}
+
+/**
+ * Resolves the collectionId "personal" to the id of the personal collection of
+ * the acting user, which is created when it does not exist yet. Other values
+ * are returned unchanged.
+ *
+ * @param ctx the API context containing the acting user.
+ * @param collectionId the requested collectionId.
+ * @returns the resolved collectionId.
+ * @throws AuthorizationError when the collection does not exist and the user
+ * may not create it.
+ */
+export async function resolvePersonalCollectionId<
+ T extends string | null | undefined,
+>(ctx: APIContext, collectionId: T): Promise {
+ return collectionId === PersonalCollectionId
+ ? (await personalCollectionLoader(ctx)).id
+ : collectionId;
+}
diff --git a/server/commands/teamUpdater.ts b/server/commands/teamUpdater.ts
index 8aa08af663..4b320471ae 100644
--- a/server/commands/teamUpdater.ts
+++ b/server/commands/teamUpdater.ts
@@ -3,7 +3,7 @@ import { TeamPreference } from "@shared/types";
import env from "@server/env";
import { ValidationError } from "@server/errors";
import type { User } from "@server/models";
-import { Team, TeamDomain } from "@server/models";
+import { Collection, Team, TeamDomain } from "@server/models";
import type { APIContext } from "@server/types";
type Props = {
@@ -16,6 +16,22 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
const { allowedDomains, preferences, subdomain, ...attributes } = params;
team.setAttributes(attributes);
+ if (attributes.defaultCollectionId) {
+ const collection = await Collection.findOne({
+ attributes: ["id"],
+ where: {
+ id: attributes.defaultCollectionId,
+ teamId: team.id,
+ ownerId: null,
+ },
+ transaction: ctx.state.transaction,
+ });
+
+ if (!collection) {
+ throw ValidationError("Default collection not found");
+ }
+ }
+
if (subdomain !== undefined && env.isCloudHosted) {
const newSubdomain = subdomain === "" ? null : subdomain;
diff --git a/server/mcp/index.ts b/server/mcp/index.ts
index 682a9219a6..de890cc309 100644
--- a/server/mcp/index.ts
+++ b/server/mcp/index.ts
@@ -103,4 +103,6 @@ Read images and attachments with the "fetch" tool by setting resource to "attach
Base64-encoded images are supported in document content for all formats. When creating a document from HTML that includes images or videos, pass the markup with format "html" — remote URLs and base64 media are imported as attachments automatically. Do not convert such HTML to markdown, and do not upload the HTML file itself as an attachment.
+Each user can have a personal collection, marked with isPersonal. It is private to that user, cannot be shared as a collection, and cannot be renamed or archived. Use the collectionId "personal" in create_document, move_document or update_document to place a document in it; the collection is created if it does not exist yet.
+
When asked to create a document that follows a template, use the "list_templates" tool to find a matching template; each result already includes the template body as markdown. To use it unchanged, pass its ID as templateId to "create_document" and the new document is pre-filled from it. To adapt it first, modify the returned body and pass the result as the text parameter to "create_document". Either way no separate fetch is needed.`;
diff --git a/server/mcp/tools/collections.test.ts b/server/mcp/tools/collections.test.ts
index 813c795522..9d2cfbd37a 100644
--- a/server/mcp/tools/collections.test.ts
+++ b/server/mcp/tools/collections.test.ts
@@ -1,6 +1,10 @@
import { DeprecationValidation } from "@shared/validations";
import { Collection } from "@server/models";
-import { buildCollection, buildUser } from "@server/test/factories";
+import {
+ buildCollection,
+ buildPersonalCollection,
+ buildUser,
+} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import {
buildOAuthUser,
@@ -32,6 +36,23 @@ describe("collection tools", () => {
expect(match!.url).toMatch(/^https?:\/\//);
});
+ it("list_collections marks the personal collection", async () => {
+ const { user, accessToken } = await buildOAuthUser();
+ const collection = await buildCollection({
+ teamId: user.teamId,
+ userId: user.id,
+ });
+ const personal = await buildPersonalCollection(user);
+
+ const res = await callMcpTool(server, accessToken, "list_collections");
+ const data = parseMcpListContent<{ id: string; isPersonal: boolean }>(
+ res?.result?.content
+ );
+
+ expect(data.find((c) => c.id === personal.id)?.isPersonal).toBe(true);
+ expect(data.find((c) => c.id === collection.id)?.isPersonal).toBe(false);
+ });
+
it("list_collections filters by name ignoring case", async () => {
const { user, accessToken } = await buildOAuthUser();
const collection = await buildCollection({
@@ -117,6 +138,20 @@ describe("collection tools", () => {
expect(collection.description).toEqual("Updated description");
});
+ it("update_collection does not rename a personal collection", async () => {
+ const { user, accessToken } = await buildOAuthUser();
+ const collection = await buildPersonalCollection(user);
+
+ const res = await callMcpTool(server, accessToken, "update_collection", {
+ id: collection.id,
+ name: "Notes",
+ });
+
+ expect(res?.result?.isError).toBe(true);
+ await collection.reload();
+ expect(collection.name).toEqual("Personal");
+ });
+
it("update_collection errors when no fields are provided to update", async () => {
const { user, accessToken } = await buildOAuthUser();
const collection = await buildCollection({
diff --git a/server/mcp/tools/collections.ts b/server/mcp/tools/collections.ts
index 85e886595b..c6a8fd1e1c 100644
--- a/server/mcp/tools/collections.ts
+++ b/server/mcp/tools/collections.ts
@@ -28,11 +28,14 @@ import {
* @param collection - the collection to present.
* @returns the presented collection object.
*/
-export function presentCollection(collection: Collection) {
- return presentCollectionBase(undefined, collection, {
- includeData: false,
- includeText: true,
- });
+export async function presentCollection(collection: Collection) {
+ return {
+ ...(await presentCollectionBase(undefined, collection, {
+ includeData: false,
+ includeText: true,
+ })),
+ isPersonal: collection.isPersonal,
+ };
}
/**
diff --git a/server/mcp/tools/documents.test.ts b/server/mcp/tools/documents.test.ts
index 2c3063f180..e105f0c24e 100644
--- a/server/mcp/tools/documents.test.ts
+++ b/server/mcp/tools/documents.test.ts
@@ -1,16 +1,23 @@
import { DeprecationValidation } from "@shared/validations";
-import { CollectionPermission, DocumentPermission, Scope } from "@shared/types";
+import {
+ CollectionPermission,
+ DocumentPermission,
+ Scope,
+ TeamPreference,
+} from "@shared/types";
import {
buildUser,
buildViewer,
buildCollection,
buildDocument,
+ buildDraftDocument,
buildTemplate,
buildOAuthAuthentication,
buildGroup,
} from "@server/test/factories";
import {
Attachment,
+ Collection,
Document,
GroupMembership,
SearchQuery,
@@ -384,6 +391,26 @@ describe("list_documents", () => {
});
describe("create_document", () => {
+ it("creates in the personal collection", async () => {
+ const { user, accessToken } = await buildOAuthUser();
+ user.team.setPreference(TeamPreference.PersonalDocs, true);
+ await user.team.save();
+
+ const res = await callMcpTool(server, accessToken, "create_document", {
+ title: "Personal Document",
+ collectionId: "personal",
+ });
+ const data = JSON.parse(res?.result?.content?.[0]?.text ?? "{}");
+ expect(data.success).toBe(true);
+
+ const document = await Document.findByPk(data.id, { rejectOnEmpty: true });
+ const collection = await Collection.findOne({
+ where: { ownerId: user.id },
+ rejectOnEmpty: true,
+ });
+ expect(document.collectionId).toEqual(collection.id);
+ });
+
it("creates in a collection", async () => {
const { user, accessToken } = await buildOAuthUser();
const collection = await buildCollection({
@@ -604,6 +631,54 @@ describe("create_document", () => {
});
describe("update_document", () => {
+ it("does not create the personal collection when it is not used", 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, "update_document", {
+ id: document.id,
+ title: "Renamed",
+ collectionId: "personal",
+ });
+ expect(res?.result?.isError).toBeFalsy();
+ expect(await Collection.count({ where: { ownerId: user.id } })).toEqual(0);
+
+ await document.reload();
+ expect(document.collectionId).toEqual(collection.id);
+ });
+
+ it("publishes a draft to the personal collection", async () => {
+ const { user, accessToken } = await buildOAuthUser();
+ const document = await buildDraftDocument({
+ teamId: user.teamId,
+ userId: user.id,
+ collectionId: null,
+ });
+
+ const res = await callMcpTool(server, accessToken, "update_document", {
+ id: document.id,
+ publish: true,
+ collectionId: "personal",
+ });
+ expect(res?.result?.isError).toBeFalsy();
+
+ const personal = await Collection.findOne({
+ where: { ownerId: user.id },
+ rejectOnEmpty: true,
+ });
+ await document.reload();
+ expect(document.collectionId).toEqual(personal.id);
+ expect(document.publishedAt).not.toBeNull();
+ });
+
it("updates title and text", async () => {
const { user, accessToken } = await buildOAuthUser();
const collection = await buildCollection({
@@ -791,6 +866,32 @@ describe("update_document", () => {
});
describe("move_document", () => {
+ it("moves a document to the personal collection", 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,
+ collectionId: "personal",
+ });
+ expect(res?.result?.isError).toBeFalsy();
+
+ const personal = await Collection.findOne({
+ where: { ownerId: user.id },
+ rejectOnEmpty: true,
+ });
+ await document.reload();
+ expect(document.collectionId).toEqual(personal.id);
+ });
+
it("moves to a different collection", async () => {
const { user, accessToken } = await buildOAuthUser();
const collection1 = await buildCollection({
diff --git a/server/mcp/tools/documents.ts b/server/mcp/tools/documents.ts
index 30c4d53b43..4d90a010dd 100644
--- a/server/mcp/tools/documents.ts
+++ b/server/mcp/tools/documents.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { PersonalCollectionId } from "@shared/constants";
import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import documentCreator, {
@@ -6,6 +7,7 @@ import documentCreator, {
authorizeDocumentPublish,
} from "@server/commands/documentCreator";
import documentMover from "@server/commands/documentMover";
+import { resolvePersonalCollectionId } from "@server/commands/personalCollectionLoader";
import documentRestorer from "@server/commands/documentRestorer";
import documentUpdater from "@server/commands/documentUpdater";
import { Collection, Document, SearchQuery, Template } from "@server/models";
@@ -368,8 +370,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
"create_document",
{
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.",
+ 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. Use the collectionId "${PersonalCollectionId}" to place the document in the user's personal collection, which only they can see and which is created if it does not exist yet. 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,
@@ -394,7 +395,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
'The name of the file the content was read from, e.g. "notes.md". Recorded on the document and shown to users as the file it was imported from, so only set it when the content genuinely came from a file. Also used as the title when the content has no heading and no title is given.'
),
collectionId: optionalString().describe(
- "The collection to place the document in."
+ `The collection to place the document in, or "${PersonalCollectionId}" for the user's personal collection.`
),
parentDocumentId: optionalString().describe(
"The parent document ID to nest this document under."
@@ -520,7 +521,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
.string()
.describe("The unique identifier of the document to move."),
collectionId: optionalString().describe(
- "The destination collection ID. Required if parentDocumentId is not provided."
+ `The destination collection ID, or "${PersonalCollectionId}" for the user's personal collection. Required if parentDocumentId is not provided.`
),
parentDocumentId: optionalString().describe(
"The ID of the document to nest this document under. The document will be moved to the parent's collection."
@@ -552,7 +553,11 @@ export function documentTools(server: McpServer, scopes: string[]) {
authorize(user, "move", document);
- let collectionId = input.collectionId;
+ // A parent decides the collection, so the personal collection is
+ // only resolved, and created, when there is no parent.
+ let collectionId = input.parentDocumentId
+ ? input.collectionId
+ : await resolvePersonalCollectionId(ctx, input.collectionId);
if (input.parentDocumentId) {
if (input.parentDocumentId === input.id) {
@@ -644,7 +649,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
'Required when editMode is "patch". The exact markdown substring to find in the document. This should be copied verbatim from the document\'s existing markdown content. The first occurrence will be replaced with the text parameter. Can span multiple blocks (paragraphs, headings, etc).'
),
collectionId: optionalString().describe(
- "The collection ID to publish a draft to, required when publishing a draft that has no collection."
+ `The collection ID to publish a draft to, or "${PersonalCollectionId}" for the user's personal collection. Required when publishing a draft that has no collection.`
),
icon: z
.string()
@@ -696,8 +701,17 @@ export function documentTools(server: McpServer, scopes: string[]) {
} else {
authorize(user, "update", document);
+ // The collection is only used when publishing a draft that has
+ // none, so the personal collection is only created in that case.
+ const collectionId =
+ input.collectionId === PersonalCollectionId
+ ? input.publish && !document.collectionId
+ ? await resolvePersonalCollectionId(ctx, input.collectionId)
+ : undefined
+ : input.collectionId;
+
if (input.publish) {
- await authorizeDocumentPublish(ctx, document, input.collectionId);
+ await authorizeDocumentPublish(ctx, document, collectionId);
}
const { revisionCount } = document;
@@ -705,6 +719,7 @@ export function documentTools(server: McpServer, scopes: string[]) {
updated = await documentUpdater(ctx, {
document,
...input,
+ collectionId,
});
// Every save increments revisionCount, so an unchanged count means
diff --git a/server/migrations/20261012120000-add-owner-id-to-collections.js b/server/migrations/20261012120000-add-owner-id-to-collections.js
new file mode 100644
index 0000000000..8feaea3f33
--- /dev/null
+++ b/server/migrations/20261012120000-add-owner-id-to-collections.js
@@ -0,0 +1,51 @@
+"use strict";
+
+/** @type {import('sequelize-cli').Migration} */
+module.exports = {
+ async up(queryInterface, Sequelize) {
+ await queryInterface.sequelize.transaction(async (transaction) => {
+ await queryInterface.addColumn(
+ "collections",
+ "ownerId",
+ {
+ type: Sequelize.UUID,
+ allowNull: true,
+ references: {
+ model: "users",
+ },
+ onDelete: "SET NULL",
+ },
+ { transaction }
+ );
+
+ // A personal collection must always be private.
+ await queryInterface.sequelize.query(
+ `ALTER TABLE "collections" ADD CONSTRAINT "collections_owner_id_private"
+ CHECK ("ownerId" IS NULL OR "permission" IS NULL);`,
+ { transaction }
+ );
+ });
+
+ // One personal collection per user and team. The leading ownerId column
+ // also covers the foreign key checks when a user is deleted.
+ await queryInterface.sequelize.query(
+ `CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "collections_owner_id_team_id"
+ ON "collections" ("ownerId", "teamId") WHERE "ownerId" IS NOT NULL;`
+ );
+ },
+
+ async down(queryInterface) {
+ await queryInterface.sequelize.query(
+ 'DROP INDEX CONCURRENTLY IF EXISTS "collections_owner_id_team_id";'
+ );
+ await queryInterface.sequelize.transaction(async (transaction) => {
+ await queryInterface.sequelize.query(
+ 'ALTER TABLE "collections" DROP CONSTRAINT IF EXISTS "collections_owner_id_private";',
+ { transaction }
+ );
+ await queryInterface.removeColumn("collections", "ownerId", {
+ transaction,
+ });
+ });
+ },
+};
diff --git a/server/models/Collection.ts b/server/models/Collection.ts
index 86582f5e88..3c2f7348d8 100644
--- a/server/models/Collection.ts
+++ b/server/models/Collection.ts
@@ -429,7 +429,9 @@ class Collection extends ParanoidModel<
const total = await this.count({
where: {
teamId: model.teamId,
+ ownerId: null,
},
+ transaction: options.transaction,
});
if (total === 1) {
throw ValidationError("Cannot delete last collection");
@@ -514,6 +516,19 @@ class Collection extends ParanoidModel<
return existing;
}
+ @BeforeUpdate
+ static checkPersonal(model: Collection) {
+ if (!model.ownerId) {
+ return;
+ }
+ if (model.changed("name")) {
+ throw ValidationError("A personal collection cannot be renamed");
+ }
+ if (model.changed("permission") && model.permission) {
+ throw ValidationError("A personal collection must stay private");
+ }
+ }
+
@BeforeUpdate
static async checkIndex(
model: Collection,
@@ -569,6 +584,15 @@ class Collection extends ParanoidModel<
@Column(DataType.UUID)
archivedById?: string | null;
+ /** The user that owns this collection, if it is a personal collection. */
+ @BelongsTo(() => User, "ownerId")
+ owner?: User | null;
+
+ @AllowNull
+ @ForeignKey(() => User)
+ @Column(DataType.UUID)
+ ownerId: string | null;
+
@HasMany(() => Document, "collectionId")
documents: Document[];
@@ -751,6 +775,7 @@ class Collection extends ParanoidModel<
return this.findOne({
where: {
teamId: user.teamId,
+ ownerId: null,
id,
},
order: [
@@ -762,6 +787,81 @@ class Collection extends ParanoidModel<
});
}
+ /**
+ * Find the personal collection of a user, with the memberships of the user
+ * loaded.
+ *
+ * @param user The user that owns the collection.
+ * @param options Additional options for the query.
+ * @returns the personal collection, or null if the user has none.
+ */
+ static async findPersonal(
+ user: User,
+ options: Omit, "where"> = {}
+ ) {
+ return this.scope([
+ "defaultScope",
+ { method: ["withMembership", user.id] },
+ ]).findOne({
+ ...options,
+ where: {
+ teamId: user.teamId,
+ ownerId: user.id,
+ },
+ });
+ }
+
+ /**
+ * Find the personal collection of the user in the context, and create it if
+ * the user does not have one yet. The caller must authorize the creation.
+ *
+ * @param ctx The request context with the acting user and a transaction.
+ * @returns the personal collection of the user.
+ */
+ static async findOrCreatePersonal(ctx: APIContext): Promise {
+ const { user } = ctx.state.auth;
+ const { transaction } = ctx.state;
+
+ const existing = await this.findPersonal(user, { transaction });
+ if (existing) {
+ return existing;
+ }
+
+ await LockHelper.acquire(
+ this.sequelize!,
+ `collections:personal:${user.teamId}:${user.id}`,
+ transaction
+ );
+
+ const locked = await this.findPersonal(user, { transaction });
+ if (locked) {
+ return locked;
+ }
+
+ const collection = await this.createWithCtx(ctx, {
+ name: "Personal",
+ teamId: user.teamId,
+ createdById: user.id,
+ ownerId: user.id,
+ permission: null,
+ });
+
+ // The owner membership is created without hooks, so clear the cache here.
+ const invalidate = () =>
+ CacheHelper.clearData(RedisPrefixHelper.getUserCollectionIdsKey(user.id));
+ if (transaction) {
+ transaction.afterCommit(invalidate);
+ } else {
+ await invalidate();
+ }
+
+ return this.findByPk(collection.id, {
+ userId: user.id,
+ transaction,
+ rejectOnEmpty: true,
+ });
+ }
+
/**
* Convenience method to return if a collection is considered private.
* This means that a membership is required to view it rather than just being
@@ -773,6 +873,16 @@ class Collection extends ParanoidModel<
return !this.permission;
}
+ /**
+ * Whether this collection is the personal collection of a user. A personal
+ * collection is private and only its owner can see or manage it.
+ *
+ * @returns boolean
+ */
+ get isPersonal() {
+ return !!this.ownerId;
+ }
+
/**
* Returns the collection's documentStructure via cache, populating it on
* miss. The cache is kept fresh by this model's save hooks, so callers
diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts
index b58df8f6f2..2282a59ec9 100644
--- a/server/models/FileOperation.ts
+++ b/server/models/FileOperation.ts
@@ -38,6 +38,8 @@ export type FileOperationOptions = {
includeAttachments?: boolean;
includePrivate?: boolean;
permission?: CollectionPermission | null;
+ /** The owner of the personal collection that was exported, if any. */
+ personalOwnerId?: string;
};
type AdditionalFindOptions = {
@@ -78,9 +80,18 @@ type CreateExportOptions =
{
model: Document.unscoped(),
as: "document",
- attributes: ["id", "title"],
+ attributes: ["id", "title", "collectionId"],
required: false,
paranoid: false,
+ include: [
+ {
+ model: Collection.unscoped(),
+ as: "collection",
+ attributes: ["id", "ownerId"],
+ required: false,
+ paranoid: false,
+ },
+ ],
},
],
}))
@@ -148,12 +159,29 @@ class FileOperation extends ParanoidModel<
): Promise {
const { user } = ctx.state.auth;
const format = options.format ?? FileOperationFormat.MarkdownZip;
+
+ // The owner is stored on the export, as a document can move out of the
+ // personal collection after it was exported.
+ const sourceCollectionId =
+ "document" in options
+ ? options.document.collectionId
+ : options.collection?.id;
+ const sourceCollection = sourceCollectionId
+ ? await Collection.unscoped().findOne({
+ attributes: ["ownerId"],
+ where: { id: sourceCollectionId },
+ transaction: ctx.state.transaction,
+ })
+ : null;
+ const personalOwnerId = sourceCollection?.ownerId ?? undefined;
+
const source =
"document" in options
? {
name: options.document.titleWithDefault,
documentId: options.document.id,
teamId: options.document.teamId,
+ options: personalOwnerId ? { personalOwnerId } : null,
}
: {
name: options.collection?.name || options.team.name,
@@ -162,6 +190,7 @@ class FileOperation extends ParanoidModel<
options: {
includeAttachments: options.includeAttachments ?? true,
includePrivate: options.includePrivate ?? true,
+ ...(personalOwnerId ? { personalOwnerId } : {}),
},
};
const { name, ...attributes } = source;
diff --git a/server/models/Share.ts b/server/models/Share.ts
index 6526154603..3d2e46b630 100644
--- a/server/models/Share.ts
+++ b/server/models/Share.ts
@@ -56,6 +56,7 @@ import Length from "./validators/Length";
"id",
"name",
"permission",
+ "ownerId",
"sharing",
"urlId",
"teamId",
@@ -81,6 +82,7 @@ import Length from "./validators/Length";
"id",
"name",
"permission",
+ "ownerId",
"urlId",
"sharing",
"teamId",
diff --git a/server/models/User.ts b/server/models/User.ts
index cc1b60fea3..3f1f47a81d 100644
--- a/server/models/User.ts
+++ b/server/models/User.ts
@@ -500,6 +500,10 @@ class User extends ParanoidModel<
attributes: ["id"],
where: {
teamId: this.teamId,
+ // Only the owner can access a personal collection.
+ ownerId: {
+ [Op.or]: [{ [Op.is]: null }, { [Op.eq]: this.id }],
+ },
[Op.or]: [
...(this.isGuest
? []
diff --git a/server/policies/collection.test.ts b/server/policies/collection.test.ts
index c43bc2a17c..fecc988328 100644
--- a/server/policies/collection.test.ts
+++ b/server/policies/collection.test.ts
@@ -1,10 +1,11 @@
-import { CollectionPermission, UserRole } from "@shared/types";
+import { CollectionPermission, TeamPreference, UserRole } from "@shared/types";
import { UserMembership, Collection } from "@server/models";
import {
buildUser,
buildTeam,
buildCollection,
buildAdmin,
+ buildPersonalCollection,
} from "@server/test/factories";
import { serialize } from "./index";
@@ -607,3 +608,126 @@ describe("manage templates", () => {
});
});
});
+
+describe("personal collection", () => {
+ const buildPersonal = async () => {
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.PersonalDocs, true);
+ await team.save();
+ const owner = await buildUser({ teamId: team.id });
+ const collection = await buildPersonalCollection(owner);
+ return { team, owner, collection };
+ };
+
+ it("should allow the owner to use but not share or remove it", async () => {
+ const { owner, collection } = await buildPersonal();
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: owner.id,
+ });
+ const abilities = serialize(owner, reloaded);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.readDocument).toBeTruthy();
+ expect(abilities.createDocument).toBeTruthy();
+ expect(abilities.updateDocument).toBeTruthy();
+ expect(abilities.update).toBeTruthy();
+ expect(abilities.export).toBeTruthy();
+ expect(abilities.shareDocument).toBeTruthy();
+ expect(abilities.share).toEqual(false);
+ expect(abilities.star).toEqual(false);
+ expect(abilities.unstar).toEqual(false);
+ expect(abilities.createTemplate).toEqual(false);
+ expect(abilities.manageTemplate).toEqual(false);
+ expect(abilities.manageUsers).toEqual(false);
+ expect(abilities.duplicate).toEqual(false);
+ expect(abilities.archive).toEqual(false);
+ expect(abilities.delete).toEqual(false);
+ expect(abilities.move).toEqual(false);
+ });
+
+ it("should allow nothing for a workspace admin", async () => {
+ const { team, collection } = await buildPersonal();
+ const admin = await buildAdmin({ teamId: team.id });
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: admin.id,
+ });
+ const abilities = serialize(admin, reloaded);
+ for (const [ability, value] of Object.entries(abilities)) {
+ expect({ ability, value }).toEqual({ ability, value: false });
+ }
+ });
+
+ it("should allow nothing for a workspace admin with a membership", async () => {
+ const { team, owner, collection } = await buildPersonal();
+ const admin = await buildAdmin({ teamId: team.id });
+ await UserMembership.create({
+ collectionId: collection.id,
+ userId: admin.id,
+ permission: CollectionPermission.Admin,
+ createdById: owner.id,
+ });
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: admin.id,
+ });
+ const abilities = serialize(admin, reloaded);
+ for (const [ability, value] of Object.entries(abilities)) {
+ expect({ ability, value }).toEqual({ ability, value: false });
+ }
+ });
+
+ it("should allow nothing for another member", async () => {
+ const { team, collection } = await buildPersonal();
+ const member = await buildUser({ teamId: team.id });
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: member.id,
+ });
+ const abilities = serialize(member, reloaded);
+ for (const [ability, value] of Object.entries(abilities)) {
+ expect({ ability, value }).toEqual({ ability, value: false });
+ }
+ });
+
+ it("should be read-only when personal documents are turned off", async () => {
+ const { team, owner, collection } = await buildPersonal();
+ team.setPreference(TeamPreference.PersonalDocs, false);
+ await team.save();
+ owner.team = team;
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: owner.id,
+ });
+ const abilities = serialize(owner, reloaded);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.readDocument).toBeTruthy();
+ expect(abilities.createDocument).toEqual(false);
+ expect(abilities.updateDocument).toEqual(false);
+ expect(abilities.createTemplate).toEqual(false);
+ });
+
+ it("should become an ordinary private collection without an owner", async () => {
+ const { team, collection } = await buildPersonal();
+ const admin = await buildAdmin({ teamId: team.id });
+ collection.ownerId = null;
+ await collection.save();
+ const reloaded = await Collection.findByPk(collection.id, {
+ userId: admin.id,
+ });
+ const abilities = serialize(admin, reloaded);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.update).toBeTruthy();
+ expect(abilities.manageUsers).toBeTruthy();
+ expect(abilities.readDocument).toEqual(false);
+ });
+
+ it("should allow only members to create a personal collection", async () => {
+ const team = await buildTeam();
+ const member = await buildUser({ teamId: team.id });
+ const viewer = await buildUser({ teamId: team.id, role: UserRole.Viewer });
+ const guest = await buildUser({ teamId: team.id, role: UserRole.Guest });
+ expect(serialize(member, team).createPersonalCollection).toBeTruthy();
+ expect(serialize(viewer, team).createPersonalCollection).toEqual(false);
+ expect(serialize(guest, team).createPersonalCollection).toEqual(false);
+
+ team.setPreference(TeamPreference.PersonalDocs, false);
+ await team.save();
+ expect(serialize(member, team).createPersonalCollection).toEqual(false);
+ });
+});
diff --git a/server/policies/collection.ts b/server/policies/collection.ts
index a7aeef58ec..d02e1281fa 100644
--- a/server/policies/collection.ts
+++ b/server/policies/collection.ts
@@ -2,7 +2,15 @@ import invariant from "invariant";
import { CollectionPermission, TeamPreference } from "@shared/types";
import { Collection, User, Team } from "@server/models";
import { allow, can } from "./cancan";
-import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";
+import {
+ and,
+ isCollectionOwner,
+ isCollectionWritable,
+ isTeamAdmin,
+ isTeamModel,
+ isTeamMutable,
+ or,
+} from "./utils";
allow(User, "createCollection", Team, (actor, team) =>
and(
@@ -22,10 +30,20 @@ allow(User, "importCollection", Team, (actor, team) =>
)
);
+allow(User, "createPersonalCollection", Team, (actor, team) =>
+ and(
+ !actor.isGuest,
+ !actor.isViewer,
+ isTeamModel(actor, team),
+ isTeamMutable(actor),
+ !!team?.getPreference(TeamPreference.PersonalDocs)
+ )
+);
+
allow(User, "move", Collection, (actor, collection) =>
and(
- //
!!collection?.isActive,
+ !collection?.isPersonal,
isTeamAdmin(actor, collection),
isTeamMutable(actor)
)
@@ -35,6 +53,9 @@ allow(User, "read", Collection, (user, collection) => {
if (!collection || user.teamId !== collection.teamId) {
return false;
}
+ if (collection.isPersonal) {
+ return isCollectionOwner(user, collection);
+ }
if (user.isAdmin) {
return true;
}
@@ -49,6 +70,7 @@ allow(User, "read", Collection, (user, collection) => {
allow(User, "duplicate", Collection, (actor, collection) =>
and(
!!collection?.isActive,
+ !collection?.isPersonal,
can(actor, "read", collection),
can(actor, "createCollection", actor.team)
)
@@ -64,15 +86,28 @@ allow(User, "download", Collection, (actor, collection) =>
)
);
+// A personal collection cannot be starred, as it has no page to link to.
+allow(User, ["star", "unstar"], Collection, (user, collection) =>
+ and(
+ //
+ !collection?.isPersonal,
+ can(user, "readDocument", collection)
+ )
+);
+
allow(
User,
- ["readDocument", "star", "unstar", "subscribe", "unsubscribe"],
+ ["readDocument", "subscribe", "unsubscribe"],
Collection,
(user, collection) => {
if (!collection || user.teamId !== collection.teamId) {
return false;
}
+ if (collection.isPersonal) {
+ return isCollectionOwner(user, collection);
+ }
+
if (collection.isPrivate || user.isGuest) {
return includesMembership(
collection,
@@ -84,7 +119,15 @@ allow(
}
);
-allow(User, "share", Collection, (user, collection) => {
+allow(User, "share", Collection, (user, collection) =>
+ and(
+ //
+ !collection?.isPersonal,
+ can(user, "shareDocument", collection)
+ )
+);
+
+allow(User, "shareDocument", Collection, (user, collection) => {
if (
!collection ||
user.isGuest ||
@@ -96,6 +139,9 @@ allow(User, "share", Collection, (user, collection) => {
if (!collection.sharing) {
return false;
}
+ if (collection.isPersonal) {
+ return isCollectionOwner(user, collection);
+ }
if (!collection.isPrivate && user.isAdmin) {
return true;
}
@@ -114,9 +160,17 @@ allow(User, "share", Collection, (user, collection) => {
});
allow(User, "updateDocument", Collection, (user, collection) => {
- if (!collection || !isTeamModel(user, collection) || !isTeamMutable(user)) {
+ if (
+ !collection ||
+ !isTeamModel(user, collection) ||
+ !isTeamMutable(user) ||
+ !isCollectionWritable(user, collection)
+ ) {
return false;
}
+ if (collection.isPersonal) {
+ return isCollectionOwner(user, collection);
+ }
if (
collection.permission !== CollectionPermission.ReadWrite ||
@@ -141,10 +195,14 @@ allow(
!collection ||
!collection.isActive ||
!isTeamModel(user, collection) ||
- !isTeamMutable(user)
+ !isTeamMutable(user) ||
+ !isCollectionWritable(user, collection)
) {
return false;
}
+ if (collection.isPersonal) {
+ return isCollectionOwner(user, collection);
+ }
if (
collection.permission !== CollectionPermission.ReadWrite ||
@@ -171,6 +229,8 @@ allow(
!!collection?.isActive,
isTeamModel(user, collection),
isTeamMutable(user),
+ // Templates in a personal collection would only be visible to its owner.
+ !collection?.isPersonal,
or(
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin]),
@@ -192,23 +252,57 @@ allow(
)
);
-allow(User, ["update", "archive"], Collection, (user, collection) =>
+allow(User, "update", Collection, (user, collection) =>
and(
!!collection,
!!collection?.isActive,
+ isOwnerIfPersonal(user, collection),
or(
+ isCollectionOwner(user, collection),
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin])
)
)
);
+// A personal collection cannot be archived or deleted, so that its owner always
+// has exactly one.
+allow(User, "archive", Collection, (user, collection) =>
+ and(
+ //
+ !collection?.isPersonal,
+ can(user, "update", collection)
+ )
+);
+
+// Pins are shown on the collection page, which a personal collection does not
+// have.
+allow(User, "pin", Collection, (user, collection) =>
+ and(
+ //
+ !collection?.isPersonal,
+ can(user, "update", collection)
+ )
+);
+
+// Only the owner is a member of a personal collection, documents in it are
+// shared through document memberships instead.
+allow(User, "manageUsers", Collection, (user, collection) =>
+ and(
+ //
+ !collection?.isPersonal,
+ can(user, "update", collection)
+ )
+);
+
allow(User, "export", Collection, (user, collection) =>
and(
!!collection,
!!collection?.isActive,
can(user, "download", collection),
+ isOwnerIfPersonal(user, collection),
or(
+ isCollectionOwner(user, collection),
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin])
)
@@ -219,6 +313,7 @@ allow(User, "delete", Collection, (user, collection) =>
and(
!!collection,
!collection?.deletedAt,
+ !collection?.isPersonal,
or(
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin])
@@ -230,7 +325,9 @@ allow(User, "restore", Collection, (user, collection) =>
and(
!!collection,
!collection?.isActive,
+ isOwnerIfPersonal(user, collection),
or(
+ isCollectionOwner(user, collection),
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin])
)
@@ -247,6 +344,18 @@ allow(User, "updateDeprecatedReason", Collection, (actor, collection) =>
)
);
+/**
+ * Check that the actor owns the collection when it is a personal collection.
+ * Admins have no access to the personal collections of other users.
+ *
+ * @param user The actor to check.
+ * @param collection The collection to check.
+ * @returns True if the collection is not personal or the actor owns it.
+ */
+function isOwnerIfPersonal(user: User, collection: Collection | null) {
+ return !collection?.isPersonal || isCollectionOwner(user, collection);
+}
+
function includesMembership(
collection: Collection | null,
permissions: CollectionPermission[]
diff --git a/server/policies/document.test.ts b/server/policies/document.test.ts
index 5c9e5d6172..5ea2841c2e 100644
--- a/server/policies/document.test.ts
+++ b/server/policies/document.test.ts
@@ -13,6 +13,7 @@ import {
buildDraftDocument,
buildCollection,
buildAdmin,
+ buildPersonalCollection,
} from "@server/test/factories";
import { serialize } from "./index";
@@ -782,3 +783,115 @@ describe("manage document", () => {
});
}
});
+
+describe("personal collection", () => {
+ const buildPersonal = async () => {
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.PersonalDocs, true);
+ await team.save();
+ const owner = await buildUser({ teamId: team.id });
+ owner.team = team;
+ const collection = await buildPersonalCollection(owner);
+ const doc = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: collection.id,
+ });
+ return { team, owner, collection, doc };
+ };
+
+ it("should allow the owner full access", async () => {
+ const { owner, doc } = await buildPersonal();
+ const document = await Document.findByPk(doc.id, { userId: owner.id });
+ const abilities = serialize(owner, document);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.update).toBeTruthy();
+ expect(abilities.move).toBeTruthy();
+ expect(abilities.archive).toBeTruthy();
+ expect(abilities.delete).toBeTruthy();
+ expect(abilities.share).toBeTruthy();
+ expect(abilities.manageUsers).toBeTruthy();
+ expect(abilities.unpublish).toEqual(false);
+ expect(abilities.updateInsights).toEqual(false);
+ expect(abilities.pin).toEqual(false);
+ expect(abilities.unpin).toEqual(false);
+ expect(abilities.pinToHome).toEqual(false);
+ });
+
+ it("should allow nothing for a workspace admin", async () => {
+ const { team, doc } = await buildPersonal();
+ const admin = await buildAdmin({ teamId: team.id });
+ const document = await Document.findByPk(doc.id, { userId: admin.id });
+ const abilities = serialize(admin, document);
+ for (const [ability, value] of Object.entries(abilities)) {
+ expect({ ability, value }).toEqual({ ability, value: false });
+ }
+ });
+
+ it("should not allow a workspace admin to permanently delete", async () => {
+ const { team, owner, doc } = await buildPersonal();
+ const admin = await buildAdmin({ teamId: team.id });
+ await doc.destroy({ hooks: false });
+ const ownerDocument = await Document.findByPk(doc.id, {
+ userId: owner.id,
+ paranoid: false,
+ });
+ const adminDocument = await Document.findByPk(doc.id, {
+ userId: admin.id,
+ paranoid: false,
+ });
+ expect(serialize(admin, adminDocument).permanentDelete).toEqual(false);
+ expect(serialize(owner, ownerDocument).restore).toBeTruthy();
+ });
+
+ it("should allow a collaborator through a document membership", async () => {
+ const { team, owner, doc } = await buildPersonal();
+ const collaborator = await buildUser({ teamId: team.id });
+ collaborator.team = team;
+ await UserMembership.create({
+ documentId: doc.id,
+ userId: collaborator.id,
+ permission: DocumentPermission.ReadWrite,
+ createdById: owner.id,
+ });
+ const document = await Document.findByPk(doc.id, {
+ userId: collaborator.id,
+ });
+ const abilities = serialize(collaborator, document);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.update).toBeTruthy();
+ expect(abilities.manageUsers).toEqual(false);
+ });
+
+ it("should be read-only when personal documents are turned off", async () => {
+ const { team, owner, doc } = await buildPersonal();
+ const collaborator = await buildUser({ teamId: team.id });
+ await UserMembership.create({
+ documentId: doc.id,
+ userId: collaborator.id,
+ permission: DocumentPermission.ReadWrite,
+ createdById: owner.id,
+ });
+ team.setPreference(TeamPreference.PersonalDocs, false);
+ await team.save();
+ owner.team = team;
+ collaborator.team = team;
+
+ const document = await Document.findByPk(doc.id, { userId: owner.id });
+ const abilities = serialize(owner, document);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.update).toEqual(false);
+ expect(abilities.createChildDocument).toEqual(false);
+ expect(abilities.move).toBeTruthy();
+ expect(abilities.archive).toBeTruthy();
+ expect(abilities.delete).toBeTruthy();
+
+ const collaboratorDocument = await Document.findByPk(doc.id, {
+ userId: collaborator.id,
+ });
+ const collaboratorAbilities = serialize(collaborator, collaboratorDocument);
+ expect(collaboratorAbilities.read).toBeTruthy();
+ expect(collaboratorAbilities.update).toEqual(false);
+ expect(collaboratorAbilities.move).toEqual(false);
+ });
+});
diff --git a/server/policies/document.ts b/server/policies/document.ts
index 2063f0a477..260402e280 100644
--- a/server/policies/document.ts
+++ b/server/policies/document.ts
@@ -6,7 +6,15 @@ import {
} from "@shared/types";
import { Document, Revision, User, Team } from "@server/models";
import { allow, cannot, can } from "./cancan";
-import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";
+import {
+ and,
+ isCollectionOwner,
+ isCollectionWritable,
+ isTeamAdmin,
+ isTeamModel,
+ isTeamMutable,
+ or,
+} from "./utils";
allow(User, "createDocument", Team, (actor, document) =>
and(
@@ -79,7 +87,7 @@ allow(User, "share", Document, (actor, document) =>
!!document?.isActive,
isTeamMutable(actor),
can(actor, "read", document),
- or(!document?.collection, can(actor, "share", document?.collection))
+ or(!document?.collection, can(actor, "shareDocument", document?.collection))
)
);
@@ -88,6 +96,7 @@ allow(User, "update", Document, (actor, document) =>
!!document?.isActive,
isTeamMutable(actor),
can(actor, "read", document),
+ isCollectionWritable(actor, document?.collection),
or(
includesMembership(document, [
DocumentPermission.ReadWrite,
@@ -140,17 +149,20 @@ allow(User, "duplicate", Document, (actor, document) =>
);
allow(User, "move", Document, (actor, document) =>
- and(
- can(actor, "update", document),
- or(
- includesMembership(document, [
- DocumentPermission.ReadWrite,
- DocumentPermission.Admin,
- ]),
- can(actor, "updateDocument", document?.collection),
- and(!!document?.isDraft && actor.id === document?.createdById),
- and(!!document?.isDraft && !document?.collection)
- )
+ or(
+ and(
+ can(actor, "update", document),
+ or(
+ includesMembership(document, [
+ DocumentPermission.ReadWrite,
+ DocumentPermission.Admin,
+ ]),
+ can(actor, "updateDocument", document?.collection),
+ and(!!document?.isDraft && actor.id === document?.createdById),
+ and(!!document?.isDraft && !document?.collection)
+ )
+ ),
+ and(!!document?.isActive, isPersonalOwner(actor, document))
)
);
@@ -162,10 +174,12 @@ allow(User, "createChildDocument", Document, (actor, document) =>
)
);
+// Pins and insights are not shown for documents in a personal collection.
allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) =>
and(
!document?.isDraft,
!actor.isGuest,
+ !document?.collection?.isPersonal,
can(actor, "update", document),
can(actor, "update", document?.collection)
)
@@ -173,9 +187,9 @@ allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) =>
allow(User, "pinToHome", Document, (actor, document) =>
and(
- //
!document?.isDraft,
!!document?.isActive,
+ !document?.collection?.isPersonal,
isTeamAdmin(actor, document),
isTeamMutable(actor)
)
@@ -189,6 +203,7 @@ allow(User, "delete", Document, (actor, document) =>
or(
can(actor, "unarchive", document),
can(actor, "update", document),
+ isPersonalOwner(actor, document),
and(!document?.collection, actor.id === document?.createdById)
)
)
@@ -215,7 +230,11 @@ allow(User, "permanentDelete", Document, (actor, document) =>
!actor.isGuest,
!!document?.isDeleted,
isTeamModel(actor, document),
- isTeamAdmin(actor, document)
+ isTeamAdmin(actor, document),
+ or(
+ !document?.collection?.isPersonal,
+ isCollectionOwner(actor, document?.collection)
+ )
)
);
@@ -223,11 +242,16 @@ allow(User, "archive", Document, (actor, document) =>
and(
!document?.isDraft,
!!document?.isActive,
- can(actor, "update", document),
or(
- includesMembership(document, [DocumentPermission.Admin]),
- and(isTeamAdmin(actor, document), can(actor, "read", document)),
- can(actor, "updateDocument", document?.collection)
+ and(
+ can(actor, "update", document),
+ or(
+ includesMembership(document, [DocumentPermission.Admin]),
+ and(isTeamAdmin(actor, document), can(actor, "read", document)),
+ can(actor, "updateDocument", document?.collection)
+ )
+ ),
+ isPersonalOwner(actor, document)
)
)
);
@@ -278,12 +302,33 @@ allow(User, "unpublish", Document, (user, document) => {
document.collection,
"collection is missing, did you forget to include in the query scope?"
);
+
+ // Documents in a personal collection are already private to the owner.
+ if (document.collection.isPersonal) {
+ return false;
+ }
if (cannot(user, "updateDocument", document.collection)) {
return false;
}
return user.teamId === document.teamId;
});
+/**
+ * Check if the actor owns the personal collection that the document is in. The
+ * owner can always move, archive and delete these documents, also when the
+ * collection is read-only.
+ *
+ * @param actor The actor to check.
+ * @param document The document to check.
+ * @returns True if the actor owns the personal collection of the document.
+ */
+function isPersonalOwner(actor: User, document: Document | null) {
+ return !!and(
+ isTeamMutable(actor),
+ isCollectionOwner(actor, document?.collection)
+ );
+}
+
function includesMembership(
document: Document | null,
permissions: DocumentPermission[]
diff --git a/server/policies/fileOperation.ts b/server/policies/fileOperation.ts
index 77cd67b8b5..246310ee85 100644
--- a/server/policies/fileOperation.ts
+++ b/server/policies/fileOperation.ts
@@ -1,7 +1,14 @@
import { FileOperationState, FileOperationType } from "@shared/types";
import { User, Team, FileOperation } from "@server/models";
import { allow, can } from "./cancan";
-import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";
+import {
+ and,
+ isCollectionOwner,
+ isTeamAdmin,
+ isTeamModel,
+ isTeamMutable,
+ or,
+} from "./utils";
const TerminalStates = [
FileOperationState.Complete,
@@ -28,6 +35,22 @@ function canAccessSource(actor: User, fileOperation: FileOperation) {
return can(actor, "createExport", actor.team);
}
+/**
+ * Admins have no access to exports of the personal collections of other users,
+ * or of the documents in them.
+ */
+function isOwnerIfPersonalSource(actor: User, fileOperation: FileOperation) {
+ // The owner at the time of the export applies, also after the source moved.
+ const personalOwnerId = fileOperation.options?.personalOwnerId;
+ if (personalOwnerId && personalOwnerId !== actor.id) {
+ return false;
+ }
+
+ const collection =
+ fileOperation.collection ?? fileOperation.document?.collection;
+ return !collection?.isPersonal || isCollectionOwner(actor, collection);
+}
+
allow(
User,
["createFileOperation", "createExport"],
@@ -40,7 +63,10 @@ allow(User, "read", FileOperation, (actor, fileOperation) =>
and(
isTeamModel(actor, fileOperation),
or(
- isTeamAdmin(actor, fileOperation),
+ and(
+ isTeamAdmin(actor, fileOperation),
+ !!fileOperation && isOwnerIfPersonalSource(actor, fileOperation)
+ ),
and(
fileOperation?.userId === actor.id,
!!fileOperation && canAccessSource(actor, fileOperation)
diff --git a/server/policies/utils.ts b/server/policies/utils.ts
index cc958192ed..a7602cfd72 100644
--- a/server/policies/utils.ts
+++ b/server/policies/utils.ts
@@ -1,8 +1,12 @@
import env from "@server/env";
-import type { User } from "@server/models";
+import type { Collection, User } from "@server/models";
import { Team, type Group } from "@server/models";
import type Model from "@server/models/base/Model";
-import { GroupPermission, type PlanFeature } from "@shared/types";
+import {
+ GroupPermission,
+ TeamPreference,
+ type PlanFeature,
+} from "@shared/types";
import invariant from "invariant";
type Args = boolean | string | Args[];
@@ -80,6 +84,42 @@ export function isTeamAdmin(
return !!and(isTeamModel(actor, model), actor.isAdmin);
}
+/**
+ * Check if the actor owns the personal collection.
+ *
+ * @param actor The actor to check
+ * @param collection The collection to check
+ * @returns True if the collection is personal and owned by the actor
+ */
+export function isCollectionOwner(
+ actor: User,
+ collection: Collection | null | undefined
+): boolean {
+ return (
+ !!collection?.ownerId &&
+ isTeamModel(actor, collection) &&
+ collection.ownerId === actor.id
+ );
+}
+
+/**
+ * Check if documents in the collection can be changed. A personal collection
+ * is read-only when the team turns personal documents off.
+ *
+ * @param actor The actor to check
+ * @param collection The collection to check
+ * @returns True if documents in the collection can be changed
+ */
+export function isCollectionWritable(
+ actor: User,
+ collection: Collection | null | undefined
+): boolean {
+ return (
+ !collection?.ownerId ||
+ !!actor.team?.getPreference(TeamPreference.PersonalDocs)
+ );
+}
+
/**
* Check if the actor is a member of the team.
*
diff --git a/server/presenters/collection.ts b/server/presenters/collection.ts
index 04db5e46aa..9b1b08bb48 100644
--- a/server/presenters/collection.ts
+++ b/server/presenters/collection.ts
@@ -64,6 +64,7 @@ export default async function presentCollection(
res.commenting = collection.commenting;
res.templateManagement = collection.templateManagement;
res.permission = collection.permission;
+ res.ownerId = collection.ownerId;
res.deletedAt = collection.deletedAt;
res.archivedAt = collection.archivedAt;
res.deprecatedReason = collection.deprecatedReason;
diff --git a/server/presenters/document.ts b/server/presenters/document.ts
index b4e6f1b90a..beb55dabe3 100644
--- a/server/presenters/document.ts
+++ b/server/presenters/document.ts
@@ -110,6 +110,13 @@ async function presentDocument(
res.tasks = document.tasks;
res.isCollectionDeleted = await document.isCollectionDeleted();
res.collectionId = document.collectionId;
+ // The owner of the personal collection that the document is in. Left out
+ // when the collection is not loaded, so that the value is not cleared.
+ if (!document.collectionId) {
+ res.ownerId = null;
+ } else if (document.collection !== undefined) {
+ res.ownerId = document.collection?.ownerId ?? null;
+ }
res.parentDocumentId = document.parentDocumentId;
res.createdBy = presentUser(document.createdBy);
res.updatedBy = presentUser(document.updatedBy);
diff --git a/server/queues/processors/UserDeletedProcessor.test.ts b/server/queues/processors/UserDeletedProcessor.test.ts
index 8a6cf74d61..741b09f6fe 100644
--- a/server/queues/processors/UserDeletedProcessor.test.ts
+++ b/server/queues/processors/UserDeletedProcessor.test.ts
@@ -1,5 +1,12 @@
import UserAuthentication from "@server/models/UserAuthentication";
-import { buildUser, buildWebhookSubscription } from "@server/test/factories";
+import { Collection } from "@server/models";
+import {
+ buildAdmin,
+ buildPersonalCollection,
+ buildUser,
+ buildWebhookSubscription,
+} from "@server/test/factories";
+import { serialize } from "@server/policies";
import UserDeletedProcessor from "./UserDeletedProcessor";
const ip = "127.0.0.1";
@@ -52,4 +59,31 @@ describe("UserDeletedProcessor", () => {
await webhook.reload();
expect(webhook.enabled).toEqual(false);
});
+
+ it("should turn the personal collection into a private collection", async () => {
+ const user = await buildUser();
+ const admin = await buildAdmin({ teamId: user.teamId });
+ const personal = await buildPersonalCollection(user);
+
+ const processor = new UserDeletedProcessor();
+ await processor.perform({
+ name: "users.delete",
+ userId: user.id,
+ actorId: admin.id,
+ teamId: user.teamId,
+ ip,
+ });
+
+ const collection = await Collection.findByPk(personal.id, {
+ userId: admin.id,
+ rejectOnEmpty: true,
+ });
+ expect(collection.ownerId).toBeNull();
+ expect(collection.permission).toBeNull();
+ expect(collection.memberships).toHaveLength(0);
+
+ const abilities = serialize(admin, collection);
+ expect(abilities.read).toBeTruthy();
+ expect(abilities.manageUsers).toBeTruthy();
+ });
});
diff --git a/server/queues/processors/UserDeletedProcessor.ts b/server/queues/processors/UserDeletedProcessor.ts
index 31ea63a61c..7b256d0a2e 100644
--- a/server/queues/processors/UserDeletedProcessor.ts
+++ b/server/queues/processors/UserDeletedProcessor.ts
@@ -1,5 +1,6 @@
import {
ApiKey,
+ Collection,
GroupUser,
OAuthAuthentication,
Star,
@@ -60,6 +61,17 @@ export default class UserDeletedProcessor extends BaseProcessor {
},
transaction,
});
+ // The personal collection becomes an ordinary private collection, so
+ // that admins can recover the documents in it.
+ await Collection.update(
+ { ownerId: null },
+ {
+ where: {
+ ownerId: event.userId,
+ },
+ transaction,
+ }
+ );
await WebhookSubscription.update(
{ enabled: false },
{
diff --git a/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts
index c984a2a185..74a310b62d 100644
--- a/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts
+++ b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts
@@ -105,6 +105,16 @@ export default class DocumentAccessRequestNotificationsTask extends BaseTask {
await fs.remove(filePath);
}
});
+
+ it("should only export a personal collection to its owner", async () => {
+ const team = await buildTeam();
+ const admin = await buildAdmin({ teamId: team.id });
+ const shared = await buildCollection({ teamId: team.id, userId: admin.id });
+ const ownPersonal = await buildPersonalCollection(admin);
+ const otherPersonal = await buildPersonalCollection(
+ await buildUser({ teamId: team.id })
+ );
+ const exportCollections = vi
+ .spyOn(ExportJSONTask.prototype, "exportCollections")
+ .mockResolvedValue("");
+ const exported = async (collectionId?: string) => {
+ const fileOperation = await buildFileOperation({
+ teamId: team.id,
+ userId: admin.id,
+ collectionId,
+ options: { includeAttachments: false, includePrivate: true },
+ });
+ exportCollections.mockClear();
+ await new ExportJSONTask().loadDataAndExport(fileOperation, admin);
+ const collections: Collection[] = exportCollections.mock.calls[0][0];
+ return collections.map((collection) => collection.id);
+ };
+
+ const workspace = await exported();
+ expect(workspace).toContain(shared.id);
+ expect(workspace).not.toContain(ownPersonal.id);
+ expect(workspace).not.toContain(otherPersonal.id);
+
+ expect(await exported(ownPersonal.id)).toEqual([ownPersonal.id]);
+ expect(await exported(otherPersonal.id)).toEqual([]);
+ });
});
diff --git a/server/queues/tasks/ExportTask.ts b/server/queues/tasks/ExportTask.ts
index fd50ad9a8e..ec1231622b 100644
--- a/server/queues/tasks/ExportTask.ts
+++ b/server/queues/tasks/ExportTask.ts
@@ -190,10 +190,14 @@ export default abstract class ExportTask extends BaseTask {
if (fileOperation.collectionId) {
where.id = fileOperation.collectionId;
+ // Only the owner can export a personal collection.
+ where.ownerId = { [Op.or]: [{ [Op.is]: null }, { [Op.eq]: user.id }] };
} else {
where.archivedAt = {
[Op.eq]: null,
};
+ // A workspace export never includes personal collections.
+ where.ownerId = { [Op.is]: null };
}
const collections = await sequelizeReadOnly.transaction((transaction) =>
diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts
index 219231dd2f..3a0ecd92b5 100644
--- a/server/routes/api/collections/collections.test.ts
+++ b/server/routes/api/collections/collections.test.ts
@@ -1,6 +1,18 @@
-import { CollectionPermission, CollectionStatusFilter } from "@shared/types";
+import {
+ CollectionPermission,
+ CollectionStatusFilter,
+ DocumentPermission,
+ Scope,
+} from "@shared/types";
import { DeprecationValidation } from "@shared/validations";
-import { Document, UserMembership, GroupMembership } from "@server/models";
+import {
+ Document,
+ UserMembership,
+ GroupMembership,
+ View,
+} from "@server/models";
+import type { User } from "@server/models";
+import { callMcpTool } from "@server/test/McpHelper";
import {
buildUser,
buildViewer,
@@ -9,6 +21,9 @@ import {
buildCollection,
buildDocument,
buildTeam,
+ buildPersonalCollection,
+ buildOAuthAuthentication,
+ buildRelationship,
} from "@server/test/factories";
import { getTestServer, mockTaskSchedule } from "@server/test/support";
@@ -2690,3 +2705,292 @@ describe("#collections.restore", () => {
expect(body.data.index).not.toBe("P");
});
});
+
+describe("personal collections", () => {
+ it("should not list the personal collection of another user", async () => {
+ const team = await buildTeam();
+ const owner = await buildUser({ teamId: team.id });
+ const admin = await buildAdmin({ teamId: team.id });
+ const personal = await buildPersonalCollection(owner);
+ const own = await buildPersonalCollection(admin);
+
+ for (const body of [{}, { includeListOnly: true }]) {
+ const res = await server.post("/api/collections.list", admin, { body });
+ const json = await res.json();
+ expect(res.status).toEqual(200);
+ const ids = json.data.map((c: { id: string }) => c.id);
+ expect(ids).not.toContain(personal.id);
+ expect(ids).toContain(own.id);
+ }
+
+ const res = await server.post("/api/collections.list", owner);
+ const json = await res.json();
+ expect(json.data.map((c: { id: string }) => c.id)).toEqual([personal.id]);
+ });
+
+ it("should not return the personal collection of another user", async () => {
+ const team = await buildTeam();
+ const owner = await buildUser({ teamId: team.id });
+ const admin = await buildAdmin({ teamId: team.id });
+ const personal = await buildPersonalCollection(owner);
+
+ for (const route of [
+ "collections.info",
+ "collections.memberships",
+ "collections.group_memberships",
+ "collections.export",
+ "collections.update",
+ "collections.archive",
+ "collections.delete",
+ ]) {
+ const res = await server.post(`/api/${route}`, admin, {
+ body: { id: personal.id },
+ });
+ expect({ route, status: res.status }).toEqual({ route, status: 403 });
+ }
+ });
+
+ it("should not allow membership changes", async () => {
+ const team = await buildTeam();
+ const owner = await buildUser({ teamId: team.id });
+ const member = await buildUser({ teamId: team.id });
+ const group = await buildGroup({ teamId: team.id });
+ const personal = await buildPersonalCollection(owner);
+
+ const res = await server.post("/api/collections.add_user", owner, {
+ body: { id: personal.id, userId: member.id },
+ });
+ expect(res.status).toEqual(403);
+
+ const res2 = await server.post("/api/collections.add_group", owner, {
+ body: { id: personal.id, groupId: group.id },
+ });
+ expect(res2.status).toEqual(403);
+
+ const res3 = await server.post("/api/collections.remove_user", owner, {
+ body: { id: personal.id, userId: owner.id },
+ });
+ expect(res3.status).toEqual(403);
+ });
+
+ it("should not allow the owner to make it public or rename it", async () => {
+ const owner = await buildUser();
+ const personal = await buildPersonalCollection(owner);
+
+ const res = await server.post("/api/collections.update", owner, {
+ body: { id: personal.id, permission: CollectionPermission.ReadWrite },
+ });
+ expect(res.status).toEqual(400);
+
+ const res2 = await server.post("/api/collections.update", owner, {
+ body: { id: personal.id, name: "Notes" },
+ });
+ expect(res2.status).toEqual(400);
+
+ const res3 = await server.post("/api/collections.update", owner, {
+ body: { id: personal.id, sort: { field: "index", direction: "asc" } },
+ });
+ expect(res3.status).toEqual(200);
+ });
+
+ it("should not allow the owner to archive, delete or duplicate it", async () => {
+ const owner = await buildUser();
+ const personal = await buildPersonalCollection(owner);
+
+ for (const route of [
+ "collections.archive",
+ "collections.delete",
+ "collections.duplicate",
+ ]) {
+ const res = await server.post(`/api/${route}`, owner, {
+ body: { id: personal.id },
+ });
+ expect({ route, status: res.status }).toEqual({ route, status: 403 });
+ }
+ });
+});
+
+describe("personal collection lists", () => {
+ const keyword = "personalcollectionlists";
+
+ type UserKey = "owner" | "collaborator" | "member" | "admin";
+
+ const userKeys: UserKey[] = ["owner", "collaborator", "member", "admin"];
+
+ let users: Record;
+ let tokens: Record;
+ let collectionId: string;
+ let rootId: string;
+ let nestedId: string;
+ let publicDocumentId: string;
+
+ /**
+ * The personal ids that a user is expected to see. The collaborator has a
+ * membership on the root document, which the nested document inherits.
+ *
+ * @param key The user.
+ * @returns the ids of the collection and documents.
+ */
+ const readableIds = (key: UserKey) => {
+ switch (key) {
+ case "owner":
+ return [collectionId, rootId, nestedId];
+ case "collaborator":
+ return [rootId, nestedId];
+ default:
+ return [];
+ }
+ };
+
+ const personalIds = () => [collectionId, rootId, nestedId];
+
+ beforeAll(async () => {
+ const team = await buildTeam();
+ const owner = await buildUser({ teamId: team.id });
+ users = {
+ owner,
+ collaborator: await buildUser({ teamId: team.id }),
+ member: await buildUser({ teamId: team.id }),
+ admin: await buildAdmin({ teamId: team.id }),
+ };
+
+ const collection = await buildPersonalCollection(owner);
+ const root = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: collection.id,
+ title: `Root ${keyword}`,
+ text: `Root ${keyword}`,
+ });
+ const nested = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: collection.id,
+ parentDocumentId: root.id,
+ title: `Nested ${keyword}`,
+ text: `Nested ${keyword}`,
+ });
+ await collection.addDocumentToStructure(root, 0);
+ await collection.addDocumentToStructure(nested, 0);
+
+ await UserMembership.create({
+ documentId: root.id,
+ userId: users.collaborator.id,
+ permission: DocumentPermission.Read,
+ createdById: owner.id,
+ });
+
+ // A public document that links to the personal document.
+ const publicCollection = await buildCollection({
+ teamId: team.id,
+ userId: owner.id,
+ });
+ const publicDocument = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: publicCollection.id,
+ });
+ await buildRelationship({
+ userId: owner.id,
+ documentId: publicDocument.id,
+ reverseDocumentId: root.id,
+ });
+
+ // Everybody has viewed the document at some point.
+ for (const user of Object.values(users)) {
+ await View.create({ documentId: root.id, userId: user.id });
+ }
+
+ tokens = {} as Record;
+ for (const key of userKeys) {
+ const auth = await buildOAuthAuthentication({
+ user: users[key],
+ scope: [Scope.Read],
+ });
+ tokens[key] = auth.accessToken!;
+ }
+
+ collectionId = collection.id;
+ rootId = root.id;
+ nestedId = nested.id;
+ publicDocumentId = publicDocument.id;
+ });
+
+ // Lists filter in queries rather than through the read policy, so they are
+ // checked here for each user.
+ it.each(userKeys)("only list what %s can read", async (key) => {
+ const ids = (values: { id: string }[]) => values.map((value) => value.id);
+ const post = async (route: string, body: Record) => {
+ const res = await server.post(`/api/${route}`, users[key], { body });
+ expect({ route, status: res.status }).toEqual({ route, status: 200 });
+ return res.json();
+ };
+ const mcpText = async (tool: string, args: Record) => {
+ const res = await callMcpTool(server, tokens[key], tool, args);
+ return res?.result?.content?.map((c) => c.text).join("\n") ?? "";
+ };
+
+ const results: Record = {
+ "collections.list": ids((await post("collections.list", {})).data),
+ "collections.list includeListOnly": ids(
+ (await post("collections.list", { includeListOnly: true })).data
+ ),
+ "documents.list": ids((await post("documents.list", {})).data),
+ "documents.viewed": ids((await post("documents.viewed", {})).data),
+ "documents.search": (
+ await post("documents.search", { query: keyword })
+ ).data.map((result: { document: { id: string } }) => result.document.id),
+ "documents.search_titles": ids(
+ (await post("documents.search_titles", { query: keyword })).data
+ ),
+ "relationships.list": ids(
+ (await post("relationships.list", { documentId: publicDocumentId }))
+ .data.documents
+ ),
+ };
+
+ // Documents include their collectionId, so only document ids are matched.
+ const collectionsText = await mcpText("list_collections", {});
+ const documentsText = await mcpText("list_documents", { query: keyword });
+ results.list_collections = personalIds().filter((id) =>
+ collectionsText.includes(id)
+ );
+ results.list_documents = [rootId, nestedId].filter((id) =>
+ documentsText.includes(id)
+ );
+
+ const readable = readableIds(key);
+ for (const [label, listed] of Object.entries(results)) {
+ const leaked = listed.filter(
+ (id) => personalIds().includes(id) && !readable.includes(id)
+ );
+ expect({ key, label, leaked }).toEqual({ key, label, leaked: [] });
+ }
+
+ if (key === "owner") {
+ expect(results["collections.list"]).toContain(collectionId);
+ expect(results["documents.search"]).toEqual(
+ expect.arrayContaining([rootId, nestedId])
+ );
+ }
+ });
+
+ it("should include the owner for the owner and collaborators", async () => {
+ for (const key of ["owner", "collaborator"] as const) {
+ const res = await server.post("/api/documents.info", users[key], {
+ body: { id: nestedId },
+ });
+ const body = await res.json();
+ expect({ key, ownerId: body.data.ownerId }).toEqual({
+ key,
+ ownerId: users.owner.id,
+ });
+ }
+
+ const res = await server.post("/api/documents.info", users.owner, {
+ body: { id: publicDocumentId },
+ });
+ const body = await res.json();
+ expect(body.data.ownerId).toBeNull();
+ });
+});
diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts
index 372c5ee3a9..7e77ccedbc 100644
--- a/server/routes/api/collections/collections.ts
+++ b/server/routes/api/collections/collections.ts
@@ -246,7 +246,7 @@ router.post(
Collection.findByPk(id, { userId: user.id, transaction }),
Group.findByPk(groupId, { transaction }),
]);
- authorize(user, "update", collection);
+ authorize(user, "manageUsers", collection);
authorize(user, "read", group);
let membership = await GroupMembership.findOne({
@@ -302,7 +302,7 @@ router.post(
transaction,
}),
]);
- authorize(user, "update", collection);
+ authorize(user, "manageUsers", collection);
authorize(user, "read", group);
const [membership] = await collection.$get("groupMemberships", {
@@ -404,7 +404,7 @@ router.post(
Collection.findByPk(id, { userId: actor.id, transaction }),
User.findByPk(userId, { transaction }),
]);
- authorize(actor, "update", collection);
+ authorize(actor, "manageUsers", collection);
authorize(actor, "read", user);
let membership = await UserMembership.findOne({
@@ -454,7 +454,7 @@ router.post(
Collection.findByPk(id, { userId: actor.id, transaction }),
User.findByPk(userId, { transaction }),
]);
- authorize(actor, "update", collection);
+ authorize(actor, "manageUsers", collection);
authorize(actor, "read", user);
const [membership] = await collection.$get("memberships", {
@@ -807,6 +807,10 @@ router.post(
// are not a member of, so they must be able to see them listed.
if (!user.isAdmin || !(includeListOnly || includeArchived)) {
where[Op.and].push({ id: collectionIds });
+ } else {
+ where[Op.and].push({
+ ownerId: { [Op.or]: [{ [Op.is]: null }, { [Op.eq]: user.id }] },
+ });
}
if (filter) {
diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts
index 3a87a73159..89e06f43fe 100644
--- a/server/routes/api/documents/documents.test.ts
+++ b/server/routes/api/documents/documents.test.ts
@@ -10,6 +10,7 @@ import {
FileOperationFormat,
HeadingPrefixStyle,
StatusFilter,
+ TeamPreference,
UserRole,
} from "@shared/types";
import { TextHelper } from "@shared/utils/TextHelper";
@@ -18,6 +19,7 @@ import { createContext } from "@server/context";
import { parser } from "@server/editor";
import type { Group, User } from "@server/models";
import {
+ Collection,
Document,
View,
Revision,
@@ -6242,6 +6244,45 @@ describe("#documents.import", () => {
});
describe("#documents.create", () => {
+ it("should create the personal collection for the personal collectionId", async () => {
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.PersonalDocs, true);
+ await team.save();
+ const user = await buildUser({ teamId: team.id });
+
+ const res = await server.post("/api/documents.create", user, {
+ body: { collectionId: "personal", title: "First", publish: true },
+ });
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+
+ const collection = await Collection.findOne({
+ where: { teamId: team.id, ownerId: user.id },
+ rejectOnEmpty: true,
+ });
+ expect(body.data.collectionId).toEqual(collection.id);
+ expect(body.data.ownerId).toEqual(user.id);
+
+ const res2 = await server.post("/api/documents.create", user, {
+ body: { collectionId: "personal", title: "Second", publish: true },
+ });
+ const body2 = await res2.json();
+ expect(res2.status).toEqual(200);
+ expect(body2.data.collectionId).toEqual(collection.id);
+ });
+
+ it("should not create the personal collection when turned off", async () => {
+ const team = await buildTeam();
+ team.setPreference(TeamPreference.PersonalDocs, false);
+ await team.save();
+ const user = await buildUser({ teamId: team.id });
+ const res = await server.post("/api/documents.create", user, {
+ body: { collectionId: "personal", title: "First", publish: true },
+ });
+ expect(res.status).toEqual(403);
+ expect(await Collection.count({ where: { ownerId: user.id } })).toEqual(0);
+ });
+
it("should replace template variables when a doc is created from a template", async () => {
const user = await buildUser();
const text = `This document was created by {author} on {date}`;
diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts
index fdf05d62c5..f533cbbb3e 100644
--- a/server/routes/api/documents/schema.ts
+++ b/server/routes/api/documents/schema.ts
@@ -1,6 +1,7 @@
import type formidable from "formidable";
import { isEmpty } from "es-toolkit/compat";
import { z } from "zod";
+import { PersonalCollectionId } from "@shared/constants";
import { createFilterSchema } from "@shared/helpers/FilterHelper";
import {
DirectionFilter,
@@ -560,8 +561,10 @@ export const DocumentsImportSchema = BaseSchema.extend({
])
.optional(),
- /** Import docs to this collection */
- collectionId: z.uuid().nullish(),
+ /** Import docs to this collection, or "personal" for the personal collection */
+ collectionId: z
+ .union([z.uuid(), z.literal(PersonalCollectionId)])
+ .nullish(),
/** Import under this parent doc */
parentDocumentId: z.uuid().nullish(),
@@ -603,8 +606,10 @@ export const DocumentsCreateSchema = BaseSchema.extend({
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
- /** Collection to create document within */
- collectionId: z.uuid().nullish(),
+ /** Collection to create document within, or "personal" for the personal collection */
+ collectionId: z
+ .union([z.uuid(), z.literal(PersonalCollectionId)])
+ .nullish(),
/** Index to create the document at within the collection */
index: z.number().optional(),
diff --git a/server/routes/api/fileOperations/fileOperations.test.ts b/server/routes/api/fileOperations/fileOperations.test.ts
index d67cb70af8..5788d73f12 100644
--- a/server/routes/api/fileOperations/fileOperations.test.ts
+++ b/server/routes/api/fileOperations/fileOperations.test.ts
@@ -1,9 +1,11 @@
// @vitest-isolate true
import {
CollectionPermission,
+ FileOperationFormat,
FileOperationState,
FileOperationType,
} from "@shared/types";
+import { createContext } from "@server/context";
import {
Collection,
User,
@@ -16,6 +18,7 @@ import {
buildCollection,
buildDocument,
buildFileOperation,
+ buildPersonalCollection,
buildTeam,
buildUser,
} from "@server/test/factories";
@@ -593,3 +596,112 @@ describe("#fileOperations.delete", () => {
expect(res.status).toEqual(403);
});
});
+
+describe("personal collection exports", () => {
+ it("should not show or allow admins to download them", async () => {
+ const team = await buildTeam();
+ const admin = await buildAdmin({ teamId: team.id });
+ const owner = await buildUser({ teamId: team.id });
+ const personal = await buildPersonalCollection(owner);
+ const document = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ const collectionExport = await buildFileOperation({
+ state: FileOperationState.Complete,
+ type: FileOperationType.Export,
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ const documentExport = await buildFileOperation({
+ state: FileOperationState.Complete,
+ type: FileOperationType.Export,
+ teamId: team.id,
+ userId: owner.id,
+ documentId: document.id,
+ });
+ const workspaceExport = await buildFileOperation({
+ state: FileOperationState.Complete,
+ type: FileOperationType.Export,
+ teamId: team.id,
+ userId: admin.id,
+ });
+
+ const res = await server.post("/api/fileOperations.list", admin, {
+ body: { type: FileOperationType.Export },
+ });
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.map((f: { id: string }) => f.id)).toEqual([
+ workspaceExport.id,
+ ]);
+
+ for (const fileOperation of [collectionExport, documentExport]) {
+ const info = await server.post("/api/fileOperations.info", admin, {
+ body: { id: fileOperation.id },
+ });
+ expect(info.status).toEqual(403);
+
+ const redirect = await server.post(
+ "/api/fileOperations.redirect",
+ admin,
+ {
+ body: { id: fileOperation.id },
+ redirect: "manual",
+ }
+ );
+ expect(redirect.status).toEqual(403);
+
+ const own = await server.post("/api/fileOperations.redirect", owner, {
+ body: { id: fileOperation.id },
+ redirect: "manual",
+ });
+ expect(own.status).toEqual(302);
+ }
+ });
+
+ it("should keep a document export private after the document moves", async () => {
+ const team = await buildTeam();
+ const admin = await buildAdmin({ teamId: team.id });
+ const owner = await buildUser({ teamId: team.id });
+ const personal = await buildPersonalCollection(owner);
+ const shared = await buildCollection({ teamId: team.id, userId: owner.id });
+ const document = await buildDocument({
+ teamId: team.id,
+ userId: owner.id,
+ collectionId: personal.id,
+ });
+ const fileOperation = await FileOperation.createExport(
+ createContext({ user: owner }),
+ { document, format: FileOperationFormat.MarkdownZip }
+ );
+ fileOperation.state = FileOperationState.Complete;
+ await fileOperation.save();
+ expect(fileOperation.options?.personalOwnerId).toEqual(owner.id);
+
+ document.collectionId = shared.id;
+ await document.save();
+
+ const list = await server.post("/api/fileOperations.list", admin, {
+ body: { type: FileOperationType.Export },
+ });
+ const body = await list.json();
+ expect(body.data.map((f: { id: string }) => f.id)).not.toContain(
+ fileOperation.id
+ );
+
+ const redirect = await server.post("/api/fileOperations.redirect", admin, {
+ body: { id: fileOperation.id },
+ redirect: "manual",
+ });
+ expect(redirect.status).toEqual(403);
+
+ const own = await server.post("/api/fileOperations.redirect", owner, {
+ body: { id: fileOperation.id },
+ redirect: "manual",
+ });
+ expect(own.status).toEqual(302);
+ });
+});
diff --git a/server/routes/api/fileOperations/fileOperations.ts b/server/routes/api/fileOperations/fileOperations.ts
index fb75c063df..60901391fb 100644
--- a/server/routes/api/fileOperations/fileOperations.ts
+++ b/server/routes/api/fileOperations/fileOperations.ts
@@ -1,5 +1,5 @@
import Router from "@koa/router";
-import type { WhereOptions } from "sequelize";
+import { Op, type WhereOptions } from "sequelize";
import { UserRole } from "@shared/types";
import { ValidationError } from "@server/errors";
import auth from "@server/middlewares/authentication";
@@ -48,6 +48,27 @@ router.post(
const where: WhereOptions = {
teamId: user.teamId,
type,
+ // Exclude operations on the personal collections of other users.
+ [Op.and]: [
+ {
+ [Op.or]: [
+ { "$collection.ownerId$": null },
+ { "$collection.ownerId$": user.id },
+ ],
+ },
+ {
+ [Op.or]: [
+ { "$document.collection.ownerId$": null },
+ { "$document.collection.ownerId$": user.id },
+ ],
+ },
+ {
+ [Op.or]: [
+ { "options.personalOwnerId": null },
+ { "options.personalOwnerId": user.id },
+ ],
+ },
+ ],
};
const team = await Team.findByPk(user.teamId);
authorize(user, "update", team);
diff --git a/server/routes/api/pins/pins.test.ts b/server/routes/api/pins/pins.test.ts
index 1d72a256e5..0030b8a6e8 100644
--- a/server/routes/api/pins/pins.test.ts
+++ b/server/routes/api/pins/pins.test.ts
@@ -4,6 +4,7 @@ import {
buildCollection,
buildDocument,
buildDraftDocument,
+ buildPersonalCollection,
buildPin,
buildUser,
} from "@server/test/factories";
@@ -35,6 +36,17 @@ describe("#pins.create", () => {
});
});
+ it("should not pin to a personal collection", async () => {
+ const personal = await buildPersonalCollection(admin);
+ const res = await server.post("/api/pins.create", admin, {
+ body: {
+ documentId: document.id,
+ collectionId: personal.id,
+ },
+ });
+ expect(res.status).toEqual(403);
+ });
+
it("should fail with status 401 unauthorized when user token is missing", async () => {
const res = await server.post("/api/pins.create", {
body: {
diff --git a/server/routes/api/pins/pins.ts b/server/routes/api/pins/pins.ts
index 79d572d9dd..283397539c 100644
--- a/server/routes/api/pins/pins.ts
+++ b/server/routes/api/pins/pins.ts
@@ -40,7 +40,7 @@ router.post(
userId: user.id,
transaction,
});
- authorize(user, "update", collection);
+ authorize(user, "pin", collection);
authorize(user, "pin", document);
} else {
authorize(user, "pinToHome", document);
diff --git a/server/routes/api/teams/schema.ts b/server/routes/api/teams/schema.ts
index 1f3439f26f..41b1541a32 100644
--- a/server/routes/api/teams/schema.ts
+++ b/server/routes/api/teams/schema.ts
@@ -78,6 +78,8 @@ export const TeamsUpdateSchema = BaseSchema.extend({
[TeamPreference.MCP]: z.boolean(),
/** List of disabled embed provider titles. */
[TeamPreference.DisabledEmbeds]: z.array(z.string()),
+ /** Whether users can create documents in a personal collection. */
+ [TeamPreference.PersonalDocs]: z.boolean(),
})
.partial()
.optional(),
diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts
index d4eafbcc44..8b37ca9059 100644
--- a/server/routes/auth/index.ts
+++ b/server/routes/auth/index.ts
@@ -72,6 +72,7 @@ router.get(
where: {
id: defaultCollectionId,
teamId: team.id,
+ ownerId: null,
},
});
diff --git a/server/test/factories.ts b/server/test/factories.ts
index 3cf59e39e2..fd2322f928 100644
--- a/server/test/factories.ts
+++ b/server/test/factories.ts
@@ -338,6 +338,27 @@ export async function buildCollection(
});
}
+/**
+ * Build the personal collection of a user.
+ *
+ * @param owner The user that owns the collection.
+ * @param overrides Attributes to set on the collection.
+ * @returns the personal collection.
+ */
+export async function buildPersonalCollection(
+ owner: User,
+ overrides: Partial = {}
+) {
+ return buildCollection({
+ name: "Personal",
+ ...overrides,
+ teamId: owner.teamId,
+ userId: owner.id,
+ ownerId: owner.id,
+ permission: null,
+ });
+}
+
export async function buildGroup(
overrides: Partial & { userId?: string } = {}
) {
diff --git a/server/utils/authentication.ts b/server/utils/authentication.ts
index 83a7401c77..5e0b99e608 100644
--- a/server/utils/authentication.ts
+++ b/server/utils/authentication.ts
@@ -196,6 +196,7 @@ export async function signIn(
where: {
id: defaultCollectionId,
teamId: team.id,
+ ownerId: null,
},
transaction,
});
diff --git a/shared/constants.ts b/shared/constants.ts
index f5ff0994bc..2264b3594d 100644
--- a/shared/constants.ts
+++ b/shared/constants.ts
@@ -52,6 +52,12 @@ export const CSRF = {
fieldName: "_csrf",
};
+/**
+ * A collectionId that refers to the personal collection of the current user,
+ * which is created when it does not exist yet.
+ */
+export const PersonalCollectionId = "personal";
+
/** The maximum number of sub-requests permitted in a single `/batch` request. */
export const BatchMaxRequests = 25;
@@ -97,6 +103,7 @@ export const TeamPreferenceDefaults: TeamPreferences = {
[TeamPreference.EmailDisplay]: EmailDisplay.Members,
[TeamPreference.MCP]: true,
[TeamPreference.DisabledEmbeds]: [],
+ [TeamPreference.PersonalDocs]: true,
};
export const DocumentPreferenceDefaults: DocumentPreferences = {
diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json
index 7bf4ea4a57..c8713f9ed8 100644
--- a/shared/i18n/locales/en_US/translation.json
+++ b/shared/i18n/locales/en_US/translation.json
@@ -657,6 +657,8 @@
"Can view": "Can view",
"Everyone in the collection": "Everyone in the collection",
"You have full access": "You have full access",
+ "Owner": "Owner",
+ "This document is in their personal space": "This document is in their personal space",
"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",
@@ -687,6 +689,7 @@
"Hide": "Hide",
"Starred": "Starred",
"Shared with me": "Shared with me",
+ "Personal": "Personal",
"Move up": "Move up",
"Move down": "Move down",
"Import files": "Import files",
@@ -1534,6 +1537,8 @@
"Email address visibility": "Email address visibility",
"Controls who can see user email addresses in the workspace": "Controls who can see user email addresses in the workspace",
"Controls who can add comments to documents": "Controls who can add comments to documents",
+ "Personal documents": "Personal documents",
+ "Allow editors to create personal documents that are only visible to themselves and the people they share them with": "Allow editors to create personal documents that are only visible to themselves and the people they share them with",
"Collection creation": "Collection creation",
"Allow editors to create new collections within the workspace": "Allow editors to create new collections within the workspace",
"Workspace creation": "Workspace creation",
diff --git a/shared/types/team.ts b/shared/types/team.ts
index 111421c534..1c6ac361d3 100644
--- a/shared/types/team.ts
+++ b/shared/types/team.ts
@@ -65,6 +65,8 @@ export enum TeamPreference {
MCP = "mcp",
/** List of disabled embed provider titles. */
DisabledEmbeds = "disabledEmbeds",
+ /** Whether users can create documents in a personal collection. */
+ PersonalDocs = "personalDocs",
}
/** Workspace preference values, keyed by preference. */
@@ -83,4 +85,5 @@ export type TeamPreferences = {
[TeamPreference.EmailDisplay]?: EmailDisplay;
[TeamPreference.MCP]?: boolean;
[TeamPreference.DisabledEmbeds]?: string[];
+ [TeamPreference.PersonalDocs]?: boolean;
};
diff --git a/shared/types/user.ts b/shared/types/user.ts
index 027831435d..8510cdb4a7 100644
--- a/shared/types/user.ts
+++ b/shared/types/user.ts
@@ -6,6 +6,8 @@ export enum SidebarSection {
SharedWithMe = "shared",
/** The collections section. */
Collections = "collections",
+ /** The user's own personal documents section. */
+ Personal = "personal",
}
/** User-level preferences. */