diff --git a/.github/workflows/update-node.yml b/.github/workflows/update-node.yml index 1c17340d86..8fa7974a26 100644 --- a/.github/workflows/update-node.yml +++ b/.github/workflows/update-node.yml @@ -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" diff --git a/.yarnrc.yml b/.yarnrc.yml index 07c071cee6..e2a8e04f87 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -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 diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 1818a499c8..59d55e817f 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -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: , to: searchPath({ query }), visible: ({ location }) => location.pathname !== searchPath(), diff --git a/app/components/Collection/CollectionForm.tsx b/app/components/Collection/CollectionForm.tsx index 6f433eeedf..520e5544ed 100644 --- a/app/components/Collection/CollectionForm.tsx +++ b/app/components/Collection/CollectionForm.tsx @@ -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"; diff --git a/app/components/ColorButton.tsx b/app/components/ColorButton.tsx index 1e59be2b9a..1c3b359a87 100644 --- a/app/components/ColorButton.tsx +++ b/app/components/ColorButton.tsx @@ -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} { diff --git a/app/components/CommandBar/SearchIndex.test.ts b/app/components/CommandBar/SearchIndex.test.ts index 617ee3e107..8fd7640999 100644 --- a/app/components/CommandBar/SearchIndex.test.ts +++ b/app/components/CommandBar/SearchIndex.test.ts @@ -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("revenue"); }); - 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("revenu"); expect(results[0]?.context).not.toContain("numbrs"); expect(results[0]?.context?.match(//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( - "revenu" - ); + expect(index.search("revenu")[0]?.context).toContain("revenu"); }); - 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("revenue numbers"); }); - 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("deployment"); expect(context?.match(//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([]); }); }); diff --git a/app/components/CommandBar/SearchIndex.ts b/app/components/CommandBar/SearchIndex.ts index dbe944360e..8b4f54008e 100644 --- a/app/components/CommandBar/SearchIndex.ts +++ b/app/components/CommandBar/SearchIndex.ts @@ -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 = { ], 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(); - // Workers are unavailable when server rendering and under jsdom, where the - // main-thread implementation stands in with an identical API. - private fuse: Fuse | FuseWorker = - typeof Worker === "undefined" - ? new Fuse([], { ...options, useTokenSearch: true }) - : new FuseWorker([], options, workerOptions); + private fuse = new Fuse([], 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 { + 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. - }); - } } diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index 3f887f5a2e..7c2c88b4d8 100644 --- a/app/components/CommandBar/useSearchIndex.ts +++ b/app/components/CommandBar/useSearchIndex.ts @@ -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([]); 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( + () => (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 }; } diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index caac5675eb..e87b5d814c 100644 --- a/app/components/DefaultCollectionInputSelect.tsx +++ b/app/components/DefaultCollectionInputSelect.tsx @@ -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"; diff --git a/app/components/IconPicker/components/EmojiPanel.tsx b/app/components/IconPicker/components/EmojiPanel.tsx index 494ae2e75c..c396180908 100644 --- a/app/components/IconPicker/components/EmojiPanel.tsx +++ b/app/components/IconPicker/components/EmojiPanel.tsx @@ -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(); + 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 = ({ } /> + ); }; +/** 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, })), }; }; diff --git a/app/components/IconPicker/components/Grid.tsx b/app/components/IconPicker/components/Grid.tsx index 54260530dd..9be2b95de9 100644 --- a/app/components/IconPicker/components/Grid.tsx +++ b/app/components/IconPicker/components/Grid.tsx @@ -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 -) => ( - - {Row} - -); +) => { + 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 ( + + {Row} + + ); +}; type RowProps = { data: React.ReactNode[][]; diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx index 9447495633..27f1df6ae0 100644 --- a/app/components/IconPicker/components/GridTemplate.tsx +++ b/app/components/IconPicker/components/GridTemplate.tsx @@ -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 ) => { 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 ( onIconSelect({ id: item.name, value: item.name })} + onMouseEnter={handleActive} + onFocus={handleActive} style={{ "--delay": `${item.delay}ms` } as React.CSSProperties} > onIconSelect({ id: item.id, value: item.value })} + onMouseEnter={handleActive} + onFocus={handleActive} > ); }; diff --git a/app/components/IconPicker/components/IconColorPicker.tsx b/app/components/IconPicker/components/IconColorPicker.tsx index 4e53c9a56f..3da41cb786 100644 --- a/app/components/IconPicker/components/IconColorPicker.tsx +++ b/app/components/IconPicker/components/IconColorPicker.tsx @@ -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 ( - + - @@ -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; diff --git a/app/components/IconPicker/components/IconPanel.tsx b/app/components/IconPicker/components/IconPanel.tsx index e179b62cd4..2c2d48831a 100644 --- a/app/components/IconPicker/components/IconPanel.tsx +++ b/app/components/IconPicker/components/IconPanel.tsx @@ -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(); + 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} + /> + ); diff --git a/app/components/IconPicker/components/IconPreview.tsx b/app/components/IconPicker/components/IconPreview.tsx new file mode 100644 index 0000000000..a2b31c8d22 --- /dev/null +++ b/app/components/IconPicker/components/IconPreview.tsx @@ -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) => ( + + {icon && ( + <> + + {icon.type === IconType.SVG ? ( + + {icon.initial} + + ) : ( + + {icon.type === IconType.Custom ? ( + + ) : ( + icon.value + )} + + )} + + + + {displayName(icon)} + + + :{shortcode(icon)}: + + + + )} + +); + +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; +`; diff --git a/app/components/Icons/CollectionIcon.tsx b/app/components/Icons/CollectionIcon.tsx index dee49b4e1a..e17e890802 100644 --- a/app/components/Icons/CollectionIcon.tsx +++ b/app/components/Icons/CollectionIcon.tsx @@ -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"; diff --git a/app/components/Lightbox.tsx b/app/components/Lightbox.tsx index 9834a3716c..45580531b9 100644 --- a/app/components/Lightbox.tsx +++ b/app/components/Lightbox.tsx @@ -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(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, diff --git a/app/components/Reactions/ReactionPicker.tsx b/app/components/Reactions/ReactionPicker.tsx index af0f87b881..6037ce24c6 100644 --- a/app/components/Reactions/ReactionPicker.tsx +++ b/app/components/Reactions/ReactionPicker.tsx @@ -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; @@ -37,7 +43,7 @@ const ReactionPicker: React.FC = ({ 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 = ({ onSelect, className, size }) => { }> = ({ onSelect, className, size }) => { const Placeholder = React.memo( () => ( - + diff --git a/app/components/Sidebar/components/ArchiveLink.tsx b/app/components/Sidebar/components/ArchiveLink.tsx index 7d95a32b31..607a547227 100644 --- a/app/components/Sidebar/components/ArchiveLink.tsx +++ b/app/components/Sidebar/components/ArchiveLink.tsx @@ -24,10 +24,7 @@ function ArchiveLink() { const [disclosure, setDisclosure] = useState(false); const [expanded, setExpanded] = useState(); - 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() { aria-label={t("Archived collections")} + fetch={collections.fetchArchived} items={collections.archived} loading={} renderError={(props) => } diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx index 7d273e6477..e215dbbef9 100644 --- a/app/components/Sidebar/components/Collections.tsx +++ b/app/components/Sidebar/components/Collections.tsx @@ -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(), }), }); diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index 612287f5bc..33367be19d 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -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) => ({ isCollectionDropping: monitor.isOver(), isDraggingAnyCollection: monitor.canDrop(), diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 095798b3d3..4021242d5c 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -226,7 +226,7 @@ export function useDropToChangeCollection( parentRef: React.RefObject ) { 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 ) { 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) { diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 17009e790e..a7d3960594 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -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) => { + // 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) => { 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); diff --git a/app/editor/extensions/CommentGutter.tsx b/app/editor/extensions/CommentGutter.tsx index bda11fa582..bbe9db2b1e 100644 --- a/app/editor/extensions/CommentGutter.tsx +++ b/app/editor/extensions/CommentGutter.tsx @@ -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); diff --git a/app/hooks/useKeyDown.ts b/app/hooks/useKeyDown.ts index daa81db888..94bf2b2a2a 100644 --- a/app/hooks/useKeyDown.ts +++ b/app/hooks/useKeyDown.ts @@ -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 diff --git a/app/scenes/Collection/components/Header.tsx b/app/scenes/Collection/components/Header.tsx index 8e6ca4277e..9dfc1b0b7a 100644 --- a/app/scenes/Collection/components/Header.tsx +++ b/app/scenes/Collection/components/Header.tsx @@ -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"; diff --git a/app/scenes/Document/components/Editor.tsx b/app/scenes/Document/components/Editor.tsx index 63bb549026..b0eedbc3b4 100644 --- a/app/scenes/Document/components/Editor.tsx +++ b/app/scenes/Document/components/Editor.tsx @@ -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"; diff --git a/app/scenes/Document/components/PresentationMode.tsx b/app/scenes/Document/components/PresentationMode.tsx index 936793c0ff..17ff26855e 100644 --- a/app/scenes/Document/components/PresentationMode.tsx +++ b/app/scenes/Document/components/PresentationMode.tsx @@ -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"; diff --git a/app/scenes/Document/components/RevisionViewer.tsx b/app/scenes/Document/components/RevisionViewer.tsx index d750f8e514..f3011cf58d 100644 --- a/app/scenes/Document/components/RevisionViewer.tsx +++ b/app/scenes/Document/components/RevisionViewer.tsx @@ -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"; diff --git a/app/utils/ApiClient.ts b/app/utils/ApiClient.ts index af2a06c52c..488c20fa29 100644 --- a/app/utils/ApiClient.ts +++ b/app/utils/ApiClient.ts @@ -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, diff --git a/app/utils/errors.ts b/app/utils/errors.ts index aaa9f6b539..98dfc45d70 100644 --- a/app/utils/errors.ts +++ b/app/utils/errors.ts @@ -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 {} diff --git a/app/utils/sentry.ts b/app/utils/sentry.ts index cb5443d94d..8240f09ad6 100644 --- a/app/utils/sentry.ts +++ b/app/utils/sentry.ts @@ -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, diff --git a/package.json b/package.json index 32edc52dfd..c25f82af03 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/plugins/email/server/auth/email.ts b/plugins/email/server/auth/email.ts index 9454444fe8..e3a8f5e741 100644 --- a/plugins/email/server/auth/email.ts +++ b/plugins/email/server/auth/email.ts @@ -212,17 +212,14 @@ const emailCallback = async (ctx: APIContext) => { 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; diff --git a/plugins/oidc/server/auth/oidcRouter.ts b/plugins/oidc/server/auth/oidcRouter.ts index 047f9a73ef..a5e9e517c8 100644 --- a/plugins/oidc/server/auth/oidcRouter.ts +++ b/plugins/oidc/server/auth/oidcRouter.ts @@ -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 diff --git a/plugins/search-postgres/server/PostgresSearchProvider.test.ts b/plugins/search-postgres/server/PostgresSearchProvider.test.ts index dd16a3121b..c65fa2d968 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.test.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.test.ts @@ -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":*` + ); + }); }); }); diff --git a/plugins/search-postgres/server/PostgresSearchProvider.ts b/plugins/search-postgres/server/PostgresSearchProvider.ts index 51ba693bdd..86f7a75130 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.ts @@ -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, "\\\\") ); } diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts index d176aef4a2..bb4962945b 100644 --- a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts +++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts @@ -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"; diff --git a/server/collaboration/PersistenceExtension.ts b/server/collaboration/PersistenceExtension.ts index 455d90322c..2f14a9c649 100644 --- a/server/collaboration/PersistenceExtension.ts +++ b/server/collaboration/PersistenceExtension.ts @@ -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(); + 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) { 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, diff --git a/server/emails/templates/ExportSuccessEmail.tsx b/server/emails/templates/ExportSuccessEmail.tsx index 5a5ab4a440..570878653e 100644 --- a/server/emails/templates/ExportSuccessEmail.tsx +++ b/server/emails/templates/ExportSuccessEmail.tsx @@ -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." )}

+

+ {this.t( + "This export will be available to download for {{ days }} days.", + { days: FileOperation.expiryDays } + )} +

diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 014b8a8d8d..2b57e8c69f 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -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; diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index 12f192c42e..6c4d2aadb0 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -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); diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 68e5a1855e..02b7d14f14 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -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; diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index 456d5d6b56..ef5eb78b97 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -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", () => { diff --git a/server/models/Document.ts b/server/models/Document.ts index a9ab10cb13..8654650a49 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -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) { diff --git a/server/models/FileOperation.test.ts b/server/models/FileOperation.test.ts new file mode 100644 index 0000000000..7453ddd430 --- /dev/null +++ b/server/models/FileOperation.test.ts @@ -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); + }); + }); +}); diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index 12cd9397dc..e18fe06782 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -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, @@ -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 & AdditionalFindOptions + ): Promise; + static async findByPk( + id: Identifier, + options?: FindOptions & AdditionalFindOptions + ): Promise; + static async findByPk( + id: Identifier, + options: FindOptions & AdditionalFindOptions = {} + ): Promise { + 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; diff --git a/server/models/Relationship.ts b/server/models/Relationship.ts index 619c031e66..c15173be40 100644 --- a/server/models/Relationship.ts +++ b/server/models/Relationship.ts @@ -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, diff --git a/server/models/User.test.ts b/server/models/User.test.ts index ec372570f1..b5bbc4c167 100644 --- a/server/models/User.test.ts +++ b/server/models/User.test.ts @@ -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({ diff --git a/server/models/User.ts b/server/models/User.ts index 7b8577632b..10c33974b6 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -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 = {}) => { + public collectionIds = async ( + options: FindOptions & { 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> + ) { + 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 diff --git a/server/models/decorators/Encrypted.test.ts b/server/models/decorators/Encrypted.test.ts index 8bd3a70433..366c7064da 100644 --- a/server/models/decorators/Encrypted.test.ts +++ b/server/models/decorators/Encrypted.test.ts @@ -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", () => { diff --git a/server/models/helpers/HTMLHelper.ts b/server/models/helpers/HTMLHelper.ts index a8fb468f03..a2ecae7578 100644 --- a/server/models/helpers/HTMLHelper.ts +++ b/server/models/helpers/HTMLHelper.ts @@ -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