mirror of
https://github.com/outline/outline.git
synced 2026-11-26 23:50:14 +03:00
feat: Filter DSL (#12176)
* feat: Normalized filter DSL for documents.list and search Add a structured filter expression language (field/operator/value leaves composed with AND/OR groups) shared by documents.list, documents.search and documents.searchTitles. Values are validated against each field's column type and per-field operator allowlists at the input layer, and translated to Sequelize where-clauses server-side. Supersedes the ad-hoc statusFilter/dateFilter/collectionId/userId parameters, adds ISO 8601 duration matching for date fields, documentId subtree expansion for search, and preserves draft visibility and collection authorization. * chore: Fix flaky Encrypted "different key" test AES-256-CBC is unauthenticated, so decrypting with the wrong key only raises "bad decrypt" when the garbage plaintext has invalid PKCS#7 padding (~255/256 of the time). Roughly 1 in 245 runs it decrypts to a non-matching value instead of throwing, failing the strict toThrow assertion. Accept either outcome, mirroring the adjacent tampered-data test. * Hardening
This commit is contained in:
1 parent
4b319702f8
commit
fc4fe65155
20 files changed
+5489
-340
No files matched your search
@@ -2,7 +2,6 @@ import { observer } from "mobx-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { StatusFilter } from "@shared/types";
|
||||
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import type { MentionMenuItem } from "~/editor/menus/mention";
|
||||
@@ -53,7 +52,10 @@ function DocumentMenu({ search = "", isActive, ...rest }: Props) {
|
||||
? documents.searchTitles({
|
||||
query,
|
||||
limit: MaxResults,
|
||||
statusFilter: [StatusFilter.Published],
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
})
|
||||
: documents.fetchRecentlyViewed({ limit: MaxDefaultResults }));
|
||||
} catch {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Waypoint } from "react-waypoint";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { Pagination } from "@shared/constants";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import type {
|
||||
SortFilter as TSortFilter,
|
||||
DirectionFilter as TDirectionFilter,
|
||||
@@ -98,29 +99,84 @@ function Search() {
|
||||
sort: isSearchable,
|
||||
};
|
||||
|
||||
const filters = React.useMemo(
|
||||
const filters = React.useMemo<Filter[] | undefined>(() => {
|
||||
const children: Filter[] = [];
|
||||
if (collectionId) {
|
||||
children.push({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: collectionId,
|
||||
});
|
||||
}
|
||||
if (userId) {
|
||||
children.push({ field: "userId", operator: "eq", value: userId });
|
||||
}
|
||||
if (documentId) {
|
||||
children.push({
|
||||
field: "documentId",
|
||||
operator: "eq",
|
||||
value: documentId,
|
||||
});
|
||||
}
|
||||
if (dateFilter) {
|
||||
const duration = (
|
||||
{
|
||||
day: "-P1D",
|
||||
week: "-P1W",
|
||||
month: "-P1M",
|
||||
year: "-P1Y",
|
||||
} as const
|
||||
)[dateFilter];
|
||||
if (duration) {
|
||||
children.push({ field: "updatedAt", operator: "gte", value: duration });
|
||||
}
|
||||
}
|
||||
if (statusFilter.length > 0) {
|
||||
const statusShape = (status: TStatusFilter): Filter => {
|
||||
if (status === TStatusFilter.Archived) {
|
||||
return { field: "archivedAt", operator: "isNotNull" };
|
||||
}
|
||||
if (status === TStatusFilter.Published) {
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
};
|
||||
}
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
};
|
||||
};
|
||||
const statusGroup =
|
||||
statusFilter.length === 1
|
||||
? statusShape(statusFilter[0])
|
||||
: ({
|
||||
operator: "OR",
|
||||
filters: statusFilter.map(statusShape),
|
||||
} as Filter);
|
||||
children.push(statusGroup);
|
||||
}
|
||||
if (children.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return children;
|
||||
}, [collectionId, userId, documentId, dateFilter, statusFilter]);
|
||||
|
||||
const requestParams = React.useMemo(
|
||||
() => ({
|
||||
query,
|
||||
statusFilter,
|
||||
collectionId,
|
||||
userId,
|
||||
dateFilter,
|
||||
titleFilter,
|
||||
documentId,
|
||||
sort,
|
||||
direction,
|
||||
filters,
|
||||
}),
|
||||
[
|
||||
query,
|
||||
statusFilter,
|
||||
collectionId,
|
||||
userId,
|
||||
dateFilter,
|
||||
titleFilter,
|
||||
documentId,
|
||||
sort,
|
||||
direction,
|
||||
]
|
||||
[query, titleFilter, sort, direction, filters]
|
||||
);
|
||||
|
||||
const requestFn = React.useMemo(() => {
|
||||
@@ -141,13 +197,19 @@ function Search() {
|
||||
limit: params?.limit,
|
||||
};
|
||||
return titleFilter
|
||||
? await documents.searchTitles({ ...filters, ...paginationParams })
|
||||
: await documents.search({ ...filters, ...paginationParams });
|
||||
? await documents.searchTitles({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
})
|
||||
: await documents.search({
|
||||
...requestParams,
|
||||
...paginationParams,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return () => Promise.resolve([] as SearchResult[]);
|
||||
}, [query, titleFilter, filters, searches, documents, isSearchable]);
|
||||
}, [query, titleFilter, requestParams, searches, documents, isSearchable]);
|
||||
|
||||
const { data, next, end, error, loading } = usePaginatedRequest(requestFn, {
|
||||
limit: Pagination.defaultLimit,
|
||||
|
||||
@@ -6,11 +6,12 @@ import {
|
||||
AttachmentPreset,
|
||||
SubscriptionType,
|
||||
type DateFilter,
|
||||
type StatusFilter,
|
||||
} from "@shared/types";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import { subtractDate } from "@shared/utils/date";
|
||||
import { bytesToHumanReadable } from "@shared/utils/files";
|
||||
import naturalSort from "@shared/utils/naturalSort";
|
||||
import type { JSONObject } from "@shared/types";
|
||||
import type RootStore from "~/stores/RootStore";
|
||||
import Store from "~/stores/base/Store";
|
||||
import Document from "~/models/Document";
|
||||
@@ -33,13 +34,10 @@ export type SearchParams = {
|
||||
query?: string;
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
dateFilter?: DateFilter;
|
||||
statusFilter?: StatusFilter[];
|
||||
collectionId?: string;
|
||||
userId?: string;
|
||||
shareId?: string;
|
||||
sort?: SortFilter;
|
||||
direction?: DirectionFilter;
|
||||
filters?: Filter[];
|
||||
};
|
||||
|
||||
type ImportOptions = {
|
||||
@@ -426,7 +424,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
|
||||
@action
|
||||
searchTitles = async (options?: SearchParams): Promise<SearchResult[]> => {
|
||||
const compactedOptions = omitBy(options, (o) => !o);
|
||||
const compactedOptions = omitBy(options, (o) => !o) as JSONObject;
|
||||
const res = await client.post("/documents.search_titles", {
|
||||
...compactedOptions,
|
||||
});
|
||||
@@ -457,7 +455,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
|
||||
@action
|
||||
search = async (options: SearchParams): Promise<SearchResult[]> => {
|
||||
const compactedOptions = omitBy(options, (o) => !o);
|
||||
const compactedOptions = omitBy(options, (o) => !o) as JSONObject;
|
||||
const res = await client.post("/documents.search", {
|
||||
...compactedOptions,
|
||||
});
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
DirectionFilter,
|
||||
DocumentPermission,
|
||||
SortFilter,
|
||||
StatusFilter,
|
||||
} from "@shared/types";
|
||||
import { DirectionFilter, DocumentPermission, SortFilter } from "@shared/types";
|
||||
import {
|
||||
buildDocument,
|
||||
buildDraftDocument,
|
||||
@@ -98,7 +93,7 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForTeam(team, {
|
||||
query: "test",
|
||||
collectionId: collection.id,
|
||||
filter: { field: "collectionId", operator: "eq", value: collection.id },
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
});
|
||||
@@ -127,7 +122,7 @@ describe("PostgresSearchProvider", () => {
|
||||
|
||||
const { results } = await provider.searchForTeam(team, {
|
||||
query: "test",
|
||||
collectionId: collection.id,
|
||||
filter: { field: "collectionId", operator: "eq", value: collection.id },
|
||||
share,
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
@@ -295,7 +290,7 @@ describe("PostgresSearchProvider", () => {
|
||||
}),
|
||||
]);
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
collectionId: collection.id,
|
||||
filter: { field: "collectionId", operator: "eq", value: collection.id },
|
||||
});
|
||||
expect(results.length).toBe(2);
|
||||
expect(results.map((r) => r.document.id).sort()).toEqual(
|
||||
@@ -343,7 +338,11 @@ describe("PostgresSearchProvider", () => {
|
||||
}),
|
||||
]);
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
collectionId: collection1.id,
|
||||
filter: {
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: collection1.id,
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(2);
|
||||
expect(results.map((r) => r.document.id).sort()).toEqual(
|
||||
@@ -386,7 +385,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
});
|
||||
@@ -402,7 +407,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].document?.id).toBe(draft.id);
|
||||
@@ -426,7 +437,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(0);
|
||||
});
|
||||
@@ -451,7 +468,19 @@ describe("PostgresSearchProvider", () => {
|
||||
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Published, StatusFilter.Archived],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
{ field: "archivedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(0);
|
||||
});
|
||||
@@ -482,7 +511,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Published],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
});
|
||||
@@ -519,7 +554,7 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Archived],
|
||||
filter: { field: "archivedAt", operator: "isNotNull" },
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
});
|
||||
@@ -547,7 +582,19 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Archived, StatusFilter.Published],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNotNull" },
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(2);
|
||||
});
|
||||
@@ -575,7 +622,25 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "draft",
|
||||
statusFilter: [StatusFilter.Published, StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(2);
|
||||
});
|
||||
@@ -603,7 +668,19 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "draft",
|
||||
statusFilter: [StatusFilter.Draft, StatusFilter.Archived],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
{ field: "archivedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(results.length).toBe(2);
|
||||
});
|
||||
@@ -817,7 +894,13 @@ describe("PostgresSearchProvider", () => {
|
||||
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "group draft",
|
||||
statusFilter: [StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(results.length).toBe(1);
|
||||
@@ -876,7 +959,7 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "test",
|
||||
collectionId: collection.id,
|
||||
filter: { field: "collectionId", operator: "eq", value: collection.id },
|
||||
});
|
||||
expect(documents.length).toBe(1);
|
||||
expect(documents[0]?.id).toBe(document.id);
|
||||
@@ -917,7 +1000,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(documents.length).toBe(1);
|
||||
});
|
||||
@@ -948,7 +1037,13 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Published],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(documents.length).toBe(1);
|
||||
});
|
||||
@@ -985,7 +1080,7 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Archived],
|
||||
filter: { field: "archivedAt", operator: "isNotNull" },
|
||||
});
|
||||
expect(documents.length).toBe(1);
|
||||
});
|
||||
@@ -1013,7 +1108,19 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "test",
|
||||
statusFilter: [StatusFilter.Archived, StatusFilter.Published],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNotNull" },
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(documents.length).toBe(2);
|
||||
});
|
||||
@@ -1041,7 +1148,25 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "draft",
|
||||
statusFilter: [StatusFilter.Published, StatusFilter.Draft],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(documents.length).toBe(2);
|
||||
});
|
||||
@@ -1069,7 +1194,19 @@ describe("PostgresSearchProvider", () => {
|
||||
});
|
||||
const documents = await provider.searchTitlesForUser(user, {
|
||||
query: "draft",
|
||||
statusFilter: [StatusFilter.Draft, StatusFilter.Archived],
|
||||
filter: {
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
},
|
||||
{ field: "archivedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(documents.length).toBe(2);
|
||||
});
|
||||
|
||||
@@ -9,8 +9,9 @@ import type {
|
||||
WhereOptions,
|
||||
} from "sequelize";
|
||||
import { Op, Sequelize } from "sequelize";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import type { SearchableModel } from "@shared/types";
|
||||
import { DirectionFilter, SortFilter, StatusFilter } from "@shared/types";
|
||||
import { DirectionFilter, SortFilter } from "@shared/types";
|
||||
import { regexIndexOf, regexLastIndexOf } from "@shared/utils/string";
|
||||
import { getUrls } from "@shared/utils/urls";
|
||||
import { ValidationError } from "@server/errors";
|
||||
@@ -20,7 +21,11 @@ import Document from "@server/models/Document";
|
||||
import Team from "@server/models/Team";
|
||||
import User from "@server/models/User";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { sequelize, sequelizeReadOnly } from "@server/storage/database";
|
||||
import {
|
||||
buildSearchWhere,
|
||||
collectEqValues,
|
||||
} from "@server/models/helpers/Filters";
|
||||
import { sequelizeReadOnly } from "@server/storage/database";
|
||||
import { QueryHelper } from "@server/storage/QueryHelper";
|
||||
import type {
|
||||
SearchOptions,
|
||||
@@ -189,7 +194,9 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
|
||||
|
||||
const where = await PostgresSearchProvider.buildWhere(team, {
|
||||
...options,
|
||||
statusFilter: [...(options.statusFilter || []), StatusFilter.Published],
|
||||
// Team-context search (used by shares) is always restricted to
|
||||
// published, non-archived documents.
|
||||
filter: PostgresSearchProvider.withPublishedConstraint(options.filter),
|
||||
});
|
||||
|
||||
if (options.share) {
|
||||
@@ -594,6 +601,26 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
|
||||
return context.slice(startIndex, endIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* AND a "published, non-archived" constraint into a filter expression.
|
||||
*
|
||||
* @param filter the filter to constrain, or undefined.
|
||||
* @returns a filter that always requires Published status.
|
||||
*/
|
||||
private static withPublishedConstraint(filter: Filter | undefined): Filter {
|
||||
const publishedShape: Filter = {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
};
|
||||
if (!filter) {
|
||||
return publishedShape;
|
||||
}
|
||||
return { operator: "AND", filters: [filter, publishedShape] };
|
||||
}
|
||||
|
||||
private static async buildWhere(model: User | Team, options: SearchOptions) {
|
||||
const teamId = model instanceof Team ? model.id : model.teamId;
|
||||
const where: WhereOptions<Document> & {
|
||||
@@ -617,122 +644,64 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
|
||||
],
|
||||
};
|
||||
|
||||
// Resolve the collections and individual documents accessible to the
|
||||
// model upfront so the search query needs no membership joins. If
|
||||
// collectionId is passed as an option it is assumed that the
|
||||
// authorization has already been done in the router.
|
||||
const [membershipDocumentIds, collectionIds] = await Promise.all([
|
||||
model instanceof User
|
||||
? Document.membershipDocumentIds(model.id)
|
||||
: Promise.resolve([]),
|
||||
options.collectionId
|
||||
? Promise.resolve([options.collectionId])
|
||||
: model.collectionIds(),
|
||||
]);
|
||||
const filter = options.filter;
|
||||
|
||||
// A document is visible if any of:
|
||||
//
|
||||
// - direct or group membership on the document
|
||||
// - the user is the creator AND the doc has no collection (unplaced
|
||||
// drafts that no membership/collection check can reach)
|
||||
// - the doc is published AND lives in a collection the user can access
|
||||
// (the common case for non-draft visibility)
|
||||
// - the user is the creator AND the doc lives in a collection they can
|
||||
// access (covers own drafts in shared collections — collection access
|
||||
// alone does not grant visibility into other users' drafts)
|
||||
//
|
||||
// Membership and collection access are resolved to id lists upfront so the
|
||||
// search query needs no membership joins. Status/date narrowing is applied
|
||||
// separately via `filter`.
|
||||
//
|
||||
// For Team contexts (share-based search), the caller is privileged and has
|
||||
// done its own authorization — narrow to the filter's collectionId if
|
||||
// specified, otherwise to the team's publicly-permissioned set.
|
||||
if (model instanceof User) {
|
||||
const [membershipDocumentIds, collectionIds] = await Promise.all([
|
||||
Document.membershipDocumentIds(model.id),
|
||||
model.collectionIds(),
|
||||
]);
|
||||
if (membershipDocumentIds.length) {
|
||||
where[Op.or].push({ id: membershipDocumentIds });
|
||||
}
|
||||
|
||||
// Allow users to see their own drafts that have no collection, where no
|
||||
// membership or collection access applies. Drafts in collections remain
|
||||
// gated by the collection/membership checks above.
|
||||
if (options.statusFilter?.includes(StatusFilter.Draft)) {
|
||||
where[Op.or].push({
|
||||
createdById: model.id,
|
||||
collectionId: { [Op.is]: null },
|
||||
publishedAt: { [Op.eq]: null },
|
||||
archivedAt: { [Op.eq]: null },
|
||||
});
|
||||
where[Op.or].push({
|
||||
createdById: model.id,
|
||||
collectionId: { [Op.is]: null },
|
||||
});
|
||||
if (collectionIds.length) {
|
||||
where[Op.or].push(
|
||||
{
|
||||
collectionId: collectionIds,
|
||||
publishedAt: { [Op.ne]: null },
|
||||
},
|
||||
{
|
||||
createdById: model.id,
|
||||
collectionId: collectionIds,
|
||||
}
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const explicitCollectionIds = filter
|
||||
? collectEqValues(filter, "collectionId")
|
||||
: [];
|
||||
const collectionIds = explicitCollectionIds.length
|
||||
? explicitCollectionIds
|
||||
: await model.collectionIds();
|
||||
if (collectionIds.length) {
|
||||
where[Op.or].push({ collectionId: collectionIds });
|
||||
}
|
||||
}
|
||||
|
||||
if (options.collectionId) {
|
||||
where[Op.and].push({ collectionId: options.collectionId });
|
||||
}
|
||||
if (collectionIds.length) {
|
||||
where[Op.or].push({ collectionId: collectionIds });
|
||||
}
|
||||
|
||||
if (options.dateFilter) {
|
||||
where[Op.and].push({
|
||||
updatedAt: {
|
||||
[Op.gt]: sequelize.literal(
|
||||
`now() - interval '1 ${options.dateFilter}'`
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (options.collaboratorIds) {
|
||||
where[Op.and].push({
|
||||
collaboratorIds: {
|
||||
[Op.contains]: options.collaboratorIds,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (options.documentIds) {
|
||||
where[Op.and].push({
|
||||
id: options.documentIds,
|
||||
});
|
||||
}
|
||||
|
||||
const statusQuery = [];
|
||||
if (options.statusFilter?.includes(StatusFilter.Published)) {
|
||||
statusQuery.push({
|
||||
[Op.and]: [
|
||||
{
|
||||
publishedAt: {
|
||||
[Op.ne]: null,
|
||||
},
|
||||
archivedAt: {
|
||||
[Op.eq]: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
options.statusFilter?.includes(StatusFilter.Draft) &&
|
||||
// Only include draft results for the user's own documents, or those
|
||||
// explicitly shared with them
|
||||
model instanceof User
|
||||
) {
|
||||
statusQuery.push({
|
||||
[Op.and]: [
|
||||
{
|
||||
publishedAt: {
|
||||
[Op.eq]: null,
|
||||
},
|
||||
archivedAt: {
|
||||
[Op.eq]: null,
|
||||
},
|
||||
[Op.or]: [
|
||||
{ createdById: model.id },
|
||||
...(membershipDocumentIds.length
|
||||
? [{ id: membershipDocumentIds }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (options.statusFilter?.includes(StatusFilter.Archived)) {
|
||||
statusQuery.push({
|
||||
archivedAt: {
|
||||
[Op.ne]: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (statusQuery.length) {
|
||||
where[Op.and].push({
|
||||
[Op.or]: statusQuery,
|
||||
});
|
||||
if (filter) {
|
||||
where[Op.and].push(buildSearchWhere<Document>(filter));
|
||||
}
|
||||
|
||||
if (options.query) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,479 @@
|
||||
import { Op, Sequelize, type Utils, type WhereOptions } from "sequelize";
|
||||
import type {
|
||||
ComparisonOperator,
|
||||
Filter,
|
||||
FilterCondition,
|
||||
FilterGroup,
|
||||
} from "@shared/helpers/FilterHelper";
|
||||
import { RANGE_OPERATORS } from "@shared/helpers/FilterHelper";
|
||||
import type { DateFilter, StatusFilter } from "@shared/types";
|
||||
import { StatusFilter as StatusFilterEnum } from "@shared/types";
|
||||
import { Collection } from "@server/models";
|
||||
import type User from "@server/models/User";
|
||||
import { authorize } from "@server/policies";
|
||||
import { isISO8601Duration } from "@server/validation";
|
||||
|
||||
const operatorMap: Record<
|
||||
ComparisonOperator,
|
||||
symbol | { op: symbol; transform?: (value: unknown) => unknown }
|
||||
> = {
|
||||
eq: Op.eq,
|
||||
neq: Op.ne,
|
||||
lt: Op.lt,
|
||||
lte: Op.lte,
|
||||
gt: Op.gt,
|
||||
gte: Op.gte,
|
||||
contains: Op.iLike,
|
||||
startsWith: Op.iLike,
|
||||
endsWith: Op.iLike,
|
||||
containsStrict: Op.like,
|
||||
startsWithStrict: Op.like,
|
||||
endsWithStrict: Op.like,
|
||||
in: Op.in,
|
||||
notIn: Op.notIn,
|
||||
isNull: Op.is,
|
||||
isNotNull: Op.not,
|
||||
};
|
||||
|
||||
/** Escape a value for safe use inside a SQL LIKE / iLike pattern. */
|
||||
function escapeLike(value: string): string {
|
||||
return value.replace(/[\\%_]/g, (c) => `\\${c}`);
|
||||
}
|
||||
|
||||
// Only date fields support ISO 8601 duration values — converting durations on
|
||||
// other fields (e.g. `title gte "P1D"`) would compare a text column against a
|
||||
// timestamp and error at the database. Follows the codebase-wide naming
|
||||
// convention for timestamp columns (`*At`, `*Date`).
|
||||
const DATE_FIELD_RE = /(At|Date)$/;
|
||||
|
||||
/**
|
||||
* Convert an ISO 8601 duration into a Sequelize literal expressing
|
||||
* `now() ± interval '<duration>'`. A leading `-` flips the sign, allowing
|
||||
* relative-past durations (`-P7D` → `now() - 7 days`) and relative-future
|
||||
* durations (`P7D` → `now() + 7 days`).
|
||||
*
|
||||
* @param duration an ISO 8601 duration, optionally signed with a leading `-`.
|
||||
* @returns a Sequelize literal that resolves to `now() ± interval '<duration>'`.
|
||||
* @throws if the input is not a valid ISO 8601 duration.
|
||||
*/
|
||||
export function dateFromDuration(duration: string): Utils.Literal {
|
||||
if (!isISO8601Duration(duration)) {
|
||||
throw new Error(`Invalid ISO 8601 duration: ${duration}`);
|
||||
}
|
||||
const negative = duration.startsWith("-");
|
||||
const magnitude = negative ? duration.slice(1) : duration;
|
||||
const op = negative ? "-" : "+";
|
||||
return Sequelize.literal(`now() ${op} interval '${magnitude}'`);
|
||||
}
|
||||
|
||||
function isGroup<F extends string>(
|
||||
filter: Filter<F>
|
||||
): filter is FilterGroup<F> {
|
||||
return "filters" in filter;
|
||||
}
|
||||
|
||||
function leafToWhere(condition: FilterCondition): Record<string, unknown> {
|
||||
const { field, operator, value } = condition;
|
||||
|
||||
// `userId` is the public-API name for the denormalized collaboratorIds array
|
||||
// column on Document. Semantics: "documents this user collaborated on".
|
||||
if (field === "userId") {
|
||||
if (operator === "eq" && value !== undefined) {
|
||||
return { collaboratorIds: { [Op.contains]: [String(value)] } };
|
||||
}
|
||||
if (operator === "in" && Array.isArray(value)) {
|
||||
// `in` means "any of" — a document matches if it shares any collaborator
|
||||
// with the list, so use array overlap (&&) rather than contains (@>),
|
||||
// which would require every listed user to be a collaborator.
|
||||
return { collaboratorIds: { [Op.overlap]: value.map(String) } };
|
||||
}
|
||||
throw new Error("`userId` only supports `eq` or `in` operators");
|
||||
}
|
||||
|
||||
switch (operator) {
|
||||
case "isNull":
|
||||
return { [field]: { [Op.is]: null } };
|
||||
case "isNotNull":
|
||||
return { [field]: { [Op.not]: null } };
|
||||
case "contains":
|
||||
return { [field]: { [Op.iLike]: `%${escapeLike(String(value))}%` } };
|
||||
case "startsWith":
|
||||
return { [field]: { [Op.iLike]: `${escapeLike(String(value))}%` } };
|
||||
case "endsWith":
|
||||
return { [field]: { [Op.iLike]: `%${escapeLike(String(value))}` } };
|
||||
case "containsStrict":
|
||||
return { [field]: { [Op.like]: `%${escapeLike(String(value))}%` } };
|
||||
case "startsWithStrict":
|
||||
return { [field]: { [Op.like]: `${escapeLike(String(value))}%` } };
|
||||
case "endsWithStrict":
|
||||
return { [field]: { [Op.like]: `%${escapeLike(String(value))}` } };
|
||||
default: {
|
||||
const op = operatorMap[operator];
|
||||
if (typeof op !== "symbol") {
|
||||
throw new Error(`Unhandled filter operator: ${operator}`);
|
||||
}
|
||||
const resolved =
|
||||
DATE_FIELD_RE.test(field) &&
|
||||
RANGE_OPERATORS.has(operator) &&
|
||||
typeof value === "string" &&
|
||||
isISO8601Duration(value)
|
||||
? dateFromDuration(value)
|
||||
: value;
|
||||
return { [field]: { [op]: resolved } };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine a list of filter expressions into a single tree, ANDing top-level entries.
|
||||
*
|
||||
* The wire-level API accepts `filters: Filter[]` with an implicit AND between
|
||||
* entries; internal helpers operate on a single Filter tree. This bridges the two.
|
||||
*
|
||||
* @param filters the list of filter expressions, or undefined.
|
||||
* @returns the equivalent single filter, or undefined if the list is empty/missing.
|
||||
*/
|
||||
export function combineFilters(
|
||||
filters: Filter[] | undefined
|
||||
): Filter | undefined {
|
||||
if (!filters || filters.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (filters.length === 1) {
|
||||
return filters[0];
|
||||
}
|
||||
return { operator: "AND", filters };
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a filter DSL expression into a Sequelize WhereOptions clause.
|
||||
*
|
||||
* @param filter the filter expression to convert.
|
||||
* @returns a Sequelize-compatible where clause.
|
||||
*/
|
||||
export function buildWhere<M extends object = object>(
|
||||
filter: Filter
|
||||
): WhereOptions<M> {
|
||||
if (isGroup(filter)) {
|
||||
const subWheres = filter.filters.map((f) => buildWhere<M>(f));
|
||||
const op = filter.operator === "AND" ? Op.and : Op.or;
|
||||
return { [op]: subWheres } as WhereOptions<M>;
|
||||
}
|
||||
return leafToWhere(filter) as WhereOptions<M>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively check whether a filter references a particular field anywhere in its tree.
|
||||
*
|
||||
* @param filter the filter to inspect.
|
||||
* @param field the field name to look for.
|
||||
* @returns true if the field appears in any leaf condition.
|
||||
*/
|
||||
export function hasFieldInFilter(filter: Filter, field: string): boolean {
|
||||
if (isGroup(filter)) {
|
||||
return filter.filters.some((f) => hasFieldInFilter(f, field));
|
||||
}
|
||||
return filter.field === field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect all values referenced by `eq` and `in` leaves for a given field.
|
||||
*
|
||||
* @param filter the filter to inspect.
|
||||
* @param field the field name to extract values for.
|
||||
* @returns the union of values across matching leaves; empty if none.
|
||||
*/
|
||||
export function collectEqValues(filter: Filter, field: string): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (f: Filter) => {
|
||||
if (isGroup(f)) {
|
||||
f.filters.forEach(walk);
|
||||
return;
|
||||
}
|
||||
if (f.field !== field) {
|
||||
return;
|
||||
}
|
||||
if (f.operator === "eq" && f.value !== undefined) {
|
||||
out.push(String(f.value));
|
||||
} else if (f.operator === "in" && Array.isArray(f.value)) {
|
||||
out.push(...f.value.map(String));
|
||||
}
|
||||
};
|
||||
walk(filter);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a single top-level eq value for a given field, if present.
|
||||
*
|
||||
* Only matches when the filter root is either a leaf condition or an AND group
|
||||
* containing exactly one matching leaf — used for handling parameters whose
|
||||
* semantics only make sense as a single value (e.g. parentDocumentId membership
|
||||
* escape, sort=index special case).
|
||||
*
|
||||
* @param filter the filter to inspect.
|
||||
* @param field the field name to extract.
|
||||
* @returns the single eq value, or undefined if not unambiguously present.
|
||||
*/
|
||||
export function extractTopLevelEqValue(
|
||||
filter: Filter,
|
||||
field: string
|
||||
): string | undefined {
|
||||
const leaves: FilterCondition[] = isGroup(filter)
|
||||
? filter.operator === "AND"
|
||||
? filter.filters.filter(
|
||||
(f): f is FilterCondition => !isGroup(f) && f.field === field
|
||||
)
|
||||
: []
|
||||
: filter.field === field
|
||||
? [filter]
|
||||
: [];
|
||||
|
||||
if (leaves.length !== 1) {
|
||||
return undefined;
|
||||
}
|
||||
const leaf = leaves[0];
|
||||
if (leaf.operator !== "eq" || leaf.value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return String(leaf.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename leaf field names according to a mapping.
|
||||
*
|
||||
* Used to bridge the public API field naming (e.g. `userId`) to the underlying
|
||||
* Sequelize column name (e.g. `createdById`) without exposing the column name
|
||||
* in the API.
|
||||
*
|
||||
* @param filter the filter to transform.
|
||||
* @param mapping map of source field name to target column name.
|
||||
* @returns a new filter with mapped field names; structure preserved.
|
||||
*/
|
||||
export function mapFilterFields(
|
||||
filter: Filter,
|
||||
mapping: Record<string, string>
|
||||
): Filter {
|
||||
if (isGroup(filter)) {
|
||||
return {
|
||||
operator: filter.operator,
|
||||
filters: filter.filters.map((f) => mapFilterFields(f, mapping)),
|
||||
};
|
||||
}
|
||||
const mapped = mapping[filter.field];
|
||||
return mapped ? { ...filter, field: mapped } : filter;
|
||||
}
|
||||
|
||||
function searchLeafToWhere(
|
||||
condition: FilterCondition
|
||||
): Record<string, unknown> {
|
||||
// documentId must be expanded to descendant ids by the route handler
|
||||
// before reaching here — the expansion is async and authorization-
|
||||
// sensitive.
|
||||
if (condition.field === "documentId") {
|
||||
throw new Error(
|
||||
"documentId leaves must be expanded to `id` leaves before buildSearchWhere"
|
||||
);
|
||||
}
|
||||
return leafToWhere(condition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a filter expression into a Sequelize WHERE clause for full-text
|
||||
* search. Mirrors `buildWhere` apart from one field-specific guard:
|
||||
*
|
||||
* - `documentId` leaves must be expanded to `id` leaves by the route
|
||||
* handler before reaching this function — `expandDocumentIdInFilter`
|
||||
* handles that.
|
||||
*
|
||||
* @param filter the filter expression.
|
||||
* @returns a Sequelize WHERE clause.
|
||||
* @throws if the filter references documentId (unexpanded).
|
||||
*/
|
||||
export function buildSearchWhere<M extends object = object>(
|
||||
filter: Filter
|
||||
): WhereOptions<M> {
|
||||
if (isGroup(filter)) {
|
||||
const subWheres = filter.filters.map((f) => buildSearchWhere<M>(f));
|
||||
const op = filter.operator === "AND" ? Op.and : Op.or;
|
||||
return { [op]: subWheres } as WhereOptions<M>;
|
||||
}
|
||||
return searchLeafToWhere(filter) as WhereOptions<M>;
|
||||
}
|
||||
|
||||
interface LegacyParams {
|
||||
userId?: string;
|
||||
collectionId?: string;
|
||||
parentDocumentId?: string | null;
|
||||
documentId?: string;
|
||||
dateFilter?: DateFilter;
|
||||
statusFilter?: StatusFilter[];
|
||||
}
|
||||
|
||||
const DURATION_BY_DATE_FILTER: Record<DateFilter, string> = {
|
||||
day: "-P1D",
|
||||
week: "-P1W",
|
||||
month: "-P1M",
|
||||
year: "-P1Y",
|
||||
};
|
||||
|
||||
function statusToFilter(status: StatusFilter): Filter {
|
||||
if (status === StatusFilterEnum.Archived) {
|
||||
return { field: "archivedAt", operator: "isNotNull" };
|
||||
}
|
||||
if (status === StatusFilterEnum.Published) {
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
};
|
||||
}
|
||||
// Draft
|
||||
return {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNull" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate deprecated top-level params into an equivalent filter expression.
|
||||
* Callers pass only the subset of params their route accepts; each one becomes
|
||||
* a leaf (or sub-tree, for `statusFilter`), and all entries are ANDed together.
|
||||
*
|
||||
* Notable shapes:
|
||||
* - `parentDocumentId === null` → `isNull` leaf (matches root-level docs).
|
||||
* - `dateFilter` → `updatedAt gte` with an ISO 8601 duration literal.
|
||||
* - `statusFilter` with multiple entries → OR of status shapes.
|
||||
*
|
||||
* @param legacy the deprecated top-level params.
|
||||
* @returns the equivalent filter, or undefined if none were set.
|
||||
*/
|
||||
export function legacyParamsToFilter(legacy: LegacyParams): Filter | undefined {
|
||||
const leaves: Filter[] = [];
|
||||
|
||||
if (legacy.userId) {
|
||||
leaves.push({ field: "userId", operator: "eq", value: legacy.userId });
|
||||
}
|
||||
if (legacy.collectionId) {
|
||||
leaves.push({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: legacy.collectionId,
|
||||
});
|
||||
}
|
||||
if (legacy.parentDocumentId === null) {
|
||||
leaves.push({ field: "parentDocumentId", operator: "isNull" });
|
||||
} else if (legacy.parentDocumentId) {
|
||||
leaves.push({
|
||||
field: "parentDocumentId",
|
||||
operator: "eq",
|
||||
value: legacy.parentDocumentId,
|
||||
});
|
||||
}
|
||||
if (legacy.documentId) {
|
||||
leaves.push({
|
||||
field: "documentId",
|
||||
operator: "eq",
|
||||
value: legacy.documentId,
|
||||
});
|
||||
}
|
||||
if (legacy.dateFilter) {
|
||||
leaves.push({
|
||||
field: "updatedAt",
|
||||
operator: "gte",
|
||||
value: DURATION_BY_DATE_FILTER[legacy.dateFilter],
|
||||
});
|
||||
}
|
||||
if (legacy.statusFilter && legacy.statusFilter.length > 0) {
|
||||
const statusShapes = legacy.statusFilter.map(statusToFilter);
|
||||
leaves.push(
|
||||
statusShapes.length === 1
|
||||
? statusShapes[0]
|
||||
: { operator: "OR", filters: statusShapes }
|
||||
);
|
||||
}
|
||||
|
||||
return combineFilters(leaves);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace `documentId` leaves in a filter with `id in [...]` leaves using ids
|
||||
* pre-resolved by the route handler (typically each document plus its
|
||||
* descendant ids). `eq` leaves map to their document's expansion; `in` leaves
|
||||
* map to the union of their documents' expansions. A document missing from the
|
||||
* map falls back to its own id, which matches at most the document itself.
|
||||
*
|
||||
* @param filter the filter to transform.
|
||||
* @param expandedIds map of documentId to its resolved id list.
|
||||
* @returns a new filter with the substitution applied.
|
||||
*/
|
||||
export function expandDocumentIdInFilter(
|
||||
filter: Filter,
|
||||
expandedIds: Map<string, string[]>
|
||||
): Filter {
|
||||
if (isGroup(filter)) {
|
||||
return {
|
||||
operator: filter.operator,
|
||||
filters: filter.filters.map((f) =>
|
||||
expandDocumentIdInFilter(f, expandedIds)
|
||||
),
|
||||
};
|
||||
}
|
||||
if (filter.field !== "documentId") {
|
||||
return filter;
|
||||
}
|
||||
// `eq` is the single-id case of `in`; both map to the deduped union of each
|
||||
// document's pre-resolved expansion (falling back to the raw id).
|
||||
let ids: string[] | undefined;
|
||||
if (filter.operator === "eq" && filter.value !== undefined) {
|
||||
ids = [String(filter.value)];
|
||||
} else if (filter.operator === "in" && Array.isArray(filter.value)) {
|
||||
ids = filter.value.map(String);
|
||||
}
|
||||
if (!ids) {
|
||||
return filter;
|
||||
}
|
||||
return {
|
||||
field: "id",
|
||||
operator: "in",
|
||||
value: Array.from(
|
||||
new Set(ids.flatMap((id) => expandedIds.get(id) ?? [id]))
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-run authorization for any auth-bearing fields referenced inside a filter.
|
||||
*
|
||||
* Currently authorizes each `collectionId` value referenced via `eq` or `in`,
|
||||
* mirroring the authorize() call the legacy top-level `collectionId` param would
|
||||
* have triggered. Throws if any referenced collection is not readable.
|
||||
*
|
||||
* @param user the current user.
|
||||
* @param filter the filter to authorize.
|
||||
* @throws if the user lacks read access to any referenced collection.
|
||||
*/
|
||||
export async function authorizeFilterFields(
|
||||
user: User,
|
||||
filter: Filter
|
||||
): Promise<void> {
|
||||
const collectionIds = collectEqValues(filter, "collectionId");
|
||||
if (collectionIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const collections = await Promise.all(
|
||||
Array.from(new Set(collectionIds)).map((id) =>
|
||||
Collection.findByPk(id, { userId: user.id })
|
||||
)
|
||||
);
|
||||
|
||||
for (const collection of collections) {
|
||||
authorize(user, "readDocument", collection);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ import Router from "koa-router";
|
||||
import { escapeRegExp, has, remove, uniq } from "es-toolkit/compat";
|
||||
import mime from "mime-types";
|
||||
import type { Order, ScopeOptions, WhereOptions } from "sequelize";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import { Op, Sequelize } from "sequelize";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { DirectionFilter, SortFilter } from "@shared/types";
|
||||
@@ -65,6 +66,17 @@ import {
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import {
|
||||
authorizeFilterFields,
|
||||
buildWhere,
|
||||
collectEqValues,
|
||||
combineFilters,
|
||||
expandDocumentIdInFilter,
|
||||
extractTopLevelEqValue,
|
||||
hasFieldInFilter,
|
||||
legacyParamsToFilter,
|
||||
mapFilterFields,
|
||||
} from "@server/models/helpers/Filters";
|
||||
import HTMLHelper from "@server/models/helpers/HTMLHelper";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import TextBundleHelper from "@server/models/helpers/TextBundleHelper";
|
||||
@@ -101,6 +113,92 @@ import {
|
||||
|
||||
const router = new Router();
|
||||
|
||||
/**
|
||||
* Resolve every `documentId` leaf in a search filter to an `id in [...]` leaf
|
||||
* containing the document and all of its descendants. When a user is given,
|
||||
* each referenced document is authorized for read access. In share contexts
|
||||
* the expansion is only scoped to the share's team — results are constrained
|
||||
* to the share's own document subtree by the provider, so no per-document
|
||||
* authorization is needed.
|
||||
*
|
||||
* @param filter the search filter to transform.
|
||||
* @param context the user performing the search, or the share's team scope.
|
||||
* @returns the filter with documentId leaves expanded, or the original filter
|
||||
* if none are present.
|
||||
*/
|
||||
async function expandDocumentIdLeaves(
|
||||
filter: Filter,
|
||||
context: { user: User } | { teamId: string }
|
||||
): Promise<Filter> {
|
||||
const documentIds = uniq(collectEqValues(filter, "documentId"));
|
||||
if (documentIds.length === 0) {
|
||||
return filter;
|
||||
}
|
||||
|
||||
const expandedIds = new Map<string, string[]>();
|
||||
await Promise.all(
|
||||
documentIds.map(async (documentId) => {
|
||||
if ("user" in context) {
|
||||
const document = await Document.findByPk(documentId, {
|
||||
userId: context.user.id,
|
||||
});
|
||||
authorize(context.user, "read", document);
|
||||
expandedIds.set(documentId, [
|
||||
documentId,
|
||||
...(await document.findAllChildDocumentIds()),
|
||||
]);
|
||||
} else {
|
||||
const document = await Document.unscoped().findOne({
|
||||
where: { id: documentId, teamId: context.teamId },
|
||||
});
|
||||
expandedIds.set(
|
||||
documentId,
|
||||
document
|
||||
? [documentId, ...(await document.findAllChildDocumentIds())]
|
||||
: [documentId]
|
||||
);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return expandDocumentIdInFilter(filter, expandedIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the ids of documents the user has a direct membership on. Used to
|
||||
* express draft visibility without referencing the (separately-loaded)
|
||||
* memberships association, which would otherwise break the COUNT query.
|
||||
*
|
||||
* @param user the user to fetch membership document ids for.
|
||||
* @returns the list of document ids.
|
||||
*/
|
||||
async function directMembershipDocumentIds(user: User): Promise<string[]> {
|
||||
const memberships = await UserMembership.findAll({
|
||||
attributes: ["documentId"],
|
||||
where: {
|
||||
userId: user.id,
|
||||
documentId: { [Op.ne]: null },
|
||||
},
|
||||
});
|
||||
return memberships.map((m) => m.documentId as string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the visibility clauses for drafts: a draft is only ever visible to its
|
||||
* creator or to a user with a direct membership on it. Both the filter-derived
|
||||
* and legacy statusFilter draft paths route through this so the invariant lives
|
||||
* in one place.
|
||||
*
|
||||
* @param user the user the drafts must be visible to.
|
||||
* @returns an array of OR-able Sequelize conditions.
|
||||
*/
|
||||
async function draftVisibilityClauses(user: User): Promise<WhereOptions[]> {
|
||||
return [
|
||||
{ createdById: user.id },
|
||||
{ id: await directMembershipDocumentIds(user) },
|
||||
];
|
||||
}
|
||||
|
||||
router.post(
|
||||
"documents.list",
|
||||
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
|
||||
@@ -111,12 +209,13 @@ router.post(
|
||||
const {
|
||||
sort,
|
||||
direction,
|
||||
collectionId,
|
||||
backlinkDocumentId,
|
||||
parentDocumentId,
|
||||
userId: createdById,
|
||||
parentDocumentId: legacyParentDocumentId,
|
||||
userId: legacyUserId,
|
||||
statusFilter,
|
||||
filters: rawFilters,
|
||||
} = ctx.input.body;
|
||||
let { collectionId: legacyCollectionId } = ctx.input.body;
|
||||
const { offset, limit } = ctx.state.pagination;
|
||||
|
||||
// always filter by the current team
|
||||
@@ -134,51 +233,26 @@ router.post(
|
||||
],
|
||||
};
|
||||
|
||||
// Exclude archived docs by default
|
||||
if (!statusFilter) {
|
||||
where[Op.and].push({ archivedAt: { [Op.eq]: null } });
|
||||
}
|
||||
|
||||
// if a specific user is passed then add to filters. If the user doesn't
|
||||
// exist in the team then nothing will be returned, so no need to check auth
|
||||
if (createdById) {
|
||||
where[Op.and].push({ createdById });
|
||||
}
|
||||
|
||||
let documentIds: string[] = [];
|
||||
|
||||
// if a specific collection is passed then we need to check auth to view it
|
||||
if (collectionId) {
|
||||
where[Op.and].push({ collectionId: [collectionId] });
|
||||
const collection = await Collection.findByPk(collectionId, {
|
||||
userId: user.id,
|
||||
includeDocumentStructure: sort === "index",
|
||||
});
|
||||
|
||||
authorize(user, "readDocument", collection);
|
||||
|
||||
// index sort is special because it uses the order of the documents in the
|
||||
// collection.documentStructure rather than a database column
|
||||
if (sort === "index") {
|
||||
// Extract all document IDs from the collection structure.
|
||||
documentIds = (collection.documentStructure || [])
|
||||
.slice(offset, offset + limit)
|
||||
.map((node) => node.id);
|
||||
where[Op.and].push({ id: documentIds });
|
||||
} // if it's not a backlink request, filter by all collections the user has access to
|
||||
} else if (!backlinkDocumentId) {
|
||||
const collectionIds = await user.collectionIds();
|
||||
where[Op.and].push({
|
||||
collectionId: collectionIds,
|
||||
});
|
||||
}
|
||||
// Resolve the parent document being targeted from either the legacy
|
||||
// top-level param or the filters DSL, so the membership escape below
|
||||
// applies in both cases. `isNull` leaves resolve to undefined here
|
||||
// (no specific parent to authorize against).
|
||||
const normalizedFilter = combineFilters(rawFilters);
|
||||
const parentDocumentId =
|
||||
legacyParentDocumentId ??
|
||||
(normalizedFilter
|
||||
? extractTopLevelEqValue(normalizedFilter, "parentDocumentId")
|
||||
: undefined);
|
||||
|
||||
// Membership escape: if the caller is filtering by a parent document they
|
||||
// are a direct member of (or have group membership to), bypass the default
|
||||
// collection access check. Mirrors the prior behavior of pushing then
|
||||
// removing the legacy collectionId predicate.
|
||||
let collectionScopeDropped = false;
|
||||
if (parentDocumentId) {
|
||||
const [groupMembership, membership] = await Promise.all([
|
||||
GroupMembership.findOne({
|
||||
where: {
|
||||
documentId: parentDocumentId,
|
||||
},
|
||||
where: { documentId: parentDocumentId },
|
||||
include: [
|
||||
{
|
||||
model: Group,
|
||||
@@ -187,36 +261,76 @@ router.post(
|
||||
{
|
||||
model: GroupUser,
|
||||
required: true,
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
where: { userId: user.id },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
UserMembership.findOne({
|
||||
where: {
|
||||
userId: user.id,
|
||||
documentId: parentDocumentId,
|
||||
},
|
||||
where: { userId: user.id, documentId: parentDocumentId },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (groupMembership || membership) {
|
||||
remove(where[Op.and], (cond) => has(cond, "collectionId"));
|
||||
collectionScopeDropped = true;
|
||||
legacyCollectionId = undefined;
|
||||
}
|
||||
|
||||
where[Op.and].push({ parentDocumentId });
|
||||
}
|
||||
|
||||
// Explicitly passing 'null' as the parentDocumentId allows listing documents
|
||||
// that have no parent document (aka they are at the root of the collection)
|
||||
if (parentDocumentId === null) {
|
||||
// The schema rejects callers that combine `filters` with the deprecated
|
||||
// top-level params, so exactly one of these is set.
|
||||
const filter =
|
||||
normalizedFilter ??
|
||||
legacyParamsToFilter({
|
||||
userId: legacyUserId,
|
||||
collectionId: legacyCollectionId,
|
||||
parentDocumentId: legacyParentDocumentId,
|
||||
});
|
||||
|
||||
// Exclude archived docs by default. Suppressed when the caller targets a
|
||||
// specific status, or when their filter already references archivedAt.
|
||||
const filterIncludesArchivedAt =
|
||||
filter !== undefined && hasFieldInFilter(filter, "archivedAt");
|
||||
if (!statusFilter && !filterIncludesArchivedAt) {
|
||||
where[Op.and].push({ archivedAt: { [Op.eq]: null } });
|
||||
}
|
||||
|
||||
// Sort=index needs the collection's documentStructure for ordering and
|
||||
// pagination. Only meaningful when the filter targets a single collection.
|
||||
let documentIds: string[] = [];
|
||||
const explicitCollectionId =
|
||||
filter !== undefined
|
||||
? extractTopLevelEqValue(filter, "collectionId")
|
||||
: undefined;
|
||||
if (explicitCollectionId && sort === "index") {
|
||||
const collection = await Collection.findByPk(explicitCollectionId, {
|
||||
userId: user.id,
|
||||
includeDocumentStructure: true,
|
||||
});
|
||||
authorize(user, "readDocument", collection);
|
||||
documentIds = (collection.documentStructure || [])
|
||||
.slice(offset, offset + limit)
|
||||
.map((node) => node.id);
|
||||
where[Op.and].push({ id: documentIds });
|
||||
}
|
||||
|
||||
// Apply filter and re-run authorize() for any auth-bearing fields. The
|
||||
// public-API `documentId` field is renamed to the underlying `id` column;
|
||||
// `userId` is handled inside `buildWhere` (maps to `collaboratorIds`).
|
||||
if (filter) {
|
||||
await authorizeFilterFields(user, filter);
|
||||
const mapped = mapFilterFields(filter, { documentId: "id" });
|
||||
where[Op.and].push(buildWhere<Document>(mapped));
|
||||
}
|
||||
|
||||
if (!backlinkDocumentId && !collectionScopeDropped) {
|
||||
const collectionIds = await user.collectionIds();
|
||||
where[Op.and].push({
|
||||
parentDocumentId: {
|
||||
[Op.is]: null,
|
||||
},
|
||||
[Op.or]: [
|
||||
{ collectionId: collectionIds },
|
||||
{ collectionId: null, createdById: user.id },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -232,6 +346,23 @@ router.post(
|
||||
remove(where[Op.and], (cond) => has(cond, "collectionId"));
|
||||
}
|
||||
|
||||
// A filter referencing publishedAt can surface drafts (the replacement
|
||||
// for the deprecated statusFilter=draft). Drafts are only ever visible to
|
||||
// their creator or users with a direct membership — enforce that here,
|
||||
// mirroring the legacy statusFilter path below.
|
||||
const filterIncludesDrafts =
|
||||
!statusFilter &&
|
||||
filter !== undefined &&
|
||||
hasFieldInFilter(filter, "publishedAt");
|
||||
if (filterIncludesDrafts) {
|
||||
where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ publishedAt: { [Op.ne]: null } },
|
||||
...(await draftVisibilityClauses(user)),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const statusQuery = [];
|
||||
if (statusFilter?.includes(StatusFilter.Published)) {
|
||||
statusQuery.push({
|
||||
@@ -249,19 +380,6 @@ router.post(
|
||||
}
|
||||
|
||||
if (statusFilter?.includes(StatusFilter.Draft)) {
|
||||
// Pre-fetch document IDs the user has a direct membership on so the
|
||||
// filter can be expressed without referencing the (separately-loaded)
|
||||
// memberships association, which would otherwise break the COUNT query.
|
||||
const membershipDocumentIds = (
|
||||
await UserMembership.findAll({
|
||||
attributes: ["documentId"],
|
||||
where: {
|
||||
userId: user.id,
|
||||
documentId: { [Op.ne]: null },
|
||||
},
|
||||
})
|
||||
).map((m) => m.documentId as string);
|
||||
|
||||
statusQuery.push({
|
||||
[Op.and]: [
|
||||
{
|
||||
@@ -271,11 +389,7 @@ router.post(
|
||||
archivedAt: {
|
||||
[Op.eq]: null,
|
||||
},
|
||||
[Op.or]: [
|
||||
// Only ever include draft results for the user's own documents
|
||||
{ createdById: user.id },
|
||||
{ id: membershipDocumentIds },
|
||||
],
|
||||
[Op.or]: await draftVisibilityClauses(user),
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -311,7 +425,8 @@ router.post(
|
||||
: undefined
|
||||
: [[sort, direction]];
|
||||
|
||||
const includeDrafts = !!statusFilter?.includes(StatusFilter.Draft);
|
||||
const includeDrafts =
|
||||
!!statusFilter?.includes(StatusFilter.Draft) || filterIncludesDrafts;
|
||||
|
||||
// The withDrafts scope drops the defaultScope filters, so re-apply the
|
||||
// ones we still want — templates and trial-import documents should never
|
||||
@@ -1051,37 +1166,33 @@ router.post(
|
||||
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
|
||||
validate(T.DocumentsSearchTitlesSchema),
|
||||
async (ctx: APIContext<T.DocumentsSearchTitlesReq>) => {
|
||||
const {
|
||||
query,
|
||||
statusFilter,
|
||||
dateFilter,
|
||||
collectionId,
|
||||
userId,
|
||||
sort,
|
||||
direction,
|
||||
} = ctx.input.body;
|
||||
const { query, sort, direction, filters: rawFilters } = ctx.input.body;
|
||||
const { collectionId, userId, documentId, statusFilter, dateFilter } =
|
||||
ctx.input.body;
|
||||
const { offset, limit } = ctx.state.pagination;
|
||||
const { user } = ctx.state.auth;
|
||||
let collaboratorIds = undefined;
|
||||
|
||||
if (collectionId) {
|
||||
const collection = await Collection.findByPk(collectionId, {
|
||||
userId: user.id,
|
||||
const filter =
|
||||
combineFilters(rawFilters) ??
|
||||
legacyParamsToFilter({
|
||||
collectionId,
|
||||
userId,
|
||||
documentId,
|
||||
statusFilter,
|
||||
dateFilter,
|
||||
});
|
||||
authorize(user, "readDocument", collection);
|
||||
|
||||
if (filter) {
|
||||
await authorizeFilterFields(user, filter);
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
collaboratorIds = [userId];
|
||||
}
|
||||
const resolvedFilter = filter
|
||||
? await expandDocumentIdLeaves(filter, { user })
|
||||
: undefined;
|
||||
|
||||
const documents =
|
||||
await SearchProviderManager.getProvider().searchTitlesForUser(user, {
|
||||
query,
|
||||
dateFilter,
|
||||
statusFilter,
|
||||
collectionId,
|
||||
collaboratorIds,
|
||||
filter: resolvedFilter,
|
||||
offset,
|
||||
limit,
|
||||
sort: sort as SortFilter,
|
||||
@@ -1107,17 +1218,24 @@ router.post(
|
||||
async (ctx: APIContext<T.DocumentsSearchReq>) => {
|
||||
const {
|
||||
query,
|
||||
collectionId,
|
||||
documentId,
|
||||
userId,
|
||||
dateFilter,
|
||||
statusFilter = [],
|
||||
shareId,
|
||||
snippetMinWords,
|
||||
snippetMaxWords,
|
||||
sort,
|
||||
direction,
|
||||
filters: rawFilters,
|
||||
} = ctx.input.body;
|
||||
const { collectionId, documentId, userId, dateFilter, statusFilter } =
|
||||
ctx.input.body;
|
||||
const filter =
|
||||
combineFilters(rawFilters) ??
|
||||
legacyParamsToFilter({
|
||||
collectionId,
|
||||
userId,
|
||||
documentId,
|
||||
statusFilter,
|
||||
dateFilter,
|
||||
});
|
||||
const { offset, limit } = ctx.state.pagination;
|
||||
const { user } = ctx.state.auth;
|
||||
|
||||
@@ -1161,12 +1279,27 @@ router.post(
|
||||
const team = await share.$get("team");
|
||||
invariant(team, "Share must belong to a team");
|
||||
|
||||
const shareScopeId = collection?.id || document?.collectionId;
|
||||
const shareFilter = combineFilters([
|
||||
...(filter ? [filter] : []),
|
||||
...(shareScopeId
|
||||
? [
|
||||
{
|
||||
field: "collectionId",
|
||||
operator: "eq" as const,
|
||||
value: shareScopeId,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
const resolvedShareFilter = shareFilter
|
||||
? await expandDocumentIdLeaves(shareFilter, { teamId: share.teamId })
|
||||
: undefined;
|
||||
|
||||
response = await SearchProviderManager.getProvider().searchForTeam(team, {
|
||||
query,
|
||||
collectionId: collection?.id || document?.collectionId,
|
||||
filter: resolvedShareFilter,
|
||||
share,
|
||||
dateFilter,
|
||||
statusFilter,
|
||||
offset,
|
||||
limit,
|
||||
snippetMinWords,
|
||||
@@ -1182,38 +1315,17 @@ router.post(
|
||||
|
||||
teamId = user.teamId;
|
||||
|
||||
if (collectionId) {
|
||||
const collection = await Collection.findByPk(collectionId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "readDocument", collection);
|
||||
if (filter) {
|
||||
await authorizeFilterFields(user, filter);
|
||||
}
|
||||
|
||||
let documentIds = undefined;
|
||||
if (documentId) {
|
||||
const document = await Document.findByPk(documentId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "read", document);
|
||||
documentIds = [
|
||||
documentId,
|
||||
...(await document.findAllChildDocumentIds()),
|
||||
];
|
||||
}
|
||||
|
||||
let collaboratorIds = undefined;
|
||||
|
||||
if (userId) {
|
||||
collaboratorIds = [userId];
|
||||
}
|
||||
const resolvedFilter = filter
|
||||
? await expandDocumentIdLeaves(filter, { user })
|
||||
: undefined;
|
||||
|
||||
response = await SearchProviderManager.getProvider().searchForUser(user, {
|
||||
query,
|
||||
collaboratorIds,
|
||||
collectionId,
|
||||
documentIds,
|
||||
dateFilter,
|
||||
statusFilter,
|
||||
filter: resolvedFilter,
|
||||
offset,
|
||||
limit,
|
||||
snippetMinWords,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type formidable from "formidable";
|
||||
import { isEmpty } from "es-toolkit/compat";
|
||||
import { z } from "zod";
|
||||
import { createFilterSchema } from "@shared/helpers/FilterHelper";
|
||||
import {
|
||||
DirectionFilter,
|
||||
DocumentPermission,
|
||||
@@ -13,6 +14,30 @@ 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",
|
||||
// `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);
|
||||
|
||||
// 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
|
||||
@@ -37,7 +62,11 @@ const DocumentsSortParamsSchema = z.object({
|
||||
});
|
||||
|
||||
const DateFilterSchema = z.object({
|
||||
/** Date filter */
|
||||
/**
|
||||
* Date filter.
|
||||
* @deprecated use `filters` with `updatedAt` and an ISO 8601 duration
|
||||
* (`-P1D`, `-P1W`, `-P1M`, `-P1Y`) instead.
|
||||
*/
|
||||
dateFilter: z
|
||||
.union([
|
||||
z.literal("day"),
|
||||
@@ -49,16 +78,28 @@ const DateFilterSchema = z.object({
|
||||
});
|
||||
|
||||
const BaseSearchSchema = DateFilterSchema.extend({
|
||||
/** Filter results for team based on the collection */
|
||||
/**
|
||||
* Filter results for team based on the collection.
|
||||
* @deprecated use `filters` with field `collectionId` instead.
|
||||
*/
|
||||
collectionId: z.uuid().optional(),
|
||||
|
||||
/** Filter results based on user */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
@@ -78,36 +119,75 @@ const BaseIdSchema = z.object({
|
||||
|
||||
export const DocumentsListSchema = BaseSchema.extend({
|
||||
body: DocumentsSortParamsSchema.extend({
|
||||
/** Id of the user who created the doc */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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 */
|
||||
/**
|
||||
* 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;
|
||||
})
|
||||
.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;
|
||||
});
|
||||
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>;
|
||||
|
||||
@@ -195,6 +275,26 @@ export const DocumentsRestoreSchema = BaseSchema.extend({
|
||||
|
||||
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 */
|
||||
@@ -207,7 +307,12 @@ export const DocumentsSearchSchema = BaseSchema.extend({
|
||||
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>;
|
||||
@@ -224,7 +329,12 @@ export const DocumentsSearchTitlesSchema = BaseSchema.extend({
|
||||
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<
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Context, Next } from "koa";
|
||||
import {
|
||||
ValidationError as SequelizeValidationError,
|
||||
EmptyResultError as SequelizeEmptyResultError,
|
||||
DatabaseError as SequelizeDatabaseError,
|
||||
} from "sequelize";
|
||||
import {
|
||||
AuthorizationError,
|
||||
@@ -9,6 +10,23 @@ import {
|
||||
ValidationError,
|
||||
} from "@server/errors";
|
||||
|
||||
/** Postgres codes for a requested date the database cannot represent. */
|
||||
const DATE_RANGE_ERROR_CODES = new Set(["22008", "22015"]);
|
||||
|
||||
/**
|
||||
* Reads the SQLSTATE code from the driver error a DatabaseError wraps.
|
||||
*
|
||||
* @param err the Sequelize error to inspect.
|
||||
* @returns the SQLSTATE code, or undefined if the driver did not supply one.
|
||||
*/
|
||||
function sqlStateOf(err: SequelizeDatabaseError): string | undefined {
|
||||
const { parent } = err;
|
||||
if (parent && "code" in parent && typeof parent.code === "string") {
|
||||
return parent.code;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export default function apiErrorHandler() {
|
||||
return async function apiErrorHandlerMiddleware(ctx: Context, next: Next) {
|
||||
try {
|
||||
@@ -34,6 +52,15 @@ export default function apiErrorHandler() {
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
err instanceof SequelizeDatabaseError &&
|
||||
DATE_RANGE_ERROR_CODES.has(sqlStateOf(err) ?? "")
|
||||
) {
|
||||
transformedErr = ValidationError(
|
||||
"Date value in request is out of range"
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
(err instanceof Error && "code" in err && err.code === "ENOENT") ||
|
||||
err instanceof SequelizeEmptyResultError ||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import Router from "koa-router";
|
||||
import { Op } from "sequelize";
|
||||
import { Sequelize } from "sequelize-typescript";
|
||||
import { StatusFilter } from "@shared/types";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Group, User } from "@server/models";
|
||||
@@ -82,7 +81,13 @@ router.post(
|
||||
query,
|
||||
offset,
|
||||
limit,
|
||||
statusFilter: [StatusFilter.Published],
|
||||
filter: {
|
||||
operator: "AND",
|
||||
filters: [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
suggestUsers(),
|
||||
can(actor, "listGroups", actor.team)
|
||||
|
||||
@@ -34,7 +34,8 @@ import {
|
||||
withTracing,
|
||||
} from "./util";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import { StatusFilter, TextEditMode } from "@shared/types";
|
||||
import { TextEditMode } from "@shared/types";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import SearchProviderManager from "@server/utils/SearchProviderManager";
|
||||
|
||||
/**
|
||||
@@ -149,7 +150,13 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
user,
|
||||
{
|
||||
query,
|
||||
collectionId,
|
||||
filter: collectionId
|
||||
? {
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: collectionId,
|
||||
}
|
||||
: undefined,
|
||||
offset: effectiveOffset,
|
||||
limit: effectiveLimit,
|
||||
}
|
||||
@@ -233,11 +240,21 @@ export function documentTools(server: McpServer, scopes: string[]) {
|
||||
// List recent documents via the search provider (with no query) so
|
||||
// access control matches the search path exactly.
|
||||
const searchProvider = SearchProviderManager.getProvider();
|
||||
const filters: Filter[] = [
|
||||
{ field: "archivedAt", operator: "isNull" },
|
||||
{ field: "publishedAt", operator: "isNotNull" },
|
||||
];
|
||||
if (collectionId) {
|
||||
filters.push({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: collectionId,
|
||||
});
|
||||
}
|
||||
const { results } = await searchProvider.searchForUser(user, {
|
||||
collectionId,
|
||||
filter: { operator: "AND", filters },
|
||||
offset: effectiveOffset,
|
||||
limit: effectiveLimit,
|
||||
statusFilter: [StatusFilter.Published],
|
||||
});
|
||||
|
||||
const documents = results.map((result) => result.document);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DateFilter } from "@shared/types";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import type { SearchableModel } from "@shared/types";
|
||||
import type { DirectionFilter, SortFilter, StatusFilter } from "@shared/types";
|
||||
import type { DirectionFilter, SortFilter } from "@shared/types";
|
||||
import type Collection from "@server/models/Collection";
|
||||
import type Comment from "@server/models/Comment";
|
||||
import type Document from "@server/models/Document";
|
||||
@@ -28,18 +28,14 @@ export interface SearchOptions {
|
||||
offset?: number;
|
||||
/** The text to search for. */
|
||||
query?: string;
|
||||
/** Limit results to a collection. Authorization is presumed to have been done before passing to this provider. */
|
||||
collectionId?: string | null;
|
||||
/**
|
||||
* A filter expression scoping results. Authorization for any auth-bearing
|
||||
* fields (e.g. collectionId) is presumed to have been done before reaching
|
||||
* the provider.
|
||||
*/
|
||||
filter?: Filter;
|
||||
/** Limit results to a shared document. */
|
||||
share?: Share;
|
||||
/** Limit results to a date range. */
|
||||
dateFilter?: DateFilter;
|
||||
/** Status of the documents to return. */
|
||||
statusFilter?: StatusFilter[];
|
||||
/** Limit results to a list of documents. */
|
||||
documentIds?: string[];
|
||||
/** Limit results to a list of users that collaborated on the document. */
|
||||
collaboratorIds?: string[];
|
||||
/** The minimum number of words to be returned in the contextual snippet. */
|
||||
snippetMinWords?: number;
|
||||
/** The maximum number of words to be returned in the contextual snippet. */
|
||||
|
||||
+101
-1
@@ -1,6 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Buckets } from "./models/helpers/AttachmentHelper";
|
||||
import { ValidateKey } from "./validation";
|
||||
import { ValidateKey, isISO8601Duration } from "./validation";
|
||||
|
||||
describe("#ValidateKey.isValid", () => {
|
||||
it("should return false if number of key components is incorrect", () => {
|
||||
@@ -69,6 +69,106 @@ describe("#ValidateKey.sanitize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("#isISO8601Duration", () => {
|
||||
describe("valid cases", () => {
|
||||
it.each([
|
||||
"P1Y",
|
||||
"P1M",
|
||||
"P1D",
|
||||
"P1W",
|
||||
"P52W",
|
||||
"P0D",
|
||||
"P10Y",
|
||||
"P365D",
|
||||
"PT1H",
|
||||
"PT30M",
|
||||
"PT45S",
|
||||
"PT1H30M",
|
||||
"PT1H30M45S",
|
||||
"PT24H",
|
||||
"PT1500S",
|
||||
"PT0S",
|
||||
"P1Y2M",
|
||||
"P1Y2M3D",
|
||||
"P2M3D",
|
||||
"P1DT12H",
|
||||
"P1Y2M3DT4H5M6S",
|
||||
"-P1D",
|
||||
"-P7D",
|
||||
"-PT1H",
|
||||
"-P1Y2M3DT4H5M6S",
|
||||
"-P1W",
|
||||
])("accepts %s", (value) => {
|
||||
expect(isISO8601Duration(value)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invalid cases", () => {
|
||||
it.each([
|
||||
// Missing prefix
|
||||
"1D",
|
||||
"T1H",
|
||||
"Y1",
|
||||
// Empty / lone prefix
|
||||
"",
|
||||
"P",
|
||||
"PT",
|
||||
"-P",
|
||||
"-PT",
|
||||
// Missing number
|
||||
"PD",
|
||||
"PMW",
|
||||
"PT H",
|
||||
// Missing unit
|
||||
"P1",
|
||||
"PT1",
|
||||
"P1Y2",
|
||||
// Unknown unit
|
||||
"P1Z",
|
||||
"P1X",
|
||||
"PT1Q",
|
||||
// Wrong section (date vs time)
|
||||
"P1H",
|
||||
"PT1Y",
|
||||
"PT1D",
|
||||
// Trailing T
|
||||
"P1DT",
|
||||
"P1YT",
|
||||
// Weeks combined with other units
|
||||
"P1W1D",
|
||||
"P1Y1W",
|
||||
// Decimals
|
||||
"P1.5D",
|
||||
"P0.5W",
|
||||
"PT1.5H",
|
||||
// Sign in wrong place
|
||||
"P-1D",
|
||||
"PT-1H",
|
||||
"--P1D",
|
||||
"+P1D",
|
||||
// Whitespace
|
||||
"P 1D",
|
||||
"P1D ",
|
||||
" P1D",
|
||||
"- P1D",
|
||||
// Lowercase
|
||||
"p1d",
|
||||
"P1d",
|
||||
"pt1h",
|
||||
// Quotes / SQL metacharacters
|
||||
"P1D'",
|
||||
"P1D; DROP TABLE",
|
||||
"P1D--",
|
||||
"P1D OR 1=1",
|
||||
// Order swap
|
||||
"P1D1Y",
|
||||
"P1M1Y",
|
||||
])("rejects %j", (value) => {
|
||||
expect(isISO8601Duration(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("#ValidateKey.sanitizeSegment", () => {
|
||||
it("should leave an ordinary name untouched", () => {
|
||||
expect(ValidateKey.sanitizeSegment("My Document")).toEqual("My Document");
|
||||
|
||||
@@ -13,6 +13,8 @@ import { isUrl } from "@shared/utils/urls";
|
||||
import { ParamRequiredError, ValidationError } from "./errors";
|
||||
import { Buckets } from "./models/helpers/AttachmentHelper";
|
||||
|
||||
export { isISO8601Duration } from "@shared/utils/date";
|
||||
|
||||
type IncomingValue = Primitive | string[];
|
||||
|
||||
export const assertPresent = (value: IncomingValue, message: string) => {
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
import { FilterValidation } from "../validations";
|
||||
import type { Filter } from "./FilterHelper";
|
||||
import { createFilterSchema } from "./FilterHelper";
|
||||
|
||||
const { FilterSchema, FilterListSchema } = createFilterSchema({
|
||||
createdAt: "date",
|
||||
title: "string",
|
||||
collectionId: "uuid",
|
||||
views: "number",
|
||||
isDraft: "boolean",
|
||||
} as const);
|
||||
|
||||
const uuid = "00000000-0000-4000-8000-000000000000";
|
||||
|
||||
const leaf: Filter = { field: "title", operator: "eq", value: "x" };
|
||||
|
||||
/** Build a flat OR group that holds `count` leaves, for a total of count + 1 nodes. */
|
||||
function groupOf(count: number): Filter {
|
||||
return {
|
||||
operator: "OR",
|
||||
filters: Array.from({ length: count }, () => leaf),
|
||||
};
|
||||
}
|
||||
|
||||
describe("createFilterSchema value validation", () => {
|
||||
describe("uuid fields", () => {
|
||||
it("accepts a valid uuid", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: uuid,
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-uuid value", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "collectionId",
|
||||
operator: "eq",
|
||||
value: "garbage",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("validates every entry of an `in` array", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "collectionId",
|
||||
operator: "in",
|
||||
value: [uuid, "garbage"],
|
||||
}).success
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "collectionId",
|
||||
operator: "in",
|
||||
value: [uuid],
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects pattern-matching operators on non-text fields", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "collectionId",
|
||||
operator: "contains",
|
||||
value: uuid,
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("date fields", () => {
|
||||
it("accepts an ISO date", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "gt",
|
||||
value: "2024-01-01T00:00:00.000Z",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a bare ISO date", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "gt",
|
||||
value: "2024-01-01",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an unparseable date", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "gt",
|
||||
value: "notadate",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts an ISO 8601 duration for range operators", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "gte",
|
||||
value: "-P7D",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an ISO 8601 duration for equality operators", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "eq",
|
||||
value: "-P7D",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("string fields", () => {
|
||||
it("accepts a string value and pattern operators", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "title",
|
||||
operator: "contains",
|
||||
value: "hello",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-string value", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "title",
|
||||
operator: "eq",
|
||||
value: 5,
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("number and boolean fields", () => {
|
||||
it("validates number values", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "views",
|
||||
operator: "eq",
|
||||
value: 5,
|
||||
}).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "views",
|
||||
operator: "eq",
|
||||
value: "5",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("validates boolean values", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "isDraft",
|
||||
operator: "eq",
|
||||
value: true,
|
||||
}).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "isDraft",
|
||||
operator: "eq",
|
||||
value: "true",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("still allows null operators with no value", () => {
|
||||
expect(
|
||||
FilterSchema.safeParse({
|
||||
field: "createdAt",
|
||||
operator: "isNull",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createFilterSchema operator allowlists", () => {
|
||||
const { FilterSchema: RestrictedSchema } = createFilterSchema({
|
||||
userId: { kind: "uuid", operators: ["eq", "in"] },
|
||||
title: "string",
|
||||
} as const);
|
||||
|
||||
it("accepts an allowed operator", () => {
|
||||
expect(
|
||||
RestrictedSchema.safeParse({
|
||||
field: "userId",
|
||||
operator: "eq",
|
||||
value: uuid,
|
||||
}).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
RestrictedSchema.safeParse({
|
||||
field: "userId",
|
||||
operator: "in",
|
||||
value: [uuid],
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects operators outside the allowlist", () => {
|
||||
for (const operator of ["neq", "notIn", "isNull", "isNotNull", "lt"]) {
|
||||
const result = RestrictedSchema.safeParse({
|
||||
field: "userId",
|
||||
operator,
|
||||
...(operator === "isNull" || operator === "isNotNull"
|
||||
? {}
|
||||
: { value: operator === "notIn" ? [uuid] : uuid }),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not restrict fields without an allowlist", () => {
|
||||
expect(
|
||||
RestrictedSchema.safeParse({
|
||||
field: "title",
|
||||
operator: "neq",
|
||||
value: "x",
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a disallowed operator nested inside a group", () => {
|
||||
expect(
|
||||
RestrictedSchema.safeParse({
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{ field: "title", operator: "eq", value: "x" },
|
||||
{ field: "userId", operator: "neq", value: uuid },
|
||||
],
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createFilterSchema node limit", () => {
|
||||
const { maxNodes } = FilterValidation;
|
||||
|
||||
it("accepts an expression at the node limit", () => {
|
||||
expect(FilterSchema.safeParse(groupOf(maxNodes - 1)).success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an expression over the node limit", () => {
|
||||
expect(FilterSchema.safeParse(groupOf(maxNodes)).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a wide expression that stays inside the depth limit", () => {
|
||||
// Depth 3 and 7 filters per group is well inside both shape limits, yet
|
||||
// holds 57 nodes.
|
||||
const wide: Filter = {
|
||||
operator: "OR",
|
||||
filters: Array.from({ length: 7 }, () => groupOf(7)),
|
||||
};
|
||||
expect(FilterSchema.safeParse(wide).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a list at the node limit", () => {
|
||||
const filters = Array.from({ length: maxNodes }, () => leaf);
|
||||
expect(FilterListSchema.safeParse(filters).success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a list whose entries total over the node limit", () => {
|
||||
// Each entry is inside the per-expression limit; the sum is not.
|
||||
const filters = Array.from({ length: 5 }, () => groupOf(10));
|
||||
expect(FilterListSchema.safeParse(filters).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an empty list", () => {
|
||||
expect(FilterListSchema.safeParse([]).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import { z } from "zod";
|
||||
import { isISO8601Duration } from "../utils/date";
|
||||
import { FilterValidation } from "../validations";
|
||||
|
||||
export const ComparisonOperator = z.enum([
|
||||
"eq",
|
||||
"neq",
|
||||
"lt",
|
||||
"lte",
|
||||
"gt",
|
||||
"gte",
|
||||
"contains",
|
||||
"startsWith",
|
||||
"endsWith",
|
||||
"containsStrict",
|
||||
"startsWithStrict",
|
||||
"endsWithStrict",
|
||||
"in",
|
||||
"notIn",
|
||||
"isNull",
|
||||
"isNotNull",
|
||||
]);
|
||||
export type ComparisonOperator = z.infer<typeof ComparisonOperator>;
|
||||
|
||||
export const LogicalOperator = z.enum(["AND", "OR"]);
|
||||
export type LogicalOperator = z.infer<typeof LogicalOperator>;
|
||||
|
||||
export const FilterValue = z.union([
|
||||
z.string(),
|
||||
z.number(),
|
||||
z.boolean(),
|
||||
z.date(),
|
||||
z.array(z.string()),
|
||||
z.array(z.number()),
|
||||
]);
|
||||
export type FilterValue = z.infer<typeof FilterValue>;
|
||||
|
||||
export interface FilterCondition<F extends string = string> {
|
||||
field: F;
|
||||
operator: ComparisonOperator;
|
||||
value?: FilterValue;
|
||||
}
|
||||
|
||||
export interface FilterGroup<F extends string = string> {
|
||||
operator: LogicalOperator;
|
||||
filters: Array<FilterCondition<F> | FilterGroup<F>>;
|
||||
}
|
||||
|
||||
export type Filter<F extends string = string> =
|
||||
| FilterCondition<F>
|
||||
| FilterGroup<F>;
|
||||
|
||||
/** The column type a filterable field maps to, used to validate values. */
|
||||
export type FieldKind = "uuid" | "string" | "number" | "boolean" | "date";
|
||||
|
||||
/**
|
||||
* A filterable field definition: either just its column type, or an object
|
||||
* that additionally restricts which operators the field supports.
|
||||
*/
|
||||
export type FieldSpec =
|
||||
| FieldKind
|
||||
| { kind: FieldKind; operators: readonly ComparisonOperator[] };
|
||||
|
||||
const uuidSchema = z.uuid();
|
||||
|
||||
// Accept a full ISO 8601 datetime (with `Z` or an offset) or a bare ISO date.
|
||||
const dateSchema = z.union([z.iso.datetime({ offset: true }), z.iso.date()]);
|
||||
|
||||
/** Operators for which range comparisons (and relative durations) apply. */
|
||||
export const RANGE_OPERATORS = new Set<ComparisonOperator>([
|
||||
"gt",
|
||||
"gte",
|
||||
"lt",
|
||||
"lte",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check whether a single scalar value is compatible with a field's column type.
|
||||
*
|
||||
* @param kind the field's column type.
|
||||
* @param value the candidate value.
|
||||
* @param operator the operator the value is used with.
|
||||
* @returns true if the value is a valid input for the field.
|
||||
*/
|
||||
function scalarMatchesKind(
|
||||
kind: FieldKind,
|
||||
value: unknown,
|
||||
operator: ComparisonOperator
|
||||
): boolean {
|
||||
switch (kind) {
|
||||
case "uuid":
|
||||
return uuidSchema.safeParse(value).success;
|
||||
case "string":
|
||||
return typeof value === "string";
|
||||
case "number":
|
||||
return typeof value === "number";
|
||||
case "boolean":
|
||||
return typeof value === "boolean";
|
||||
case "date":
|
||||
if (typeof value !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (RANGE_OPERATORS.has(operator) && isISO8601Duration(value)) {
|
||||
return true;
|
||||
}
|
||||
return dateSchema.safeParse(value).success;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isGroup(filter: Filter): filter is FilterGroup {
|
||||
return "filters" in filter;
|
||||
}
|
||||
|
||||
function depthOf(filter: Filter): number {
|
||||
if (isGroup(filter)) {
|
||||
return 1 + Math.max(...filter.filters.map(depthOf));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function countNodes(filter: Filter): number {
|
||||
if (isGroup(filter)) {
|
||||
return filter.filters.reduce((total, f) => total + countNodes(f), 1);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a zod schema for a typed filter DSL constrained to a field allowlist.
|
||||
*
|
||||
* Each field maps to a column type ({@link FieldKind}) so that values are
|
||||
* validated against the field at the input layer, returning a clean 400 rather
|
||||
* than letting malformed input (e.g. a non-uuid id, an invalid date) reach the
|
||||
* database. A field may also restrict its supported operators
|
||||
* ({@link FieldSpec}) so that combinations the query layer cannot execute are
|
||||
* rejected here as well.
|
||||
*
|
||||
* @param fields map of allowed field name to its column type, optionally with a restricted operator set.
|
||||
* @returns FilterSchema for a single expression, and FilterListSchema for the wire-level `filters` array.
|
||||
*/
|
||||
export function createFilterSchema<S extends Record<string, FieldSpec>>(
|
||||
fields: S
|
||||
) {
|
||||
const FieldEnum = z.enum(
|
||||
Object.keys(fields) as [
|
||||
Extract<keyof S, string>,
|
||||
...Extract<keyof S, string>[],
|
||||
]
|
||||
);
|
||||
|
||||
const FilterConditionSchema = z
|
||||
.object({
|
||||
field: FieldEnum,
|
||||
operator: ComparisonOperator,
|
||||
value: FilterValue.optional(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
const { field, operator, value } = data;
|
||||
const spec: FieldSpec = fields[field];
|
||||
const kind = typeof spec === "string" ? spec : spec.kind;
|
||||
const allowedOperators =
|
||||
typeof spec === "string" ? undefined : spec.operators;
|
||||
|
||||
if (allowedOperators && !allowedOperators.includes(operator)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `operator '${operator}' is not supported for field '${field}'`,
|
||||
path: ["operator"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const isArrayOp = operator === "in" || operator === "notIn";
|
||||
const isNullOp = operator === "isNull" || operator === "isNotNull";
|
||||
const isStringOp =
|
||||
operator === "contains" ||
|
||||
operator === "startsWith" ||
|
||||
operator === "endsWith" ||
|
||||
operator === "containsStrict" ||
|
||||
operator === "startsWithStrict" ||
|
||||
operator === "endsWithStrict";
|
||||
|
||||
if (isNullOp) {
|
||||
if (value !== undefined) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must not be provided for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === undefined) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value is required for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isArrayOp) {
|
||||
if (!Array.isArray(value) || value.length === 0) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must be a non-empty array for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (value.length > FilterValidation.maxInValues) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must contain at most ${FilterValidation.maxInValues} entries for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
}
|
||||
if (value.some((entry) => !scalarMatchesKind(kind, entry, operator))) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must contain only valid ${kind} entries for field '${field}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must not be an array for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isStringOp) {
|
||||
if (typeof value !== "string") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must be a string for operator '${operator}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Pattern matching (iLike/like) only applies to text columns; running
|
||||
// it against a uuid/date/etc. column would error at the database.
|
||||
if (kind !== "string") {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `operator '${operator}' is only valid for text fields, not field '${field}'`,
|
||||
path: ["operator"],
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!scalarMatchesKind(kind, value, operator)) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `value must be a valid ${kind} for field '${field}'`,
|
||||
path: ["value"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
type Condition = z.infer<typeof FilterConditionSchema>;
|
||||
type Group = {
|
||||
operator: LogicalOperator;
|
||||
filters: Array<Condition | Group>;
|
||||
};
|
||||
|
||||
const FilterGroupSchema: z.ZodType<Group> = z.lazy(() =>
|
||||
z.object({
|
||||
operator: LogicalOperator,
|
||||
filters: z
|
||||
.array(z.union([FilterConditionSchema, FilterGroupSchema]))
|
||||
.min(1)
|
||||
.max(FilterValidation.maxNodes),
|
||||
})
|
||||
);
|
||||
|
||||
const FilterSchema = z
|
||||
.union([FilterConditionSchema, FilterGroupSchema])
|
||||
.superRefine((data, ctx) => {
|
||||
const filter = data as Filter;
|
||||
if (depthOf(filter) > FilterValidation.maxDepth) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `filter nesting depth exceeds maximum of ${FilterValidation.maxDepth}`,
|
||||
});
|
||||
}
|
||||
if (countNodes(filter) > FilterValidation.maxNodes) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `filter contains more than the maximum of ${FilterValidation.maxNodes} conditions`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const FilterListSchema = z
|
||||
.array(FilterSchema)
|
||||
.min(1)
|
||||
.max(FilterValidation.maxNodes)
|
||||
.superRefine((filters, ctx) => {
|
||||
const total = filters.reduce(
|
||||
(sum, filter) => sum + countNodes(filter as Filter),
|
||||
0
|
||||
);
|
||||
if (total > FilterValidation.maxNodes) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: `filters contain more than the maximum of ${FilterValidation.maxNodes} conditions`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return { FilterSchema, FilterListSchema };
|
||||
}
|
||||
@@ -140,6 +140,38 @@ export function parseDate(dateStr: string): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ISO8601_DURATION_RE =
|
||||
/^-?P(?:(\d+W)|((?:\d+Y)?(?:\d+M)?(?:\d+D)?)(T(?:\d+H)?(?:\d+M)?(?:\d+S)?)?)$/;
|
||||
|
||||
/**
|
||||
* Validate a string against the ISO 8601 duration format.
|
||||
*
|
||||
* Supported subset: an optional leading `-`, then `P[nY][nM][nW][nD][T[nH][nM][nS]]`.
|
||||
* The weeks form (`PnW`) is mutually exclusive with year/month/day units.
|
||||
* Decimals are not supported.
|
||||
*
|
||||
* @param value the candidate string.
|
||||
* @returns true if the string is a syntactically valid ISO 8601 duration.
|
||||
*/
|
||||
export function isISO8601Duration(value: string): boolean {
|
||||
const m = ISO8601_DURATION_RE.exec(value);
|
||||
if (!m) {
|
||||
return false;
|
||||
}
|
||||
const [, weeks, date, time] = m;
|
||||
if (weeks) {
|
||||
return true;
|
||||
}
|
||||
// A bare `T` separator with no following time unit is invalid even if a date
|
||||
// portion is present (e.g. `P1DT` should be rejected).
|
||||
if (time === "T") {
|
||||
return false;
|
||||
}
|
||||
const hasDate = !!date && date.length > 0;
|
||||
const hasTime = !!time && time.length > 1;
|
||||
return hasDate || hasTime;
|
||||
}
|
||||
|
||||
export function subtractDate(date: Date, period: DateFilter) {
|
||||
switch (period) {
|
||||
case "day":
|
||||
|
||||
@@ -176,6 +176,17 @@ export const WebhookSubscriptionValidation = {
|
||||
maxUrlLength: 1024,
|
||||
};
|
||||
|
||||
export const FilterValidation = {
|
||||
/** The maximum nesting depth of a filter expression */
|
||||
maxDepth: 5,
|
||||
|
||||
/** The maximum number of values in an `in` / `notIn` array */
|
||||
maxInValues: 100,
|
||||
|
||||
/** The maximum number of conditions and groups a filter may contain */
|
||||
maxNodes: 50,
|
||||
};
|
||||
|
||||
export const EmojiValidation = {
|
||||
/** The maximum length of the emoji name */
|
||||
maxNameLength: 25,
|
||||
|
||||
Reference in new issue
Block a user