Merge remote-tracking branch 'origin/main' into tommoor/collection-multiplayer-editing

# Conflicts:
#	server/collaboration/PersistenceExtension.ts
This commit is contained in:
Tom Moor committed 2026-07-28 09:07:22 -04:00
commit 593bd22669
101 files changed
+2546 -920

No files matched your search

+6
View File
@@ -38,9 +38,15 @@ jobs:
echo "latest=$LATEST_VERSION" >> "$GITHUB_OUTPUT"
echo "Latest Node.js LTS version: $LATEST_VERSION"
# Only update when the latest LTS is strictly newer, never downgrade
NEWEST=$(printf '%s\n%s\n' "$CURRENT_VERSION" "$LATEST_VERSION" | sort -V | tail -n1)
if [ "$CURRENT_VERSION" = "$LATEST_VERSION" ]; then
echo "updated=false" >> "$GITHUB_OUTPUT"
echo "Already up to date."
elif [ "$NEWEST" = "$CURRENT_VERSION" ]; then
echo "updated=false" >> "$GITHUB_OUTPUT"
echo "Current version $CURRENT_VERSION is newer than the latest LTS $LATEST_VERSION, skipping."
else
echo "updated=true" >> "$GITHUB_OUTPUT"
echo "Update available: $CURRENT_VERSION -> $LATEST_VERSION"
+1
View File
@@ -12,3 +12,4 @@ npmPreapprovedPackages:
npmAuditIgnoreAdvisories:
- "1113517" # GHSA-mw96-cpmx-2vgc rollup <2.80.0 path traversal (workbox-build, build-time)
- "1113686" # GHSA-5c6j-r48x-rmvq serialize-javascript RCE (@rollup/plugin-terser, build-time)
- "1124334" # GHSA-mh99-v99m-4gvg brace-expansion DoS is a false positive
+3 -1
View File
@@ -66,6 +66,7 @@ import {
import {
ActiveDocumentSection,
DocumentSection,
SearchResultsSection,
TrashSection,
} from "~/actions/sections";
import { setPersistedState } from "~/hooks/usePersistedState";
@@ -1227,7 +1228,8 @@ export const searchDocumentsForQueryActionFactory = (query: string) =>
name: ({ t }) =>
t(`Search documents for "{{searchQuery}}"`, { searchQuery: query }),
analyticsName: "Search documents",
section: DocumentSection,
section: SearchResultsSection,
priority: -1,
icon: <SearchIcon />,
to: searchPath({ query }),
visible: ({ location }) => location.pathname !== searchPath(),
+1 -1
View File
@@ -9,7 +9,7 @@ import { randomElement } from "@shared/random";
import { CollectionPermission } from "@shared/types";
import type { Option } from "~/components/InputSelect";
import { IconLibrary } from "@shared/utils/IconLibrary";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import { CollectionValidation } from "@shared/validations";
import type Collection from "~/models/Collection";
import Button from "~/components/Button";
+8 -3
View File
@@ -1,5 +1,5 @@
import * as React from "react";
import styled from "styled-components";
import styled, { css } from "styled-components";
import NudeButton from "./NudeButton";
import { hover, s } from "@shared/styles";
@@ -29,6 +29,9 @@ export const ColorButton = React.forwardRef(
)
);
/** Highlight for the hovered or selected swatch, falls back for the gradient. */
const ring = css`2px solid var(--color, ${s("textTertiary")})`;
const Selected = styled.span`
width: 10px;
height: 5px;
@@ -52,9 +55,11 @@ const ColorButtonInternal = styled(NudeButton)<{
linear-gradient(135deg, #ff5858 0%, #fbcc34 50%, #00c6ff 100%)
);
outline-offset: 1px;
outline: ${({ $active }) => ($active ? ring : "none")};
&: ${hover} {
outline: 2px solid ${s("menuBackground")} !important;
box-shadow: 0px 0px 3px 3px var(--color);
outline: ${ring} !important;
}
& ${Selected} {
+40 -42
View File
@@ -1,26 +1,26 @@
import { SearchIndex } from "./SearchIndex";
describe("SearchIndex", () => {
it("returns no results for an empty query", async () => {
it("returns no results for an empty query", () => {
const index = new SearchIndex();
index.update([{ id: "1", title: "Engineering Handbook", url: "/doc/1" }]);
expect(await index.search("")).toEqual([]);
expect(await index.search(" ")).toEqual([]);
expect(index.search("")).toEqual([]);
expect(index.search(" ")).toEqual([]);
});
it("matches titles despite spelling mistakes", async () => {
it("matches titles despite spelling mistakes", () => {
const index = new SearchIndex();
index.update([
{ id: "1", title: "Engineering Handbook", url: "/doc/1" },
{ id: "2", title: "Marketing Plan", url: "/doc/2" },
]);
const results = await index.search("enginering handbok");
const results = index.search("enginering handbok");
expect(results[0]?.document.id).toBe("1");
});
it("matches document content and highlights the context", async () => {
it("matches document content and highlights the context", () => {
const index = new SearchIndex();
index.update([
{
@@ -31,12 +31,12 @@ describe("SearchIndex", () => {
},
]);
const results = await index.search("revenue");
const results = index.search("revenue");
expect(results[0]?.document.id).toBe("1");
expect(results[0]?.context).toContain("<b>revenue</b>");
});
it("highlights only exact matches, not fuzzy character runs", async () => {
it("highlights only exact matches, not fuzzy character runs", () => {
const index = new SearchIndex();
index.update([
{
@@ -49,14 +49,14 @@ describe("SearchIndex", () => {
// The typo "numbrs" has no literal occurrence, so only whole contiguous
// matches are marked rather than the scattered characters Fuse matched on.
const results = await index.search("revenu numbrs");
const results = index.search("revenu numbrs");
expect(results[0]?.document.id).toBe("1");
expect(results[0]?.context).toContain("<b>revenu</b>");
expect(results[0]?.context).not.toContain("numbrs");
expect(results[0]?.context?.match(/<b>/g)).toHaveLength(1);
});
it("highlights the query where it appears inside a longer word", async () => {
it("highlights the query where it appears inside a longer word", () => {
const index = new SearchIndex();
index.update([
{
@@ -68,12 +68,10 @@ describe("SearchIndex", () => {
]);
// Partway through typing "revenue", the typed prefix is still marked.
expect((await index.search("revenu"))[0]?.context).toContain(
"<b>revenu</b>"
);
expect(index.search("revenu")[0]?.context).toContain("<b>revenu</b>");
});
it("highlights each term of a multi-word query separately", async () => {
it("highlights each term of a multi-word query separately", () => {
const index = new SearchIndex();
index.update([
{
@@ -84,11 +82,11 @@ describe("SearchIndex", () => {
},
]);
const context = (await index.search("revenue numbers"))[0]?.context;
const context = index.search("revenue numbers")[0]?.context;
expect(context).toContain("<b>revenue numbers</b>");
});
it("marks a match as one contiguous run rather than letter runs", async () => {
it("marks a match as one contiguous run rather than letter runs", () => {
const index = new SearchIndex();
index.update([
{
@@ -99,13 +97,13 @@ describe("SearchIndex", () => {
},
]);
const context = (await index.search("deployment"))[0]?.context;
const context = index.search("deployment")[0]?.context;
// The whole word is marked once, rather than scattered letter runs.
expect(context).toContain("<b>deployment</b>");
expect(context?.match(/<b>/g)).toHaveLength(1);
});
it("preserves previously indexed content when a later update omits it", async () => {
it("preserves previously indexed content when a later update omits it", () => {
const index = new SearchIndex();
index.update([
{
@@ -118,10 +116,10 @@ describe("SearchIndex", () => {
// A subsequent update (e.g. a title-only tree pass) must not drop content.
index.update([{ id: "1", title: "Report", url: "/doc/1" }]);
expect((await index.search("pineapple"))[0]?.document.id).toBe("1");
expect(index.search("pineapple")[0]?.document.id).toBe("1");
});
it("clears content when an update sets text to an empty string", async () => {
it("clears content when an update sets text to an empty string", () => {
const index = new SearchIndex();
index.update([
{
@@ -134,10 +132,10 @@ describe("SearchIndex", () => {
// An explicit empty string (e.g. content emptied) must replace stale text.
index.update([{ id: "1", title: "Report", url: "/doc/1", text: "" }]);
expect(await index.search("pineapple")).toEqual([]);
expect(index.search("pineapple")).toEqual([]);
});
it("previews content for a title match that has no content match", async () => {
it("previews content for a title match that has no content match", () => {
const index = new SearchIndex();
index.update([
{
@@ -148,18 +146,18 @@ describe("SearchIndex", () => {
},
]);
const context = (await index.search("engineering"))[0]?.context;
const context = index.search("engineering")[0]?.context;
expect(context).toBe("Everything a new hire needs to know about our team.");
});
it("has no context for a document with no content", async () => {
it("has no context for a document with no content", () => {
const index = new SearchIndex();
index.update([{ id: "1", title: "Engineering Handbook", url: "/doc/1" }]);
expect((await index.search("engineering"))[0]?.context).toBeUndefined();
expect(index.search("engineering")[0]?.context).toBeUndefined();
});
it("truncates a long preview", async () => {
it("truncates a long preview", () => {
const index = new SearchIndex();
index.update([
{
@@ -170,12 +168,12 @@ describe("SearchIndex", () => {
},
]);
const context = (await index.search("engineering"))[0]?.context ?? "";
const context = index.search("engineering")[0]?.context ?? "";
expect(context.endsWith("…")).toBe(true);
expect(context.length).toBeLessThan(220);
});
it("orders a title prefix ahead of a shorter mid-title match", async () => {
it("orders a title prefix ahead of a shorter mid-title match", () => {
const index = new SearchIndex();
index.update([
// Fuse scores this higher on its own, as the field is shorter and
@@ -188,10 +186,10 @@ describe("SearchIndex", () => {
},
]);
expect((await index.search("design"))[0]?.document.id).toBe("prefix");
expect(index.search("design")[0]?.document.id).toBe("prefix");
});
it("orders a title prefix ahead of a shorter trailing-word match", async () => {
it("orders a title prefix ahead of a shorter trailing-word match", () => {
const index = new SearchIndex();
index.update([
{ id: "mid", title: "Team Onboarding", url: "/doc/mid" },
@@ -202,10 +200,10 @@ describe("SearchIndex", () => {
},
]);
expect((await index.search("onboarding"))[0]?.document.id).toBe("prefix");
expect(index.search("onboarding")[0]?.document.id).toBe("prefix");
});
it("orders a title prefix ahead of an equally scored mid-title match", async () => {
it("orders a title prefix ahead of an equally scored mid-title match", () => {
const index = new SearchIndex();
index.update([
// Both score identically in Fuse, leaving the order arbitrary.
@@ -213,10 +211,10 @@ describe("SearchIndex", () => {
{ id: "prefix", title: "Design Is A Guide", url: "/doc/prefix" },
]);
expect((await index.search("design"))[0]?.document.id).toBe("prefix");
expect(index.search("design")[0]?.document.id).toBe("prefix");
});
it("orders a title prefix ahead of a content-only match", async () => {
it("orders a title prefix ahead of a content-only match", () => {
const index = new SearchIndex();
index.update([
{ id: "content", title: "Q3", url: "/doc/content", text: "revenue" },
@@ -227,10 +225,10 @@ describe("SearchIndex", () => {
},
]);
expect((await index.search("revenue"))[0]?.document.id).toBe("prefix");
expect(index.search("revenue")[0]?.document.id).toBe("prefix");
});
it("breaks ties within a tier by fuzzy score", async () => {
it("breaks ties within a tier by fuzzy score", () => {
const index = new SearchIndex();
index.update([
{ id: "long", title: "Design System Guidelines", url: "/doc/long" },
@@ -238,10 +236,10 @@ describe("SearchIndex", () => {
]);
// Both are prefix matches, so the closer title wins.
expect((await index.search("design"))[0]?.document.id).toBe("short");
expect(index.search("design")[0]?.document.id).toBe("short");
});
it("weights title matches above content matches", async () => {
it("weights title matches above content matches", () => {
const index = new SearchIndex();
index.update([
{ id: "1", title: "Onboarding", url: "/doc/1", text: "unrelated body" },
@@ -253,21 +251,21 @@ describe("SearchIndex", () => {
},
]);
const results = await index.search("onboarding");
const results = index.search("onboarding");
expect(results[0]?.document.id).toBe("1");
});
it("reports whether an update changed the collection", async () => {
it("reports whether an update changed the collection", () => {
const index = new SearchIndex();
expect(index.update([{ id: "1", title: "A", url: "/doc/1" }])).toBe(true);
expect(index.update([{ id: "1", title: "A", url: "/doc/1" }])).toBe(false);
});
it("clears all indexed documents", async () => {
it("clears all indexed documents", () => {
const index = new SearchIndex();
index.update([{ id: "1", title: "Engineering", url: "/doc/1" }]);
index.clear();
expect(await index.search("engineering")).toEqual([]);
expect(index.search("engineering")).toEqual([]);
});
});
+7 -43
View File
@@ -1,6 +1,5 @@
import { escapeRegExp } from "es-toolkit/compat";
import Fuse, { type IFuseOptions } from "fuse.js";
import { FuseWorker } from "fuse.js/worker";
/** A document as represented within the search index. */
export interface SearchIndexDocument {
@@ -40,18 +39,11 @@ const options: IFuseOptions<SearchIndexDocument> = {
],
includeScore: true,
ignoreLocation: true,
useTokenSearch: true,
threshold: 0.3,
minMatchCharLength: minTermLength,
};
/**
* Scanning document content is the expensive part of a query, so it is sharded
* across web workers to keep it off the main thread. Indices here hold at most
* a few hundred documents, where more shards cost more in messaging overhead
* and worker startup than they win back in parallelism.
*/
const workerOptions = { numWorkers: 2 };
const resultLimit = 25;
const contextLead = 40;
const contextLength = 200;
@@ -179,12 +171,7 @@ function buildContext(
export class SearchIndex {
private records = new Map<string, SearchIndexDocument>();
// Workers are unavailable when server rendering and under jsdom, where the
// main-thread implementation stands in with an identical API.
private fuse: Fuse<SearchIndexDocument> | FuseWorker<SearchIndexDocument> =
typeof Worker === "undefined"
? new Fuse<SearchIndexDocument>([], { ...options, useTokenSearch: true })
: new FuseWorker<SearchIndexDocument>([], options, workerOptions);
private fuse = new Fuse<SearchIndexDocument>([], options);
/**
* Merges documents into the index, rebuilding the collection only when
@@ -223,7 +210,7 @@ export class SearchIndex {
}
if (changed) {
this.setCollection(Array.from(this.records.values()));
this.fuse.setCollection(Array.from(this.records.values()));
}
return changed;
@@ -234,17 +221,7 @@ export class SearchIndex {
*/
public clear(): void {
this.records.clear();
this.setCollection([]);
}
/**
* Releases the workers backing the index. The index must not be used again
* afterwards.
*/
public dispose(): void {
if (this.fuse instanceof FuseWorker) {
this.fuse.terminate();
}
this.fuse.setCollection([]);
}
/**
@@ -255,17 +232,16 @@ export class SearchIndex {
* @param query the search query.
* @returns the matching documents ordered by relevance.
*/
public async search(query: string): Promise<SearchIndexResult[]> {
public search(query: string): SearchIndexResult[] {
const trimmed = query.trim();
if (!trimmed) {
return [];
}
const matches = await this.fuse.search(trimmed);
// Building context scans the full text of a document, so it is deferred
// until the results have been truncated to those actually displayed.
return matches
return this.fuse
.search(trimmed)
.map((result) => ({
document: result.item,
score: result.score ?? 1,
@@ -279,16 +255,4 @@ export class SearchIndex {
context: buildContext(document.text, trimmed),
}));
}
/**
* Replaces the indexed collection. Workers apply this asynchronously, but
* they process messages in order, so a search issued afterwards always sees
* the new collection.
*/
private setCollection(documents: SearchIndexDocument[]): void {
void Promise.resolve(this.fuse.setCollection(documents)).catch(() => {
// A worker that failed to accept the collection will also fail the next
// search, which is where the error surfaces.
});
}
}
+9 -33
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import type Document from "~/models/Document";
import { ProsemirrorHelper } from "~/models/helpers/ProsemirrorHelper";
import {
@@ -78,7 +78,7 @@ export interface UseSearchIndex {
/**
* Maintains a client-side fuzzy search index and searches it for the given
* query. The index is fed incrementally via the returned `feed` function, and
* matching runs in web workers so that typing is never blocked by it.
* results are computed synchronously so they never lag behind the query.
*
* @param query the current search query.
* @returns the current results and functions to feed or reset the index.
@@ -90,9 +90,8 @@ export function useSearchIndex(query: string): UseSearchIndex {
}
const index = indexRef.current;
// Bumped whenever the index changes, to re-run the search below.
// Bumped whenever the index changes, to re-run the memoized search below.
const [version, setVersion] = useState(0);
const [results, setResults] = useState<SearchIndexResult[]>([]);
const feed = useCallback(
(documents: SearchIndexDocument[]) => {
@@ -108,35 +107,12 @@ export function useSearchIndex(query: string): UseSearchIndex {
setVersion((v) => v + 1);
}, [index]);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
// Searches resolve out of order, so a stale response must not overwrite the
// results of a query the user has since moved on from.
let disposed = false;
void index
.search(query)
.then((next) => {
if (!disposed) {
setResults(next);
}
})
.catch(() => {
if (!disposed) {
setResults([]);
}
});
return () => {
disposed = true;
};
}, [index, query, version]);
useEffect(() => () => index.dispose(), [index]);
const results = useMemo<SearchIndexResult[]>(
() => (query ? index.search(query) : []),
// The index mutates in place, so `version` is what marks the memo stale.
// eslint-disable-next-line react-hooks/exhaustive-deps
[index, query, version]
);
return { results, feed, reset };
}
@@ -10,7 +10,7 @@ import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { toError } from "@shared/utils/error";
import Icon from "@shared/components/Icon";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import type { Option } from "~/components/InputSelect";
import { InputSelect } from "~/components/InputSelect";
import useStores from "~/hooks/useStores";
@@ -8,8 +8,9 @@ import { getEmojis, getEmojisWithCategory, search } from "@shared/utils/emoji";
import Flex from "~/components/Flex";
import { EmojiCreateDialog } from "~/components/EmojiDialog/EmojiCreateDialog";
import { DisplayCategory } from "../utils";
import type { DataNode, EmojiNode } from "./GridTemplate";
import type { DataNode, EmojiNode, IconNode } from "./GridTemplate";
import GridTemplate from "./GridTemplate";
import { IconPreview, PREVIEW_HEIGHT } from "./IconPreview";
import SkinTonePicker from "./SkinTonePicker";
import { StyledInputSearch, UserInputContainer } from "./Components";
import { useIconState } from "../useIconState";
@@ -136,6 +137,20 @@ const EmojiPanel = ({
});
}, [emojis, getFrequentCustomIcons]);
const [activeEmoji, setActiveEmoji] = React.useState<EmojiNode>();
const [hasMoreBelow, setHasMoreBelow] = React.useState(false);
const handleEmojiActive = React.useCallback((icon: IconNode) => {
if (icon.type !== IconType.SVG) {
setActiveEmoji(icon);
}
}, []);
// Drop the preview when the grid contents change out from under it.
React.useEffect(() => {
setActiveEmoji(undefined);
}, [query, skinTone]);
const isSearch = query !== "";
const templateData: DataNode[] = isSearch
? getSearchResults({
@@ -180,9 +195,11 @@ const EmojiPanel = ({
<GridTemplate
ref={scrollableRef}
width={panelWidth}
height={height - 48}
height={height - 48 - PREVIEW_HEIGHT}
data={templateData}
onIconSelect={handleEmojiSelection}
onIconActive={handleEmojiActive}
onOverflowChange={setHasMoreBelow}
empty={
<IconButton
onClick={handleUploadClick}
@@ -192,10 +209,20 @@ const EmojiPanel = ({
</IconButton>
}
/>
<IconPreview
icon={activeEmoji ?? firstIcon(templateData)}
showFade={hasMoreBelow}
/>
</Flex>
);
};
/** The first icon shown in the grid, previewed until the user hovers another. */
const firstIcon = (data: DataNode[]): EmojiNode | undefined => {
const icon = data.find((node) => node.icons.length)?.icons[0];
return icon && icon.type !== IconType.SVG ? icon : undefined;
};
const getSearchResults = ({
query,
skinTone,
@@ -218,6 +245,7 @@ const getSearchResults = ({
type: IconType.Emoji as const,
id: emoji.id,
value: emoji.value,
name: emoji.name,
})),
];
@@ -251,6 +279,7 @@ const getAllEmojis = ({
type: IconType.Emoji as const,
id: emoji.id,
value: emoji.value,
name: emoji.name,
})),
...freqCustomEmojis,
];
@@ -269,6 +298,7 @@ const getAllEmojis = ({
type: IconType.Emoji,
id: emoji.id,
value: emoji.value,
name: emoji.name,
})),
};
};
+35 -13
View File
@@ -9,23 +9,45 @@ type Props = {
data: React.ReactNode[][];
columns: number;
itemWidth: number;
onOverflowChange?: (hasMoreBelow: boolean) => void;
};
const Grid = (
{ width, height, data, columns, itemWidth }: Props,
{ width, height, data, columns, itemWidth, onOverflowChange }: Props,
ref: React.Ref<HTMLDivElement>
) => (
<Container
outerRef={ref}
width={width}
height={height}
itemCount={data.length}
itemSize={itemWidth}
itemData={{ data, columns }}
>
{Row}
</Container>
);
) => {
const offsetRef = React.useRef(0);
const maxOffset = Math.max(0, data.length * itemWidth - height);
const notify = React.useCallback(() => {
onOverflowChange?.(offsetRef.current < maxOffset - 1);
}, [onOverflowChange, maxOffset]);
// The amount of scrollable content changes as rows are added or removed.
React.useEffect(notify, [notify]);
const handleScroll = React.useCallback(
({ scrollOffset }: { scrollOffset: number }) => {
offsetRef.current = scrollOffset;
notify();
},
[notify]
);
return (
<Container
outerRef={ref}
width={width}
height={height}
itemCount={data.length}
itemSize={itemWidth}
itemData={{ data, columns }}
onScroll={handleScroll}
>
{Row}
</Container>
);
};
type RowProps = {
data: React.ReactNode[][];
@@ -21,7 +21,7 @@ const BUTTON_SIZE_MOBILE = 40;
const ICON_SIZE_DESKTOP = 24;
const ICON_SIZE_MOBILE = 32;
type OutlineNode = {
export type OutlineNode = {
type: IconType.SVG;
name: string;
color: string;
@@ -36,9 +36,11 @@ export type EmojiNode = {
name?: string;
};
export type IconNode = OutlineNode | EmojiNode;
export type DataNode = {
category: keyof typeof TRANSLATED_CATEGORIES;
icons: (OutlineNode | EmojiNode)[];
icons: IconNode[];
};
type Props = {
@@ -52,10 +54,22 @@ type Props = {
empty?: React.ReactNode;
/** Callback when an icon is selected */
onIconSelect: ({ id, value }: { id: string; value: string }) => void;
/** Callback when an icon is hovered or focused */
onIconActive?: (icon: IconNode) => void;
/** Callback when whether the grid has content below the fold changes */
onOverflowChange?: (hasMoreBelow: boolean) => void;
};
const GridTemplate = (
{ width, height, data, empty, onIconSelect }: Props,
{
width,
height,
data,
empty,
onIconSelect,
onIconActive,
onOverflowChange,
}: Props,
ref: React.Ref<HTMLDivElement>
) => {
const isMobile = useMobile();
@@ -85,11 +99,15 @@ const GridTemplate = (
}
const items = node.icons.map((item) => {
const handleActive = () => onIconActive?.(item);
if (item.type === IconType.SVG) {
return (
<IconButton
key={item.name}
onClick={() => onIconSelect({ id: item.name, value: item.name })}
onMouseEnter={handleActive}
onFocus={handleActive}
style={{ "--delay": `${item.delay}ms` } as React.CSSProperties}
>
<Icon
@@ -107,6 +125,8 @@ const GridTemplate = (
<IconButton
key={item.id}
onClick={() => onIconSelect({ id: item.id, value: item.value })}
onMouseEnter={handleActive}
onFocus={handleActive}
>
<Emoji
width={iconSize}
@@ -136,6 +156,7 @@ const GridTemplate = (
data={gridItems}
columns={itemsPerRow}
itemWidth={buttonSize}
onOverflowChange={onOverflowChange}
/>
);
};
@@ -1,11 +1,11 @@
import * as React from "react";
import styled from "styled-components";
import { s } from "@shared/styles";
import { colorPalette } from "@shared/utils/collections";
import Flex from "~/components/Flex";
import { colorPalette } from "@shared/constants";
import { SwatchButton } from "~/components/SwatchButton";
import { ColorButton } from "~/components/ColorButton";
const SWATCH_SIZE = 20;
type Props = {
width: number;
activeColor: string;
@@ -27,12 +27,12 @@ const IconColorPicker = ({ activeColor, onSelect }: Props) => {
};
return (
<Container justify="space-between" align="center" auto>
<Container>
<PresetColors activeColor={selectedColor} onClick={handleSelect} />
<Divider />
<SwatchButton
color={color}
active={!isBuiltInColor}
size={SWATCH_SIZE}
onChange={handleSelect}
pickerInModal
/>
@@ -40,12 +40,6 @@ const IconColorPicker = ({ activeColor, onSelect }: Props) => {
);
};
const Divider = styled.div`
width: 1px;
height: 24px;
background-color: ${s("inputBorder")};
`;
const PresetColors = ({
activeColor,
onClick,
@@ -59,16 +53,22 @@ const PresetColors = ({
key={color}
color={color}
active={color === activeColor}
size={SWATCH_SIZE}
onClick={() => onClick(color)}
/>
))}
</>
);
const Container = styled(Flex)`
// One column per preset color plus the custom swatch, matching the horizontal
// rhythm of the icon grid below.
const Container = styled.div`
display: grid;
grid-template-columns: repeat(${colorPalette.length + 1}, 1fr);
align-items: center;
justify-items: center;
height: 48px;
padding: 8px 12px;
border-bottom: 1px solid ${s("inputBorder")};
`;
export default IconColorPicker;
@@ -7,8 +7,9 @@ import Flex from "~/components/Flex";
import InputSearch from "~/components/InputSearch";
import { DisplayCategory } from "../utils";
import IconColorPicker from "./IconColorPicker";
import type { DataNode } from "./GridTemplate";
import type { DataNode, IconNode } from "./GridTemplate";
import GridTemplate from "./GridTemplate";
import { IconPreview, PREVIEW_HEIGHT } from "./IconPreview";
import { useIconState } from "../useIconState";
const IconNames = Object.keys(IconLibrary.mapping);
@@ -18,7 +19,7 @@ const TotalIcons = IconNames.length;
* This is needed as a constant for react-window.
* Calculated from the heights of TabPanel, ColorPicker and InputSearch.
*/
const GRID_HEIGHT = 314;
const GRID_HEIGHT = 314 - PREVIEW_HEIGHT;
type Props = {
panelWidth: number;
@@ -75,6 +76,24 @@ const IconPanel = ({
[onIconChange, incrementIconCount]
);
const [activeIcon, setActiveIcon] = React.useState<string>();
const [hasMoreBelow, setHasMoreBelow] = React.useState(false);
const handleIconActive = React.useCallback((icon: IconNode) => {
if (icon.type === IconType.SVG) {
setActiveIcon(icon.name);
}
}, []);
React.useEffect(() => {
setActiveIcon(undefined);
}, [query]);
// Preview the first icon shown in the grid until the user hovers another.
const previewIcon =
activeIcon ??
(isSearch ? filteredIcons[0] : (freqIcons[0] ?? filteredIcons[0]));
const baseIcons: DataNode = {
category,
icons: filteredIcons.map((name, index) => ({
@@ -133,6 +152,22 @@ const IconPanel = ({
height={GRID_HEIGHT}
data={templateData}
onIconSelect={handleIconSelection}
onIconActive={handleIconActive}
onOverflowChange={setHasMoreBelow}
/>
<IconPreview
showFade={hasMoreBelow}
icon={
previewIcon
? {
type: IconType.SVG,
name: previewIcon,
color,
initial,
delay: 0,
}
: undefined
}
/>
</Flex>
);
@@ -0,0 +1,117 @@
import { startCase } from "es-toolkit/compat";
import styled from "styled-components";
import { s } from "@shared/styles";
import { IconType } from "@shared/types";
import { IconLibrary } from "@shared/utils/IconLibrary";
import { CustomEmoji } from "@shared/components/CustomEmoji";
import { Emoji } from "~/components/Emoji";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
import type { IconNode } from "./GridTemplate";
/** Height of the preview bar, used to size the grid above it. */
export const PREVIEW_HEIGHT = 56;
const GLYPH_SIZE = 28;
type Props = {
/** The icon or emoji to preview, nothing is rendered when empty */
icon?: IconNode;
/** Whether the grid above has content below the fold, fades the last row */
showFade?: boolean;
};
/**
* Displays a large preview of the hovered icon or emoji alongside its name and
* shortcode.
*/
export const IconPreview = ({ icon, showFade }: Props) => (
<Container align="center" gap={12} $showFade={showFade}>
{icon && (
<>
<Glyph justify="center" align="center">
{icon.type === IconType.SVG ? (
<Icon
as={IconLibrary.getComponent(icon.name)}
color={icon.color}
size={GLYPH_SIZE}
>
{icon.initial}
</Icon>
) : (
<Emoji size={GLYPH_SIZE}>
{icon.type === IconType.Custom ? (
<CustomEmoji value={icon.value} title={icon.name} />
) : (
icon.value
)}
</Emoji>
)}
</Glyph>
<Labels column>
<Name weight="bold" ellipsis>
{displayName(icon)}
</Name>
<Text type="tertiary" size="xsmall" monospace ellipsis>
:{shortcode(icon)}:
</Text>
</Labels>
</>
)}
</Container>
);
const displayName = (icon: IconNode) =>
icon.type === IconType.SVG
? startCase(icon.name)
: startCase(icon.name ?? "");
const shortcode = (icon: IconNode) => {
if (icon.type === IconType.SVG) {
return icon.name;
}
return icon.type === IconType.Custom ? (icon.name ?? icon.value) : icon.id;
};
const Container = styled(Flex)<{ $showFade?: boolean }>`
position: relative;
flex-shrink: 0;
height: ${PREVIEW_HEIGHT}px;
padding: 0 16px;
background: ${s("menuBackground")};
// Offsets the bottom padding of the containing popover.
margin-bottom: -6px;
// Fades out the last row of the grid while there's more to scroll.
&:before {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 100%;
height: 24px;
pointer-events: none;
opacity: ${({ $showFade }) => ($showFade ? 1 : 0)};
transition: opacity 150ms ease-in-out;
background: linear-gradient(to bottom, transparent, ${s("menuBackground")});
}
`;
const Name = styled(Text)`
font-size: 15px;
`;
const Glyph = styled(Flex)`
width: ${GLYPH_SIZE}px;
height: ${GLYPH_SIZE}px;
flex-shrink: 0;
`;
const Labels = styled(Flex)`
min-width: 0;
`;
const Icon = styled.svg`
flex-shrink: 0;
`;
+1 -1
View File
@@ -2,7 +2,7 @@ import { observer } from "mobx-react";
import { CollectionIcon, PrivateCollectionIcon } from "outline-icons";
import { getLuminance } from "polished";
import Icon from "@shared/components/Icon";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import type Collection from "~/models/Collection";
import useStores from "~/hooks/useStores";
+5 -1
View File
@@ -65,6 +65,7 @@ import { HStack } from "./primitives/HStack";
import { useDocumentContext } from "./DocumentContext";
import LightboxComments from "~/scenes/Document/components/Comments/LightboxComments";
import { PortalContext } from "./Portal";
import useCurrentUser from "~/hooks/useCurrentUser";
import useHideElement from "~/hooks/useHideElement";
import type { Status } from "./LightboxState";
import {
@@ -272,10 +273,13 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) {
} | null>(null);
const zoomPanPinchRef = useRef<ReactZoomPanPinchRef>(null);
const editor = useEditor();
const user = useCurrentUser({ rejectOnEmpty: false });
const { document: contextDocument } = useDocumentContext();
const activeNode = editor?.view?.state?.doc?.nodeAt(activeImage.pos);
// Comments are unavailable without a signed in session, for example when
// viewing a publicly shared document.
const canShowComments =
!!contextDocument && activeNode?.type.name === "image";
!!user && !!contextDocument && activeNode?.type.name === "image";
const currentImageIndex = findIndex(
images,
+12 -3
View File
@@ -20,6 +20,12 @@ const EmojiPanel = createLazyComponent(
() => import("~/components/IconPicker/components/EmojiPanel")
);
/** Fits nine 32px emoji per row, with 12px of padding on either side. */
const PANEL_WIDTH = 332;
/** Leaves room for two more 32px rows than the panel's minimum. */
const PANEL_HEIGHT = 364;
type Props = {
/** Callback when an emoji is selected by the user. */
onSelect: (emoji: string) => Promise<void>;
@@ -37,7 +43,7 @@ const ReactionPicker: React.FC<Props> = ({ onSelect, className, size }) => {
const [query, setQuery] = React.useState("");
const popoverWidth = isMobile ? windowWidth : 300;
const popoverWidth = isMobile ? windowWidth : PANEL_WIDTH;
// In mobile, popover is absolutely positioned to leave 8px on both sides.
const panelWidth = isMobile ? windowWidth - 16 : popoverWidth;
@@ -79,7 +85,7 @@ const ReactionPicker: React.FC<Props> = ({ onSelect, className, size }) => {
<React.Suspense fallback={<Placeholder />}>
<EventBoundary>
<EmojiPanel.Component
height={300}
height={PANEL_HEIGHT}
panelWidth={panelWidth}
query={query}
onEmojiChange={handleEmojiSelect}
@@ -96,7 +102,10 @@ const ReactionPicker: React.FC<Props> = ({ onSelect, className, size }) => {
const Placeholder = React.memo(
() => (
<VStack spacing={6} style={{ height: "300px", padding: "6px 12px" }}>
<VStack
spacing={6}
style={{ height: `${PANEL_HEIGHT}px`, padding: "6px 12px" }}
>
<HStack>
<PlaceholderText height={32} minWidth={90} />
<PlaceholderText height={32} width={32} />
@@ -24,10 +24,7 @@ function ArchiveLink() {
const [disclosure, setDisclosure] = useState<boolean>(false);
const [expanded, setExpanded] = useState<boolean | undefined>();
const { request, data, loading, error } = useRequest(
collections.fetchArchived,
true
);
const { data, loading, error } = useRequest(collections.fetchArchived, true);
useEffect(() => {
if (!isUndefined(data) && !loading && isUndefined(error)) {
@@ -45,12 +42,6 @@ function ArchiveLink() {
}
}, [disclosure, expanded]);
useEffect(() => {
if (expanded) {
void request();
}
}, [expanded, request]);
const handleDisclosureClick = useCallback((ev) => {
ev.preventDefault();
ev.stopPropagation();
@@ -84,6 +75,7 @@ function ArchiveLink() {
<Relative>
<PaginatedList<Collection>
aria-label={t("Archived collections")}
fetch={collections.fetchArchived}
items={collections.archived}
loading={<PlaceholderCollections />}
renderError={(props) => <StyledError {...props} />}
@@ -23,7 +23,7 @@ import Text from "@shared/components/Text";
import usePolicy from "~/hooks/usePolicy";
function Collections() {
const { documents, auth, collections } = useStores();
const { documents, auth, collections, policies } = useStores();
const { t } = useTranslation();
const can = usePolicy(auth.team?.id);
const orderedCollections = collections.allActive;
@@ -46,10 +46,12 @@ function Collections() {
fractionalIndex(null, orderedCollections[0].index)
);
},
canDrop: (item) => item.id !== orderedCollections[0].id,
canDrop: (item) =>
item.id !== orderedCollections[0]?.id &&
!!policies.abilities(item.id).move,
collect: (monitor) => ({
isCollectionDropping: monitor.isOver(),
isDraggingAnyCollection: monitor.getItemType() === "collection",
isDraggingAnyCollection: monitor.canDrop(),
}),
});
@@ -58,7 +58,7 @@ function DraggableCollectionLink({
canDrop: (item) =>
collection.id !== item.id &&
(!belowCollection || item.id !== belowCollection.id) &&
policies.abilities(item.id)?.move,
!!policies.abilities(item.id).move,
collect: (monitor: DropTargetMonitor<Collection, Collection>) => ({
isCollectionDropping: monitor.isOver(),
isDraggingAnyCollection: monitor.canDrop(),
@@ -226,7 +226,7 @@ export function useDropToChangeCollection(
parentRef: React.RefObject<HTMLDivElement>
) {
const { t } = useTranslation();
const { documents, collections, dialogs } = useStores();
const { documents, collections, dialogs, policies } = useStores();
const can = usePolicy(collection);
const startHover = useHover(parentRef, expandNode);
@@ -281,7 +281,7 @@ export function useDropToChangeCollection(
}
}
},
canDrop: () => can.createDocument,
canDrop: (item) => can.createDocument && !!policies.abilities(item.id).move,
hover: (_, monitor) => {
if (
collection.hasDocuments &&
@@ -311,7 +311,7 @@ export function useDropToReparentDocument(
parentRef: React.RefObject<HTMLDivElement>
) {
const { t } = useTranslation();
const { documents, collections, dialogs } = useStores();
const { documents, collections, dialogs, policies } = useStores();
const hasChildDocuments = !!node?.children.length;
const document = node ? documents.get(node.id) : undefined;
const pathToNode = React.useMemo(
@@ -373,7 +373,7 @@ export function useDropToReparentDocument(
}
},
canDrop: (item) => {
if (!node || item.id === node.id) {
if (!node || item.id === node.id || !policies.abilities(item.id).move) {
return false;
}
@@ -425,7 +425,7 @@ export function useDropToReorderDocument(
}
) {
const { t } = useTranslation();
const { documents, collections, dialogs } = useStores();
const { documents, collections, dialogs, policies } = useStores();
const document = documents.get(node.id);
@@ -435,7 +435,7 @@ export function useDropToReorderDocument(
if (item.id === node.id || (document && !document.isActive)) {
return false;
}
return true;
return !!policies.abilities(item.id).move;
},
drop: async (item) => {
if (!collection?.isManualSort && item.collectionId === collection?.id) {
+8 -13
View File
@@ -120,16 +120,6 @@ function useConnectionHandlers() {
data,
});
});
// received a message from the API server that we should request
// to join or leave a specific room. Forward that to the ws server.
socket.on("join", (event) => {
socket.emit("join", event);
});
socket.on("leave", (event) => {
socket.emit("leave", event);
});
};
}
@@ -641,19 +631,24 @@ function useUserHandlers() {
users.add(event);
});
socket.on("users.demote", async (event: PartialExcept<User, "id">) => {
// the current user's role changed, so their policies are invalid and the
// set of accessible collections may have changed.
const handleRoleChange = async (event: PartialExcept<User, "id">) => {
if (event.id === auth.user?.id) {
documents.all.forEach((document) => policies.remove(document.id));
try {
await collections.fetchAll();
} catch (err) {
Logger.error(
"Failed to fetch collections after demote",
"Failed to fetch collections after role change",
toError(err)
);
}
}
});
};
socket.on("users.promote", handleRoleChange);
socket.on("users.demote", handleRoleChange);
socket.on("users.delete", (event: WebsocketEntityDeletedEvent) => {
users.remove(event.modelId);
+5 -2
View File
@@ -7,12 +7,14 @@ import { changedDescendants } from "@shared/editor/lib/changedDescendants";
import { mapDecorations } from "@shared/editor/lib/multiplayer";
import { UserPreferenceDefaults } from "@shared/constants";
import { UserPreference } from "@shared/types";
import { isMobile } from "@shared/utils/browser";
import { CommentGutter as CommentGutterComponent } from "../components/CommentGutter";
/**
* Adds an indicator in the gutter beside any line that contains an unresolved
* comment mark, when the user has enabled the preference. Each indicator shows
* the number of comments in the thread and opens the thread when clicked.
* There is no room for the gutter at mobile widths, so it is disabled there.
*/
export default class CommentGutter extends Extension {
get name() {
@@ -25,8 +27,9 @@ export default class CommentGutter extends Extension {
get plugins() {
const isEnabled = () =>
this.editor.props.userPreferences?.[UserPreference.CommentsInGutter] ??
UserPreferenceDefaults[UserPreference.CommentsInGutter];
!isMobile() &&
(this.editor.props.userPreferences?.[UserPreference.CommentsInGutter] ??
UserPreferenceDefaults[UserPreference.CommentsInGutter]);
const handleClickCommentMark = (commentId: string) =>
this.editor.props.onClickCommentMark?.(commentId);
+5
View File
@@ -53,6 +53,11 @@ const createKeyPredicate = (keyFilter: KeyFilter, options?: Options) =>
? keyFilter
: typeof keyFilter === "string"
? (event: KeyboardEvent) => {
// Synthetic events may be dispatched without a key.
if (!event.key) {
return false;
}
// Match case-insensitively only when Shift is required, since a
// shifted letter reports an uppercase event.key (e.g. Cmd+Shift+P).
// Otherwise match exactly so a bare shortcut does not fire when Shift
+1 -1
View File
@@ -9,7 +9,7 @@ import Heading from "~/components/Heading";
import ContentEditable from "~/components/ContentEditable";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import type Collection from "~/models/Collection";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import usePolicy from "~/hooks/usePolicy";
import { observer } from "mobx-react";
import lazyWithRetry from "~/utils/lazyWithRetry";
+1 -1
View File
@@ -6,7 +6,7 @@ import { useRouteMatch } from "react-router-dom";
import styled from "styled-components";
import Text from "@shared/components/Text";
import { richExtensions, withComments } from "@shared/editor/nodes";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import Comment from "~/models/Comment";
import type Document from "~/models/Document";
import type Template from "~/models/Template";
@@ -10,7 +10,7 @@ import { s, depths, hover } from "@shared/styles";
import { cloneDeep } from "es-toolkit/compat";
import type { ProsemirrorData } from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import Editor from "~/components/Editor";
import NudeButton from "~/components/NudeButton";
import Text from "~/components/Text";
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import * as React from "react";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import type Document from "~/models/Document";
import type Revision from "~/models/Revision";
import type { Props as EditorProps } from "~/components/Editor";
+7
View File
@@ -12,6 +12,7 @@ import {
AuthorizationError,
BadGatewayError,
BadRequestError,
ClientClosedRequestError,
NetworkError,
NotFoundError,
OfflineError,
@@ -311,6 +312,12 @@ class ApiClient {
);
}
// The client, or an intermediate proxy, closed the connection before the
// response was received – there is nothing actionable to report.
if (response.status === 499) {
throw new ClientClosedRequestError(error.message);
}
const err = new RequestError(`Error ${response.status}`);
Logger.error("Request failed", err, {
...error,
+3
View File
@@ -30,6 +30,9 @@ export class UnprocessableEntityError extends ExtendableError {}
/** Error thrown when the client has exceeded the allowed request rate. */
export class RateLimitExceededError extends ExtendableError {}
/** Error thrown when the client closed the connection before a response. */
export class ClientClosedRequestError extends ExtendableError {}
/** Error thrown when a request fails for a generic reason. */
export class RequestError extends ExtendableError {}
+2
View File
@@ -4,6 +4,7 @@ import env from "~/env";
import {
AuthorizationError,
BadRequestError,
ClientClosedRequestError,
NetworkError,
NotFoundError,
OfflineError,
@@ -22,6 +23,7 @@ export function initSentry(history: History) {
const ignoredErrorTypes = [
AuthorizationError,
BadRequestError,
ClientClosedRequestError,
NetworkError,
NotFoundError,
OfflineError,
+7 -8
View File
@@ -102,8 +102,8 @@
"@radix-ui/react-toolbar": "^1.1.15",
"@radix-ui/react-tooltip": "^1.2.12",
"@radix-ui/react-visually-hidden": "^1.2.7",
"@sentry/node": "^10.65.0",
"@sentry/react": "^10.65.0",
"@sentry/node": "^10.68.0",
"@sentry/react": "^10.68.0",
"@simplewebauthn/browser": "^13.3.0",
"@simplewebauthn/server": "^13.3.1",
"@tanstack/react-table": "^8.21.3",
@@ -126,7 +126,7 @@
"core-js": "^3.49.0",
"crypto-js": "^4.2.0",
"date-fns": "^3.6.0",
"dd-trace": "^5.115.0",
"dd-trace": "^5.117.0",
"diff": "^5.2.2",
"email-providers": "^1.14.0",
"emoji-mart": "^5.6.0",
@@ -150,7 +150,7 @@
"i18next-fs-backend": "^2.6.6",
"i18next-http-backend": "^3.0.6",
"invariant": "^2.2.4",
"ioredis": "^5.10.1",
"ioredis": "^5.11.1",
"ipaddr.js": "^2.4.0",
"is-printable-key-event": "^1.0.0",
"iso-639-3": "^3.0.1",
@@ -266,7 +266,7 @@
"uuid": "^11.1.1",
"validator": "13.15.35",
"vaul": "^1.1.2",
"vite": "^8.0.16",
"vite": "^8.1.5",
"vite-plugin-pwa": "1.3.0",
"winston": "^3.17.0",
"ws": "^7.5.11",
@@ -331,7 +331,7 @@
"@types/react-router-dom": "^5.3.3",
"@types/react-virtualized-auto-sizer": "^1.0.8",
"@types/react-window": "^1.8.8",
"@types/readable-stream": "^4.0.23",
"@types/readable-stream": "^4.0.24",
"@types/redis-info": "^3.0.3",
"@types/refractor": "^3.4.1",
"@types/resolve-path": "^1.4.3",
@@ -345,7 +345,7 @@
"@types/utf8": "^3.0.3",
"@types/validator": "^13.15.10",
"@types/yauzl": "^2.10.3",
"@types/yazl": "^2.4.6",
"@types/yazl": "^3.3.1",
"@vitest/ui": "^4.1.8",
"browserslist-to-esbuild": "^1.2.0",
"concurrently": "^8.2.2",
@@ -382,7 +382,6 @@
"ws@npm:~8.17.1": "^8.21.0",
"uuid": "^11.1.1",
"nodemailer@npm:9.0.0": "^9.0.1",
"fast-uri@npm:^3.0.1": "3.1.4",
"linkify-it@npm:5.0.1": "5.0.2"
},
"version": "1.9.1",
+7 -10
View File
@@ -212,17 +212,14 @@ const emailCallback = async (ctx: APIContext<T.EmailCallbackReq>) => {
client,
});
};
router.get(
router.register(
"email.callback",
rateLimiter(RateLimiterStrategy.FivePerMinute),
validate(T.EmailCallbackSchema),
emailCallback
);
router.post(
"email.callback",
rateLimiter(RateLimiterStrategy.FivePerMinute),
validate(T.EmailCallbackSchema),
emailCallback
["get", "post"],
[
rateLimiter(RateLimiterStrategy.FivePerMinute),
validate(T.EmailCallbackSchema),
emailCallback,
]
);
export default router;
+5 -2
View File
@@ -255,8 +255,11 @@ export function createOIDCRouter(
);
router.get(config.id, startOAuthFlow, passport.authenticate(config.id));
router.get(`${config.id}.callback`, passportMiddleware(config.id));
router.post(`${config.id}.callback`, passportMiddleware(config.id));
router.register(
`${config.id}.callback`,
["get", "post"],
passportMiddleware(config.id)
);
// Performs a spec-compliant RP-initiated logout against the provider's end
// session endpoint. Passing `id_token_hint` identifies the session being
@@ -1420,5 +1420,23 @@ describe("PostgresSearchProvider", () => {
`"plugins"`
);
});
it("should not escape colons outside of a phrase", () => {
// pg-tsquery drops an unquoted colon but keeps a preceding backslash,
// so escaping here would leave a dangling "\" operand.
expect(
PostgresSearchProvider.webSearchQuery("hoffe, gehts gut :) bei")
).toBe("(hoffe|gehts&gut)&bei:*");
expect(PostgresSearchProvider.webSearchQuery("sub:title:here")).toBe(
"sub&title&here:*"
);
});
it("should escape colons inside a phrase", () => {
expect(PostgresSearchProvider.webSearchQuery(`"sub:title:here"`)).toBe(
`"sub\\:title\\:here"`
);
expect(PostgresSearchProvider.webSearchQuery(`'sub:title'`)).toBe(
`"sub\\:title":*`
);
});
});
});
@@ -840,9 +840,7 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
*/
public static webSearchQuery(query: string): string {
// limit length of search queries as we're using regex against untrusted input
let limitedQuery = PostgresSearchProvider.escapeQuery(
query.slice(0, PostgresSearchProvider.maxQueryLength)
);
let limitedQuery = query.slice(0, PostgresSearchProvider.maxQueryLength);
const quotedSearch =
limitedQuery.startsWith('"') && limitedQuery.endsWith('"');
@@ -867,6 +865,9 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
}
}
// Escape only once the phrase delimiters above have settled.
limitedQuery = PostgresSearchProvider.escapeTsQuery(limitedQuery);
return (
queryParser()(
// Although queryParser trims the query, looks like there's a
@@ -882,14 +883,26 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
}
private static escapeQuery(query: string): string {
return (
query
// replace "\" with escaped "\\" because sequelize.escape doesn't do it
// see: https://github.com/sequelize/sequelize/issues/2950
.replace(/\\/g, "\\\\")
// replace ":" with escaped "\:" because it's a reserved character in tsquery
// see: https://github.com/outline/outline/issues/6542
.replace(/:/g, "\\:")
// replace "\" with escaped "\\" because sequelize.escape doesn't do it
// see: https://github.com/sequelize/sequelize/issues/2950
return query.replace(/\\/g, "\\\\");
}
/**
* Escapes the characters that are reserved in tsquery, segment by segment so
* that quoted phrases can be treated differently to the rest of the query.
*
* ":" only needs escaping inside a phrase, where pg-tsquery passes it through
* verbatim (see: https://github.com/outline/outline/issues/6542). Elsewhere
* pg-tsquery drops the colon but keeps a preceding backslash, which would
* leave to_tsquery with a dangling escape character.
*/
private static escapeTsQuery(query: string): string {
return query.replace(/"[^"]*"|'[^']*'|[\s\S]/g, (segment) =>
// a match longer than the single character fallback is a quoted phrase
segment.length > 1
? segment.replace(/[\\:]/g, "\\$&")
: segment.replace(/\\/g, "\\\\")
);
}
@@ -1,7 +1,7 @@
import { FetchError } from "node-fetch";
import { Op, QueryTypes } from "sequelize";
import { toError } from "@shared/utils/error";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import WebhookDisabledEmail from "@server/emails/templates/WebhookDisabledEmail";
import env from "@server/env";
import Logger from "@server/logging/Logger";
+37 -3
View File
@@ -1,6 +1,7 @@
import type {
onStoreDocumentPayload,
onLoadDocumentPayload,
afterLoadDocumentPayload,
onChangePayload,
Extension,
} from "@hocuspocus/server";
@@ -24,6 +25,9 @@ import type { withContext } from "./types";
@trace()
export default class PersistenceExtension implements Extension {
/** The names of entities that have changed since they were last persisted. */
private unsavedDocumentNames = new Set<string>();
async onLoadDocument({
documentName,
...data
@@ -44,6 +48,18 @@ export default class PersistenceExtension implements Extension {
return this.loadDocument(id, fieldName);
}
async afterLoadDocument({
documentName,
document,
}: afterLoadDocumentPayload) {
// Track changes from the ydoc itself rather than the onChange hook, which
// runs behind other extensions in an async chain and so may not have
// recorded the change by the time the document is stored on disconnect.
document.on("update", () => {
this.unsavedDocumentNames.add(documentName);
});
}
async onChange({ context, documentName }: withContext<onChangePayload>) {
const { id } = parseMultiplayerName(documentName);
@@ -74,13 +90,28 @@ export default class PersistenceExtension implements Extension {
const { type, id } = parseMultiplayerName(documentName);
const clientVersion = requestParameters.get("editorVersion");
const key = RedisPrefixHelper.getCollaboratorsKey(id);
const sessionCollaboratorIds = await Redis.defaultClient.lrange(key, 0, -1);
if (sessionCollaboratorIds.length === 0) {
// Nothing to do if the entity hasn't changed since it was last persisted.
// Note the flag is cleared before writing so that changes received while
// persisting will schedule another store.
if (!this.unsavedDocumentNames.delete(documentName)) {
Logger.debug("multiplayer", `No changes for ${documentName}`);
return;
}
// Collaborators are used for attribution only, failure to load them must
// not prevent the entity itself from being persisted.
const key = RedisPrefixHelper.getCollaboratorsKey(id);
let sessionCollaboratorIds: string[] = [];
try {
sessionCollaboratorIds = await Redis.defaultClient.lrange(key, 0, -1);
} catch (err) {
Logger.warn("Unable to load collaborators", {
documentId: id,
message: toError(err).message,
});
}
try {
if (type === MultiplayerEntityType.Collection) {
await collectionCollaborativeUpdater({
@@ -106,6 +137,9 @@ export default class PersistenceExtension implements Extension {
});
}
} catch (err) {
// Restore the flag so that a subsequent store will retry the write.
this.unsavedDocumentNames.add(documentName);
Logger.error(`Unable to persist ${type}`, toError(err), {
documentId: id,
userId: context.user?.id,
@@ -1,6 +1,7 @@
import * as React from "react";
import { NotificationEventType } from "@shared/types";
import env from "@server/env";
import { FileOperation } from "@server/models";
import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper";
import type { EmailProps } from "./BaseEmail";
import BaseEmail, { EmailMessageCategory } from "./BaseEmail";
@@ -68,6 +69,8 @@ ${this.t("Your Data Export")}
${this.t("Your requested data export is complete, you can download from the link below in a browser that is logged into your account.")}
${this.t("This export will be available to download for {{ days }} days.", { days: FileOperation.expiryDays })}
${downloadLink}
`;
}
@@ -89,6 +92,12 @@ ${downloadLink}
"Your requested data export is complete - you can download from the link below in a browser that is logged into your account."
)}
</p>
<p>
{this.t(
"This export will be available to download for {{ days }} days.",
{ days: FileOperation.expiryDays }
)}
</p>
<EmptySpace height={10} />
<p>
<Button href={downloadLink}>{this.t("Download")}</Button>
+4 -1
View File
@@ -1,5 +1,6 @@
import type { Next } from "koa";
import { capitalize } from "es-toolkit/compat";
import httpErrors from "http-errors";
import type { UserRole } from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import tracer, {
@@ -64,7 +65,9 @@ export default function auth(options: AuthenticationOptions = {}) {
);
}
} catch (err) {
if (options.optional) {
// Credentials that are valid but insufficient are always surfaced,
// otherwise the request would be silently downgraded to anonymous.
if (options.optional && !(err instanceof httpErrors.Forbidden)) {
ctx.state.auth = {};
} else {
throw err;
+24
View File
@@ -487,6 +487,30 @@ describe("#findByPk", () => {
expect(response!.id).toBe(collection.id);
});
it("should not allow a passed where to override the id", async () => {
const collection = await buildCollection();
const other = await buildCollection();
const response = await Collection.findByPk(collection.id, {
where: { id: other.id },
});
expect(response!.id).toBe(collection.id);
const byUrlId = await Collection.findByPk(collection.urlId, {
where: { urlId: other.urlId },
});
expect(byUrlId!.id).toBe(collection.id);
});
it("should throw the passed error when rejectOnEmpty is an error", async () => {
const error = new Error("does not exist");
await expect(
Collection.findByPk("0e8280ea-7b4c-40e5-98ba-ec8a2f00f5e8", {
rejectOnEmpty: error,
})
).rejects.toThrow(error);
});
it("should not return documentStructure by default", async () => {
const collection = await buildCollection();
const response = await Collection.findByPk(collection.id);
+8 -4
View File
@@ -740,15 +740,17 @@ class Collection extends ParanoidModel<
if (isUUID(id)) {
const collection = await scope.findOne({
...rest,
where: {
id,
},
...rest,
rejectOnEmpty: false,
});
if (!collection && rest.rejectOnEmpty) {
throw new EmptyResultError(`Collection doesn't exist with id: ${id}`);
throw rest.rejectOnEmpty instanceof Error
? rest.rejectOnEmpty
: new EmptyResultError(`Collection doesn't exist with id: ${id}`);
}
return collection;
@@ -757,15 +759,17 @@ class Collection extends ParanoidModel<
const match = id.match(UrlHelper.SLUG_URL_REGEX);
if (match) {
const collection = await scope.findOne({
...rest,
where: {
urlId: match[1],
},
...rest,
rejectOnEmpty: false,
});
if (!collection && rest.rejectOnEmpty) {
throw new EmptyResultError(`Collection doesn't exist with id: ${id}`);
throw rest.rejectOnEmpty instanceof Error
? rest.rejectOnEmpty
: new EmptyResultError(`Collection doesn't exist with id: ${id}`);
}
return collection;
+75 -1
View File
@@ -1,5 +1,5 @@
import { EmptyResultError, Op } from "sequelize";
import { CollectionPermission } from "@shared/types";
import { CollectionPermission, DocumentPermission } from "@shared/types";
import slugify from "@shared/utils/slugify";
import { parser } from "@server/editor";
import Document from "@server/models/Document";
@@ -300,6 +300,30 @@ describe("#findByPk", () => {
).rejects.toThrow(EmptyResultError);
});
it("should not allow a passed where to override the id", async () => {
const document = await buildDocument();
const other = await buildDocument();
const response = await Document.findByPk(document.id, {
where: { id: other.id },
});
expect(response?.id).toBe(document.id);
const byUrlId = await Document.findByPk(document.urlId, {
where: { urlId: other.urlId },
});
expect(byUrlId?.id).toBe(document.id);
});
it("should throw the passed error when rejectOnEmpty is an error", async () => {
const error = new Error("does not exist");
await expect(
Document.findByPk("0e8280ea-7b4c-40e5-98ba-ec8a2f00f5e8", {
rejectOnEmpty: error,
})
).rejects.toThrow(error);
});
it("should load state as a fallback when content is empty", async () => {
const state = Buffer.from([1, 2, 3]);
const document = await buildDocument();
@@ -389,6 +413,56 @@ describe("findByIds", () => {
);
expect(documents.length).toBe(1);
});
it("should not return another user's unfiled draft", async () => {
const team = await buildTeam();
const author = await buildUser({ teamId: team.id });
const user = await buildUser({ teamId: team.id });
const draft = await buildDraftDocument({
teamId: team.id,
userId: author.id,
collectionId: null,
});
const documents = await Document.findByIds([draft.id], {
userId: user.id,
});
expect(documents.length).toBe(0);
});
it("should return the user's own unfiled draft", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const draft = await buildDraftDocument({
teamId: team.id,
userId: user.id,
collectionId: null,
});
const documents = await Document.findByIds([draft.id], {
userId: user.id,
});
expect(documents.length).toBe(1);
});
it("should return an unfiled draft shared with the user", async () => {
const team = await buildTeam();
const author = await buildUser({ teamId: team.id });
const user = await buildUser({ teamId: team.id });
const draft = await buildDraftDocument({
teamId: team.id,
userId: author.id,
collectionId: null,
});
await UserMembership.create({
createdById: author.id,
documentId: draft.id,
userId: user.id,
permission: DocumentPermission.Read,
});
const documents = await Document.findByIds([draft.id], {
userId: user.id,
});
expect(documents.length).toBe(1);
});
});
describe("tasks", () => {
+30 -13
View File
@@ -360,6 +360,10 @@ class Document extends ArchivableModel<
* @deprecated Use `content` instead, or `DocumentHelper.toMarkdown` if exporting lossy markdown.
* This column will be removed in a future migration.
*/
@SimpleLength({
max: DocumentValidation.maxLength,
msg: `Document text content must be ${DocumentValidation.maxLength} characters or less`,
})
@Column(DataType.TEXT)
@SkipChangeset
text: string;
@@ -804,15 +808,17 @@ class Document extends ArchivableModel<
if (isUUID(id)) {
const document = await scope.findOne({
...rest,
where: {
id,
},
...rest,
rejectOnEmpty: false,
});
if (!document && rest.rejectOnEmpty) {
throw new EmptyResultError(`Document doesn't exist with id: ${id}`);
throw rest.rejectOnEmpty instanceof Error
? rest.rejectOnEmpty
: new EmptyResultError(`Document doesn't exist with id: ${id}`);
}
return document;
@@ -821,15 +827,17 @@ class Document extends ArchivableModel<
const match = id.match(UrlHelper.SLUG_URL_REGEX);
if (match) {
const document = await scope.findOne({
...rest,
where: {
urlId: match[1],
},
...rest,
rejectOnEmpty: false,
});
if (!document && rest.rejectOnEmpty) {
throw new EmptyResultError(`Document doesn't exist with id: ${id}`);
throw rest.rejectOnEmpty instanceof Error
? rest.rejectOnEmpty
: new EmptyResultError(`Document doesn't exist with id: ${id}`);
}
return document;
@@ -879,14 +887,23 @@ class Document extends ArchivableModel<
return documents;
}
return documents.filter(
(doc) =>
(!doc.collection?.isPrivate && !user?.isGuest) ||
(doc.collection?.memberships.length || 0) > 0 ||
(doc.collection?.groupMemberships.length || 0) > 0 ||
doc.memberships.length > 0 ||
doc.groupMemberships.length > 0
);
return documents.filter((doc) => {
if (doc.memberships.length > 0 || doc.groupMemberships.length > 0) {
return true;
}
// A document without a collection is either an unfiled draft or lives in
// a collection the user cannot see – access is limited to the creator.
if (!doc.collection) {
return doc.createdById === userId;
}
return (
(!doc.collection.isPrivate && !user?.isGuest) ||
doc.collection.memberships.length > 0 ||
doc.collection.groupMemberships.length > 0
);
});
}
// instance methods
@@ -1072,7 +1089,7 @@ class Document extends ArchivableModel<
const collection = await Collection.findByPk(this.collectionId, {
includeDocumentStructure: true,
transaction,
lock: Transaction.LOCK.UPDATE,
lock: Transaction.LOCK.NO_KEY_UPDATE,
});
if (collection) {
+39
View File
@@ -0,0 +1,39 @@
import {
buildFileOperation,
buildTeam,
buildUser,
} from "@server/test/factories";
import FileOperation from "./FileOperation";
describe("FileOperation", () => {
describe("findByPk", () => {
it("should not allow a passed where to override the id", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const fileOperation = await buildFileOperation({
teamId: team.id,
userId: user.id,
});
const other = await buildFileOperation({
teamId: team.id,
userId: user.id,
});
const found = await FileOperation.findByPk(fileOperation.id, {
where: { id: other.id },
});
expect(found?.id).toEqual(fileOperation.id);
});
it("should throw the passed error when rejectOnEmpty is an error", async () => {
const error = new Error("does not exist");
await expect(
FileOperation.findByPk("3a1b2c3d-0000-4000-8000-000000000000", {
rejectOnEmpty: error,
})
).rejects.toThrow(error);
});
});
});
+100 -1
View File
@@ -1,12 +1,16 @@
import type {
FindOptions,
Identifier,
InferAttributes,
InferCreationAttributes,
NonNullFindOptions,
WhereOptions,
} from "sequelize";
import { Op } from "sequelize";
import { EmptyResultError, Op } from "sequelize";
import {
ForeignKey,
DefaultScope,
Scopes,
Column,
BeforeDestroy,
BelongsTo,
@@ -30,6 +34,11 @@ export type FileOperationOptions = {
permission?: CollectionPermission | null;
};
type AdditionalFindOptions = {
userId?: string;
rejectOnEmpty?: boolean | Error;
};
@DefaultScope(() => ({
include: [
{
@@ -52,6 +61,47 @@ export type FileOperationOptions = {
},
],
}))
@Scopes(() => ({
withSource: (userId: string) => {
if (!userId) {
return {};
}
return {
include: [
{
model: User,
as: "user",
paranoid: false,
},
{
model: Collection.scope([
"defaultScope",
{
method: ["withMembership", userId],
},
]),
as: "collection",
required: false,
paranoid: false,
},
{
model: Document.scope([
"defaultScope",
{
method: ["withMembership", userId, false],
},
]),
as: "document",
// Content columns are not needed to authorize or present an export.
attributes: { exclude: ["text", "content", "state"] },
required: false,
paranoid: false,
},
],
};
},
}))
@Table({ tableName: "file_operations", modelName: "file_operation" })
class FileOperation extends ParanoidModel<
InferAttributes<FileOperation>,
@@ -59,6 +109,55 @@ class FileOperation extends ParanoidModel<
> {
static eventNamespace = "fileOperations";
/** The number of days a completed file operation remains downloadable. */
static expiryDays = 15;
/**
* Overrides the standard findByPk behavior to allow loading the exported
* collection or document with memberships for a user passed in by `userId`.
*
* @param id uuid
* @param options FindOptions
* @returns a promise resolving to a file operation instance or null.
*/
static async findByPk(
id: Identifier,
options?: NonNullFindOptions<FileOperation> & AdditionalFindOptions
): Promise<FileOperation>;
static async findByPk(
id: Identifier,
options?: FindOptions<FileOperation> & AdditionalFindOptions
): Promise<FileOperation | null>;
static async findByPk(
id: Identifier,
options: FindOptions<FileOperation> & AdditionalFindOptions = {}
): Promise<FileOperation | null> {
if (typeof id !== "string") {
return null;
}
const { userId, ...rest } = options;
// Preserve the caller's scope when no userId is passed
const scope = userId
? this.scope({ method: ["withSource", userId] })
: this;
const fileOperation = await scope.findOne({
...rest,
where: { id },
rejectOnEmpty: false,
});
if (!fileOperation && rest.rejectOnEmpty) {
throw rest.rejectOnEmpty instanceof Error
? rest.rejectOnEmpty
: new EmptyResultError(`File operation doesn't exist with id: ${id}`);
}
return fileOperation;
}
@Column(DataType.ENUM(...Object.values(FileOperationType)))
type: FileOperationType;
+1 -1
View File
@@ -70,7 +70,7 @@ class Relationship extends IdModel<
const documents = await Document.findByIds(
relationships.map((relationship) => relationship.reverseDocumentId),
{
attributes: ["id"],
attributes: ["id", "createdById"],
userId: user.id,
includeState: false,
includeViews: false,
+16
View File
@@ -229,6 +229,22 @@ describe("user model", () => {
expect(response[0]).toEqual(collection.id);
});
it("should not return a cached response after a role change", async () => {
const team = await buildTeam();
const user = await buildGuestUser({
teamId: team.id,
});
const collection = await buildCollection({
teamId: team.id,
permission: CollectionPermission.ReadWrite,
});
expect(await user.collectionIds()).toEqual([]);
await user.update({ role: UserRole.Member });
expect(await user.collectionIds()).toEqual([collection.id]);
});
it("should not return private collections", async () => {
const team = await buildTeam();
const user = await buildUser({
+34 -5
View File
@@ -482,12 +482,17 @@ class User extends ParanoidModel<
* Returns the user's active collection ids. This includes collections the user
* has access to through group memberships.
*
* @param options Additional options to pass to the find
* @param options Additional options to pass to the find, set `skipCache` to bypass the cached response
* @returns An array of collection ids
*/
public collectionIds = async (options: FindOptions<Collection> = {}) => {
public collectionIds = async (
options: FindOptions<Collection> & { skipCache?: boolean } = {}
) => {
const { skipCache, ...findOptions } = options;
const hasOptions =
options.transaction || options.paranoid === false || options.lock;
findOptions.transaction ||
findOptions.paranoid === false ||
findOptions.lock;
const fetchCollectionIds = async () => {
const collectionStubs = await Collection.findAll({
@@ -545,13 +550,13 @@ class User extends ParanoidModel<
},
],
paranoid: true,
...options,
...findOptions,
});
return Array.from(new Set(collectionStubs.map((c) => c.id)));
};
if (hasOptions) {
if (hasOptions || skipCache) {
return fetchCollectionIds();
}
@@ -863,6 +868,30 @@ class User extends ParanoidModel<
}
}
// When a user's role changes their set of accessible collections may also
// change, so invalidate the cached collection ids.
@AfterUpdate
static async invalidateCollectionIdsAfterRoleChange(
model: User,
options: InstanceUpdateOptions<InferAttributes<User>>
) {
if (!model.changed("role")) {
return;
}
const invalidate = () =>
CacheHelper.removeData(
RedisPrefixHelper.getUserCollectionIdsKey(model.id)
);
if (options.transaction) {
const transaction = options.transaction.parent || options.transaction;
transaction.afterCommit(invalidate);
} else {
await invalidate();
}
}
// When a user's suspension state changes, invalidate the cached member count
// for every group they belong to so the count reflects only active members.
@AfterUpdate
+17 -3
View File
@@ -1,3 +1,4 @@
import { errToString } from "@shared/utils/error";
import env from "@server/env";
import { encrypt, decrypt } from "./Encrypted";
@@ -40,10 +41,23 @@ describe("Encrypted", () => {
expect(encrypt(value).equals(encrypt(value))).toBe(false);
});
it("should fail to decrypt tampered data", () => {
const encrypted = encrypt(JSON.stringify("hello world"));
it("should not return the original value for tampered data", () => {
const value = JSON.stringify("hello world");
const encrypted = encrypt(value);
encrypted[encrypted.length - 1] ^= 0xff;
expect(() => decrypt(encrypted)).toThrow();
try {
expect(decrypt(encrypted)).not.toEqual(value);
} catch (err) {
expect(errToString(err)).toMatch(/bad decrypt/);
}
});
it("should fail to decrypt a truncated ciphertext", () => {
const encrypted = encrypt(JSON.stringify("hello world"));
expect(() =>
decrypt(encrypted.subarray(0, encrypted.length - 1))
).toThrow();
});
it("should fail to decrypt with a different key", () => {
+32 -10
View File
@@ -30,24 +30,46 @@ export default class HTMLHelper {
contentType: string | null | undefined,
buffer: Buffer
): string | null {
if (!contentType?.startsWith("image/")) {
return null;
}
if (buffer.length === 0 || buffer.length > HTMLHelper.maxInlineImageSize) {
return null;
}
const pattern = new RegExp(escapeRegExp(redirectUrl), "g");
if ((html.match(pattern)?.length ?? 0) !== 1) {
if (
!HTMLHelper.canInlineImage(html, redirectUrl, contentType, buffer.length)
) {
return null;
}
return html.replace(
pattern,
new RegExp(escapeRegExp(redirectUrl), "g"),
`data:${contentType};base64,${buffer.toString("base64")}`
);
}
/**
* Whether an image meets the criteria for inlining, determined from its
* size alone so that callers can avoid reading images into memory that
* would be written to the export as an external file regardless.
*
* @param html The HTML content referencing the image.
* @param redirectUrl The redirect URL of the image within the HTML.
* @param contentType The content type of the image, e.g. "image/png".
* @param size The size of the image in bytes.
* @returns True if the image is a candidate for inlining.
*/
public static canInlineImage(
html: string,
redirectUrl: string,
contentType: string | null | undefined,
size: number
): boolean {
if (!contentType?.startsWith("image/")) {
return false;
}
if (size === 0 || size > HTMLHelper.maxInlineImageSize) {
return false;
}
const pattern = new RegExp(escapeRegExp(redirectUrl), "g");
return (html.match(pattern)?.length ?? 0) === 1;
}
/**
* Move CSS styles from <style> tags to inline styles with default settings.
*
+25 -3
View File
@@ -1,7 +1,7 @@
import invariant from "invariant";
import { CollectionPermission } from "@shared/types";
import { CollectionPermission, TeamPreference } from "@shared/types";
import { Collection, User, Team } from "@server/models";
import { allow } from "./cancan";
import { allow, can } from "./cancan";
import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";
allow(User, "createCollection", Team, (actor, team) =>
@@ -46,6 +46,16 @@ allow(User, "read", Collection, (user, collection) => {
return true;
});
allow(User, "download", Collection, (actor, collection) =>
and(
can(actor, "read", collection),
or(
and(!actor.isGuest, !actor.isViewer),
!!actor.team.getPreference(TeamPreference.ViewersCanExport)
)
)
);
allow(
User,
["readDocument", "star", "unstar", "subscribe", "unsubscribe"],
@@ -174,7 +184,7 @@ allow(
)
);
allow(User, ["update", "export", "archive"], Collection, (user, collection) =>
allow(User, ["update", "archive"], Collection, (user, collection) =>
and(
!!collection,
!!collection?.isActive,
@@ -185,6 +195,18 @@ allow(User, ["update", "export", "archive"], Collection, (user, collection) =>
)
);
allow(User, "export", Collection, (user, collection) =>
and(
!!collection,
!!collection?.isActive,
can(user, "download", collection),
or(
isTeamAdmin(user, collection),
includesMembership(collection, [CollectionPermission.Admin])
)
)
);
allow(User, "delete", Collection, (user, collection) =>
and(
!!collection,
+27 -2
View File
@@ -1,6 +1,6 @@
import { FileOperationState, FileOperationType } from "@shared/types";
import { User, Team, FileOperation } from "@server/models";
import { allow } from "./cancan";
import { allow, can } from "./cancan";
import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils";
const TerminalStates = [
@@ -9,6 +9,25 @@ const TerminalStates = [
FileOperationState.Expired,
];
/**
* An export is a snapshot that outlives the permissions it was created under,
* so access to the source is re-checked rather than trusting the ownership of
* the file operation alone.
*/
function canAccessSource(actor: User, fileOperation: FileOperation) {
if (fileOperation.type !== FileOperationType.Export) {
return true;
}
if (fileOperation.documentId) {
return can(actor, "download", fileOperation.document);
}
if (fileOperation.collectionId) {
return can(actor, "download", fileOperation.collection);
}
// Exports without a collection or document cover the entire workspace.
return can(actor, "createExport", actor.team);
}
allow(
User,
["createFileOperation", "createExport"],
@@ -20,7 +39,13 @@ allow(
allow(User, "read", FileOperation, (actor, fileOperation) =>
and(
isTeamModel(actor, fileOperation),
or(isTeamAdmin(actor, fileOperation), fileOperation?.userId === actor.id)
or(
isTeamAdmin(actor, fileOperation),
and(
fileOperation?.userId === actor.id,
!!fileOperation && canAccessSource(actor, fileOperation)
)
)
)
);
+19 -3
View File
@@ -1,7 +1,21 @@
import type { Share } from "@server/models";
import { presentUser } from ".";
export default function presentShare(share: Share, isAdmin = false) {
interface Options {
/** Whether the viewer is an admin of the team that owns the share. */
isAdmin?: boolean;
/** Whether the share is presented to a viewer without access to it. */
isPublic?: boolean;
}
/**
* Serializes a share for the API.
*
* @param share the share to present.
* @param options options controlling which fields are included.
* @returns the serialized share.
*/
export default function presentShare(share: Share, options: Options = {}) {
const data = {
id: share.id,
sourceTitle: share.collection?.name ?? share.document?.title,
@@ -13,7 +27,9 @@ export default function presentShare(share: Share, isAdmin = false) {
published: share.published,
url: share.canonicalUrl,
urlId: share.urlId,
createdBy: presentUser(share.user),
...(options.isPublic || !share.user
? {}
: { createdBy: presentUser(share.user) }),
includeChildDocuments: share.includeChildDocuments,
allowIndexing: share.allowIndexing,
allowSubscriptions: share.allowSubscriptions,
@@ -28,7 +44,7 @@ export default function presentShare(share: Share, isAdmin = false) {
updatedAt: share.updatedAt,
};
if (!isAdmin) {
if (!options.isAdmin) {
delete data.lastAccessedAt;
}
+1 -1
View File
@@ -23,7 +23,7 @@ import {
ImportTaskState,
MentionType,
} from "@shared/types";
import { colorPalette } from "@shared/utils/collections";
import { colorPalette } from "@shared/constants";
import { UrlHelper } from "@shared/utils/UrlHelper";
import { CollectionValidation } from "@shared/validations";
import { createContext } from "@server/context";
+127 -65
View File
@@ -332,16 +332,17 @@ export default class WebsocketsProcessor {
return;
}
// guests are excluded as they cannot read team-visible collections
// without an explicit membership.
const rooms = collection.isPrivate
? [`user-${event.actorId}`]
: [`user-${event.actorId}`, `team-${collection.teamId}.members`];
socketio
.to(this.getCollectionEventChannels(event, collection))
.to(rooms)
.emit(event.name, await presentCollection(undefined, collection));
return socketio
.to(this.getCollectionEventChannels(event, collection))
.emit("join", {
event: event.name,
collectionId: collection.id,
});
return socketio.in(rooms).socketsJoin(`collection-${collection.id}`);
}
case "collections.update": {
@@ -352,9 +353,44 @@ export default class WebsocketsProcessor {
return;
}
return socketio
socketio
.to(this.getCollectionEventChannels(event, collection))
.emit(event.name, await presentCollection(undefined, collection));
const { attributes, previous } = event.changes ?? {};
// the collection became team-visible, all team members gain access.
if (attributes?.permission && previous?.permission === null) {
return socketio
.in(`team-${collection.teamId}.members`)
.socketsJoin(`collection-${collection.id}`);
}
// the collection became private, rebuild the channel from explicit
// memberships only.
if (attributes?.permission === null && previous?.permission) {
socketio
.in(`collection-${collection.id}`)
.socketsLeave(`collection-${collection.id}`);
const [memberships, groupMemberships] = await Promise.all([
UserMembership.findAll({
where: { collectionId: collection.id },
}),
GroupMembership.findAll({
where: { collectionId: collection.id },
}),
]);
const rooms = [
...memberships.map((m) => `user-${m.userId}`),
...groupMemberships.map((m) => `group-${m.groupId}`),
];
if (rooms.length) {
socketio.in(rooms).socketsJoin(`collection-${collection.id}`);
}
}
return;
}
case "collections.delete": {
@@ -412,12 +448,9 @@ export default class WebsocketsProcessor {
.to(`user-${membership.userId}`)
.to(`collection-${membership.collectionId}`)
.emit(event.name, presentMembership(membership));
// tell any user clients to connect to the websocket channel for the collection
socketio.to(`user-${event.userId}`).emit("join", {
event: event.name,
collectionId: event.collectionId,
});
socketio
.in(`user-${event.userId}`)
.socketsJoin(`collection-${event.collectionId}`);
return;
}
@@ -444,11 +477,9 @@ export default class WebsocketsProcessor {
.emit("collections.remove_user", membership);
if (cannot(user, "read", collection)) {
// tell any user clients to disconnect from the websocket channel for the collection
socketio.to(`user-${event.userId}`).emit("leave", {
event: event.name,
collectionId: event.collectionId,
});
socketio
.in(`user-${event.userId}`)
.socketsLeave(`collection-${event.collectionId}`);
}
return;
@@ -466,11 +497,9 @@ export default class WebsocketsProcessor {
.to(`group-${membership.groupId}`)
.to(`collection-${membership.collectionId}`)
.emit(event.name, presentGroupMembership(membership));
socketio.to(`group-${membership.groupId}`).emit("join", {
event: event.name,
collectionId: event.collectionId,
});
socketio
.in(`group-${membership.groupId}`)
.socketsJoin(`collection-${event.collectionId}`);
return;
}
@@ -504,11 +533,9 @@ export default class WebsocketsProcessor {
}
if (cannot(user, "read", collection)) {
// tell any user clients to disconnect from the websocket channel for the collection
socketio.to(`user-${groupUser.userId}`).emit("leave", {
event: event.name,
collectionId: event.collectionId,
});
socketio
.in(`user-${groupUser.userId}`)
.socketsLeave(`collection-${event.collectionId}`);
}
}
}
@@ -700,11 +727,9 @@ export default class WebsocketsProcessor {
socketio
.to(`team-${event.teamId}`)
.emit("groups.add_user", presentGroupUser(groupUser));
socketio.to(`user-${event.userId}`).emit("join", {
event: event.name,
groupId: event.modelId,
});
socketio
.in(`user-${event.userId}`)
.socketsJoin(`group-${event.modelId}`);
await GroupMembership.findAllInBatches<GroupMembership>(
{
@@ -722,12 +747,9 @@ export default class WebsocketsProcessor {
"collections.add_group",
presentGroupMembership(groupMembership)
);
// tell any user clients to connect to the websocket channel for the collection
socketio.to(`user-${event.userId}`).emit("join", {
event: event.name,
collectionId: groupMembership.collectionId,
});
socketio
.in(`user-${event.userId}`)
.socketsJoin(`collection-${groupMembership.collectionId}`);
}
if (groupMembership.documentId) {
socketio
@@ -755,11 +777,9 @@ export default class WebsocketsProcessor {
socketio
.to(`team-${event.teamId}`)
.emit("groups.remove_user", membership);
socketio.to(`user-${event.userId}`).emit("leave", {
event: event.name,
groupId: event.modelId,
});
socketio
.in(`user-${event.userId}`)
.socketsLeave(`group-${event.modelId}`);
const user = await User.findByPk(event.userId);
if (!user) {
@@ -794,11 +814,9 @@ export default class WebsocketsProcessor {
);
if (cannot(user, "read", collection)) {
// tell any user clients to disconnect from the websocket channel for the collection
socketio.to(`user-${event.userId}`).emit("leave", {
event: event.name,
collectionId: groupMembership.collectionId,
});
socketio
.in(`user-${event.userId}`)
.socketsLeave(`collection-${groupMembership.collectionId}`);
}
}
}
@@ -811,10 +829,9 @@ export default class WebsocketsProcessor {
socketio.to(`team-${event.teamId}`).emit(event.name, {
modelId: event.modelId,
});
socketio.to(`group-${event.modelId}`).emit("leave", {
event: event.name,
groupId: event.modelId,
});
socketio
.in(`group-${event.modelId}`)
.socketsLeave(`group-${event.modelId}`);
const groupMemberships = await GroupMembership.findAll({
where: {
@@ -853,11 +870,11 @@ export default class WebsocketsProcessor {
);
if (cannot(groupUser.user, "read", collection)) {
// tell any user clients to disconnect from the websocket channel for the collection
socketio.to(`user-${groupUser.userId}`).emit("leave", {
event: event.name,
collectionId: groupMembership.collectionId,
});
socketio
.in(`user-${groupUser.userId}`)
.socketsLeave(
`collection-${groupMembership.collectionId}`
);
}
}
}
@@ -915,16 +932,60 @@ export default class WebsocketsProcessor {
return;
}
case "users.promote":
case "users.demote": {
return socketio
socketio
.to(`user-${event.userId}`)
.emit(event.name, { id: event.userId });
// the user's accessible collections may have changed with their role.
const user = await User.findByPk(event.userId);
if (!user) {
return;
}
const membersRoom = `team-${user.teamId}.members`;
const accessibleCollectionIds = await user.collectionIds({
skipCache: true,
});
if (user.isGuest) {
const teamCollections = await Collection.findAll({
attributes: ["id"],
where: { teamId: user.teamId },
});
const accessibleCollectionIdsSet = new Set(accessibleCollectionIds);
const inaccessibleRooms = teamCollections
.map((collection) => collection.id)
.filter((id) => !accessibleCollectionIdsSet.has(id))
.map((id) => `collection-${id}`);
return socketio
.in(`user-${user.id}`)
.socketsLeave([membersRoom, ...inaccessibleRooms]);
}
return socketio
.in(`user-${user.id}`)
.socketsJoin([
membersRoom,
...accessibleCollectionIds.map((id) => `collection-${id}`),
]);
}
case "users.signout":
case "users.suspend": {
// authentication is no longer valid, disconnect all of the user's clients.
return socketio.in(`user-${event.userId}`).disconnectSockets(true);
}
case "users.delete": {
return socketio
socketio
.to(`team-${event.teamId}`)
.emit(event.name, { modelId: event.userId });
// authentication is no longer valid, disconnect all of the user's clients.
return socketio.in(`user-${event.userId}`).disconnectSockets(true);
}
case "userMemberships.update": {
@@ -948,10 +1009,11 @@ export default class WebsocketsProcessor {
channels.push(`user-${event.actorId}`);
}
if (collection.isPrivate) {
channels.push(`collection-${collection.id}`);
} else {
channels.push(`team-${collection.teamId}`);
// guests are never included in the team members channel, they receive
// events via the collection channel when they have an explicit membership.
channels.push(`collection-${collection.id}`);
if (!collection.isPrivate) {
channels.push(`team-${collection.teamId}.members`);
}
return channels;
@@ -9,11 +9,14 @@ import { CronTask, TaskInterval } from "./base/CronTask";
export default class CleanupExpiredFileOperationsTask extends CronTask {
public async perform({ limit }: Props) {
Logger.info("task", `Expiring file operations older than 15 days…`);
Logger.info(
"task",
`Expiring file operations older than ${FileOperation.expiryDays} days…`
);
const fileOperations = await FileOperation.unscoped().findAll({
where: {
createdAt: {
[Op.lt]: subDays(new Date(), 15),
[Op.lt]: subDays(new Date(), FileOperation.expiryDays),
},
state: {
[Op.ne]: FileOperationState.Expired,
+47 -39
View File
@@ -84,39 +84,50 @@ export default abstract class ExportDocumentTreeTask extends ExportTask {
}
const dir = path.dirname(pathInZip);
let buffer: Buffer;
try {
buffer = await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
buffer = Buffer.from("");
}
// Inline small images referenced a single time as base64 data URIs
// rather than writing an external file. PDF export renders from HTML too.
// Only these are read into memory; the rest are streamed into the archive.
if (
format === FileOperationFormat.HTMLZip ||
format === FileOperationFormat.PDF
) {
const inlined = HTMLHelper.inlineImage(
(format === FileOperationFormat.HTMLZip ||
format === FileOperationFormat.PDF) &&
HTMLHelper.canInlineImage(
text,
attachment.redirectUrl,
attachment.contentType,
buffer
);
attachment.size
)
) {
let buffer: Buffer | undefined;
try {
buffer = await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
}
const inlined = buffer
? HTMLHelper.inlineImage(
text,
attachment.redirectUrl,
attachment.contentType,
buffer
)
: null;
if (inlined !== null) {
text = inlined;
continue;
}
}
zip.addBuffer(buffer, path.join(dir, attachment.key), {
mtime: attachment.updatedAt,
});
this.addAttachmentToArchive(
zip,
attachment,
path.join(dir, attachment.key)
);
text = text.replace(
new RegExp(escapeRegExp(attachment.redirectUrl), "g"),
@@ -165,33 +176,30 @@ export default abstract class ExportDocumentTreeTask extends ExportTask {
* @returns The path to the zip file in tmp.
*/
protected async addCollectionsToArchive(
zip: ZipFile,
collections: Collection[],
format: FileOperationFormat,
includeAttachments = true
) {
const pathMap = this.createPathMap(collections, format);
await this.addDocumentsToArchive({
zip,
pathMap,
format,
includeAttachments,
});
return await ZipHelper.toTmpFile(zip);
return await ZipHelper.toTmpFile((zip) =>
this.addDocumentsToArchive({
zip,
pathMap,
format,
includeAttachments,
})
);
}
protected async addDocumentToArchive({
document,
format,
documentStructure,
zip,
includeAttachments = true,
}: {
document: Document;
format: FileOperationFormat;
documentStructure: NavigationNode[];
zip: ZipFile;
includeAttachments?: boolean;
}) {
const pathMap = new Map<string, string>();
@@ -209,14 +217,14 @@ export default abstract class ExportDocumentTreeTask extends ExportTask {
format
);
await this.addDocumentsToArchive({
zip,
pathMap,
format,
includeAttachments,
});
return await ZipHelper.toTmpFile(zip);
return await ZipHelper.toTmpFile((zip) =>
this.addDocumentsToArchive({
zip,
pathMap,
format,
includeAttachments,
})
);
}
/**
-7
View File
@@ -1,4 +1,3 @@
import { ZipFile } from "yazl";
import type { NavigationNode } from "@shared/types";
import { FileOperationFormat } from "@shared/types";
import type { Collection, FileOperation } from "@server/models";
@@ -10,10 +9,7 @@ export default class ExportHTMLZipTask extends ExportDocumentTreeTask {
collections: Collection[],
fileOperation: FileOperation
) {
const zip = new ZipFile();
return await this.addCollectionsToArchive(
zip,
collections,
FileOperationFormat.HTMLZip,
fileOperation.options?.includeAttachments ?? true
@@ -25,13 +21,10 @@ export default class ExportHTMLZipTask extends ExportDocumentTreeTask {
documentStructure: NavigationNode[],
includeAttachments: boolean
): Promise<string> {
const zip = new ZipFile();
return await this.addDocumentToArchive({
document,
documentStructure,
format: FileOperationFormat.HTMLZip,
zip,
includeAttachments,
});
}
+26 -42
View File
@@ -1,9 +1,7 @@
import { ZipFile } from "yazl";
import type { ZipFile } from "yazl";
import { omit } from "es-toolkit/compat";
import { errToString } from "@shared/utils/error";
import type { NavigationNode } from "@shared/types";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import type { Collection, FileOperation } from "@server/models";
import { Attachment, Document } from "@server/models";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
@@ -20,29 +18,28 @@ export default class ExportJSONTask extends ExportTask {
collections: Collection[],
fileOperation: FileOperation
) {
const zip = new ZipFile();
const usedFilenames = new Set<string>();
// serial to avoid overloading, slow and steady wins the race
for (const collection of collections) {
let filename = serializeFilename(collection.name);
let i = 0;
while (usedFilenames.has(filename)) {
filename = `${serializeFilename(collection.name)} (${++i})`;
return ZipHelper.toTmpFile(async (zip) => {
// serial to avoid overloading, slow and steady wins the race
for (const collection of collections) {
let filename = serializeFilename(collection.name);
let i = 0;
while (usedFilenames.has(filename)) {
filename = `${serializeFilename(collection.name)} (${++i})`;
}
usedFilenames.add(filename);
await this.addCollectionToArchive(
zip,
collection,
fileOperation.options?.includeAttachments ?? true,
filename
);
}
usedFilenames.add(filename);
await this.addCollectionToArchive(
zip,
collection,
fileOperation.options?.includeAttachments ?? true,
filename
);
}
await this.addMetadataToArchive(zip, fileOperation);
return ZipHelper.toTmpFile(zip);
await this.addMetadataToArchive(zip, fileOperation);
});
}
private async addMetadataToArchive(
@@ -87,31 +84,18 @@ export default class ExportJSONTask extends ExportTask {
attachments: {},
};
async function addAttachments(attachments: Attachment[]) {
const addAttachments = (attachments: Attachment[]) => {
for (const attachment of attachments) {
let buffer: Buffer;
try {
buffer = await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
buffer = Buffer.from("");
}
zip.addBuffer(buffer, attachment.key, {
mtime: attachment.updatedAt,
});
this.addAttachmentToArchive(zip, attachment, attachment.key);
output.attachments[attachment.id] = {
...omit(presentAttachment(attachment), "url"),
key: attachment.key,
};
}
}
};
async function addDocumentTree(nodes: NavigationNode[]) {
const addDocumentTree = async (nodes: NavigationNode[]) => {
for (const node of nodes) {
const document = await Document.findByPk(node.id, {
includeState: true,
@@ -132,7 +116,7 @@ export default class ExportJSONTask extends ExportTask {
})
: [];
await addAttachments(documentAttachments);
addAttachments(documentAttachments);
output.documents[document.id] = {
id: document.id,
@@ -157,7 +141,7 @@ export default class ExportJSONTask extends ExportTask {
await addDocumentTree(node.children);
}
}
}
};
const collectionAttachments = includeAttachments
? await Attachment.findAll({
@@ -170,7 +154,7 @@ export default class ExportJSONTask extends ExportTask {
})
: [];
await addAttachments(collectionAttachments);
addAttachments(collectionAttachments);
if (collection.documentStructure) {
await addDocumentTree(collection.documentStructure);
@@ -1,8 +1,12 @@
import { Readable } from "node:stream";
import fs from "fs-extra";
import { vi } from "vitest";
import FileStorage from "@server/storage/files";
import ZipHelper from "@server/utils/ZipHelper";
import {
buildCollection,
buildDocument,
buildDocumentWithAttachment,
buildFileOperation,
buildTeam,
buildUser,
@@ -10,6 +14,10 @@ import {
import ExportMarkdownZipTask from "./ExportMarkdownZipTask";
describe("ExportMarkdownZipTask", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("should not duplicate documents in the zip file", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
@@ -58,4 +66,88 @@ describe("ExportMarkdownZipTask", () => {
await fs.remove(filePath);
}
});
it("should stream attachment contents into the zip file", async () => {
const { collection, attachment, fileOperation } =
await buildDocumentWithAttachment();
const getFileStream = vi
.spyOn(FileStorage, "getFileStream")
.mockResolvedValue(Readable.from(["image-", "bytes"]));
const task = new ExportMarkdownZipTask();
const filePath = await task.exportCollections([collection], fileOperation);
try {
const contents = await readZipContents(filePath);
expect(contents[`${collection.name}/${attachment.key}`]).toBe(
"image-bytes"
);
expect(getFileStream).toHaveBeenCalledWith(attachment.key);
} finally {
await fs.remove(filePath);
}
});
it("should fail the export when an attachment cannot be read", async () => {
const { collection, fileOperation } = await buildDocumentWithAttachment();
vi.spyOn(FileStorage, "getFileStream").mockRejectedValue(
new Error("storage unavailable")
);
const task = new ExportMarkdownZipTask();
await expect(
task.exportCollections([collection], fileOperation)
).rejects.toThrow("storage unavailable");
});
it("should fail the export when an attachment read is interrupted", async () => {
const { collection, fileOperation } = await buildDocumentWithAttachment();
vi.spyOn(FileStorage, "getFileStream").mockResolvedValue(
new Readable({
read() {
this.push("partial");
this.destroy(new Error("connection reset"));
},
})
);
const task = new ExportMarkdownZipTask();
await expect(
task.exportCollections([collection], fileOperation)
).rejects.toThrow("connection reset");
});
it("should write an empty entry when an attachment is missing from storage", async () => {
const { collection, attachment, fileOperation } =
await buildDocumentWithAttachment();
vi.spyOn(FileStorage, "getFileStream").mockResolvedValue(null);
const task = new ExportMarkdownZipTask();
const filePath = await task.exportCollections([collection], fileOperation);
try {
const contents = await readZipContents(filePath);
expect(contents[`${collection.name}/${attachment.key}`]).toBe("");
} finally {
await fs.remove(filePath);
}
});
});
async function readZipContents(
filePath: string
): Promise<Record<string, string>> {
const contents: Record<string, string> = {};
await ZipHelper.walk(filePath, async (entry) => {
if (!entry.isDirectory) {
contents[entry.fileName] = (await entry.readBuffer(1024 * 1024)).toString(
"utf8"
);
}
});
return contents;
}
@@ -1,4 +1,3 @@
import { ZipFile } from "yazl";
import type { NavigationNode } from "@shared/types";
import { FileOperationFormat } from "@shared/types";
import type { Collection, FileOperation } from "@server/models";
@@ -10,10 +9,7 @@ export default class ExportMarkdownZipTask extends ExportDocumentTreeTask {
collections: Collection[],
fileOperation: FileOperation
) {
const zip = new ZipFile();
return await this.addCollectionsToArchive(
zip,
collections,
FileOperationFormat.MarkdownZip,
fileOperation.options?.includeAttachments
@@ -25,13 +21,10 @@ export default class ExportMarkdownZipTask extends ExportDocumentTreeTask {
documentStructure: NavigationNode[],
includeAttachments: boolean
): Promise<string> {
const zip = new ZipFile();
return await this.addDocumentToArchive({
document,
documentStructure,
format: FileOperationFormat.MarkdownZip,
zip,
includeAttachments,
});
}
+45
View File
@@ -1,5 +1,7 @@
import { Readable } from "node:stream";
import fs from "fs-extra";
import { truncate } from "es-toolkit/compat";
import type { ZipFile } from "yazl";
import { toError } from "@shared/utils/error";
import type { NavigationNode } from "@shared/types";
import { FileOperationState, NotificationEventType } from "@shared/types";
@@ -221,6 +223,49 @@ export default abstract class ExportTask extends BaseTask<Props> {
includeAttachments: boolean
): Promise<string>;
/**
* Add an attachment to the archive, streaming its contents from storage as
* the archive is written so that the file is never held in memory whole.
*
* A read that fails, or is interrupted part way through, fails the export —
* a silently truncated archive is worse than none, as it looks complete.
* An attachment that is simply absent from storage is written as an empty
* entry, since a row outliving its file must not make export impossible.
*
* @param zip The archive to add the attachment to
* @param attachment The attachment to add
* @param pathInZip The path to store the attachment at within the archive
*/
protected addAttachmentToArchive(
zip: ZipFile,
attachment: Attachment,
pathInZip: string
) {
zip.addReadStreamLazy(
pathInZip,
{ mtime: attachment.updatedAt },
(callback) => {
attachment.stream.then(
(stream) => {
if (!stream) {
Logger.warn(`Attachment is missing from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
});
return callback(null, Readable.from([]));
}
// yazl does not watch the streams it is handed, so an interrupted
// read would otherwise stall the archive rather than fail it.
stream.on("error", (err) => zip.emit("error", toError(err)));
return callback(null, stream);
},
(err) => callback(toError(err), Readable.from([]))
);
}
);
}
/**
* Update the state of the underlying FileOperation in the database and send
* an event to the client.
+7 -10
View File
@@ -337,17 +337,14 @@ const handleAttachmentsRedirect = async (
}
};
router.get(
router.register(
"attachments.redirect",
auth({ optional: true }),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
);
router.post(
"attachments.redirect",
auth({ optional: true }),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect
["get", "post"],
[
auth({ optional: true }),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect,
]
);
export default router;
@@ -56,6 +56,44 @@ describe("#collections.list", () => {
expect(body.data[0].archivedBy.id).toBe(collection.archivedById);
});
it("should include archived private collections for admin", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
archivedAt: new Date(),
});
const res = await server.post("/api/collections.list", admin, {
body: {
statusFilter: [CollectionStatusFilter.Archived],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
expect(body.data[0].id).toEqual(collection.id);
expect(body.policies[0].abilities.restore).toBeTruthy();
});
it("should not include archived private collections for member", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
await buildCollection({
teamId: team.id,
permission: null,
archivedAt: new Date(),
});
const res = await server.post("/api/collections.list", user, {
body: {
statusFilter: [CollectionStatusFilter.Archived],
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toHaveLength(0);
});
it("should exclude archived collections", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
+9 -3
View File
@@ -725,11 +725,17 @@ router.post(
],
};
const includeArchived = !!statusFilter?.includes(
CollectionStatusFilter.Archived
);
if (!statusFilter) {
where[Op.and].push({ archivedAt: { [Op.eq]: null } });
}
if (!includeListOnly || !user.isAdmin) {
// Admins can restore any archived collection, including private ones they
// are not a member of, so they must be able to see them listed.
if (!user.isAdmin || !(includeListOnly || includeArchived)) {
where[Op.and].push({ id: collectionIds });
}
@@ -740,7 +746,7 @@ router.post(
}
const statusQuery = [];
if (statusFilter?.includes(CollectionStatusFilter.Archived)) {
if (includeArchived) {
statusQuery.push({
archivedAt: {
[Op.ne]: null,
@@ -758,7 +764,7 @@ router.post(
const [collections, total] = await Promise.all([
Collection.scope(
statusFilter?.includes(CollectionStatusFilter.Archived)
includeArchived
? [
{
method: ["withMembership", user.id],
+10 -4
View File
@@ -93,11 +93,17 @@ const cronHandler = async (ctx: APIContext<T.CronSchemaReq>) => {
success: true,
};
};
router.get("cron.:period", validate(T.CronSchema), cronHandler);
router.post("cron.:period", validate(T.CronSchema), cronHandler);
router.register(
"cron.:period",
["get", "post"],
[validate(T.CronSchema), cronHandler]
);
// For backwards compatibility
router.get("utils.gc", validate(T.CronSchema), cronHandler);
router.post("utils.gc", validate(T.CronSchema), cronHandler);
router.register(
"utils.gc",
["get", "post"],
[validate(T.CronSchema), cronHandler]
);
export default router;
+76 -1
View File
@@ -10,6 +10,7 @@ import {
UserRole,
} from "@shared/types";
import { TextHelper } from "@shared/utils/TextHelper";
import { DocumentValidation } from "@shared/validations";
import { createContext } from "@server/context";
import { parser } from "@server/editor";
import type { Group, User } from "@server/models";
@@ -38,8 +39,13 @@ import {
buildGroup,
buildAdmin,
buildTemplate,
buildAttachment,
} from "@server/test/factories";
import { getTestServer, withAPIContext } from "@server/test/support";
import {
getTestServer,
readZipResponse,
withAPIContext,
} from "@server/test/support";
const server = getTestServer();
@@ -603,6 +609,10 @@ describe("#documents.info", () => {
});
describe("#documents.export", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("should return published document", async () => {
const user = await buildUser();
const document = await buildDocument({
@@ -687,6 +697,45 @@ describe("#documents.export", () => {
expect(body.data).toEqual(await DocumentHelper.toMarkdown(document));
});
it("should stream a zip when the document has attachments", async () => {
const user = await buildUser();
const attachment = await buildAttachment({
teamId: user.teamId,
userId: user.id,
});
const document = await buildDocument({
title: "Export Test",
userId: user.id,
teamId: user.teamId,
text: `![image](${attachment.redirectUrl})`,
});
vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue(
Buffer.from("image-data")
);
const res = await server.post("/api/documents.export", user, {
body: {
id: document.id,
},
headers: {
accept: "text/markdown",
},
});
expect(res.status).toEqual(200);
expect(res.headers.get("content-type")).toEqual("application/zip");
expect(res.headers.get("content-disposition")).toContain(
`filename="export-test.zip"`
);
const location = `attachments/${attachment.id}.png`;
const entries = await readZipResponse(res);
expect(Object.keys(entries).sort()).toEqual([location, "export-test.md"]);
expect(entries[location]).toEqual("image-data");
expect(entries["export-test.md"]).toContain(location);
expect(entries["export-test.md"]).not.toContain(attachment.redirectUrl);
});
it("should require authorization without token", async () => {
const document = await buildDocument();
const res = await server.post("/api/documents.export", {
@@ -3456,6 +3505,17 @@ describe("#documents.create", () => {
expect(body.data.title).toEqual("");
});
it("should not create a document with text over the maximum length", async () => {
const user = await buildUser();
const res = await server.post("/api/documents.create", user, {
body: {
title: "title",
text: "a".repeat(DocumentValidation.maxLength + 1),
},
});
expect(res.status).toEqual(400);
});
it("should use template title when doc is created using a template and title is not explicitly passed", async () => {
const user = await buildUser();
const template = await buildTemplate({
@@ -3794,6 +3854,21 @@ describe("#documents.update", () => {
expect(events.length).toEqual(1);
});
it("should not update a document with text over the maximum length", async () => {
const user = await buildUser();
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
});
const res = await server.post("/api/documents.update", user, {
body: {
id: document.id,
text: "a".repeat(DocumentValidation.maxLength + 1),
},
});
expect(res.status).toEqual(400);
});
it("should not allow publishing a draft without specifying the collection", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
+11 -1
View File
@@ -958,7 +958,7 @@ router.post(
return;
}
await streamZipResponse(ctx, `${fileName}.zip`, async (zip) => {
streamZipResponse(ctx, `${fileName}.zip`, (zip) => {
for (const { attachment, buffer } of externalAttachments) {
const location = path.join(
"attachments",
@@ -982,6 +982,7 @@ router.post(
router.post(
"documents.restore",
auth({ role: UserRole.Member }),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
validate(T.DocumentsRestoreSchema),
transaction(),
async (ctx: APIContext<T.DocumentsRestoreReq>) => {
@@ -1326,6 +1327,7 @@ router.post(
router.post(
"documents.duplicate",
auth(),
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
validate(T.DocumentsDuplicateSchema),
transaction(),
async (ctx: APIContext<T.DocumentsDuplicateReq>) => {
@@ -1384,6 +1386,7 @@ router.post(
router.post(
"documents.move",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
validate(T.DocumentsMoveSchema),
transaction(),
async (ctx: APIContext<T.DocumentsMoveReq>) => {
@@ -1439,6 +1442,7 @@ router.post(
router.post(
"documents.archive",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
validate(T.DocumentsArchiveSchema),
transaction(),
async (ctx: APIContext<T.DocumentsArchiveReq>) => {
@@ -1465,6 +1469,7 @@ router.post(
router.post(
"documents.delete",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
validate(T.DocumentsDeleteSchema),
transaction(),
async (ctx: APIContext<T.DocumentsDeleteReq>) => {
@@ -1509,6 +1514,7 @@ router.post(
router.post(
"documents.unpublish",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerMinute),
validate(T.DocumentsUnpublishSchema),
transaction(),
async (ctx: APIContext<T.DocumentsUnpublishReq>) => {
@@ -1793,6 +1799,7 @@ router.post(
router.post(
"documents.remove_user",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerHour),
validate(T.DocumentsRemoveUserSchema),
transaction(),
async (ctx: APIContext<T.DocumentsRemoveUserReq>) => {
@@ -1838,6 +1845,7 @@ router.post(
router.post(
"documents.add_group",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerHour),
validate(T.DocumentsAddGroupSchema),
transaction(),
async (ctx: APIContext<T.DocumentsAddGroupsReq>) => {
@@ -1898,6 +1906,7 @@ router.post(
router.post(
"documents.remove_group",
auth(),
rateLimiter(RateLimiterStrategy.OneHundredPerHour),
validate(T.DocumentsRemoveGroupSchema),
transaction(),
async (ctx: APIContext<T.DocumentsRemoveGroupReq>) => {
@@ -2064,6 +2073,7 @@ router.post(
router.post(
"documents.empty_trash",
auth({ role: UserRole.Admin }),
rateLimiter(RateLimiterStrategy.TenPerHour),
async (ctx: APIContext) => {
const { user } = ctx.state.auth;
+3 -2
View File
@@ -8,6 +8,7 @@ import {
TextEditMode,
SortFilter,
} from "@shared/types";
import { DocumentValidation } from "@shared/validations";
import { BaseSchema } from "@server/routes/api/schema";
import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod";
import { ValidateColor } from "@server/validation";
@@ -264,7 +265,7 @@ export const DocumentsUpdateSchema = BaseSchema.extend({
title: z.string().optional(),
/** Doc text to be updated */
text: z.string().optional(),
text: z.string().max(DocumentValidation.maxLength).optional(),
/** Icon displayed alongside doc title */
icon: zodIconType().nullish(),
@@ -428,7 +429,7 @@ export const DocumentsCreateSchema = BaseSchema.extend({
title: z.string().optional(),
/** Document text */
text: z.string().optional(),
text: z.string().max(DocumentValidation.maxLength).optional(),
/** Icon displayed alongside doc title */
icon: zodIconType().optional(),
@@ -1,8 +1,19 @@
import { FileOperationState, FileOperationType } from "@shared/types";
import { Collection, User, Event, FileOperation } from "@server/models";
import {
CollectionPermission,
FileOperationState,
FileOperationType,
} from "@shared/types";
import {
Collection,
User,
Event,
FileOperation,
UserMembership,
} from "@server/models";
import {
buildAdmin,
buildCollection,
buildDocument,
buildFileOperation,
buildTeam,
buildUser,
@@ -37,6 +48,47 @@ describe("#fileOperations.info", () => {
});
it("should allow user to read their own export", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({ teamId: team.id });
const exportData = await buildFileOperation({
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const res = await server.post("/api/fileOperations.info", user, {
body: {
id: exportData.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.id).toBe(exportData.id);
});
it("should not allow user to read their own export of a collection they lost access to", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
});
const exportData = await buildFileOperation({
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const res = await server.post("/api/fileOperations.info", user, {
body: {
id: exportData.id,
},
});
expect(res.status).toEqual(403);
});
it("should not allow demoted admin to read their own workspace export", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const exportData = await buildFileOperation({
@@ -49,9 +101,7 @@ describe("#fileOperations.info", () => {
id: exportData.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.id).toBe(exportData.id);
expect(res.status).toEqual(403);
});
it("should not allow user to read another user's export", async () => {
@@ -307,11 +357,13 @@ describe("#fileOperations.redirect", () => {
it("should allow user to redirect their own export", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({ teamId: team.id });
const exportData = await buildFileOperation({
state: FileOperationState.Complete,
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const res = await server.post("/api/fileOperations.redirect", user, {
body: {
@@ -322,6 +374,110 @@ describe("#fileOperations.redirect", () => {
expect(res.status).toEqual(302);
});
it("should not allow user to redirect their own export of a collection they lost access to", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
});
const exportData = await buildFileOperation({
state: FileOperationState.Complete,
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const res = await server.post("/api/fileOperations.redirect", user, {
body: {
id: exportData.id,
},
redirect: "manual",
});
expect(res.status).toEqual(403);
});
it("should allow user to redirect their own export of a private collection they are a member of", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
});
await UserMembership.create({
createdById: user.id,
collectionId: collection.id,
userId: user.id,
permission: CollectionPermission.Admin,
});
const exportData = await buildFileOperation({
state: FileOperationState.Complete,
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const res = await server.post("/api/fileOperations.redirect", user, {
body: {
id: exportData.id,
},
redirect: "manual",
});
expect(res.status).toEqual(302);
});
it("should allow user to redirect their own document export", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({ teamId: team.id });
const document = await buildDocument({
teamId: team.id,
userId: user.id,
collectionId: collection.id,
});
const exportData = await buildFileOperation({
state: FileOperationState.Complete,
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
documentId: document.id,
});
const res = await server.post("/api/fileOperations.redirect", user, {
body: {
id: exportData.id,
},
redirect: "manual",
});
expect(res.status).toEqual(302);
});
it("should not allow user to redirect their own document export after losing access", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
teamId: team.id,
permission: null,
});
const document = await buildDocument({
teamId: team.id,
collectionId: collection.id,
});
const exportData = await buildFileOperation({
state: FileOperationState.Complete,
type: FileOperationType.Export,
teamId: team.id,
userId: user.id,
documentId: document.id,
});
const res = await server.post("/api/fileOperations.redirect", user, {
body: {
id: exportData.id,
},
redirect: "manual",
});
expect(res.status).toEqual(403);
});
it("should not allow user to redirect another user's export", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
@@ -24,6 +24,7 @@ router.post(
const { user } = ctx.state.auth;
const fileOperation = await FileOperation.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
});
@@ -77,7 +78,8 @@ const handleFileOperationsRedirect = async (
const id = (ctx.input.body.id ?? ctx.input.query.id) as string;
const { user } = ctx.state.auth;
const fileOperation = await FileOperation.unscoped().findByPk(id, {
const fileOperation = await FileOperation.findByPk(id, {
userId: user.id,
rejectOnEmpty: true,
});
authorize(user, "read", fileOperation);
@@ -90,17 +92,14 @@ const handleFileOperationsRedirect = async (
ctx.redirect(accessUrl);
};
router.get(
router.register(
"fileOperations.redirect",
auth(),
validate(T.FileOperationsRedirectSchema),
handleFileOperationsRedirect
);
router.post(
"fileOperations.redirect",
auth(),
validate(T.FileOperationsRedirectSchema),
handleFileOperationsRedirect
["get", "post"],
[
auth(),
validate(T.FileOperationsRedirectSchema),
handleFileOperationsRedirect,
]
);
router.post(
+1 -5
View File
@@ -131,11 +131,7 @@ if (env.isDevelopment) {
router.use("/", developer.routes());
}
router.post("*", (ctx) => {
ctx.throw(NotFoundError("Endpoint not found"));
});
router.get("*", (ctx) => {
router.register("*", ["get", "post"], (ctx) => {
ctx.throw(NotFoundError("Endpoint not found"));
});
@@ -232,21 +232,33 @@ describe("#relationships.list", () => {
expect(body.message).toEqual("Authentication required");
});
it("should succeed with status 200 ok returning all relationships", async () => {
it("should fail with status 400 bad request when no anchor document is supplied", async () => {
const res = await server.post("/api/relationships.list", admin);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data).toBeTruthy();
expect(body.data.relationships).toBeTruthy();
expect(body.data.relationships.length).toBeGreaterThanOrEqual(3);
expect(body.data.documents).toBeTruthy();
expect(body.pagination).toBeTruthy();
expect(body.policies).toBeTruthy();
expect(res.status).toEqual(400);
expect(body.message).toContain(
"One of documentId or reverseDocumentId is required"
);
});
it("should fail with status 400 bad request when both anchor documents are supplied", async () => {
const res = await server.post("/api/relationships.list", admin, {
body: {
documentId: documents[0].id,
reverseDocumentId: documents[1].id,
},
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toContain(
"One of documentId or reverseDocumentId is required"
);
});
it("should succeed with status 200 ok returning relationships filtered by type", async () => {
const res = await server.post("/api/relationships.list", admin, {
body: {
documentId: documents[0].id,
type: RelationshipType.Backlink,
},
});
@@ -339,6 +351,7 @@ describe("#relationships.list", () => {
it("should respect pagination", async () => {
const res = await server.post("/api/relationships.list", admin, {
body: {
documentId: documents[1].id,
limit: 1,
offset: 0,
},
@@ -351,16 +364,31 @@ describe("#relationships.list", () => {
expect(body.pagination.offset).toEqual(0);
});
it("should return empty results when no relationships match filters", async () => {
it("should fail with status 404 not found when the anchor document does not exist", async () => {
const res = await server.post("/api/relationships.list", admin, {
body: {
documentId: "550e8400-e29b-41d4-a716-446655440000",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.relationships).toHaveLength(0);
expect(body.data.documents).toHaveLength(0);
expect(res.status).toEqual(404);
});
it("should fail with status 403 forbidden when user cannot read the anchor document", async () => {
const cannotAccessCollection = await buildCollection({
teamId: user.teamId,
permission: null,
});
const cannotAccessDocument = await buildDocument({
collectionId: cannotAccessCollection.id,
teamId: user.teamId,
});
const res = await server.post("/api/relationships.list", user, {
body: {
documentId: cannotAccessDocument.id,
},
});
expect(res.status).toEqual(403);
});
it("should only return documents that the user can read", async () => {
@@ -400,4 +428,39 @@ describe("#relationships.list", () => {
expect(body.data.relationships).toHaveLength(0);
expect(body.data.documents).toHaveLength(0);
});
it("should not disclose documents that the user cannot read when anchored on reverseDocumentId", async () => {
const cannotAccessCollection = await buildCollection({
teamId: user.teamId,
permission: null,
});
const collection = await buildCollection({
teamId: user.teamId,
permission: CollectionPermission.Read,
});
const userDocument = await buildDocument({
collectionId: collection.id,
teamId: user.teamId,
});
const cannotAccessDocument = await buildDocument({
collectionId: cannotAccessCollection.id,
teamId: user.teamId,
});
await buildRelationship({
userId: user.id,
documentId: cannotAccessDocument.id,
reverseDocumentId: userDocument.id,
});
const res = await server.post("/api/relationships.list", user, {
body: {
reverseDocumentId: userDocument.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.relationships).toHaveLength(0);
expect(body.data.documents).toHaveLength(0);
});
});
@@ -1,4 +1,5 @@
import Router from "koa-router";
import { InvalidRequestError } from "@server/errors";
import auth from "@server/middlewares/authentication";
import validate from "@server/middlewares/validate";
import { Document, Relationship } from "@server/models";
@@ -58,32 +59,48 @@ router.post(
pagination(),
validate(T.RelationshipsListSchema),
async (ctx: APIContext<T.RelationshipsListReq>) => {
const { type, documentId, reverseDocumentId } = ctx.input.body;
const { user } = ctx.state.auth;
const where = ctx.input.body || {};
// Results are anchored to a single document, which the user must be able to
// read. Documents on the opposite side of each relationship are filtered by
// access below.
const anchorId = documentId ?? reverseDocumentId;
if (!anchorId) {
throw InvalidRequestError(
"One of documentId or reverseDocumentId is required"
);
}
const anchorDocument = await Document.findByPk(anchorId, {
userId: user.id,
rejectOnEmpty: true,
});
authorize(user, "read", anchorDocument);
const relationships = await Relationship.findAll({
where,
where: {
...(type ? { type } : {}),
...(documentId
? { documentId: anchorDocument.id }
: { reverseDocumentId: anchorDocument.id }),
},
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
});
const relatedDocumentId = (relationship: Relationship) =>
documentId ? relationship.reverseDocumentId : relationship.documentId;
const documents = await Document.findByIds(
relationships.flatMap((relationship) =>
where.reverseDocumentId
? relationship.documentId
: relationship.reverseDocumentId
),
relationships.map(relatedDocumentId),
{ userId: user.id }
);
const documentIds = new Set(documents.map((d) => d.id));
const filteredRelationships = relationships.filter((relationship) =>
documentIds.has(
where.reverseDocumentId
? relationship.documentId
: relationship.reverseDocumentId
)
documentIds.has(relatedDocumentId(relationship))
);
ctx.body = {
+4 -1
View File
@@ -28,7 +28,10 @@ export const RelationshipsListSchema = BaseSchema.extend({
})
.optional(),
})
.optional(),
.refine(
(body) => !!body.documentId !== !!body.reverseDocumentId,
"One of documentId or reverseDocumentId is required"
),
});
export type RelationshipsListReq = z.infer<typeof RelationshipsListSchema>;
+50 -1
View File
@@ -1,12 +1,14 @@
import { createContext } from "@server/context";
import { UserMembership, Revision } from "@server/models";
import FileStorage from "@server/storage/files";
import {
buildAdmin,
buildAttachment,
buildCollection,
buildDocument,
buildUser,
} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import { getTestServer, readZipResponse } from "@server/test/support";
const server = getTestServer();
@@ -245,6 +247,53 @@ describe("#revisions.list", () => {
});
describe("#revisions.export", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("should stream a zip when the revision has attachments", async () => {
const user = await buildUser();
const attachment = await buildAttachment({
teamId: user.teamId,
userId: user.id,
});
const document = await buildDocument({
title: "Export Test",
userId: user.id,
teamId: user.teamId,
text: `![image](${attachment.redirectUrl})`,
});
const revision = await Revision.createFromDocument(
createContext({ user }),
document
);
vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue(
Buffer.from("image-data")
);
const res = await server.post("/api/revisions.export", user, {
body: {
id: revision.id,
},
headers: {
accept: "text/markdown",
},
});
expect(res.status).toEqual(200);
expect(res.headers.get("content-type")).toEqual("application/zip");
expect(res.headers.get("content-disposition")).toContain(
`filename="export-test.zip"`
);
const location = `attachments/${attachment.id}.png`;
const entries = await readZipResponse(res);
expect(Object.keys(entries).sort()).toEqual([location, "export-test.md"]);
expect(entries[location]).toEqual("image-data");
expect(entries["export-test.md"]).toContain(location);
expect(entries["export-test.md"]).not.toContain(attachment.redirectUrl);
});
it("should return revision as markdown by default", async () => {
const user = await buildUser();
const document = await buildDocument({
+1 -1
View File
@@ -195,7 +195,7 @@ router.post(
return;
}
await streamZipResponse(ctx, `${fileName}.zip`, async (zip) => {
streamZipResponse(ctx, `${fileName}.zip`, async (zip) => {
for (const attachment of attachments) {
const location = path.join(
"attachments",
+66
View File
@@ -177,6 +177,27 @@ describe("#shares.list", () => {
expect(body.data[0].documentTitle).toBe(document.title);
});
it("admins should return shares created by a deleted user", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({ userId: admin.id, teamId: team.id });
const share = await buildShare({
documentId: document.id,
teamId: team.id,
userId: user.id,
});
await user.destroy();
const res = await server.post("/api/shares.list", admin);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toEqual(1);
expect(body.pagination.total).toEqual(1);
expect(body.data[0].id).toEqual(share.id);
expect(body.data[0].createdBy).toBeUndefined();
});
it("admins should not return shares in collection not a member of", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
@@ -703,6 +724,51 @@ describe("#shares.info", () => {
expect(body.data.shares[0].id).toEqual(share.id);
});
it("should not return the sharer for an unauthenticated viewer", async () => {
const user = await buildUser();
const document = await buildDocument({
createdById: user.id,
teamId: user.teamId,
});
const share = await buildShare({
documentId: document.id,
teamId: user.teamId,
userId: user.id,
published: true,
});
const res = await server.post("/api/shares.info", {
body: {
id: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.shares[0].id).toEqual(share.id);
expect(body.data.shares[0].createdBy).toBeUndefined();
});
it("should return the sharer for a viewer with access to the share", async () => {
const user = await buildUser();
const document = await buildDocument({
createdById: user.id,
teamId: user.teamId,
});
const share = await buildShare({
documentId: document.id,
teamId: user.teamId,
userId: user.id,
published: true,
});
const res = await server.post("/api/shares.info", user, {
body: {
id: share.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.shares[0].createdBy.id).toEqual(user.id);
});
it("should allow reading share by documentId", async () => {
const user = await buildUser();
const document = await buildDocument({
+14 -5
View File
@@ -104,7 +104,12 @@ router.post(
ctx.body = {
data: {
shares: [presentShare(share, user?.isAdmin ?? false)],
shares: [
presentShare(share, {
isAdmin: user?.isAdmin ?? false,
isPublic: cannot(user, "read", share),
}),
],
sharedTree,
team: serializedTeam,
collection: serializedCollection,
@@ -135,7 +140,9 @@ router.post(
ctx.body = {
data: {
shares: shares.map((s) => presentShare(s, user.isAdmin ?? false)),
shares: shares.map((s) =>
presentShare(s, { isAdmin: user.isAdmin ?? false })
),
},
policies: presentPolicies(user, shares),
};
@@ -221,7 +228,7 @@ router.post(
},
{
model: User,
required: true,
required: false,
as: "user",
},
{
@@ -245,7 +252,9 @@ router.post(
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: shares.map((share) => presentShare(share, user.isAdmin)),
data: shares.map((share) =>
presentShare(share, { isAdmin: user.isAdmin })
),
policies: presentPolicies(user, shares),
};
}
@@ -406,7 +415,7 @@ router.post(
await share.saveWithCtx(ctx);
ctx.body = {
data: presentShare(share, user.isAdmin),
data: presentShare(share, { isAdmin: user.isAdmin }),
policies: presentPolicies(user, [share]),
};
}
+9 -48
View File
@@ -12,8 +12,7 @@ import Logger from "@server/logging/Logger";
import Metrics from "@server/logging/Metrics";
import * as Tracing from "@server/logging/tracer";
import { traceFunction } from "@server/logging/tracing";
import { Collection, Group, User } from "@server/models";
import { can } from "@server/policies";
import type { User } from "@server/models";
import Redis from "@server/storage/redis";
import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper";
import { getUserForJWT } from "@server/utils/jwt";
@@ -183,9 +182,14 @@ async function authenticated(
// and user so we can send authenticated events
const rooms = [`team-${user.teamId}`, `user-${user.id}`];
// the rooms associated with collections this user has access to on
// connection. New collection and group subscriptions are managed
// from the client as needed through the 'join' event.
// the room of non-guest team members, who have access to all
// team-visible collections.
if (!user.isGuest) {
rooms.push(`team-${user.teamId}.members`);
}
// the rooms associated with collections and groups this user
// has access to on connection.
const [collectionIds, groupIds] = await Promise.all([
user.collectionIds(),
user.groupIds(),
@@ -194,49 +198,6 @@ async function authenticated(
collectionIds.forEach((colId) => rooms.push(`collection-${colId}`));
groupIds.forEach((groupId) => rooms.push(`group-${groupId}`));
const { id: userId } = user;
// allow the client to request to join rooms
socket.on("join", async (event) => {
// The user is reloaded here rather than captured by this handler so the
// full model is not retained for the lifetime of the connection.
const authUser = await User.findByPk(userId);
if (!authUser) {
return;
}
// user is joining a collection channel, because their permissions have
// changed, granting them access.
if (event.collectionId) {
const collection = await Collection.findByPk(event.collectionId, {
userId: authUser.id,
});
if (can(authUser, "read", collection)) {
await socket.join(`collection-${event.collectionId}`);
}
}
if (event.groupId) {
const group = await Group.scope({
method: ["withMembership", authUser.id],
}).findByPk(event.groupId);
if (can(authUser, "read", group)) {
await socket.join(`group-${event.groupId}`);
}
}
});
// allow the client to request to leave rooms
socket.on("leave", async (event) => {
if (event.collectionId) {
await socket.leave(`collection-${event.collectionId}`);
}
if (event.groupId) {
await socket.leave(`group-${event.groupId}`);
}
});
// join all of the rooms at once
await socket.join(rooms);
}
+29
View File
@@ -638,6 +638,35 @@ export async function buildAttachment(
});
}
/**
* Build a collection holding one document that references one attachment,
* along with a file operation to export it with.
*
* @param overrides Optional team and user to build the records under.
* @returns the created collection, document, attachment and file operation.
*/
export async function buildDocumentWithAttachment(
overrides: { teamId?: string; userId?: string } = {}
) {
const teamId = overrides.teamId ?? (await buildTeam()).id;
const userId = overrides.userId ?? (await buildUser({ teamId })).id;
const collection = await buildCollection({ teamId, createdById: userId });
const attachment = await buildAttachment({ teamId, userId });
const document = await buildDocument({
teamId,
userId,
collectionId: collection.id,
title: "Test",
text: `![image](${attachment.redirectUrl})`,
});
await collection.addDocumentToStructure(document);
const fileOperation = await buildFileOperation({ teamId, userId });
return { collection, document, attachment, fileOperation };
}
export async function buildEmoji(
overrides: Partial<Emoji> = {}
): Promise<Emoji> {
+30
View File
@@ -1,3 +1,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { faker } from "@faker-js/faker";
import type { Transaction } from "sequelize";
import { afterEach, beforeEach, vi } from "vitest";
@@ -11,6 +15,7 @@ import webService from "@server/services/web";
import { sequelize } from "@server/storage/database";
import type { APIContext } from "@server/types";
import { AuthenticationType } from "@server/types";
import ZipHelper from "@server/utils/ZipHelper";
import TestServer from "./TestServer";
export function getTestServer() {
@@ -78,6 +83,31 @@ export function withAPIContext<T>(
});
}
/**
* Read a zip archive returned from an API endpoint into memory.
*
* @param res The response to read the archive from.
* @returns a map of entry filename to the entry contents as a string.
*/
export async function readZipResponse(
res: Awaited<ReturnType<TestServer["post"]>>
): Promise<Record<string, string>> {
const filePath = path.join(os.tmpdir(), `test-${randomUUID()}.zip`);
await fs.writeFile(filePath, Buffer.from(await res.arrayBuffer()));
try {
const entries: Record<string, string> = {};
await ZipHelper.walk(filePath, async (entry) => {
entries[entry.fileName] = (
await entry.readBuffer(1024 * 1024)
).toString();
});
return entries;
} finally {
await fs.rm(filePath, { force: true });
}
}
/**
* Helper function to convert an object to form-urlencoded string.
* Useful for testing OAuth endpoints that expect application/x-www-form-urlencoded content type.
+5
View File
@@ -2,6 +2,11 @@ import "yazl";
declare module "yazl" {
interface Options {
/**
* Upstream types only declare `fileComment` for entries added from a file
* or stream, and only as a string. yazl reads it for every entry type —
* `addBuffer` included — and accepts a Buffer as well.
*/
fileComment: string | Buffer;
}
}
+121
View File
@@ -1,6 +1,8 @@
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import fs from "fs-extra";
import tmp from "tmp";
import { vi } from "vitest";
import { ZipFile } from "yazl";
import ZipHelper from "./ZipHelper";
@@ -19,6 +21,125 @@ async function writeZip(
return zipPath;
}
/**
* Watch for the temporary file toTmpFile writes to, so that cleanup can be
* asserted against that exact path rather than by scanning the shared temp
* directory, which tests running in parallel also write to.
*/
function watchTmpFile() {
const createWriteStream = vi.spyOn(fs, "createWriteStream");
return () => {
expect(createWriteStream).toHaveBeenCalledTimes(1);
return String(createWriteStream.mock.calls[0][0]);
};
}
async function readZip(filePath: string): Promise<Record<string, string>> {
const contents: Record<string, string> = {};
await ZipHelper.walk(filePath, async (entry) => {
if (!entry.isDirectory) {
contents[entry.fileName] = (await entry.readBuffer(1024)).toString(
"utf8"
);
}
});
return contents;
}
describe("ZipHelper.toTmpFile", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("writes buffered and streamed entries to a temporary file", async () => {
const filePath = await ZipHelper.toTmpFile(async (zip) => {
zip.addBuffer(Buffer.from("hello"), "a.txt");
zip.addReadStreamLazy("b.txt", {}, (callback) =>
callback(null, Readable.from(["wo", "rld"]))
);
await Promise.resolve();
});
expect(await readZip(filePath)).toEqual({
"a.txt": "hello",
"b.txt": "world",
});
await fs.remove(filePath);
});
it("opens each lazy stream only when its entry is written", async () => {
const opened: string[] = [];
const filePath = await ZipHelper.toTmpFile(async (zip) => {
for (const name of ["a.txt", "b.txt", "c.txt"]) {
zip.addReadStreamLazy(name, {}, (callback) => {
opened.push(name);
callback(null, Readable.from([name]));
});
}
await Promise.resolve();
// Nothing is read up front — sources are opened one at a time as the
// archive is pumped, so only one file is ever held open.
expect(opened.length).toBeLessThan(3);
});
expect(opened).toEqual(["a.txt", "b.txt", "c.txt"]);
await fs.remove(filePath);
});
it("propagates errors thrown while adding entries and cleans up", async () => {
const tmpFile = watchTmpFile();
await expect(
ZipHelper.toTmpFile(async (zip) => {
zip.addBuffer(Buffer.from("partial"), "a.txt");
await Promise.resolve();
throw new Error("boom");
})
).rejects.toThrow("boom");
expect(await fs.pathExists(tmpFile())).toBe(false);
});
it("propagates errors raised when opening an entry and cleans up", async () => {
const tmpFile = watchTmpFile();
await expect(
ZipHelper.toTmpFile(async (zip) => {
zip.addReadStreamLazy("a.txt", {}, (callback) =>
callback(new Error("stream unavailable"), Readable.from([]))
);
await Promise.resolve();
})
).rejects.toThrow("stream unavailable");
expect(await fs.pathExists(tmpFile())).toBe(false);
});
it("fails rather than stalls when an entry's stream errors mid-read", async () => {
const tmpFile = watchTmpFile();
await expect(
ZipHelper.toTmpFile(async (zip) => {
const source = new Readable({
read() {
this.push("partial");
this.destroy(new Error("connection reset"));
},
});
// Mirrors how ExportTask surfaces an interrupted read, which yazl
// does not watch for on the streams it is given.
source.on("error", (err) => zip.emit("error", err));
zip.addReadStreamLazy("a.txt", {}, (callback) =>
callback(null, source)
);
await Promise.resolve();
})
).rejects.toThrow("connection reset");
expect(await fs.pathExists(tmpFile())).toBe(false);
});
});
describe("ZipHelper.toFileTree", () => {
it("builds a nested tree with normalized pathInZip", async () => {
const zipPath = await writeZip({
+50 -14
View File
@@ -4,7 +4,7 @@ import fs from "fs-extra";
import tmp from "tmp";
import type { Entry } from "yauzl";
import yauzl, { validateFileName } from "yauzl";
import type { ZipFile } from "yazl";
import { ZipFile } from "yazl";
import { bytesToHumanReadable } from "@shared/utils/files";
import { ValidationError } from "@server/errors";
import Logger from "@server/logging/Logger";
@@ -46,33 +46,56 @@ export default class ZipHelper {
/**
* Write a zip file to a temporary disk location.
*
* The caller is responsible for adding entries to the `ZipFile`; this method
* calls `end()` and waits for the output stream to drain to disk.
* Entries are added by the `addEntries` callback, which receives an archive
* that is already draining to disk. Adding entries only after a reader is
* attached keeps memory proportional to a single entry rather than to the
* size of the whole archive.
*
* @param zip yazl ZipFile object with entries already added.
* @param addEntries Callback that populates the archive.
* @returns pathname of the temporary file where the zip was written to disk.
* @throws if the archive could not be built or written to disk.
*/
public static async toTmpFile(zip: ZipFile): Promise<string> {
public static async toTmpFile(
addEntries: (zip: ZipFile) => Promise<void>
): Promise<string> {
Logger.debug("utils", "Creating tmp file…");
const filePath = await createTmpFile({
prefix: "export-",
postfix: ".zip",
});
const zip = new ZipFile();
const writeStream = fs.createWriteStream(filePath);
// yazl reports failures on the archive rather than on its output stream,
// so route them into the pipeline to get a single failure path.
zip.on("error", (error: Error) => writeStream.destroy(error));
const writing = pipeline(zip.outputStream, writeStream);
// Resolve rather than reject, so that a write failure while entries are
// still being added is never an unhandled rejection.
const written = writing.then(
() => undefined,
(error: Error) => error
);
try {
const writing = pipeline(
zip.outputStream,
fs.createWriteStream(filePath)
);
await addEntries(zip);
zip.end();
await writing;
} catch (error) {
await fs.remove(filePath).catch((rmErr) => {
Logger.error("Failed to remove tmp file", rmErr);
});
// Unblock the pipeline, which is still waiting on entries that will now
// never arrive.
writeStream.destroy();
await written;
await removeTmpFile(filePath);
throw error;
}
const writeError = await written;
if (writeError) {
await removeTmpFile(filePath);
throw writeError;
}
Logger.debug("utils", "Writing zip complete", { path: filePath });
return filePath;
}
@@ -293,12 +316,25 @@ export default class ZipHelper {
/**
* Promisified wrapper around tmp.file.
*
* The descriptor tmp opens is discarded, as the file is written through a
* separate stream — retaining it would leak a descriptor per call.
*
* @param options options passed through to tmp.
* @returns the path of the created temporary file.
*/
const createTmpFile = (options: tmp.FileOptions) =>
new Promise<string>((resolve, reject) => {
tmp.file(options, (err, filePath) =>
tmp.file({ ...options, discardDescriptor: true }, (err, filePath) =>
err ? reject(err) : resolve(filePath)
);
});
/**
* Delete a temporary file, logging rather than throwing on failure.
*
* @param filePath the path of the file to remove.
*/
const removeTmpFile = (filePath: string) =>
fs.remove(filePath).catch((error) => {
Logger.error("Failed to remove tmp file", error);
});
+15 -6
View File
@@ -36,13 +36,12 @@ export const getFileFromRequest = (
* @param fileName The filename to advertise in the Content-Disposition header.
* @param build Callback that adds entries to the provided ZipFile.
*/
export const streamZipResponse = async (
export const streamZipResponse = (
ctx: Context,
fileName: string,
build: (zip: ZipFile) => void | Promise<void>
): Promise<void> => {
): void => {
const zip = new ZipFile();
await build(zip);
ctx.set("Content-Type", "application/zip");
ctx.set(
@@ -50,10 +49,20 @@ export const streamZipResponse = async (
contentDisposition(fileName, { type: "attachment" })
);
zip.outputStream.on("error", (err) => {
const handleError = (err: Error) => {
ctx.app.emit("error", err, ctx);
ctx.res.destroy(err);
});
};
zip.outputStream.on("error", handleError);
ctx.body = zip.outputStream;
zip.end();
void (async () => {
try {
await build(zip);
zip.end();
} catch (err) {
handleError(err instanceof Error ? err : new Error(String(err)));
}
})();
};
+1 -1
View File
@@ -5,7 +5,7 @@ import breakpoint from "styled-components-breakpoint";
import useStores from "../hooks/useStores";
import { IconType } from "../types";
import { IconLibrary } from "../utils/IconLibrary";
import { colorPalette } from "../utils/collections";
import { colorPalette } from "../constants";
import { determineIconType } from "../utils/icon";
import EmojiIcon from "./EmojiIcon";
import Flex from "./Flex";
+15
View File
@@ -10,6 +10,21 @@ import {
export const MAX_AVATAR_DISPLAY = 6;
/** Preset colors offered when choosing an icon color. */
export const colorPalette = [
"#4E5C6E",
"#0366D6",
"#2BC2FF",
"#9E5CF7",
"#FF825C",
"#FF5C80",
"#FFBE0B",
"#42DED1",
"#00D084",
"#FF4DFA",
"#2F362F",
];
export const Pagination = {
defaultLimit: 25,
defaultOffset: 0,
+30 -3
View File
@@ -1,6 +1,7 @@
import { TextSelection } from "prosemirror-state";
import { createEditorState, codeBlock, doc } from "@shared/test/editor";
import { indentInCode, outdentInCode } from "./codeFence";
import { baseKeymap, chainCommands } from "prosemirror-commands";
import { NodeSelection, TextSelection } from "prosemirror-state";
import { createEditorState, codeBlock, doc, p } from "@shared/test/editor";
import { enterInCode, indentInCode, outdentInCode } from "./codeFence";
/**
* Helper that runs a command against a code block document with the given
@@ -135,3 +136,29 @@ describe("indentInCode", () => {
expect(text).toBe("a\n b\n c");
});
});
describe("enterInCode", () => {
it("adds a paragraph below when the code block is selected", () => {
const testDoc = doc([
p("before"),
codeBlock("graph TD; A-->B", "mermaidjs"),
]);
let state = createEditorState(testDoc);
const pos = state.doc.firstChild!.nodeSize;
state = state.apply(
state.tr.setSelection(NodeSelection.create(state.doc, pos))
);
const handled = chainCommands(enterInCode, baseKeymap.Enter)(
state,
(tr) => {
state = state.apply(tr);
}
);
expect(handled).toBe(true);
expect(state.doc.child(1).textContent).toBe("graph TD; A-->B");
expect(state.doc.lastChild?.type.name).toBe("paragraph");
expect(state.doc.childCount).toBe(3);
});
});
+4 -2
View File
@@ -1,6 +1,6 @@
import { exitCode } from "prosemirror-commands";
import type { Command, EditorState } from "prosemirror-state";
import { TextSelection } from "prosemirror-state";
import { NodeSelection, TextSelection } from "prosemirror-state";
import { findNextNewline, findPreviousNewline } from "../queries/findNewlines";
import { isInCode } from "../queries/isInCode";
import { findParentNode } from "../queries/findParentNode";
@@ -67,7 +67,9 @@ export const moveToNextNewline: Command = (state, dispatch) => {
* @returns A prosemirror command
*/
export const newlineInCode: Command = (state, dispatch) => {
if (!isInCode(state)) {
// A selected code block has no cursor to insert a newline at, and replacing
// it with one would delete the block.
if (state.selection instanceof NodeSelection || !isInCode(state)) {
return false;
}
const { tr, selection } = state;
+25 -9
View File
@@ -322,6 +322,7 @@ function getNewState({
autoEditEmpty?: boolean;
}): MermaidState {
const decorations: Decoration[] = [];
const usedRenderers = new Set<MermaidRenderer>();
let newEditingId: string | undefined;
// Find all blocks that represent Mermaid diagrams (supports both "mermaid" and "mermaidjs"),
@@ -331,11 +332,25 @@ function getNewState({
);
blocks.forEach((block) => {
const existingDecorations = pluginState.decorationSet.find(
block.pos,
block.pos + block.node.nodeSize,
(spec) => !!spec.diagramId
);
const existingDecorations = pluginState.decorationSet
.find(
block.pos,
block.pos + block.node.nodeSize,
(spec) => !!spec.diagramId
)
// A widget sitting exactly at the start of this block belongs to the
// preceding diagram, whose end position is shared with this one.
.filter((decoration) => {
if (
decoration.from === decoration.to &&
decoration.from === block.pos
) {
return false;
}
// Each renderer owns a single DOM element, so it can only back one
// diagram — reusing it would place the same node in two places.
return !usedRenderers.has(decoration.spec.renderer);
});
const bestDecoration = findBestOverlapDecoration(
existingDecorations,
@@ -345,6 +360,7 @@ function getNewState({
const isNewBlock = !bestDecoration;
const renderer: MermaidRenderer =
bestDecoration?.spec?.renderer ?? new MermaidRenderer(editor);
usedRenderers.add(renderer);
// Auto-enter edit mode for newly created empty mermaid diagrams
if (
@@ -355,16 +371,16 @@ function getNewState({
newEditingId = renderer.diagramId;
}
void renderer.render(block, pluginState.isDark);
const diagramDecoration = Decoration.widget(
block.pos + block.node.nodeSize,
() => {
void renderer.render(block, pluginState.isDark);
return renderer.element;
},
() => renderer.element,
{
diagramId: renderer.diagramId,
renderer,
side: -10,
key: `mermaid-${renderer.diagramId}`,
}
);
+37 -7
View File
@@ -1,6 +1,6 @@
import type { Node } from "prosemirror-model";
import { Fragment, Slice } from "prosemirror-model";
import { Plugin } from "prosemirror-state";
import { NodeSelection, Plugin } from "prosemirror-state";
import { v4 as uuidv4 } from "uuid";
import {
getDataTransferFiles,
@@ -45,13 +45,43 @@ export class UploadPlugin extends Plugin {
return false;
}
const { tr } = view.state;
if (!tr.selection.empty) {
tr.deleteSelection();
}
const pos = tr.selection.from;
const { selection } = view.state;
void insertFiles(view, event, pos, files, options);
// With an image selected, pasting a single image replaces it in
// place rather than inserting a second image alongside.
if (
selection instanceof NodeSelection &&
selection.node.type.name === "image" &&
files.length === 1 &&
FileHelper.isImage(files[0].type) &&
!options.isAttachment
) {
const { attrs } = selection.node;
void insertFiles(view, event, selection.from, files, {
...options,
replaceExisting: true,
attrs: {
width: attrs.width,
height: attrs.height,
alt: attrs.alt,
layoutClass: attrs.layoutClass,
},
});
return true;
}
if (!selection.empty) {
view.dispatch(view.state.tr.deleteSelection());
}
void insertFiles(
view,
event,
view.state.selection.from,
files,
options
);
return true;
},
drop(view, event: DragEvent): boolean {
@@ -93,6 +93,15 @@ describe("AuthenticationHelper", () => {
expect(canAccess("/api/documents.memberships", scopes)).toBe(false);
});
it("attachments read scope grants access to redirect", async () => {
const scopes = ["attachments:read"];
expect(canAccess("/api/attachments.info", scopes)).toBe(true);
expect(canAccess("/api/attachments.redirect", scopes)).toBe(true);
expect(canAccess("/api/attachments.create", scopes)).toBe(false);
expect(canAccess("/api/attachments.delete", scopes)).toBe(false);
});
it("write", async () => {
const scopes = ["documents:write"];
@@ -132,6 +141,7 @@ describe("AuthenticationHelper", () => {
expect(canAccess("/api/collections.group_memberships", scopes)).toBe(
true
);
expect(canAccess("/api/attachments.redirect", scopes)).toBe(true);
expect(canAccess("/api/documents.create", scopes)).toBe(false);
expect(canAccess("/api/documents.update", scopes)).toBe(false);
expect(canAccess("/api/users.create", scopes)).toBe(false);
+2
View File
@@ -10,6 +10,7 @@ export default class AuthenticationHelper {
* - `documents.info` -> `Scope.Read`
* - `collections.memberships` -> `Scope.Read`
* - `collections.group_memberships` -> `Scope.Read`
* - `attachments.redirect` -> `Scope.Read`
*/
private static methodToScope = {
create: Scope.Create,
@@ -21,6 +22,7 @@ export default class AuthenticationHelper {
drafts: Scope.Read,
viewed: Scope.Read,
export: Scope.Read,
redirect: Scope.Read,
memberships: Scope.Read,
group_memberships: Scope.Read,
};
@@ -1746,6 +1746,7 @@
"Go to export": "Go to export",
"Here's your request data export from {{ appName }}": "Here's your request data export from {{ appName }}",
"Your requested data export is complete, you can download from the link below in a browser that is logged into your account.": "Your requested data export is complete, you can download from the link below in a browser that is logged into your account.",
"This export will be available to download for {{ days }} days.": "This export will be available to download for {{ days }} days.",
"Download export": "Download export",
"Your requested data export is complete - you can download from the link below in a browser that is logged into your account.": "Your requested data export is complete - you can download from the link below in a browser that is logged into your account.",
"The {{ groupName }} group was mentioned in “{{ documentTitle }}”": "The {{ groupName }} group was mentioned in “{{ documentTitle }}”",
-13
View File
@@ -40,16 +40,3 @@ export const sortNavigationNodes = (
return { ...node, children: sortedChildren };
});
};
export const colorPalette = [
"#4E5C6E",
"#0366D6",
"#9E5CF7",
"#FF825C",
"#FF5C80",
"#FFBE0B",
"#42DED1",
"#00D084",
"#FF4DFA",
"#2F362F",
];
+3
View File
@@ -67,6 +67,9 @@ export const DocumentValidation = {
/** The maximum recommended size of the document content */
maxRecommendedLength: 250000,
/** The maximum length of the document text content */
maxLength: 1500 * 1024,
};
export const GroupValidation = {
+1 -2
View File
@@ -37,8 +37,7 @@
// Vite 8 and its plugins ship types only via their exports map, which
// resolvePackageJsonExports disables; point tsc at their declaration entries.
"vite": ["./node_modules/vite/dist/node/index.d.ts"],
"@vitejs/plugin-react": ["./node_modules/@vitejs/plugin-react/dist/index.d.ts"],
"fuse.js/worker": ["./node_modules/fuse.js/dist/fuse-worker.d.ts"]
"@vitejs/plugin-react": ["./node_modules/@vitejs/plugin-react/dist/index.d.ts"]
}
},
"exclude": ["node_modules", "build", "server/migrations"]
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more