Files
outline/server/routes/api/documents/schema.ts
T
Tom Moor f8496ea2f7 feat: Personal collections (#14062)
* feat: Personal collections backend

Adds an owner to collections. A personal collection is private, one per user
per team, created lazily through collections.personal, and only its owner can
see or manage it. Admin bypasses in policies, lists, exports, events, webhooks
and file operations exclude the personal collections of other users. Turning
off the PersonalDocs preference makes the collection read-only.

* test: Access matrix for personal collections

Checks that collection and document endpoints, list and search results, MCP
tools, collaboration and websocket rooms agree with the read policy for the
owner, collaborators, members, admins, guests and other teams.

* feat: Personal collection in the sidebar

Adds a Personal sidebar section that renders the personal collection with the
collection document tree, creates the collection on the first new document,
and keeps it out of the Collections section. Adds the workspace setting, the
personal sidebar context, and hides collection sharing and membership UI for
personal collections.

* fix: Drag and drop in shared with me trees

Anchors the reorder drop cursor inside the row, and prefetches documents on
hover so that nested rows that were never opened can be dragged.

* feat: Personal collection owner for collaborators, no collection page

Presents the owner of the personal collection on documents, so that
collaborators see the owner in the share popover. Root rows in the Personal
section show the default document icon. A personal collection has no page:
the scene shows not found, and the breadcrumb, command bar and delete redirect
no longer link to it.

* fix: Personal sidebar indent and breadcrumb items without a link

Children of rows at depth 0 skip a level so that they start beyond the row
icon. Breadcrumb items without a destination, such as the personal and deleted
collection, are shown as plain text.

* test: Reduce personal collection tests to list paths

Endpoints that authorize a single model are already covered by the policy
tests. Keeps the lists and searches, which filter in queries, and the
presenter.

* test: Move personal collection list tests into collections tests

* feat: Create documents in the personal collection by alias

documents.create, documents.import and the MCP create_document tool accept
the collectionId "personal", which refers to the personal collection of the
user and creates it when it does not exist yet.

* refactor: Remove collections.personal route

The sidebar creates its first personal document with the personal
collectionId alias, so documents.create is the only path that creates the
personal collection.

* feat: Personal collection name, starring, templates and default

Personal collections cannot be starred, renamed or hold templates, and the
PersonalDocs preference is on by default. The app shows collections through a
displayName getter, which is the translated "Personal" for a personal
collection.

* fix: Use the same policy for starring and unstarring collections

* fix: No pins or viewer insights for personal documents

* revert: Show personal collection events in the audit log

Admins with audit access should see events in personal collections, even when
they cannot open the documents.

* fix: Load collection owner in share scopes

* fix: Keep personal collections out of workspace exports and webhooks

Workspace exports skip all personal collections, while an explicit export of
a personal collection stays available to its owner. Events in personal
collections, including attachments and documents moved after queueing, are
never delivered to workspace webhooks. Personal collections cannot be
renamed or made public through any path, cannot hold pins, and are not
offered as mentions.

* Change icon to avatar

* fix: Personal documents cannot be unpublished

* feat: Personal collection context for MCP

Collections are presented with an isPersonal flag, the server instructions
explain the personal collection, and move_document and update_document accept
the personal collectionId alias.

* fix: Keep moved personal exports private and remove pins on move

Document exports record the owner of the personal collection they came from,
so they stay private after the document moves. Moving documents into a
personal collection removes their pins, including pins to home.

* fix: Only create the personal collection in MCP when it is used
2026-10-13 07:53:06 -04:00

736 lines
22 KiB
TypeScript

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,
DocumentPermission,
HeadingPrefixStyle,
StatusFilter,
TextEditMode,
SortFilter,
} from "@shared/types";
import { DeprecationValidation, DocumentValidation } from "@shared/validations";
import { BaseSchema } from "@server/routes/api/schema";
import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod";
import { ValidateColor } from "@server/validation";
const documentFilterFields = {
createdAt: "date",
updatedAt: "date",
publishedAt: "date",
archivedAt: "date",
title: "string",
templateId: "uuid",
collectionId: "uuid",
createdById: { kind: "uuid", operators: ["eq", "in"] },
// `userId` maps to the collaboratorIds array column and only supports
// membership checks.
userId: { kind: "uuid", operators: ["eq", "in"] },
documentId: "uuid",
parentDocumentId: "uuid",
} as const;
const documentListFilter = createFilterSchema(documentFilterFields);
const documentsDeletedFilter = createFilterSchema({
deletedAt: "date",
deletedById: "uuid",
} as const);
// On search endpoints `documentId` scopes results to a document subtree and is
// resolved by the route handler, which only supports `eq` and `in`.
const documentSearchFilter = createFilterSchema({
...documentFilterFields,
documentId: { kind: "uuid", operators: ["eq", "in"] },
} as const);
const DocumentsSortParamsSchema = z.object({
/** Specifies the attributes by which documents will be sorted in the list */
sort: z
.string()
.refine((val) =>
[
"createdAt",
"updatedAt",
"publishedAt",
"index",
"title",
"popularityScore",
].includes(val)
)
.prefault("updatedAt"),
/** Specifies the sort order with respect to sort field */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
});
const DateFilterSchema = z.object({
/**
* Date filter.
* @deprecated use `filters` with `updatedAt` and an ISO 8601 duration
* (`-P1D`, `-P1W`, `-P1M`, `-P1Y`) instead.
*/
dateFilter: z
.union([
z.literal("day"),
z.literal("week"),
z.literal("month"),
z.literal("year"),
])
.optional(),
});
const BaseSearchSchema = DateFilterSchema.extend({
/**
* Filter results for team based on the collection.
* @deprecated use `filters` with field `collectionId` instead.
*/
collectionId: z.uuid().optional(),
/**
* Filter results based on user.
* @deprecated use `filters` with field `userId` instead.
*/
userId: z.uuid().optional(),
/**
* Filter results based on content within a document and it's children.
* @deprecated use `filters` with field `documentId` instead.
*/
documentId: z.uuid().optional(),
/**
* Document statuses to include in results.
* @deprecated use `filters` with `archivedAt`/`publishedAt` instead.
*/
statusFilter: z.enum(StatusFilter).array().optional(),
/** Filter results for the team derived from shareId */
shareId: zodShareIdType().optional(),
/** Min words to be shown in the results snippets */
snippetMinWords: z.number().prefault(20),
/** Max words to be accommodated in the results snippets */
snippetMaxWords: z.number().prefault(30),
});
const BaseIdSchema = z.object({
/** Id of the document to be updated */
id: zodIdType(),
});
export const DocumentsListSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({
/**
* Id of a user who collaborated on the doc.
* @deprecated use `filters` with field `userId` instead.
*/
userId: z.uuid().optional(),
/**
* Alias for userId - kept for backwards compatibility.
* @deprecated use `filters` with field `userId` instead.
*/
user: z.uuid().optional(),
/**
* Id of the collection to which the document belongs.
* @deprecated use `filters` with field `collectionId` instead.
*/
collectionId: z.uuid().optional(),
/**
* Alias for collectionId - kept for backwards compatibility.
* @deprecated use `filters` with field `collectionId` instead.
*/
collection: z.uuid().optional(),
/** Id of the backlinked document */
backlinkDocumentId: z.uuid().optional(),
/**
* Id of the parent document to which the document belongs.
* @deprecated use `filters` with field `parentDocumentId` instead.
*/
parentDocumentId: z.uuid().nullish(),
/**
* Document statuses to include in results.
* @deprecated use `filters` with `archivedAt`/`publishedAt` instead.
*/
statusFilter: z.enum(StatusFilter).array().optional(),
/** List of filter expressions. Implicit AND between top-level entries. */
filters: documentListFilter.FilterListSchema.optional(),
}),
// Maintains backwards compatibility
})
.transform((req) => {
req.body.collectionId = req.body.collectionId || req.body.collection;
req.body.userId = req.body.userId || req.body.user;
delete req.body.collection;
delete req.body.user;
return req;
})
.refine(
(req) => {
if (req.body.filters === undefined) {
return true;
}
return (
req.body.userId === undefined &&
req.body.collectionId === undefined &&
req.body.parentDocumentId === undefined &&
req.body.statusFilter === undefined
);
},
{
message:
"filters cannot be combined with deprecated parameters userId, collectionId, parentDocumentId, or statusFilter",
}
);
export type DocumentsListReq = z.infer<typeof DocumentsListSchema>;
export const DocumentsArchivedSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({
/** Id of the collection to which archived documents should belong */
collectionId: z.uuid().optional(),
}),
});
export type DocumentsArchivedReq = z.infer<typeof DocumentsArchivedSchema>;
export const DocumentsDeletedSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend({
/** Filter expression applied to the documents in the trash */
filters: documentsDeletedFilter.FilterListSchema.optional(),
}),
});
export type DocumentsDeletedReq = z.infer<typeof DocumentsDeletedSchema>;
export const DocumentsViewedSchema = BaseSchema.extend({
body: z.object({
/** Sort by a column of the view record, not the document */
sort: z.enum(["updatedAt", "createdAt"]).prefault("updatedAt"),
/** Specifies the sort order with respect to sort field */
direction: z
.string()
.optional()
.transform((val) => (val !== "ASC" ? "DESC" : val)),
}),
});
export type DocumentsViewedReq = z.infer<typeof DocumentsViewedSchema>;
export const DocumentsDraftsSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema.extend(DateFilterSchema.shape).extend({
/** Id of the collection to which the document belongs */
collectionId: z.uuid().optional(),
}),
});
export type DocumentsDraftsReq = z.infer<typeof DocumentsDraftsSchema>;
export const DocumentsInfoSchema = BaseSchema.extend({
body: z.object({
id: zodIdType().optional(),
/** Share Id, if available */
shareId: zodShareIdType().optional(),
/** @deprecated Version of the API to be used, remove in a few releases */
apiVersion: z.number().optional(),
}),
}).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.body.shareId)), {
message: "one of id or shareId is required",
});
export type DocumentsInfoReq = z.infer<typeof DocumentsInfoSchema>;
export const DocumentsInsightsSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Start of the insights window (inclusive). Defaults to 30 days ago. */
startDate: z.coerce.date().optional(),
/** End of the insights window (inclusive). Defaults to today. */
endDate: z.coerce.date().optional(),
}),
}).refine(
(req) =>
!req.body.startDate ||
!req.body.endDate ||
req.body.startDate <= req.body.endDate,
{
message: "startDate must be on or before endDate",
}
);
export type DocumentsInsightsReq = z.infer<typeof DocumentsInsightsSchema>;
export const DocumentsExportSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
signedUrls: z.number().optional(),
includeChildDocuments: z.boolean().prefault(false),
}),
});
export type DocumentsExportReq = z.infer<typeof DocumentsExportSchema>;
export const DocumentsRestoreSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the collection to which the document belongs */
collectionId: z.uuid().optional(),
/** Id of document revision */
revisionId: z.uuid().optional(),
}),
});
export type DocumentsRestoreReq = z.infer<typeof DocumentsRestoreSchema>;
const filterIncompatibleWithLegacy = (req: {
body: {
filters?: unknown;
collectionId?: unknown;
userId?: unknown;
documentId?: unknown;
dateFilter?: unknown;
statusFilter?: unknown;
};
}) =>
req.body.filters === undefined ||
(req.body.collectionId === undefined &&
req.body.userId === undefined &&
req.body.documentId === undefined &&
req.body.dateFilter === undefined &&
req.body.statusFilter === undefined);
const filterIncompatibleWithLegacyMessage =
"filters cannot be combined with deprecated parameters collectionId, userId, documentId, dateFilter, or statusFilter";
export const DocumentsSearchSchema = BaseSchema.extend({
body: BaseSearchSchema.extend({
/** Query for search */
query: z.string().optional(),
/** Specifies the attributes by which search results will be sorted */
sort: z.enum(Object.values(SortFilter) as [string, ...string[]]).optional(),
/** Specifies the sort order with respect to sort field */
direction: z
.enum(Object.values(DirectionFilter) as [string, ...string[]])
.optional(),
/** List of filter expressions. Implicit AND between top-level entries. */
filters: documentSearchFilter.FilterListSchema.optional(),
}),
}).refine(filterIncompatibleWithLegacy, {
message: filterIncompatibleWithLegacyMessage,
});
export type DocumentsSearchReq = z.infer<typeof DocumentsSearchSchema>;
export const DocumentsSearchTitlesSchema = BaseSchema.extend({
body: BaseSearchSchema.extend({
/** Query for search */
query: z.string().refine((val) => val.trim() !== ""),
/** Specifies the attributes by which search results will be sorted */
sort: z.enum(Object.values(SortFilter) as [string, ...string[]]).optional(),
/** Specifies the sort order with respect to sort field */
direction: z
.enum(Object.values(DirectionFilter) as [string, ...string[]])
.optional(),
/** List of filter expressions. Implicit AND between top-level entries. */
filters: documentSearchFilter.FilterListSchema.optional(),
}),
}).refine(filterIncompatibleWithLegacy, {
message: filterIncompatibleWithLegacyMessage,
});
export type DocumentsSearchTitlesReq = z.infer<
typeof DocumentsSearchTitlesSchema
>;
export const DocumentsDuplicateSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** New document title */
title: z.string().optional(),
/** Whether child documents should also be duplicated */
recursive: z.boolean().optional(),
/** Whether the new document should be published */
publish: z.boolean().optional(),
/** Id of the collection to which the document should be copied */
collectionId: z.uuid().optional(),
/** Id of the parent document to which the document should be copied */
parentDocumentId: z.uuid().optional(),
}),
});
export type DocumentsDuplicateReq = z.infer<typeof DocumentsDuplicateSchema>;
export const DocumentsTemplatizeSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the collection inside which the template should be created */
collectionId: z.string().nullish(),
/** Whether the new template should be published */
publish: z.boolean(),
}),
});
export type DocumentsTemplatizeReq = z.infer<typeof DocumentsTemplatizeSchema>;
export const DocumentsUpdateSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** The reason the document is archived or deleted. */
deprecatedReason: z
.string()
.trim()
.max(DeprecationValidation.maxReasonLength)
.nullish(),
/** Doc title to be updated */
title: z.string().optional(),
/** Doc text to be updated */
text: z.string().max(DocumentValidation.maxLength).optional(),
/** Icon displayed alongside doc title */
icon: zodIconType().nullish(),
/** Icon color */
color: z
.string()
.regex(ValidateColor.regex, { message: ValidateColor.message })
.nullish(),
/** Boolean to denote if the doc should occupy full width */
fullWidth: z.boolean().optional(),
/** Display preferences for the doc */
preferences: z
.object({
/** The style of prefix displayed before headings in the doc */
headingPrefix: z.enum(HeadingPrefixStyle).optional(),
})
.nullish(),
/** Boolean to denote if insights should be visible on the doc */
insightsEnabled: z.boolean().optional(),
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
/** Doc template Id */
templateId: z.uuid().nullish(),
/** Doc collection Id */
collectionId: z.uuid().nullish(),
/** If set, the update is rejected when the doc revision does not match */
lastRevision: z.number().int().nonnegative().optional(),
/** @deprecated Use editMode instead */
append: z.boolean().optional(),
/** The edit mode for text updates: "replace", "append", "prepend", or "patch" */
editMode: z.enum(TextEditMode).optional(),
/** The markdown text to find when using "patch" edit mode */
findText: z.string().optional(),
/** @deprecated Version of the API to be used, remove in a few releases */
apiVersion: z.number().optional(),
/** Whether the editing session is complete */
done: z.boolean().optional(),
}),
})
.refine(
(req) =>
!(
(req.body.append ||
req.body.editMode === TextEditMode.Append ||
req.body.editMode === TextEditMode.Prepend) &&
!req.body.text
),
{
message: "text is required when using append, prepend, or editMode",
}
)
.refine(
(req) =>
!(
req.body.editMode === TextEditMode.Patch && req.body.text === undefined
),
{
message: "text is required when using patch editMode",
}
)
.refine(
(req) => !(req.body.editMode === TextEditMode.Patch && !req.body.findText),
{
message: "findText is required when using patch editMode",
}
)
.transform((req) => {
// Transform deprecated append to editMode for backwards compatibility
if (req.body.append && !req.body.editMode) {
req.body.editMode = TextEditMode.Append;
}
delete req.body.append;
return req;
});
export type DocumentsUpdateReq = z.infer<typeof DocumentsUpdateSchema>;
export const DocumentsMoveSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of collection to which the doc is supposed to be moved */
collectionId: z.uuid().optional().nullish(),
/** Parent Id, in case if the doc is moved to a new parent */
parentDocumentId: z.uuid().nullish(),
/** Helps evaluate the new index in collection structure upon move */
index: z.number().gte(0).optional(),
}),
}).refine((req) => !(req.body.parentDocumentId === req.body.id), {
message: "infinite loop detected, cannot nest a document inside itself",
});
export type DocumentsMoveReq = z.infer<typeof DocumentsMoveSchema>;
export const DocumentsArchiveSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** The reason for archiving the document. */
reason: z
.string()
.trim()
.max(DeprecationValidation.maxReasonLength)
.nullish(),
}),
});
export type DocumentsArchiveReq = z.infer<typeof DocumentsArchiveSchema>;
export const DocumentsDeleteSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** The reason for deleting the document. */
reason: z
.string()
.trim()
.max(DeprecationValidation.maxReasonLength)
.nullish(),
/** Whether to permanently delete the doc as opposed to soft-delete */
permanent: z.boolean().optional(),
}),
});
export type DocumentsDeleteReq = z.infer<typeof DocumentsDeleteSchema>;
export const DocumentsUnpublishSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Whether to detach the document from the collection */
detach: z.boolean().prefault(false),
/** @deprecated Version of the API to be used, remove in a few releases */
apiVersion: z.number().optional(),
}),
});
export type DocumentsUnpublishReq = z.infer<typeof DocumentsUnpublishSchema>;
export const DocumentsImportSchema = BaseSchema.extend({
body: z
.object({
/** Whether to publish the imported docs. String as this is always multipart/form-data */
publish: z
.union([
z.boolean(),
z.preprocess((val) => val === "true", z.boolean()),
])
.optional(),
/** 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(),
/** ID of a pre-uploaded attachment to import from */
attachmentId: z.uuid().optional(),
})
.refine(
(req) => !(isEmpty(req.collectionId) && isEmpty(req.parentDocumentId)),
{
error: "one of collectionId or parentDocumentId is required",
}
),
file: z.custom<formidable.File>().optional(),
});
export type DocumentsImportReq = z.infer<typeof DocumentsImportSchema>;
export const DocumentsCreateSchema = BaseSchema.extend({
body: z.object({
/** Id of the document to be created */
id: zodIdType().optional(),
/** Document title */
title: z.string().optional(),
/** Document text */
text: z.string().max(DocumentValidation.maxLength).optional(),
/** Icon displayed alongside doc title */
icon: zodIconType().optional(),
/** Icon color */
color: z
.string()
.regex(ValidateColor.regex, { message: ValidateColor.message })
.nullish(),
/** Boolean to denote if the doc should be published */
publish: z.boolean().optional(),
/** 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(),
/** Parent document to create within */
parentDocumentId: z.uuid().nullish(),
/** A template to create the document from */
templateId: z.uuid().optional(),
/** Optionally set the created date in the past */
createdAt: z.coerce
.date()
.optional()
.refine((data) => !data || data < new Date(), {
error: "createdAt must be in the past",
}),
/** Boolean to denote if the document should occupy full width */
fullWidth: z.boolean().optional(),
/** Display preferences for the document */
preferences: z
.object({
/** The style of prefix displayed before headings in the document */
headingPrefix: z.enum(HeadingPrefixStyle).optional(),
})
.nullish(),
}),
}).refine(
(req) =>
!(req.body.publish && !req.body.parentDocumentId && !req.body.collectionId),
{
message: "collectionId or parentDocumentId is required to publish",
}
);
export type DocumentsCreateReq = z.infer<typeof DocumentsCreateSchema>;
export const DocumentsUsersSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Query term to search users by name */
query: z.string().optional(),
/** Id of the user to search within document access */
userId: z.uuid().optional(),
}),
});
export type DocumentsUsersReq = z.infer<typeof DocumentsUsersSchema>;
export const DocumentsChildrenSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsChildrenReq = z.infer<typeof DocumentsChildrenSchema>;
export const DocumentsAddUserSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the user who is to be added */
userId: z.uuid(),
/** Permission to be granted to the added user */
permission: z.enum(DocumentPermission).optional(),
}),
});
export type DocumentsAddUserReq = z.infer<typeof DocumentsAddUserSchema>;
export const DocumentsRemoveUserSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the user who is to be removed */
userId: z.uuid(),
}),
});
export type DocumentsRemoveUserReq = z.infer<typeof DocumentsRemoveUserSchema>;
export const DocumentsAddGroupSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
groupId: z.uuid(),
permission: z
.enum(DocumentPermission)
.prefault(DocumentPermission.ReadWrite),
}),
});
export type DocumentsAddGroupsReq = z.infer<typeof DocumentsAddGroupSchema>;
export const DocumentsRemoveGroupSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
groupId: z.uuid(),
}),
});
export type DocumentsRemoveGroupReq = z.infer<
typeof DocumentsRemoveGroupSchema
>;
export const DocumentsSharedWithUserSchema = BaseSchema.extend({
body: DocumentsSortParamsSchema,
});
export type DocumentsSharedWithUserReq = z.infer<
typeof DocumentsSharedWithUserSchema
>;
export const DocumentsMembershipsSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
query: z.string().optional(),
permission: z.enum(DocumentPermission).optional(),
}),
});
export type DocumentsMembershipsReq = z.infer<
typeof DocumentsMembershipsSchema
>;
export const DocumentsSitemapSchema = BaseSchema.extend({
query: z.object({
shareId: zodShareIdType().optional(),
}),
});
export type DocumentsSitemapReq = z.infer<typeof DocumentsSitemapSchema>;