From 6a4e188ec7fea4ac41cee24d1f53552b55c9626a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 18:33:35 -0400 Subject: [PATCH 001/368] fix: Align attachment upload permissions (#13654) --- .../api/attachments/attachments.test.ts | 76 ++++++++++++++----- server/routes/api/attachments/attachments.ts | 19 +++-- 2 files changed, 71 insertions(+), 24 deletions(-) diff --git a/server/routes/api/attachments/attachments.test.ts b/server/routes/api/attachments/attachments.test.ts index e03c4e7c6b..7e910be918 100644 --- a/server/routes/api/attachments/attachments.test.ts +++ b/server/routes/api/attachments/attachments.test.ts @@ -226,24 +226,21 @@ describe("#attachments.create", () => { } }); - it("should create expiring attachment using import preset", async () => { - const user = await buildUser(); - const res = await server.post("/api/attachments.create", user, { - body: { - name: "test.zip", - contentType: "application/zip", - size: 10000, - preset: AttachmentPreset.WorkspaceImport, - }, - }); - expect(res.status).toEqual(200); - - const body = await res.json(); - const attachment = await Attachment.findByPk(body.data.attachment.id, { - rejectOnEmpty: true, - }); - expect(attachment.expiresAt).toBeTruthy(); - }); + it.each([AttachmentPreset.Import, AttachmentPreset.WorkspaceImport])( + "should not allow upload using %s preset", + async (preset) => { + const user = await buildUser(); + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + preset, + }, + }); + expect(res.status).toEqual(403); + } + ); it("should not allow attachment creation for other documents", async () => { const user = await buildUser(); @@ -361,6 +358,49 @@ describe("#attachments.create", () => { expect(res.status).toEqual(200); }); }); + + describe("admin", () => { + it.each([AttachmentPreset.Import, AttachmentPreset.WorkspaceImport])( + "should create expiring attachment using %s preset", + async (preset) => { + const user = await buildAdmin(); + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + preset, + }, + }); + expect(res.status).toEqual(200); + + const body = await res.json(); + const attachment = await Attachment.findByPk(body.data.attachment.id, { + rejectOnEmpty: true, + }); + expect(attachment.expiresAt).toBeTruthy(); + } + ); + + it.each([AttachmentPreset.Import, AttachmentPreset.WorkspaceImport])( + "should not allow upload using %s preset for another team's document", + async (preset) => { + const user = await buildAdmin(); + const document = await buildDocument(); + + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + documentId: document.id, + preset, + }, + }); + expect(res.status).toEqual(403); + } + ); + }); }); describe("#attachments.delete", () => { diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 316146ae50..2c5089f2cc 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -91,16 +91,23 @@ router.post( const { auth, transaction } = ctx.state; const { user } = auth; + if (documentId) { + const document = await Document.findByPk(documentId, { + userId: user.id, + transaction, + }); + authorize(user, "update", document); + } + // All user types can upload an avatar so no additional authorization is needed. if (preset === AttachmentPreset.Avatar) { assertIn(contentType, AttachmentValidation.avatarContentTypes); } else { - if (preset === AttachmentPreset.DocumentAttachment && documentId) { - const document = await Document.findByPk(documentId, { - userId: user.id, - transaction, - }); - authorize(user, "update", document); + if ( + preset === AttachmentPreset.Import || + preset === AttachmentPreset.WorkspaceImport + ) { + authorize(user, "createImport", user.team); } if (preset === AttachmentPreset.Emoji) { assertIn(contentType, AttachmentValidation.emojiContentTypes); From 9411535ee84f2f4d46ec50f3cb571c88c54daee6 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 19:42:42 -0400 Subject: [PATCH 002/368] fix: Load revision content in history (#13656) --- app/scenes/Document/components/RevisionViewer.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/app/scenes/Document/components/RevisionViewer.tsx b/app/scenes/Document/components/RevisionViewer.tsx index 961217f2c7..6a1540fc09 100644 --- a/app/scenes/Document/components/RevisionViewer.tsx +++ b/app/scenes/Document/components/RevisionViewer.tsx @@ -102,6 +102,7 @@ function RevisionViewer(props: Props, ref: React.Ref) { showChanges ? "changes" : "no-changes", compareToRevisionId ?? revision.before?.id ?? "none", comparisonData ? "loaded" : "pending", + revision.data ? "loaded" : "pending", ].join("-"); return ( From 21df3db7a60ad4f98683ccd7896307ce8a0ef051 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 19:56:52 -0400 Subject: [PATCH 003/368] fix: Register revision editor with DocumentContext (#13657) Co-authored-by: Claude Opus 4.8 (1M context) --- app/scenes/Document/components/RevisionViewer.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/scenes/Document/components/RevisionViewer.tsx b/app/scenes/Document/components/RevisionViewer.tsx index 6a1540fc09..b80d8cdf15 100644 --- a/app/scenes/Document/components/RevisionViewer.tsx +++ b/app/scenes/Document/components/RevisionViewer.tsx @@ -1,5 +1,6 @@ import { observer } from "mobx-react"; import * as React from "react"; +import { mergeRefs } from "react-merge-refs"; import { colorPalette } from "@shared/constants"; import type Document from "~/models/Document"; import type Revision from "~/models/Revision"; @@ -17,6 +18,7 @@ import useStores from "~/hooks/useStores"; import { type Editor as TEditor } from "~/editor"; import { ChangesetHelper } from "@shared/editor/lib/ChangesetHelper"; import CodeWordBreak from "@shared/editor/extensions/CodeWordBreak"; +import { useDocumentContext } from "~/components/DocumentContext"; type Props = Omit & { /** The ID of the revision */ @@ -42,6 +44,7 @@ type Props = Omit & { function RevisionViewer(props: Props, ref: React.Ref) { const { document, children, revision } = props; const { revisions } = useStores(); + const { setEditor } = useDocumentContext(); const query = useQuery(); const showChanges = props.showChanges ?? query.has("changes"); const compareToParam = query.get("compareTo"); @@ -122,7 +125,7 @@ function RevisionViewer(props: Props, ref: React.Ref) { /> Date: Sat, 5 Sep 2026 09:13:46 +0900 Subject: [PATCH 004/368] fix: Cannot sort observable array --- shared/utils/naturalSort.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/shared/utils/naturalSort.ts b/shared/utils/naturalSort.ts index f83b544db6..844fc3ac1b 100644 --- a/shared/utils/naturalSort.ts +++ b/shared/utils/naturalSort.ts @@ -40,9 +40,10 @@ function naturalSortBy( }) : sorter; - return items.sort((a: T, b: T) => - sort(getSortByField(a, key), getSortByField(b, key)) - ); + // Sort a copy, `items` may be an observable array which cannot be sorted in place. + return items + .slice() + .sort((a: T, b: T) => sort(getSortByField(a, key), getSortByField(b, key))); } export default naturalSortBy; From 7e94a38cf67455ead72a70e51d4d4ed026774202 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 20:19:18 -0400 Subject: [PATCH 005/368] fix: Editor crash when placeholder targets a position with no node (#13658) Returning the plugin state instead of undefined keeps the decoration set valid on subsequent transactions. --- shared/editor/lib/uploadPlaceholder.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/editor/lib/uploadPlaceholder.tsx b/shared/editor/lib/uploadPlaceholder.tsx index 8fa9bf01f3..dac64b4154 100644 --- a/shared/editor/lib/uploadPlaceholder.tsx +++ b/shared/editor/lib/uploadPlaceholder.tsx @@ -22,7 +22,7 @@ const uploadPlaceholder = new Plugin({ const $pos = tr.doc.resolve(action.add.pos); const nodeAfter = $pos.nodeAfter; if (!nodeAfter) { - return; + return set; } const deco = Decoration.node( From f3f30d133513295cada8e6387adf664d7280f255 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 21:36:18 -0400 Subject: [PATCH 006/368] fix: Guard null (#13660) Allow toggling block with selection content --- shared/editor/commands/toggleBlock.ts | 34 +++++++++++++-------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/shared/editor/commands/toggleBlock.ts b/shared/editor/commands/toggleBlock.ts index 324904c787..390524270d 100644 --- a/shared/editor/commands/toggleBlock.ts +++ b/shared/editor/commands/toggleBlock.ts @@ -72,16 +72,16 @@ export const deleteSelectionPreservingBody: Command = (state, dispatch) => { export const joinForwardPreservingBody: Command = (state, dispatch) => { const { $cursor } = state.selection as TextSelection; - if (!isSelectionAtEndOfToggleBlockHead(state)) { + if (!$cursor || !isSelectionAtEndOfToggleBlockHead(state)) { return false; } - const toggleBlock = $cursor!.node($cursor!.depth - 1); + const toggleBlock = $cursor.node($cursor.depth - 1); if (!isToggleBlockFolded(state, toggleBlock)) { return false; } - const pos = $cursor!.before($cursor!.depth - 1); + const pos = $cursor.before($cursor.depth - 1); const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); let tr = liftChildrenOfNodeAt(pos, tr1); @@ -152,16 +152,16 @@ export const joinBackwardWithToggleblock: Command = chainCommands( export const selectNodeForwardPreservingBody: Command = (state, dispatch) => { const { $cursor } = state.selection as TextSelection; - if (!isSelectionAtEndOfToggleBlockHead(state)) { + if (!$cursor || !isSelectionAtEndOfToggleBlockHead(state)) { return false; } - const toggleBlock = $cursor!.node($cursor!.depth - 1); + const toggleBlock = $cursor.node($cursor.depth - 1); if (!isToggleBlockFolded(state, toggleBlock)) { return false; } - const pos = $cursor!.before($cursor!.depth - 1); + const pos = $cursor.before($cursor.depth - 1); const { tr: tr1, body } = detachToggleBlockBody(pos, state.tr); let tr = selectNodeForwardTr(tr1); tr = attachToggleBlockBody(pos, body, tr); @@ -243,7 +243,7 @@ export const indentBlock: Command = (state, dispatch) => { }; export const toggleBlock: Command = (state, dispatch) => { - const { $cursor } = state.selection as TextSelection; + const { $from } = state.selection; if (!isSelectionInToggleBlock(state)) { return false; } @@ -254,13 +254,13 @@ export const toggleBlock: Command = (state, dispatch) => { } const isToggle = isToggleBlock(state); - const toggle = nearest(ancestors($cursor!).filter(isToggle)); + const toggle = nearest(ancestors($from).filter(isToggle)); if (!toggle) { return false; } - const d = getToggleBlockDepth($cursor!, toggle); - const pos = $cursor!.before(d); + const d = getToggleBlockDepth($from, toggle); + const pos = $from.before(d); const isFolded = isToggleBlockFolded(state, toggle); dispatch?.( @@ -464,28 +464,28 @@ export const exitToggleBlockOnEmptyParagraph: Command = (state, dispatch) => { export const splitBlockPreservingBody: Command = (state, dispatch) => { const { $cursor } = state.selection as TextSelection; - if (!isSelectionInMiddleOfToggleBlockHead(state)) { + if (!$cursor || !isSelectionInMiddleOfToggleBlockHead(state)) { return false; } - const toggle = $cursor!.node($cursor!.depth - 1); + const toggle = $cursor.node($cursor.depth - 1); if (!isToggleBlockFolded(state, toggle)) { return false; } let tr = state.tr; tr = tr.insert( - $cursor!.after(-1), + $cursor.after(-1), toggle.firstChild!.type.create( undefined, - tr.doc.slice($cursor!.pos, $cursor!.end()).content + tr.doc.slice($cursor.pos, $cursor.end()).content ) ); - tr = wrapNodeAt($cursor!.after(-1), toggle.type, { id: v4() }, tr); + tr = wrapNodeAt($cursor.after(-1), toggle.type, { id: v4() }, tr); tr = tr.setSelection( - TextSelection.near(tr.doc.resolve($cursor!.after(-1)), 1) + TextSelection.near(tr.doc.resolve($cursor.after(-1)), 1) ); - tr = tr.delete($cursor!.pos, $cursor!.end()); + tr = tr.delete($cursor.pos, $cursor.end()); dispatch?.(tr); return true; }; From f56155541eb8fd7b05ac5e2859c298603ac55996 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 21:49:14 -0400 Subject: [PATCH 007/368] fix: Load collection tree with document so child documents show without sidebar (#13662) Co-authored-by: Claude Fable 5.1 --- app/scenes/Document/components/DataLoader.tsx | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 9aead2a8f4..a18d6b737e 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -67,7 +67,8 @@ type Props = RouteComponentProps & { }; function DataLoader({ match, children }: Props) { - const { ui, views, shares, comments, documents, revisions } = useStores(); + const { ui, views, shares, comments, documents, revisions, collections } = + useStores(); const team = useCurrentTeam(); const user = useCurrentUser(); const { setDocument } = useDocumentContext(); @@ -171,6 +172,21 @@ function DataLoader({ match, children }: Props) { void fetchViews(); }, [document?.id, document?.isDeleted, revisionId, views, isJustCreated]); + // The collection tree provides the child documents list, so load it here + // rather than relying on the sidebar having rendered the collection. + const collectionId = document?.collectionId; + React.useEffect(() => { + if (!collectionId) { + return; + } + void collections + .fetch(collectionId) + .then((collection) => collection.fetchDocuments()) + .catch((err) => + Logger.error("Failed to fetch collection documents", toError(err)) + ); + }, [collections, collectionId]); + const onCreateLink = React.useCallback( async (params: Properties, nested?: boolean) => { if (!document) { From 68981c0952edf7a9f1ab35134ea8581dd6a34476 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 22:00:46 -0400 Subject: [PATCH 008/368] fix: Restrict views.create to session authentication (#13663) Co-authored-by: Claude Opus 4.8 (1M context) --- server/routes/api/views/views.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/routes/api/views/views.ts b/server/routes/api/views/views.ts index 378c4cb65e..3e405cbf71 100644 --- a/server/routes/api/views/views.ts +++ b/server/routes/api/views/views.ts @@ -6,6 +6,7 @@ import validate from "@server/middlewares/validate"; import { View, Document } from "@server/models"; import { authorize } from "@server/policies"; import { presentView } from "@server/presenters"; +import { AuthenticationType } from "@server/types"; import type { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import * as T from "./schema"; @@ -41,7 +42,7 @@ router.post( router.post( "views.create", rateLimiter(RateLimiterStrategy.OneThousandPerHour), - auth(), + auth({ type: AuthenticationType.APP }), validate(T.ViewsCreateSchema), transaction(), async (ctx: APIContext) => { From 62bfc7b5f5f05221be418b639bee2edcf3f95960 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 22:42:31 -0400 Subject: [PATCH 009/368] fix: Markdown list dropped when a plain item precedes a checkbox item (#13665) Closes #13661 Co-authored-by: Claude Fable 5.1 --- shared/editor/rules/checkboxes.test.ts | 46 ++++++++++++++++++++++++++ shared/editor/rules/checkboxes.ts | 31 +++++++++++++---- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/shared/editor/rules/checkboxes.test.ts b/shared/editor/rules/checkboxes.test.ts index 7f80277611..5daf3ab68e 100644 --- a/shared/editor/rules/checkboxes.test.ts +++ b/shared/editor/rules/checkboxes.test.ts @@ -48,3 +48,49 @@ it("does not convert nested bullet list items inside checkbox lists", () => { expect(nestedList).toBeDefined(); expect(nestedList?.content?.[0].type).toBe("list_item"); }); + +it("converts a list where a plain item precedes a checkbox item", () => { + const markdown = `- Item one +- [ ] Item two`; + + const ast = parser.parse(markdown); + const [checkboxList] = findNodes(ast?.toJSON(), "checkbox_list"); + + expect(checkboxList).toBeDefined(); + expect(checkboxList?.content).toHaveLength(2); + expect(checkboxList?.content?.[0].type).toBe("checkbox_item"); + expect(checkboxList?.content?.[1].type).toBe("checkbox_item"); + expect(serializer.serialize(ast)).toBe(`- [ ] Item one +- [ ] Item two`); +}); + +it("converts a nested list where a plain item precedes a checkbox item", () => { + const markdown = `- Parent + - Nested plain + - [x] Nested checkbox +- Sibling`; + + const ast = parser.parse(markdown); + const [bulletList] = findNodes(ast?.toJSON(), "bullet_list"); + const [checkboxList] = findNodes(ast?.toJSON(), "checkbox_list"); + + expect(bulletList?.content).toHaveLength(2); + expect(checkboxList).toBeDefined(); + expect(checkboxList?.content).toHaveLength(2); + expect(checkboxList?.content?.[0].type).toBe("checkbox_item"); + expect(checkboxList?.content?.[1].type).toBe("checkbox_item"); + expect(checkboxList?.content?.[1].attrs?.checked).toBe(true); +}); + +it("converts an ordered list containing a checkbox item", () => { + const markdown = `1. Item one +2. [ ] Item two`; + + const ast = parser.parse(markdown); + const [checkboxList] = findNodes(ast?.toJSON(), "checkbox_list"); + + expect(checkboxList).toBeDefined(); + expect(checkboxList?.content).toHaveLength(2); + expect(checkboxList?.content?.[0].type).toBe("checkbox_item"); + expect(checkboxList?.content?.[1].type).toBe("checkbox_item"); +}); diff --git a/shared/editor/rules/checkboxes.ts b/shared/editor/rules/checkboxes.ts index b2e08f7060..cae2539d2b 100644 --- a/shared/editor/rules/checkboxes.ts +++ b/shared/editor/rules/checkboxes.ts @@ -22,6 +22,18 @@ function isListItem(token: Token): boolean { return !!token && token.type === "list_item_open"; } +function isListOpen(token: Token): boolean { + return ( + token.type === "bullet_list_open" || token.type === "ordered_list_open" + ); +} + +function isListClose(token: Token): boolean { + return ( + token.type === "bullet_list_close" || token.type === "ordered_list_close" + ); +} + function looksLikeChecklist(tokens: Token[], index: number) { return ( isInline(tokens[index]) && @@ -61,13 +73,20 @@ export default function markdownItCheckbox(md: MarkdownIt): void { const value = matchesChecklist[1]; const checked = value.toLowerCase() === "x"; - // convert surrounding list tokens - if (tokens[i - 3].type === "bullet_list_open") { - tokens[i - 3].type = "checkbox_list_open"; + // convert the enclosing list tokens, which may not be adjacent when + // the checkbox item is preceded by plain items or contains nested lists. + const listLevel = tokens[i - 2].level - 1; + for (let k = i - 3; k >= 0; k--) { + if (tokens[k].level === listLevel && isListOpen(tokens[k])) { + tokens[k].type = "checkbox_list_open"; + break; + } } - - if (tokens[i + 3].type === "bullet_list_close") { - tokens[i + 3].type = "checkbox_list_close"; + for (let k = i + 1; k < tokens.length; k++) { + if (tokens[k].level === listLevel && isListClose(tokens[k])) { + tokens[k].type = "checkbox_list_close"; + break; + } } // remove [ ] [x] from list item label – must use the content from the From cd082e7e3b5c725180f82a96a80f50d5483393e0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 23:08:31 -0400 Subject: [PATCH 010/368] fix: Allow document mentions to wrap (#13639) * fix: Allow document mentions to wrap * fix: Prevent mention icons from shrinking * fix: Preserve mention icon and text styles * fix: Prevent Font Awesome icons from shrinking --- shared/editor/components/Styles.ts | 43 +++++++++++++++++++----------- shared/utils/IconLibrary.tsx | 1 + 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index e0984dec77..edc12645ed 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -545,6 +545,7 @@ width: 100%; .mention { background: ${props.theme.mentionBackground}; + color: ${props.theme.text}; border-radius: 8px; padding-top: 1px; padding-bottom: 1px; @@ -560,27 +561,37 @@ width: 100%; gap: 4px; vertical-align: bottom; - /* Long labels are truncated so a mention never wraps onto a second line. */ - max-width: 100%; - white-space: nowrap; - overflow: hidden; - - span { - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - /* Text sets white-space: normal, so nowrap cannot simply be inherited. */ - white-space: nowrap; - } - - /* Only the label truncates; icons and trailing identifiers stay whole. */ + /* Keep icons at their intended size when the mention wraps. */ &::before, svg, - img, - span ~ span { + img { flex-shrink: 0; } + /* External resource titles stay on one line, while internal mentions can + wrap to fit constrained containers such as table cells. */ + &[data-type="issue"], + &[data-type="pull_request"], + &[data-type="project"], + &[data-type="url"] { + max-width: 100%; + white-space: nowrap; + overflow: hidden; + + span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + /* Text sets white-space: normal, so nowrap cannot simply be inherited. */ + white-space: nowrap; + } + + /* Only the label truncates; trailing identifiers stay whole. */ + span ~ span { + flex-shrink: 0; + } + } + &:${hover} { cursor: default; background: ${props.theme.mentionHoverBackground}; diff --git a/shared/utils/IconLibrary.tsx b/shared/utils/IconLibrary.tsx index c4abcf014d..73bb34d840 100644 --- a/shared/utils/IconLibrary.tsx +++ b/shared/utils/IconLibrary.tsx @@ -607,6 +607,7 @@ export class IconLibrary { const FontAwesomeWrapper = styled.span<{ size: number }>` display: flex; + flex-shrink: 0; align-items: center; justify-content: center; width: ${(props) => props.size}px; From a577d5c2c8bd352f13c9ee8b1734a46ab7a9fd83 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 4 Sep 2026 23:10:32 -0400 Subject: [PATCH 011/368] fix: Validate API key and OAuth scopes at the model layer (#13664) * fix: Validate API key scopes with Sequelize-level validators * test: Add API regression tests for duplicate OAuth redirect URIs * fix: Preserve wildcard scope and guard non-string redirect URIs --------- Co-authored-by: Claude Fable 5.1 --- app/scenes/ApiKeyNew/index.tsx | 2 +- server/.oxlintrc.json | 25 +++++++++++ server/models/AccessRequest.ts | 2 +- server/models/ApiKey.test.ts | 35 +++++++++++++++ server/models/ApiKey.ts | 11 +++-- server/models/Document.ts | 3 +- server/models/Emoji.ts | 8 ++-- server/models/Template.ts | 2 +- .../models/oauth/OAuthAuthentication.test.ts | 24 +++++++++++ server/models/oauth/OAuthAuthentication.ts | 11 +++-- .../oauth/OAuthAuthorizationCode.test.ts | 19 ++++++++ server/models/oauth/OAuthAuthorizationCode.ts | 8 +--- server/models/oauth/OAuthClient.ts | 22 +--------- server/models/validators/IsFQDN.ts | 2 +- server/models/validators/IsHexColor.ts | 2 +- server/models/validators/IsScope.ts | 26 +++++++++++ server/models/validators/IsUrl.ts | 2 +- server/models/validators/IsUrlList.ts | 43 +++++++++++++++++++ .../models/validators/IsUrlOrRelativePath.ts | 2 +- server/routes/api/apiKeys/apiKeys.test.ts | 30 +++++++++++++ server/routes/api/apiKeys/apiKeys.ts | 9 +--- server/routes/api/apiKeys/schema.ts | 25 ++++++++++- .../api/oauthClients/oauthClients.test.ts | 19 ++++++++ server/routes/oauth/oauth.test.ts | 17 ++++++++ 24 files changed, 289 insertions(+), 60 deletions(-) create mode 100644 server/models/validators/IsScope.ts create mode 100644 server/models/validators/IsUrlList.ts diff --git a/app/scenes/ApiKeyNew/index.tsx b/app/scenes/ApiKeyNew/index.tsx index c86224c885..2258ca742e 100644 --- a/app/scenes/ApiKeyNew/index.tsx +++ b/app/scenes/ApiKeyNew/index.tsx @@ -83,7 +83,7 @@ function ApiKeyNew({ onSubmit }: Props) { await apiKeys.create({ name, expiresAt: expiresAt?.toISOString(), - scope: scope ? scope.split(" ") : undefined, + scope: scope ? scope.split(/[\s,]+/).filter(Boolean) : undefined, }); toast.success( t( diff --git a/server/.oxlintrc.json b/server/.oxlintrc.json index b8e20e663b..d36f3cf20c 100644 --- a/server/.oxlintrc.json +++ b/server/.oxlintrc.json @@ -23,6 +23,31 @@ ] }, "plugins": ["import"] + }, + { + "files": ["models/**/*.ts"], + "rules": { + "no-restricted-imports": [ + "error", + { + "name": "fetch-with-proxy", + "message": "Use `@server/utils/fetch` instead" + }, + { + "name": "node-fetch", + "message": "Use `@server/utils/fetch` instead" + }, + { + "name": "passport", + "message": "Use the `@outlinewiki/koa-passport` package" + }, + { + "name": "class-validator", + "message": "class-validator decorators are never executed by Sequelize. Use a decorator from `server/models/validators` or sequelize-typescript, and import check functions from `validator/lib/*`." + } + ] + }, + "plugins": ["import"] } ], "env": { diff --git a/server/models/AccessRequest.ts b/server/models/AccessRequest.ts index 49e9912921..4137ab10b1 100644 --- a/server/models/AccessRequest.ts +++ b/server/models/AccessRequest.ts @@ -13,12 +13,12 @@ import { AllowNull, DefaultScope, BeforeCreate, + IsIn, } from "sequelize-typescript"; import Document from "./Document"; import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; -import { IsIn } from "class-validator"; import { ValidationError } from "@server/errors"; import type { APIContext } from "@server/types"; diff --git a/server/models/ApiKey.test.ts b/server/models/ApiKey.test.ts index 09a53e8018..0ba0c285c5 100644 --- a/server/models/ApiKey.test.ts +++ b/server/models/ApiKey.test.ts @@ -129,5 +129,40 @@ describe("#ApiKey", () => { expect(apiKey.canAccess("/mcp")).toBe(true); }); + + it("should not allow MCP access when no scope is well-formed", async () => { + const apiKey = await buildApiKey({ + name: "Dev", + scope: [Scope.Read], + }); + apiKey.scope = ["documents:read,documents:write"]; + + expect(apiKey.canAccess("/mcp")).toBe(false); + expect(apiKey.canAccess("/api/documents.info")).toBe(false); + }); + }); + + describe("scope", () => { + it("should reject malformed scopes", async () => { + await expect( + buildApiKey({ + name: "Dev", + scope: ["documents:read,documents:write"], + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + + it("should accept well-formed scopes", async () => { + const apiKey = await buildApiKey({ + name: "Dev", + scope: ["documents:read", "/api/users.info", Scope.Write], + }); + + expect(apiKey.scope).toEqual([ + "documents:read", + "/api/users.info", + Scope.Write, + ]); + }); }); }); diff --git a/server/models/ApiKey.ts b/server/models/ApiKey.ts index 87961504f2..debc969242 100644 --- a/server/models/ApiKey.ts +++ b/server/models/ApiKey.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import { subMinutes } from "date-fns"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Op } from "sequelize"; @@ -22,6 +21,7 @@ import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; import { SkipChangeset } from "./decorators/Changeset"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; +import IsScope from "./validators/IsScope"; import Length from "./validators/Length"; @Table({ tableName: "apiKeys", modelName: "apiKey" }) @@ -52,10 +52,7 @@ class ApiKey extends ParanoidModel< name: string; /** A list of scopes that this API key has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[] | null; @@ -178,7 +175,9 @@ class ApiKey extends ParanoidModel< // MCP endpoint access is allowed if the key has any valid scope. // Fine-grained scope enforcement happens at the tool level. if (path.startsWith("/mcp")) { - return this.scope.length > 0; + return this.scope.some((scope) => + AuthenticationHelper.isValidScope(scope) + ); } return AuthenticationHelper.canAccess(path, this.scope); diff --git a/server/models/Document.ts b/server/models/Document.ts index 23976e251b..2c8632c365 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -42,7 +42,6 @@ import { AfterUpdate, IsFloat, } from "sequelize-typescript"; -import { MaxLength } from "class-validator"; import isUUID from "validator/lib/isUUID"; import type { DocumentPermission, @@ -386,8 +385,8 @@ class Document extends ArchivableModel< text: string; /** The likely language of the content, in ISO 639-1 format. */ + @Length({ max: 2, msg: "language must be an ISO 639-1 code" }) @Column(DataType.STRING(2)) - @MaxLength(2) language: string; /** diff --git a/server/models/Emoji.ts b/server/models/Emoji.ts index c370f8b0a2..6c8ac52329 100644 --- a/server/models/Emoji.ts +++ b/server/models/Emoji.ts @@ -7,6 +7,7 @@ import { Column, DataType, ForeignKey, + Is, Table, } from "sequelize-typescript"; import { EmojiValidation } from "@shared/validations"; @@ -15,7 +16,6 @@ import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; import Length from "./validators/Length"; -import { Matches } from "class-validator"; import FileStorage from "@server/storage/files"; import Attachment from "./Attachment"; @@ -28,9 +28,9 @@ class Emoji extends IdModel< max: EmojiValidation.maxNameLength, msg: `emoji name must be less than ${EmojiValidation.maxNameLength} characters`, }) - @Matches(EmojiValidation.allowedNameCharacters, { - message: - "emoji name can only contain lowercase letters, numbers, and underscores", + @Is({ + args: EmojiValidation.allowedNameCharacters, + msg: "emoji name can only contain lowercase letters, numbers, and underscores", }) @Column(DataType.STRING) name: string; diff --git a/server/models/Template.ts b/server/models/Template.ts index acfc5460ac..5c1091ef46 100644 --- a/server/models/Template.ts +++ b/server/models/Template.ts @@ -1,4 +1,4 @@ -import { isUUID } from "class-validator"; +import isUUID from "validator/lib/isUUID"; import type { Identifier, InferAttributes, diff --git a/server/models/oauth/OAuthAuthentication.test.ts b/server/models/oauth/OAuthAuthentication.test.ts index 978edf079e..1924d57b79 100644 --- a/server/models/oauth/OAuthAuthentication.test.ts +++ b/server/models/oauth/OAuthAuthentication.test.ts @@ -2,6 +2,19 @@ import { Scope } from "@shared/types"; import { buildOAuthAuthentication, buildUser } from "@server/test/factories"; describe("OAuthAuthentication", () => { + describe("scope", () => { + it("should reject malformed scopes", async () => { + const user = await buildUser(); + + await expect( + buildOAuthAuthentication({ + user, + scope: ["documents:read,documents:write"], + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + }); + describe("canAccess", () => { it("should allow MCP access for scoped tokens", async () => { const user = await buildUser(); @@ -24,6 +37,17 @@ describe("OAuthAuthentication", () => { expect(authentication.canAccess("/mcp")).toBe(false); }); + it("should deny MCP access when no scope is well-formed", async () => { + const user = await buildUser(); + const authentication = await buildOAuthAuthentication({ + user, + scope: [Scope.Read], + }); + authentication.scope = ["documents:read,documents:write"]; + + expect(authentication.canAccess("/mcp")).toBe(false); + }); + it("should always allow the revoke endpoint", async () => { const user = await buildUser(); const authentication = await buildOAuthAuthentication({ diff --git a/server/models/oauth/OAuthAuthentication.ts b/server/models/oauth/OAuthAuthentication.ts index f428812530..efd0061cdd 100644 --- a/server/models/oauth/OAuthAuthentication.ts +++ b/server/models/oauth/OAuthAuthentication.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import { subMinutes } from "date-fns"; import type { FindOptions, @@ -19,6 +18,7 @@ import env from "@server/env"; import User from "@server/models/User"; import ParanoidModel from "@server/models/base/ParanoidModel"; import { SkipChangeset } from "@server/models/decorators/Changeset"; +import IsScope from "@server/models/validators/IsScope"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { hash } from "@server/utils/crypto"; import OAuthClient from "./OAuthClient"; @@ -81,10 +81,7 @@ class OAuthAuthentication extends ParanoidModel< grantId: string | null; /** A list of scopes that this authentication has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[]; @@ -148,7 +145,9 @@ class OAuthAuthentication extends ParanoidModel< // MCP endpoint access is allowed if the token has any valid scope. // Fine-grained scope enforcement happens at the tool level. if (path.startsWith("/mcp")) { - return this.scope.length > 0; + return this.scope.some((scope) => + AuthenticationHelper.isValidScope(scope) + ); } return AuthenticationHelper.canAccess(path, this.scope); diff --git a/server/models/oauth/OAuthAuthorizationCode.test.ts b/server/models/oauth/OAuthAuthorizationCode.test.ts index 353ef5fa74..677b71f213 100644 --- a/server/models/oauth/OAuthAuthorizationCode.test.ts +++ b/server/models/oauth/OAuthAuthorizationCode.test.ts @@ -23,6 +23,25 @@ const buildCode = async () => { }; describe("OAuthAuthorizationCode", () => { + describe("scope", () => { + it("should reject malformed scopes", async () => { + const user = await buildUser(); + const client = await buildOAuthClient({ teamId: user.teamId }); + + await expect( + OAuthAuthorizationCode.create({ + authorizationCodeHash: hash(crypto.randomBytes(32).toString("hex")), + scope: ["documents:read,documents:write"], + redirectUri: client.redirectUris[0], + oauthClientId: client.id, + userId: user.id, + expiresAt: new Date(Date.now() + 10000), + grantId: crypto.randomUUID(), + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + }); + describe("consume", () => { it("should consume the code once", async () => { const code = await buildCode(); diff --git a/server/models/oauth/OAuthAuthorizationCode.ts b/server/models/oauth/OAuthAuthorizationCode.ts index 60062e16f1..445d62faca 100644 --- a/server/models/oauth/OAuthAuthorizationCode.ts +++ b/server/models/oauth/OAuthAuthorizationCode.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Column, @@ -8,12 +7,12 @@ import { Table, Length, } from "sequelize-typescript"; -import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { OAuthClientValidation } from "@shared/validations"; import env from "@server/env"; import User from "@server/models/User"; import IdModel from "@server/models/base/IdModel"; import { SkipChangeset } from "@server/models/decorators/Changeset"; +import IsScope from "@server/models/validators/IsScope"; import { hash } from "@server/utils/crypto"; import OAuthClient from "./OAuthClient"; @@ -56,10 +55,7 @@ class OAuthAuthorizationCode extends IdModel< grantId: string | null; /** A list of scopes that this authorization code has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[]; diff --git a/server/models/oauth/OAuthClient.ts b/server/models/oauth/OAuthClient.ts index f0d6e79be4..ef535dd9f6 100644 --- a/server/models/oauth/OAuthClient.ts +++ b/server/models/oauth/OAuthClient.ts @@ -1,10 +1,3 @@ -import { - ArrayMaxSize, - ArrayMinSize, - ArrayNotEmpty, - ArrayUnique, - IsUrl, -} from "class-validator"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Column, @@ -27,6 +20,7 @@ import { SkipChangeset } from "@server/models/decorators/Changeset"; import Encrypted from "@server/models/decorators/Encrypted"; import { hash } from "@server/utils/crypto"; import IsUrlOrRelativePath from "@server/models/validators/IsUrlOrRelativePath"; +import IsUrlList from "@server/models/validators/IsUrlList"; import Length from "@server/models/validators/Length"; import NotContainsUrl from "@server/models/validators/NotContainsUrl"; import type { FindOptions } from "sequelize"; @@ -103,19 +97,7 @@ class OAuthClient extends ParanoidModel< @Column(DataType.BOOLEAN) published: boolean; - @ArrayNotEmpty() - @ArrayUnique() - @ArrayMinSize(1) - @ArrayMaxSize(10) - @IsUrl( - { - require_tld: false, - allow_underscores: true, - }, - { - each: true, - } - ) + @IsUrlList({ min: 1, max: OAuthClientValidation.maxRedirectUris }) @Column(DataType.ARRAY(DataType.STRING)) redirectUris: string[]; diff --git a/server/models/validators/IsFQDN.ts b/server/models/validators/IsFQDN.ts index ea4c59eb47..df25bd512c 100644 --- a/server/models/validators/IsFQDN.ts +++ b/server/models/validators/IsFQDN.ts @@ -1,4 +1,4 @@ -import { isFQDN } from "class-validator"; +import isFQDN from "validator/lib/isFQDN"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/models/validators/IsHexColor.ts b/server/models/validators/IsHexColor.ts index 320ef0e617..b90eeb7c20 100644 --- a/server/models/validators/IsHexColor.ts +++ b/server/models/validators/IsHexColor.ts @@ -1,4 +1,4 @@ -import { isHexColor } from "class-validator"; +import isHexColor from "validator/lib/isHexColor"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/models/validators/IsScope.ts b/server/models/validators/IsScope.ts new file mode 100644 index 0000000000..41068003c4 --- /dev/null +++ b/server/models/validators/IsScope.ts @@ -0,0 +1,26 @@ +import { addAttributeOptions } from "sequelize-typescript"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; + +/** + * A decorator that validates that every element of a string array is a + * well-formed API scope. + */ +export default function IsScope(target: object, propertyName: string) { + return addAttributeOptions(target, propertyName, { + validate: { + validScope(value: string[] | null) { + if (!value) { + return; + } + if (!Array.isArray(value)) { + throw new Error("Scope must be an array"); + } + for (const scope of value) { + if (!AuthenticationHelper.isValidScope(scope)) { + throw new Error("Scope must be a valid API scope"); + } + } + }, + }, + }); +} diff --git a/server/models/validators/IsUrl.ts b/server/models/validators/IsUrl.ts index 80c1268f74..4adebfa232 100644 --- a/server/models/validators/IsUrl.ts +++ b/server/models/validators/IsUrl.ts @@ -1,4 +1,4 @@ -import { isURL } from "class-validator"; +import isURL from "validator/lib/isURL"; import { addAttributeOptions } from "sequelize-typescript"; import env from "@server/env"; diff --git a/server/models/validators/IsUrlList.ts b/server/models/validators/IsUrlList.ts new file mode 100644 index 0000000000..ac916f1a34 --- /dev/null +++ b/server/models/validators/IsUrlList.ts @@ -0,0 +1,43 @@ +import { addAttributeOptions } from "sequelize-typescript"; +import isURL from "validator/lib/isURL"; + +/** + * A decorator that validates that a value is an array of unique, well-formed + * URLs with a length within the given bounds. A top-level domain is not + * required, allowing local and internal hostnames. + */ +export default function IsUrlList({ + min = 1, + max, +}: { + min?: number; + max: number; +}): (target: object, propertyName: string) => void { + return (target: object, propertyName: string) => + addAttributeOptions(target, propertyName, { + validate: { + validUrlList(value: string[] | null) { + if (!Array.isArray(value)) { + throw new Error("Must be an array of urls"); + } + if (value.length < min || value.length > max) { + throw new Error(`Must contain between ${min} and ${max} urls`); + } + if (new Set(value).size !== value.length) { + throw new Error("Must not contain duplicate urls"); + } + for (const url of value) { + if ( + typeof url !== "string" || + !isURL(url, { + require_tld: false, + allow_underscores: true, + }) + ) { + throw new Error("Must be a valid url"); + } + } + }, + }, + }); +} diff --git a/server/models/validators/IsUrlOrRelativePath.ts b/server/models/validators/IsUrlOrRelativePath.ts index 19703b1fd6..f00924de19 100644 --- a/server/models/validators/IsUrlOrRelativePath.ts +++ b/server/models/validators/IsUrlOrRelativePath.ts @@ -1,4 +1,4 @@ -import { isURL } from "class-validator"; +import isURL from "validator/lib/isURL"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/routes/api/apiKeys/apiKeys.test.ts b/server/routes/api/apiKeys/apiKeys.test.ts index 68acaff701..c0d02c162f 100644 --- a/server/routes/api/apiKeys/apiKeys.test.ts +++ b/server/routes/api/apiKeys/apiKeys.test.ts @@ -44,6 +44,36 @@ describe("#apiKeys.create", () => { expect(body.data.lastActiveAt).toBeNull(); }); + it("should allow the wildcard scope", async () => { + const user = await buildUser(); + + const res = await server.post("/api/apiKeys.create", user, { + body: { + name: "My API Key", + scope: ["*"], + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.scope).toEqual(["*"]); + }); + + it("should reject malformed scopes", async () => { + const user = await buildUser(); + + const res = await server.post("/api/apiKeys.create", user, { + body: { + name: "My API Key", + scope: ["documents:read,documents:write"], + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(400); + expect(body.message).toContain("Scope must be a valid API scope"); + }); + it("should allow creating an api key with scopes", async () => { const user = await buildUser(); diff --git a/server/routes/api/apiKeys/apiKeys.ts b/server/routes/api/apiKeys/apiKeys.ts index 779d750430..713e1c595e 100644 --- a/server/routes/api/apiKeys/apiKeys.ts +++ b/server/routes/api/apiKeys/apiKeys.ts @@ -1,6 +1,5 @@ import Router from "koa-router"; import { Op, Sequelize, type WhereOptions } from "sequelize"; -import { Scope } from "@shared/types"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import { transaction } from "@server/middlewares/transaction"; @@ -17,8 +16,6 @@ import * as T from "./schema"; const router = new Router(); -const globalScopes = new Set(Object.values(Scope)); - router.post( "apiKeys.create", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), @@ -37,11 +34,7 @@ router.post( name, userId: user.id, expiresAt, - scope: scope?.map((s) => - s.startsWith("/api/") || s.includes(":") || globalScopes.has(s) - ? s - : `/api/${s.replace(/^\//, "")}` - ), + scope, }); apiKey.user = user; diff --git a/server/routes/api/apiKeys/schema.ts b/server/routes/api/apiKeys/schema.ts index 54f5964712..69f13ff648 100644 --- a/server/routes/api/apiKeys/schema.ts +++ b/server/routes/api/apiKeys/schema.ts @@ -1,8 +1,21 @@ import { z } from "zod"; import { ApiKey } from "@server/models"; import { BaseSchema } from "@server/routes/api/schema"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; +import { Scope } from "@shared/types"; import { ApiKeyValidation } from "@shared/validations"; +const globalScopes = new Set([...Object.values(Scope), "*"]); + +/** + * Normalizes a user-supplied scope into its canonical form by prefixing bare + * route scopes with `/api/`. + */ +const normalizeScope = (scope: string) => + scope.startsWith("/api/") || scope.includes(":") || globalScopes.has(scope) + ? scope + : `/api/${scope.replace(/^\//, "")}`; + export const APIKeysCreateSchema = BaseSchema.extend({ body: z.object({ /** API Key name */ @@ -14,7 +27,17 @@ export const APIKeysCreateSchema = BaseSchema.extend({ /** API Key expiry date */ expiresAt: z.coerce.date().optional(), /** A list of scopes that this API key has access to */ - scope: z.array(z.string()).optional(), + scope: z + .array( + z + .string() + .trim() + .transform(normalizeScope) + .refine((scope) => AuthenticationHelper.isValidScope(scope), { + error: "Scope must be a valid API scope", + }) + ) + .optional(), }), }); diff --git a/server/routes/api/oauthClients/oauthClients.test.ts b/server/routes/api/oauthClients/oauthClients.test.ts index 0a034cebc3..e3f1d259fc 100644 --- a/server/routes/api/oauthClients/oauthClients.test.ts +++ b/server/routes/api/oauthClients/oauthClients.test.ts @@ -285,6 +285,25 @@ describe("oauthClients.create", () => { expect(body.data.name).toEqual("Test Client"); expect(body.data.redirectUris).toEqual(["https://example.com/callback"]); }); + + it("should reject duplicate redirect uris", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + + const res = await server.post("/api/oauthClients.create", admin, { + body: { + name: "Test Client", + redirectUris: [ + "https://example.com/callback", + "https://example.com/callback", + ], + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toContain("Must not contain duplicate urls"); + }); }); describe("oauthclients.update", () => { diff --git a/server/routes/oauth/oauth.test.ts b/server/routes/oauth/oauth.test.ts index c86e274f47..c3d73975a8 100644 --- a/server/routes/oauth/oauth.test.ts +++ b/server/routes/oauth/oauth.test.ts @@ -174,6 +174,23 @@ describe("#oauth.register", () => { expect(res.status).toEqual(201); }); + it("should reject duplicate redirect_uris", async () => { + const res = await server.post("/oauth/register", { + body: { + client_name: "Test Client", + redirect_uris: [ + "https://example.com/callback", + "https://example.com/callback", + ], + }, + headers: { + host: `${subdomain}.outline.dev`, + }, + }); + + expect(res.status).toEqual(400); + }); + it("should reject too many redirect_uris and report the received count", async () => { const count = OAuthClientValidation.maxRedirectUris + 1; const res = await server.post("/oauth/register", { From c11c9107162913ac21ae24b941ae2ee2a0495525 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 5 Sep 2026 06:25:18 -0400 Subject: [PATCH 012/368] fix: Persist comment sidebar open/close state across reloads (#13667) Co-authored-by: Claude Opus 4.8 (1M context) --- app/stores/UiStore.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index a31e877024..d2e164add1 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -410,6 +410,7 @@ class UiStore { this.secondaryRightSidebar = panel; } else { this.rightSidebar = panel; + this.persist(); } }; From 4533038cb4a16ce0d7e2736ed215a6a4ca8b6f52 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 5 Sep 2026 10:40:02 -0400 Subject: [PATCH 013/368] fix: Allow dropping a document after an expanded subtree in the sidebar (#13668) Co-authored-by: Claude Fable 5.1 --- app/components/DocumentListItem.tsx | 1 - .../Sidebar/components/DocumentLink.tsx | 168 +++++++++++++----- .../Sidebar/components/DragPlaceholder.tsx | 52 ++---- .../Sidebar/components/DropCursor.tsx | 48 +++-- .../Sidebar/components/SidebarLink.tsx | 13 +- .../Sidebar/hooks/useDragAndDrop.tsx | 31 ++-- 6 files changed, 211 insertions(+), 102 deletions(-) diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index eb20ccc727..eeb3f79f0e 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -135,7 +135,6 @@ function DocumentListItem( document.asNavigationNode, 0, document, - false, false ); diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 58d39467c6..1a5928ee59 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -36,6 +36,7 @@ import { useSidebarExpansion } from "./SidebarExpansionContext"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; +import { indentForDepth } from "./SidebarLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; @@ -49,6 +50,19 @@ type Props = { depth: number; index: number; parentId?: string; + /** + * Positions directly after each ancestor whose subtree ends with this node, + * nearest first. They let a drop at the end of an expanded subtree land + * beside an ancestor instead of inside it. + */ + ancestorDropTargets?: DropTarget[]; +}; + +/** A position in the document tree that a dragged document can be dropped at. */ +type DropTarget = { + parentDocumentId: string | undefined; + index: number; + depth: number; }; // Approximate rendered row height; used to reserve space for unmounted rows so @@ -117,6 +131,20 @@ const DocumentLink = observer(function DocumentLink(props: Props) { [draftNavNode, collection, node.children] ); + // The last child shares its bottom edge with this node's subtree, so a drop + // there may also target the position after this node or its ancestors. + const lastChildDropTargets = React.useMemo( + () => [ + { + parentDocumentId: props.parentId, + index: props.index + 1, + depth: props.depth, + }, + ...(props.ancestorDropTargets ?? []), + ], + [props.parentId, props.index, props.depth, props.ancestorDropTargets] + ); + // Visibility gate: only mount the heavy inner content when scrolled near the // viewport, but keep it mounted while a drag is in progress so the dragged // source (or a drop target the user is heading toward) isn't yanked. @@ -179,6 +207,11 @@ const DocumentLink = observer(function DocumentLink(props: Props) { depth={props.depth + 1} index={childIndex} parentId={node.id} + ancestorDropTargets={ + childIndex === nodeChildren.length - 1 + ? lastChildDropTargets + : undefined + } /> ))} @@ -200,6 +233,7 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ index, parentId, hasChildren, + ancestorDropTargets, }: InnerProps) { const { documents } = useStores(); const { t } = useTranslation(); @@ -325,43 +359,34 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ // Fall back so document-only access (e.g. "Manage" on a parent) can reorder. const moveCollectionId = collection?.id ?? document?.collectionId; - const [{ isOverReorder: isOverReorderAbove }, dropToReorderAbove] = - useDropToReorderDocument(node, collection, (item) => { - if (!moveCollectionId) { - return; - } - return { - documentId: item.id, - collectionId: moveCollectionId, - parentDocumentId: parentId, - index, - }; - }); - - const [{ isOverReorder }, dropToReorder] = useDropToReorderDocument( - node, - collection, - (item) => { - if (!moveCollectionId) { - return; - } - if (expansion.isExpanded(node.id)) { - return { - documentId: item.id, - collectionId: moveCollectionId, - parentDocumentId: node.id, - index: 0, - }; - } - return { - documentId: item.id, - collectionId: moveCollectionId, - parentDocumentId: parentId, - index: index + 1, - }; - } + const targetAbove = React.useMemo( + () => ({ parentDocumentId: parentId, index, depth }), + [parentId, index, depth] ); + // Below an expanded node the only position is its first child. Otherwise the + // position after the node comes first, then any ancestor positions that end + // here, so the pointer's horizontal position picks the depth. The node being + // dragged skips the position after itself, which would be a no-op. + const targetsBelow = React.useMemo(() => { + if (expanded && hasChildren) { + return [{ parentDocumentId: node.id, index: 0, depth: depth + 1 }]; + } + const afterSelf = isDragging + ? [] + : [{ parentDocumentId: parentId, index: index + 1, depth }]; + return [...afterSelf, ...(ancestorDropTargets ?? [])]; + }, [ + expanded, + hasChildren, + isDragging, + node.id, + parentId, + index, + depth, + ancestorDropTargets, + ]); + const title = document?.title || node.title || t("Untitled"); const handleNewDoc = React.useCallback( @@ -422,16 +447,33 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ // the tree for every row. const cursorBefore = canReorderHere && index === 0 ? ( - ) : undefined; - const cursorAfter = canReorderHere ? ( - - ) : undefined; + // Later cursors render on top, so each outer level's narrower hit area wins + // when the pointer is left of the previous level's indent. + const cursorAfter = canReorderHere + ? targetsBelow.map((target, level) => ( + 0 + ? indentForDepth(targetsBelow[level - 1].depth) + : undefined + } + /> + )) + : undefined; return ( { + if (!collectionId) { + return; + } + return { + documentId: item.id, + collectionId, + parentDocumentId: target.parentDocumentId, + index: target.index, + }; + } + ); + + return ( + + ); +}); + export default DocumentLink; diff --git a/app/components/Sidebar/components/DragPlaceholder.tsx b/app/components/Sidebar/components/DragPlaceholder.tsx index b6c98972b0..e7a4feba33 100644 --- a/app/components/Sidebar/components/DragPlaceholder.tsx +++ b/app/components/Sidebar/components/DragPlaceholder.tsx @@ -16,26 +16,18 @@ const layerStyles: React.CSSProperties = { height: "100%", }; -function getItemStyles( - initialOffset: XYCoord | null, - currentOffset: XYCoord | null, - sidebarWidth: number, - constrainToSidebar: boolean -) { - if (!initialOffset || !currentOffset) { +// Keep the ghost beside the pointer so it never covers the drop cursor. +const POINTER_OFFSET_X = 12; +const POINTER_OFFSET_Y = 14; + +function getItemStyles(pointerOffset: XYCoord | null, sidebarWidth: number) { + if (!pointerOffset) { return { display: "none", }; } - const { y } = currentOffset; - // Sidebar drags keep the ghost tethered near its origin, but drags from - // outside the sidebar should follow the cursor freely. - const x = constrainToSidebar - ? Math.max( - initialOffset.x, - Math.min(initialOffset.x + sidebarWidth / 4, currentOffset.x) - ) - : currentOffset.x; + const x = pointerOffset.x + POINTER_OFFSET_X; + const y = pointerOffset.y - POINTER_OFFSET_Y; const transform = `translate(${x}px, ${y}px)`; return { @@ -49,35 +41,25 @@ const DragPlaceholder = () => { const { t } = useTranslation(); const { ui } = useStores(); - const { isDragging, item, initialOffset, currentOffset } = useDragLayer( - (monitor) => ({ - item: monitor.getItem(), - itemType: monitor.getItemType(), - initialOffset: monitor.getInitialSourceClientOffset(), - currentOffset: monitor.getSourceClientOffset(), - isDragging: monitor.isDragging(), - }) - ); + const { isDragging, item, pointerOffset } = useDragLayer((monitor) => ({ + item: monitor.getItem(), + itemType: monitor.getItemType(), + pointerOffset: monitor.getClientOffset(), + isDragging: monitor.isDragging(), + })); - if (!isDragging || !currentOffset) { + if (!isDragging || !pointerOffset) { return null; } return (
-
+
diff --git a/app/components/Sidebar/components/DropCursor.tsx b/app/components/Sidebar/components/DropCursor.tsx index cd4859129d..a32b4e9642 100644 --- a/app/components/Sidebar/components/DropCursor.tsx +++ b/app/components/Sidebar/components/DropCursor.tsx @@ -5,17 +5,35 @@ type Props = { isActiveDrop: boolean; innerRef: React.Ref; position?: "top"; + /** Inline-start offset of the visible line in pixels, to match a tree depth. */ + indent?: number; + /** Width of the area that accepts a drop in pixels, defaults to the full row. */ + hitWidth?: number; className?: string; }; -function DropCursor({ isActiveDrop, innerRef, position, className }: Props) { +function DropCursor({ + isActiveDrop, + innerRef, + position, + indent = 0, + hitWidth, + className, +}: Props) { + const hitStyle = React.useMemo( + () => (hitWidth === undefined ? undefined : { width: hitWidth }), + [hitWidth] + ); + return ( + > + + ); } @@ -23,30 +41,40 @@ function DropCursor({ isActiveDrop, innerRef, position, className }: Props) { const Cursor = styled.div<{ isOver?: boolean; position?: "top"; + $indent: number; }>` opacity: ${(props) => (props.isOver ? 1 : 0)}; transition: opacity 150ms; position: absolute; z-index: 1; pointer-events: none; - - [data-drag-active] & { - pointer-events: auto; - } - width: 100%; height: 14px; background: transparent; ${(props) => (props.position === "top" ? "top: -7px;" : "bottom: -7px;")} ::after { - background: ${(props) => props.theme.slateDark}; + background: ${(props) => props.theme.accent}; position: absolute; top: 6px; + inset-inline: ${(props) => props.$indent}px 0; content: ""; height: 2px; border-radius: 2px; - width: 100%; + } +`; + +// The drop target. Narrower than the line when several cursors share a band so +// that the pointer's horizontal position picks between them. +const HitArea = styled.div` + position: absolute; + inset-block: 0; + inset-inline-start: 0; + width: 100%; + pointer-events: none; + + [data-drag-active] & { + pointer-events: auto; } `; diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 46d89cd5e7..7b1e24a376 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -16,6 +16,17 @@ import type { ActionFactory, ActionWithChildren } from "~/types"; import { ContextMenu } from "~/components/Menu/ContextMenu"; import { useTranslation } from "react-i18next"; +/** + * Returns the inline-start offset in pixels of a sidebar row's content at the + * given nesting depth. + * + * @param depth The nesting depth of the row, 0-based. + * @returns the offset in pixels. + */ +export function indentForDepth(depth: number): number { + return depth * 16 + 12; +} + /** * Props for the SidebarLink component. * Extends NavLink props with additional sidebar-specific functionality. @@ -104,7 +115,7 @@ function SidebarLink( const { handleMouseEnter, handleMouseLeave } = useClickIntent(onClickIntent); const style = React.useMemo( () => ({ - paddingInlineStart: `${(depth || 0) * 16 + (icon ? -8 : 12)}px`, + paddingInlineStart: `${indentForDepth(depth || 0) - (icon ? 20 : 0)}px`, paddingInlineEnd: unreadBadge ? "32px" : undefined, }), [depth, icon, unreadBadge] diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 6fce7a890e..146bfd9b1d 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -27,12 +27,6 @@ import { useSidebarLabelAndIcon } from "./useSidebarLabelAndIcon"; export type DragObject = NavigationNode & { depth: number; collectionId: string; - /** - * Whether the drag ghost should stay tethered to the sidebar. Defaults to - * tethered when unset — the placeholder only lets the ghost follow the - * cursor when this is explicitly `false` (e.g. drags from a document list). - */ - constrainToSidebar?: boolean; }; function useHover( @@ -237,16 +231,12 @@ export function useDropToReorderSidebarSection( * @param depth The depth of the node in the sidebar. * @param document The related Document model. * @param isEditing Whether the sidebar item is currently being edited. - * @param constrainToSidebar Whether the drag ghost should stay tethered to the - * sidebar. Defaults to true; pass false when dragging from outside the sidebar - * (e.g. a document list) so the ghost follows the cursor. */ export function useDragDocument( node: NavigationNode, depth: number, document?: Document, - isEditing?: boolean, - constrainToSidebar = true + isEditing?: boolean ) { const icon = document?.icon || node.icon || node.emoji; const color = document?.color || node.color; @@ -266,7 +256,6 @@ export function useDragDocument( ) : undefined, collectionId: document?.collectionId || "", - constrainToSidebar, }) as DragObject, canDrag: () => !!document?.isActive && !isEditing, collect: (monitor) => ({ @@ -493,10 +482,24 @@ export function useDropToReorderDocument( return useDrop, { isOverReorder: boolean }>({ accept: "document", canDrop: (item: DragObject) => { - if (item.id === node.id || (document && !document.isActive)) { + if ( + (document && !document.isActive) || + !policies.abilities(item.id).move + ) { return false; } - return !!policies.abilities(item.id).move; + if (item.id !== node.id) { + return true; + } + // A document can only be dropped on its own cursor when that moves it to + // a different parent, e.g. out of the end of an expanded subtree. + const params = getMoveParams(item); + return ( + !!params && + params.parentDocumentId !== item.id && + (params.parentDocumentId ?? null) !== + (document?.parentDocumentId ?? null) + ); }, drop: async (item) => { if (!collection?.isManualSort && item.collectionId === collection?.id) { From 7bd59ba1b3575219a143d3e0f9005af80c75bb84 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 5 Sep 2026 18:40:27 -0400 Subject: [PATCH 014/368] fix: History "Current version" entry never finishes loading (#13669) * fix: Current version history entry loads forever Assigning the primary key on a built Revision is a silent no-op in Sequelize, so revisions.info returned a random UUID instead of the synthetic latest id the client waits for. Co-Authored-By: Claude Fable 5.1 * fix: Apply policies from fetchLatest response Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- app/stores/RevisionsStore.ts | 7 +++++++ server/routes/api/revisions/revisions.test.ts | 20 +++++++++++++++++++ server/routes/api/revisions/revisions.ts | 3 ++- shared/utils/RevisionHelper.ts | 10 ++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/app/stores/RevisionsStore.ts b/app/stores/RevisionsStore.ts index 5c1d071280..b7fcdb0b3a 100644 --- a/app/stores/RevisionsStore.ts +++ b/app/stores/RevisionsStore.ts @@ -1,4 +1,5 @@ import { type JSONObject } from "@shared/types"; +import { RevisionHelper } from "@shared/utils/RevisionHelper"; import type RootStore from "~/stores/RootStore"; import Store from "~/stores/base/Store"; import Revision from "~/models/Revision"; @@ -17,6 +18,11 @@ export default class RevisionsStore extends Store { * @returns A promise that resolves to the fetched revision. */ async fetch(id: string, options: JSONObject = {}): Promise { + const documentId = RevisionHelper.documentIdFromLatestId(id); + if (documentId) { + return this.fetchLatest(documentId); + } + const item = this.get(id); const force = Boolean(options.force) || (!!item && !item.data); return super.fetch(id, { ...options, force }); @@ -39,6 +45,7 @@ export default class RevisionsStore extends Store { */ fetchLatest = async (documentId: string) => { const res = await client.post(`/revisions.info`, { documentId }); + this.addPolicies(res.policies); return this.add(res.data); }; } diff --git a/server/routes/api/revisions/revisions.test.ts b/server/routes/api/revisions/revisions.test.ts index 788b6ab620..1381e74e7e 100644 --- a/server/routes/api/revisions/revisions.test.ts +++ b/server/routes/api/revisions/revisions.test.ts @@ -3,6 +3,7 @@ import { ExportContentType, TeamPreference, } from "@shared/types"; +import { RevisionHelper } from "@shared/utils/RevisionHelper"; import { createContext } from "@server/context"; import { UserMembership, Revision } from "@server/models"; import FileStorage from "@server/storage/files"; @@ -44,6 +45,25 @@ describe("#revisions.info", () => { expect(body.data.text).toBeDefined(); }); + it("should return the latest revision by documentId with a stable id", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/revisions.info", user, { + body: { + documentId: document.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.id).toEqual(RevisionHelper.latestId(document.id)); + expect(body.data.documentId).toEqual(document.id); + expect(body.data.title).toEqual(document.title); + expect(body.data.data).toBeDefined(); + }); + it("should require authorization", async () => { const admin = await buildAdmin(); const document = await buildDocument({ diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index 36f2afb750..c5a27ce042 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -53,7 +53,8 @@ router.post( }); authorize(user, "listRevisions", document); revision = Revision.buildFromDocument(document); - revision.id = RevisionHelper.latestId(document.id); + // Sequelize ignores primary key assignment on built instances. + revision.setDataValue("id", RevisionHelper.latestId(document.id)); revision.user = document.updatedBy; } else { throw ValidationError("Either id or documentId must be provided"); diff --git a/shared/utils/RevisionHelper.ts b/shared/utils/RevisionHelper.ts index 8481f61f29..d728c525e1 100644 --- a/shared/utils/RevisionHelper.ts +++ b/shared/utils/RevisionHelper.ts @@ -8,4 +8,14 @@ export class RevisionHelper { static latestId(documentId?: string) { return documentId ? `latest-${documentId}` : ""; } + + /** + * Extract the document id from a latest revision id. + * + * @param id The revision id to inspect. + * @returns The document id if the id is a latest revision id, otherwise undefined. + */ + static documentIdFromLatestId(id: string) { + return id.startsWith("latest-") ? id.slice("latest-".length) : undefined; + } } From 4ba91fcb8ef64ab2dfe39aa0cfad3a558a772f98 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 5 Sep 2026 19:26:27 -0400 Subject: [PATCH 015/368] fix: AuthStore.availableTeams never becomes observable (#13672) Add an initializer so makeObservable picks up the field, and add a local oxlint rule that flags @observable fields without an initializer in classes that call makeObservable(this). Co-authored-by: Claude Fable 5.1 --- .oxlint/mobx.mjs | 133 ++++++++++++++++++++++++++++++++++++++++ .oxlintrc.json | 2 + app/stores/AuthStore.ts | 2 +- 3 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 .oxlint/mobx.mjs diff --git a/.oxlint/mobx.mjs b/.oxlint/mobx.mjs new file mode 100644 index 0000000000..ae1dfd14ca --- /dev/null +++ b/.oxlint/mobx.mjs @@ -0,0 +1,133 @@ +/** + * Local oxlint plugin with MobX-specific rules. + */ + +/** Returns true if the decorator is `@observable` or `@observable.`. */ +function isObservableDecorator(decorator) { + const expression = decorator.expression; + + if (expression.type === "Identifier") { + return expression.name === "observable"; + } + + if (expression.type === "MemberExpression") { + return ( + expression.object.type === "Identifier" && + expression.object.name === "observable" + ); + } + + return false; +} + +/** Returns true if the expression is a `makeObservable(this, …)` call. */ +function isMakeObservableCall(expression) { + return ( + expression.type === "CallExpression" && + expression.callee.type === "Identifier" && + expression.callee.name === "makeObservable" && + expression.arguments.length > 0 && + expression.arguments[0].type === "ThisExpression" + ); +} + +/** Returns the property name if the expression is `this. = …`, else null. */ +function assignedThisProperty(expression) { + if ( + expression.type !== "AssignmentExpression" || + expression.left.type !== "MemberExpression" || + expression.left.object.type !== "ThisExpression" || + expression.left.property.type !== "Identifier" + ) { + return null; + } + return expression.left.property.name; +} + +/** + * Walks the constructor body and returns the set of `this.` properties + * assigned before `makeObservable(this)` is called, or null if the constructor + * never calls it. + */ +function propertiesAssignedBeforeMakeObservable(classBody) { + const ctor = classBody.body.find( + (member) => + member.type === "MethodDefinition" && member.kind === "constructor" + ); + if (!ctor?.value?.body) { + return null; + } + + const assigned = new Set(); + for (const statement of ctor.value.body.body) { + if (statement.type !== "ExpressionStatement") { + continue; + } + if (isMakeObservableCall(statement.expression)) { + return assigned; + } + const name = assignedThisProperty(statement.expression); + if (name) { + assigned.add(name); + } + } + + return null; +} + +const plugin = { + meta: { + name: "mobx", + }, + rules: { + "observable-needs-initializer": { + meta: { + type: "problem", + docs: { + description: + "Require an initializer on @observable class fields in classes that call makeObservable(this). A field that does not exist as an own property when makeObservable runs is silently skipped by MobX.", + }, + messages: { + missing: + "@observable field '{{name}}' has no initializer, so makeObservable() will silently skip it. Add `= undefined` or another initial value.", + }, + }, + create(context) { + return { + ClassBody(node) { + const assigned = propertiesAssignedBeforeMakeObservable(node); + if (assigned === null) { + return; + } + + for (const member of node.body) { + if ( + member.type !== "PropertyDefinition" || + member.value !== null || + member.static || + member.declare || + member.key.type !== "Identifier" || + assigned.has(member.key.name) + ) { + continue; + } + + const decorators = member.decorators ?? []; + if (!decorators.some(isObservableDecorator)) { + continue; + } + + context.report({ + node: member, + messageId: "missing", + data: { name: member.key.name }, + }); + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlintrc.json b/.oxlintrc.json index 7b2243a1a5..5cc0cbd062 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,7 +9,9 @@ "patches/**", "*.d.ts" ], + "jsPlugins": ["./.oxlint/mobx.mjs"], "rules": { + "mobx/observable-needs-initializer": "error", "for-direction": "error", "no-async-promise-executor": "error", "no-case-declarations": "error", diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 7136702fcd..0c5bf82142 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -67,7 +67,7 @@ export default class AuthStore extends Store { avatarUrl: string; url: string; isSignedIn: boolean; - }[]; + }[] = undefined; /* The authentication provider the user signed in with. */ @observable From 07aa125b586e287e9c5472abb3732a26731ad3aa Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 00:11:51 -0400 Subject: [PATCH 016/368] fix: Expand folded toggle blocks when printing (#13677) Co-authored-by: Claude Fable 5.1 --- shared/editor/components/Styles.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index edc12645ed..1f5b6ea9e4 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -2755,15 +2755,20 @@ li > .${EditorStyleHelper.toggleBlock} { &:dir(ltr) { --rotate-by: -90deg; } - > .${EditorStyleHelper.toggleBlockContent} > :is(:not(.${EditorStyleHelper.toggleBlockHead})) { - display: none; - } - > .${EditorStyleHelper.toggleBlockContent} > :is(a.heading-name) { - display: unset; + /* Folded content is always included when printing */ + @media not print { + > .${EditorStyleHelper.toggleBlockContent} > :is(:not(.${EditorStyleHelper.toggleBlockHead})) { + display: none; + } + > .${EditorStyleHelper.toggleBlockContent} > :is(a.heading-name) { + display: unset; + } + > .${EditorStyleHelper.toggleBlockButton} svg { + transform: rotate(var(--rotate-by)); + } } > .${EditorStyleHelper.toggleBlockButton} { svg { - transform: rotate(var(--rotate-by)); pointer-events: none; } opacity: 1; From d3c8be2dbc23ecb27444b74f1c1045b35a52ee80 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 00:45:30 -0400 Subject: [PATCH 017/368] feat: Alt/Mod-click toggle disclosure folds nested or all toggle blocks (#13678) * feat: Alt-click toggle disclosure folds or unfolds all toggle blocks Co-Authored-By: Claude Fable 5.1 * Alt toggles nested blocks, Mod toggles all blocks Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- shared/editor/nodes/ToggleBlock.ts | 180 ++++++++++++++++++------- shared/editor/nodes/ToggleBlockView.ts | 28 ++-- 2 files changed, 145 insertions(+), 63 deletions(-) diff --git a/shared/editor/nodes/ToggleBlock.ts b/shared/editor/nodes/ToggleBlock.ts index 30da9fc8f6..2c3dfe9f34 100644 --- a/shared/editor/nodes/ToggleBlock.ts +++ b/shared/editor/nodes/ToggleBlock.ts @@ -8,7 +8,7 @@ import type { Node as ProsemirrorNode, Schema, } from "prosemirror-model"; -import type { Command, Transaction } from "prosemirror-state"; +import type { Command, EditorState, Transaction } from "prosemirror-state"; import { Plugin, PluginKey, TextSelection } from "prosemirror-state"; import { findWrapping } from "prosemirror-transform"; import { Decoration, DecorationSet } from "prosemirror-view"; @@ -52,6 +52,14 @@ export enum Action { UNFOLD, } +interface FoldAction { + type: Action; + /** Position of the target block; omitted to target every toggle block. */ + at?: number; + /** Whether toggle blocks nested inside the target are included. */ + nested?: boolean; +} + interface ToggleFoldState { foldedIds: Set; knownIds: Set; @@ -168,16 +176,13 @@ export default class ToggleBlock extends Node { state: { init: (_config, state) => { - const { foldedIds, knownIds, blocks } = - this.collectFoldState(state.doc); + const { foldedIds, knownIds, blocks } = this.collectFoldState( + state.doc + ); return { foldedIds, knownIds, - decorations: this.createDecorations( - state.doc, - foldedIds, - blocks - ), + decorations: this.createDecorations(state.doc, foldedIds, blocks), }; }, @@ -203,26 +208,15 @@ export default class ToggleBlock extends Node { const newFoldedIds = new Set(pluginState.foldedIds); const newKnownIds = new Set(pluginState.knownIds); - switch (action.type) { - case Action.FOLD: { - const node = newState.doc.nodeAt(action.at); - if (node?.attrs.id) { - newFoldedIds.add(node.attrs.id); - newKnownIds.add(node.attrs.id); - foldStateCache.set(node.attrs.id, { fold: true }); - } - break; - } - - case Action.UNFOLD: { - const node = newState.doc.nodeAt(action.at); - if (node?.attrs.id) { - newFoldedIds.delete(node.attrs.id); - newKnownIds.add(node.attrs.id); - foldStateCache.set(node.attrs.id, { fold: false }); - } - break; + const fold = action.type === Action.FOLD; + for (const { node } of this.resolveTargets(newState.doc, action)) { + if (fold) { + newFoldedIds.add(node.attrs.id); + } else { + newFoldedIds.delete(node.attrs.id); } + newKnownIds.add(node.attrs.id); + foldStateCache.set(node.attrs.id, { fold }); } return { @@ -268,31 +262,12 @@ export default class ToggleBlock extends Node { if (eventTr) { const event = eventTr.getMeta(toggleEventPluginKey); - const node = newState.doc.nodeAt(event.at); + const targets = this.resolveTargets(newState.doc, event); - if (node) { - if (event.type === Action.FOLD) { - // Move cursor out of body if folding - const { $anchor } = newState.selection; - const startOfNode = event.at + 1; - const endOfFirstChild = startOfNode + node.firstChild!.nodeSize; - const endOfNode = startOfNode + node.nodeSize - 1; - - if ($anchor.pos > endOfFirstChild && $anchor.pos < endOfNode) { - const $endOfFirstChild = newState.doc.resolve(endOfFirstChild); - tr = newState.tr.setSelection( - TextSelection.near($endOfFirstChild, -1) - ); - } - } else if (event.type === Action.UNFOLD) { - // Insert empty paragraph if body is empty (for placeholder visibility) - if (node.childCount === 1) { - tr = newState.tr.insert( - event.at + 1 + node.content.size, - newState.schema.nodes.paragraph.create({}) - ); - } - } + if (event.type === Action.FOLD) { + tr = this.moveSelectionOutOfBody(newState, targets); + } else if (event.type === Action.UNFOLD) { + tr = this.insertParagraphIntoEmptyBodies(newState, targets); } } @@ -495,6 +470,103 @@ export default class ToggleBlock extends Node { }; } + /** + * Resolve the toggle blocks an action applies to: the block at the given + * position, that block and every toggle block nested inside it when + * `nested` is set, or every toggle block in the document when no position + * is given. + * + * @param doc The document to look in. + * @param action The fold action describing the target position and scope. + * @return The matching toggle blocks with their positions, in document order. + */ + private resolveTargets( + doc: ProsemirrorNode, + action: FoldAction + ): NodeWithPos[] { + const isToggle = (b: { + node: ProsemirrorNode | null; + pos: number; + }): b is NodeWithPos => + b.node !== null && b.node.type.name === this.name && !!b.node.attrs.id; + + if (action.at === undefined) { + return findBlockNodes(doc, true).filter(isToggle); + } + + const at = action.at; + const root = { node: doc.nodeAt(at), pos: at }; + if (!isToggle(root)) { + return []; + } + + if (!action.nested) { + return [root]; + } + + const descendants = findBlockNodes(root.node, true) + .map((b) => ({ node: b.node, pos: at + 1 + b.pos })) + .filter(isToggle); + return [root, ...descendants]; + } + + /** + * Move the selection to the end of the title of the outermost target whose + * body contains it, so that folding does not hide the cursor. + * + * @param state The editor state after the fold. + * @param targets The toggle blocks being folded, in document order. + * @return A transaction moving the selection, or null if none is needed. + */ + private moveSelectionOutOfBody( + state: EditorState, + targets: NodeWithPos[] + ): Transaction | null { + const { $anchor } = state.selection; + + for (const { node, pos } of targets) { + const startOfNode = pos + 1; + const endOfFirstChild = startOfNode + node.firstChild!.nodeSize; + const endOfNode = startOfNode + node.nodeSize - 1; + + if ($anchor.pos > endOfFirstChild && $anchor.pos < endOfNode) { + return state.tr.setSelection( + TextSelection.near(state.doc.resolve(endOfFirstChild), -1) + ); + } + } + + return null; + } + + /** + * Insert an empty paragraph into every target with an empty body so that + * the placeholder is visible after unfolding. + * + * @param state The editor state after the unfold. + * @param targets The toggle blocks being unfolded, in document order. + * @return A transaction inserting paragraphs, or null if none is needed. + */ + private insertParagraphIntoEmptyBodies( + state: EditorState, + targets: NodeWithPos[] + ): Transaction | null { + const emptyBlocks = targets.filter((b) => b.node.childCount === 1); + if (emptyBlocks.length === 0) { + return null; + } + + const tr = state.tr; + // Insert from the end so earlier positions stay valid. + for (const { node, pos } of emptyBlocks.reverse()) { + tr.insert( + pos + 1 + node.content.size, + state.schema.nodes.paragraph.create({}) + ); + } + return tr; + } + /** * Collect initial fold state for every toggle block in the document. * @@ -605,7 +677,11 @@ export default class ToggleBlock extends Node { return { foldedIds, knownIds, - decorations: this.buildDecorationsFromBlocks(doc, toggleBlocks, foldedIds), + decorations: this.buildDecorationsFromBlocks( + doc, + toggleBlocks, + foldedIds + ), }; } diff --git a/shared/editor/nodes/ToggleBlockView.ts b/shared/editor/nodes/ToggleBlockView.ts index d5a54e26ca..8718ec065c 100644 --- a/shared/editor/nodes/ToggleBlockView.ts +++ b/shared/editor/nodes/ToggleBlockView.ts @@ -1,6 +1,7 @@ import type { Node as ProsemirrorNode } from "prosemirror-model"; import type { EditorView, NodeView, DecorationSource } from "prosemirror-view"; import type { Decoration } from "prosemirror-view"; +import { isModKey } from "../../utils/keyboard"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import { Action, @@ -64,7 +65,7 @@ export class ToggleBlockView implements NodeView { return; } - this.handleToggle(); + this.handleToggle(event); }; private handleToggleHeadClick = (event: MouseEvent) => { @@ -93,10 +94,15 @@ export class ToggleBlockView implements NodeView { } event.preventDefault(); - this.handleToggle(); + this.handleToggle(event); }; - private handleToggle = () => { + /** + * Fold or unfold this block. With Alt held the block and every toggle block + * nested inside it are toggled; with the Mod key held every toggle block in + * the document is toggled. + */ + private handleToggle = (event: MouseEvent) => { const pos = this.getPos(); if (pos === undefined) { return; @@ -106,16 +112,16 @@ export class ToggleBlockView implements NodeView { EditorStyleHelper.toggleBlockFolded ); + const type = isFolded ? Action.UNFOLD : Action.FOLD; + // Omitting the position applies the action to every toggle block. + const action = isModKey(event) + ? { type } + : { type, at: pos, nested: event.altKey }; + this.view.dispatch( this.view.state.tr - .setMeta(toggleFoldPluginKey, { - type: isFolded ? Action.UNFOLD : Action.FOLD, - at: pos, - }) - .setMeta(toggleEventPluginKey, { - type: isFolded ? Action.UNFOLD : Action.FOLD, - at: pos, - }) + .setMeta(toggleFoldPluginKey, action) + .setMeta(toggleEventPluginKey, action) ); }; From 90f70913160c5fa2e170ca1952fc32169448c1e0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 04:05:12 -0400 Subject: [PATCH 018/368] fix: Signed file downloads rejected when an API key lacks scope for the route (#13681) * fix: Signed file downloads rejected when an API key lacks scope for the route Adds a skip option to the auth middleware so routes authorized by other means can ignore credentials on the request, and applies it to signed file requests. Also maps the get method to the read scope. Co-Authored-By: Claude Fable 5.1 * Restrict skip option to optional authentication Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- plugins/storage/server/api/files.test.ts | 36 ++++++++++++++ plugins/storage/server/api/files.ts | 3 +- server/middlewares/authentication.test.ts | 54 +++++++++++++++++++++ server/middlewares/authentication.ts | 25 ++++++++-- shared/helpers/AuthenticationHelper.test.ts | 9 ++++ shared/helpers/AuthenticationHelper.ts | 2 + 6 files changed, 125 insertions(+), 4 deletions(-) diff --git a/plugins/storage/server/api/files.test.ts b/plugins/storage/server/api/files.test.ts index d75532e965..e538ef2b2c 100644 --- a/plugins/storage/server/api/files.test.ts +++ b/plugins/storage/server/api/files.test.ts @@ -11,6 +11,7 @@ import AttachmentHelper, { } from "@server/models/helpers/AttachmentHelper"; import FileStorage from "@server/storage/files"; import { + buildApiKey, buildAttachment, buildFileOperation, buildUser, @@ -595,4 +596,39 @@ describe("#files.get", () => { 'attachment; filename="export-markdown.zip"' ); }); + it("should succeed with status 200 ok when signed file is requested with an API key lacking scope", async () => { + const user = await buildUser(); + const apiKey = await buildApiKey({ + userId: user.id, + scope: ["/api/fileOperations.redirect"], + }); + const fileName = "export-markdown.zip"; + const key = `${Buckets.uploads}/${user.teamId}/${crypto.randomUUID()}/${fileName}`; + + await buildFileOperation({ + userId: user.id, + teamId: user.teamId, + type: FileOperationType.Export, + state: FileOperationState.Complete, + key, + }); + + ensureDirSync( + path.dirname(path.join(env.FILE_STORAGE_LOCAL_ROOT_DIR, key)) + ); + + copyFileSync( + path.resolve(__dirname, "..", "test", "fixtures", fileName), + path.join(env.FILE_STORAGE_LOCAL_ROOT_DIR, key) + ); + + const signedUrl = await FileStorage.getSignedUrl(key); + const url = new URL(signedUrl); + const res = await server.get(url.pathname + url.search, { + headers: { authorization: `Bearer ${apiKey.value}` }, + }); + + expect(res.status).toEqual(200); + expect(res.headers.get("Content-Type")).toEqual("application/zip"); + }); }); diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index fd0e6913d9..7b26714598 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -98,7 +98,8 @@ router.post( router.get( "files.get", - auth({ optional: true }), + // Signed requests are authorized by their signature alone. + auth({ optional: true, skip: (ctx) => !!ctx.query.sig }), validate(T.FilesGetSchema), async (ctx: APIContext) => { const actor = ctx.state.auth.user; diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index dbfab995bb..100134c270 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -441,4 +441,58 @@ describe("Authentication middleware", () => { expect(errToString(error)).toEqual("Invalid token"); }); + describe("with skip", () => { + it("should ignore credentials when skip returns true", async () => { + const state = {} as DefaultState; + const user = await buildUser(); + const apiKey = await buildApiKey({ + userId: user.id, + scope: ["/api/documents.info"], + }); + const next = vi.fn(); + const authMiddleware = auth({ + optional: true, + skip: (ctx) => !!ctx.query.sig, + }); + await authMiddleware( + { + // @ts-expect-error mock request + request: { + get: vi.fn(() => `Bearer ${apiKey.value}`), + }, + query: { sig: "signature" }, + originalUrl: "/api/files.get?sig=signature", + state, + cache: {}, + }, + next + ); + expect(next).toHaveBeenCalled(); + expect(state.auth).toEqual({}); + }); + + it("should authenticate when skip returns false", async () => { + const state = {} as DefaultState; + const user = await buildUser(); + const next = vi.fn(); + const authMiddleware = auth({ + optional: true, + skip: (ctx) => !!ctx.query.sig, + }); + await authMiddleware( + { + // @ts-expect-error mock request + request: { + get: vi.fn(() => `Bearer ${user.getSessionToken()}`), + }, + query: {}, + state, + cache: {}, + }, + next + ); + expect(next).toHaveBeenCalled(); + expect(state.auth.user.id).toEqual(user.id); + }); + }); }); diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 036fd44d23..32f8efc518 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -17,15 +17,29 @@ import { UserSuspendedError, } from "../errors"; -type AuthenticationOptions = { +type BaseAuthenticationOptions = { /** Role required to access the route. */ role?: UserRole; /** Type of authentication required to access the route. */ type?: AuthenticationType | AuthenticationType[]; - /** Authentication is parsed, but optional. */ - optional?: boolean; }; +type AuthenticationOptions = + | (BaseAuthenticationOptions & { + /** Authentication is required. */ + optional?: false; + skip?: never; + }) + | (BaseAuthenticationOptions & { + /** Authentication is parsed, but optional. */ + optional: true; + /** + * Returns true when the request is authorized by other means, in which + * case any credentials on the request are ignored rather than parsed. + */ + skip?: (ctx: AppContext) => boolean; + }); + type AuthTransport = "cookie" | "header" | "body" | "query"; type AuthInput = { @@ -37,6 +51,11 @@ type AuthInput = { export default function auth(options: AuthenticationOptions = {}) { return async function authMiddleware(ctx: AppContext, next: Next) { + if (options.skip?.(ctx)) { + ctx.state.auth = {}; + return next(); + } + try { const { type, token, user, service, scope } = await validateAuthentication(ctx, options); diff --git a/shared/helpers/AuthenticationHelper.test.ts b/shared/helpers/AuthenticationHelper.test.ts index 0cc654925f..b05768cb01 100644 --- a/shared/helpers/AuthenticationHelper.test.ts +++ b/shared/helpers/AuthenticationHelper.test.ts @@ -102,6 +102,14 @@ describe("AuthenticationHelper", () => { expect(canAccess("/api/attachments.delete", scopes)).toBe(false); }); + it("files read scope grants access to get", async () => { + const scopes = ["files:read"]; + + expect(canAccess("/api/files.get", scopes)).toBe(true); + expect(canAccess("/api/files.get?sig=abc", scopes)).toBe(true); + expect(canAccess("/api/files.create", scopes)).toBe(false); + }); + it("write", async () => { const scopes = ["documents:write"]; @@ -142,6 +150,7 @@ describe("AuthenticationHelper", () => { true ); expect(canAccess("/api/attachments.redirect", scopes)).toBe(true); + expect(canAccess("/api/files.get", 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); diff --git a/shared/helpers/AuthenticationHelper.ts b/shared/helpers/AuthenticationHelper.ts index 998977bfec..435d8897cf 100644 --- a/shared/helpers/AuthenticationHelper.ts +++ b/shared/helpers/AuthenticationHelper.ts @@ -11,6 +11,7 @@ export default class AuthenticationHelper { * - `collections.memberships` -> `Scope.Read` * - `collections.group_memberships` -> `Scope.Read` * - `attachments.redirect` -> `Scope.Read` + * - `files.get` -> `Scope.Read` */ private static methodToScope = { create: Scope.Create, @@ -23,6 +24,7 @@ export default class AuthenticationHelper { viewed: Scope.Read, export: Scope.Read, redirect: Scope.Read, + get: Scope.Read, memberships: Scope.Read, group_memberships: Scope.Read, }; From d457e3998a91277e9146819d33f01ff9d5ee5645 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 07:50:44 -0400 Subject: [PATCH 019/368] fix: AuthStore.fetchConfig writes config outside a MobX action (#13682) Co-authored-by: Claude Fable 5.1 --- app/stores/AuthStore.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 0c5bf82142..ef7d3b17a0 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -195,11 +195,12 @@ export default class AuthStore extends Store { }; } - @action fetchConfig = async () => { const res = await client.post("/auth.config"); invariant(res?.data, "Config not available"); - this.config = res.data; + runInAction(() => { + this.config = res.data; + }); }; @action From e78bb0d4e3c60b6294589e933055056e9febc112 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 08:29:12 -0400 Subject: [PATCH 020/368] fix: previous() on UserMembership and Star returned the next item (#13684) Co-authored-by: Claude Fable 5.1 --- app/models/Star.ts | 2 +- app/models/UserMembership.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/Star.ts b/app/models/Star.ts index 19326cb21b..3e14e6c7f3 100644 --- a/app/models/Star.ts +++ b/app/models/Star.ts @@ -48,7 +48,7 @@ class Star extends Model { */ previous(): Star | undefined { const index = this.store.orderedData.indexOf(this); - return this.store.orderedData[index + 1]; + return this.store.orderedData[index - 1]; } } diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts index 9847342557..eab66c31d9 100644 --- a/app/models/UserMembership.ts +++ b/app/models/UserMembership.ts @@ -87,7 +87,7 @@ class UserMembership extends NavigableModel { userId: this.userId, }); const index = memberships.indexOf(this); - return memberships[index + 1]; + return memberships[index - 1]; } } From 9ad078074e1ba24078ba86b9b9afb9eea77cdc73 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 22:36:03 -0400 Subject: [PATCH 021/368] fix: Crash opening the template editor (#13686) Fixes OUTLINE-CLOUD-D5Z --- app/scenes/Document/components/Editor.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/scenes/Document/components/Editor.tsx b/app/scenes/Document/components/Editor.tsx index f07e0421c9..894d7790c0 100644 --- a/app/scenes/Document/components/Editor.tsx +++ b/app/scenes/Document/components/Editor.tsx @@ -11,7 +11,7 @@ import { getLangFor } from "@shared/utils/language"; import { DocumentPreference } from "@shared/types"; import { colorPalette } from "@shared/constants"; import Comment from "~/models/Comment"; -import type Document from "~/models/Document"; +import Document from "~/models/Document"; import type Template from "~/models/Template"; import type { RefHandle } from "~/components/ContentEditable"; import { useDocumentContext } from "~/components/DocumentContext"; @@ -289,7 +289,7 @@ function DocumentEditor(props: Props, ref: React.ForwardedRef) { onDestroy={handleDestroy} onChange={updateDocState} headingPrefix={ - "preferences" in document + document instanceof Document ? document.getPreference(DocumentPreference.HeadingPrefix) : undefined } From af2608536ab6dd253e9f9ef9b1d80c1d7e160fa2 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 6 Sep 2026 22:44:49 -0400 Subject: [PATCH 022/368] fix: robots.txt disallowed crawlers on self-hosted installs (#13687) Closes #13685 --- server/routes/discovery/index.ts | 21 +++++ server/routes/discovery/mcp.ts | 75 +++++++++++++++++ .../{utils => routes/discovery}/opensearch.ts | 0 server/routes/discovery/robots.ts | 31 +++++++ server/routes/index.ts | 80 +------------------ server/utils/robots.ts | 21 ----- 6 files changed, 129 insertions(+), 99 deletions(-) create mode 100644 server/routes/discovery/index.ts create mode 100644 server/routes/discovery/mcp.ts rename server/{utils => routes/discovery}/opensearch.ts (100%) create mode 100644 server/routes/discovery/robots.ts delete mode 100644 server/utils/robots.ts diff --git a/server/routes/discovery/index.ts b/server/routes/discovery/index.ts new file mode 100644 index 0000000000..0f541f1fc5 --- /dev/null +++ b/server/routes/discovery/index.ts @@ -0,0 +1,21 @@ +import Router from "koa-router"; +import { Day } from "@shared/utils/time"; +import { opensearchResponse } from "./opensearch"; +import { robotsResponse } from "./robots"; +import mcp from "./mcp"; + +const router = new Router(); + +router.get("/robots.txt", (ctx) => { + ctx.body = robotsResponse(); +}); + +router.get("/opensearch.xml", (ctx) => { + ctx.type = "text/xml"; + ctx.response.set("Cache-Control", `public, max-age=${7 * Day.seconds}`); + ctx.body = opensearchResponse(ctx.request.URL.origin); +}); + +router.use(mcp.routes()); + +export default router; diff --git a/server/routes/discovery/mcp.ts b/server/routes/discovery/mcp.ts new file mode 100644 index 0000000000..0427692d44 --- /dev/null +++ b/server/routes/discovery/mcp.ts @@ -0,0 +1,75 @@ +import Router from "koa-router"; +import { TeamPreference } from "@shared/types"; +import env from "@server/env"; +import { getTeamFromContext } from "@server/utils/passport"; + +const router = new Router(); + +router.get( + [ + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-authorization-server/mcp", + ], + async (ctx) => { + // Use the configured URL for self-hosted deployments to preserve the port when behind + // a reverse proxy that may strip the port from the Host header. + const origin = env.isCloudHosted + ? ctx.request.URL.origin + : new URL(env.URL).origin; + const team = await getTeamFromContext(ctx, { includeOAuthState: false }); + const mcpEnabled = team?.getPreference(TeamPreference.MCP) ?? true; + + ctx.body = { + issuer: origin, + authorization_endpoint: `${origin}/oauth/authorize`, + token_endpoint: `${origin}/oauth/token`, + revocation_endpoint: `${origin}/oauth/revoke`, + ...(!env.OAUTH_DISABLE_DCR && + mcpEnabled && { + registration_endpoint: `${origin}/oauth/register`, + }), + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + token_endpoint_auth_methods_supported: ["client_secret_post", "none"], + code_challenge_methods_supported: ["S256"], + scopes_supported: ["read", "write"], + }; + } +); + +router.get( + [ + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/mcp", + ], + async (ctx) => { + const team = await getTeamFromContext(ctx, { includeOAuthState: false }); + const mcpEnabled = team?.getPreference(TeamPreference.MCP) ?? true; + + if (!mcpEnabled) { + ctx.status = 404; + return; + } + + // Use the configured URL for self-hosted deployments to preserve the port when behind + // a reverse proxy that may strip the port from the Host header. + const origin = env.isCloudHosted + ? ctx.request.URL.origin + : new URL(env.URL).origin; + + ctx.body = { + resource: `${origin}/mcp`, + authorization_servers: [origin], + scopes_supported: ["read", "write"], + bearer_methods_supported: ["header"], + }; + } +); + +// MCP clients sometimes probe the origin for a legacy HTTP+SSE endpoint. The +// application shell is not a valid response to that probe, so answer with a 404. +router.get("/sse", (ctx) => { + ctx.status = 404; +}); + +export default router; diff --git a/server/utils/opensearch.ts b/server/routes/discovery/opensearch.ts similarity index 100% rename from server/utils/opensearch.ts rename to server/routes/discovery/opensearch.ts diff --git a/server/routes/discovery/robots.ts b/server/routes/discovery/robots.ts new file mode 100644 index 0000000000..f6bfce1ed6 --- /dev/null +++ b/server/routes/discovery/robots.ts @@ -0,0 +1,31 @@ +/** + * Returns the robots.txt content. Crawlers may fetch share pages, the share + * sitemap, and attachment redirects; per-page indexing is controlled by the + * robots meta tag. + * + * @returns the robots.txt content. + */ +export const robotsResponse = (): string => ` +User-agent: * +Allow: /api/shares.sitemap +Allow: /api/attachments.redirect +Disallow: /api/ +Disallow: /auth/ +Disallow: /oauth/ +Disallow: /mcp +Disallow: /sse +Disallow: /realtime +Disallow: /embeds/ +Disallow: /settings +Disallow: /search +Disallow: /home +Disallow: /drafts +Disallow: /trash +Disallow: /archive +Disallow: /starred +Disallow: /templates +Disallow: /dashboard +Disallow: /create +Disallow: /logout +Disallow: /desktop-redirect +`; diff --git a/server/routes/index.ts b/server/routes/index.ts index 2785f12107..2ba7e35581 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -12,12 +12,11 @@ import env from "@server/env"; import { NotFoundError } from "@server/errors"; import shareDomains from "@server/middlewares/shareDomains"; import { Integration } from "@server/models"; -import { opensearchResponse } from "@server/utils/opensearch"; import { getTeamFromContext } from "@server/utils/passport"; -import { robotsResponse } from "@server/utils/robots"; import { isInvalidAppPath } from "@server/utils/url"; import apexRedirect from "../middlewares/apexRedirect"; import { renderApp, renderShare } from "./app"; +import discovery from "./discovery"; import { renderEmbed } from "./embeds"; import errors from "./errors"; @@ -113,82 +112,7 @@ router.get("/locales/:lng.json", async (ctx) => { }); }); -router.get( - [ - "/.well-known/oauth-authorization-server", - "/.well-known/oauth-authorization-server/mcp", - ], - async (ctx) => { - // Use the configured URL for self-hosted deployments to preserve the port when behind - // a reverse proxy that may strip the port from the Host header. - const origin = env.isCloudHosted - ? ctx.request.URL.origin - : new URL(env.URL).origin; - const team = await getTeamFromContext(ctx, { includeOAuthState: false }); - const mcpEnabled = team?.getPreference(TeamPreference.MCP) ?? true; - - ctx.body = { - issuer: origin, - authorization_endpoint: `${origin}/oauth/authorize`, - token_endpoint: `${origin}/oauth/token`, - revocation_endpoint: `${origin}/oauth/revoke`, - ...(!env.OAUTH_DISABLE_DCR && - mcpEnabled && { - registration_endpoint: `${origin}/oauth/register`, - }), - response_types_supported: ["code"], - grant_types_supported: ["authorization_code", "refresh_token"], - token_endpoint_auth_methods_supported: ["client_secret_post", "none"], - code_challenge_methods_supported: ["S256"], - scopes_supported: ["read", "write"], - }; - } -); - -router.get( - [ - "/.well-known/oauth-protected-resource", - "/.well-known/oauth-protected-resource/mcp", - ], - async (ctx) => { - const team = await getTeamFromContext(ctx, { includeOAuthState: false }); - const mcpEnabled = team?.getPreference(TeamPreference.MCP) ?? true; - - if (!mcpEnabled) { - ctx.status = 404; - return; - } - - // Use the configured URL for self-hosted deployments to preserve the port when behind - // a reverse proxy that may strip the port from the Host header. - const origin = env.isCloudHosted - ? ctx.request.URL.origin - : new URL(env.URL).origin; - - ctx.body = { - resource: `${origin}/mcp`, - authorization_servers: [origin], - scopes_supported: ["read", "write"], - bearer_methods_supported: ["header"], - }; - } -); - -// MCP clients sometimes probe the origin for a legacy HTTP+SSE endpoint. The -// application shell is not a valid response to that probe, so answer with a 404. -router.get("/sse", (ctx) => { - ctx.status = 404; -}); - -router.get("/robots.txt", (ctx) => { - ctx.body = robotsResponse(); -}); - -router.get("/opensearch.xml", (ctx) => { - ctx.type = "text/xml"; - ctx.response.set("Cache-Control", `public, max-age=${7 * Day.seconds}`); - ctx.body = opensearchResponse(ctx.request.URL.origin); -}); +router.use(discovery.routes()); router.get("/s/:shareId.:format", shareDomains(), renderShare); router.get("/s/:shareId", shareDomains(), renderShare); diff --git a/server/utils/robots.ts b/server/utils/robots.ts deleted file mode 100644 index 6eb86e28d2..0000000000 --- a/server/utils/robots.ts +++ /dev/null @@ -1,21 +0,0 @@ -import env from "@server/env"; - -/** - * Returns the robots.txt content for the installation, allowing crawlers on - * cloud-hosted installations and disallowing them when self-hosted. - * - * @returns the robots.txt content. - */ -export const robotsResponse = () => { - if (env.isCloudHosted) { - return ` -User-agent: * -Allow: / -`; - } - - return ` -User-agent: * -Disallow: / -`; -}; From 70ef12bd279e15495d948d71cff0750b27b1f041 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 00:48:56 -0400 Subject: [PATCH 023/368] fix: History changes indicator missing on load and stuck on "N changes" (#13673) * fix: History changes indicator missing on load and stuck on "N changes" Co-Authored-By: Claude Opus 4.8 (1M context) * fix: Match changes param check to RevisionViewer Co-Authored-By: Claude Opus 4.8 (1M context) * fix: Disable change nav buttons until Diff extension is available Co-Authored-By: Claude Opus 4.8 (1M context) * fix: Reset changes count only on unmount to avoid flicker Co-Authored-By: Claude Opus 4.8 (1M context) --------- Co-authored-by: Claude Opus 4.8 (1M context) --- app/components/DocumentContext.tsx | 12 +++++- .../Document/components/ChangesNavigation.tsx | 24 +++++------- app/scenes/Document/components/Document.tsx | 1 - app/scenes/Document/components/Header.tsx | 5 +-- .../Document/components/RevisionViewer.tsx | 36 +++++++++++++----- shared/editor/extensions/Diff.ts | 37 ++++++++++++------- 6 files changed, 71 insertions(+), 44 deletions(-) diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx index a5bd9ca81b..8633969aa4 100644 --- a/app/components/DocumentContext.tsx +++ b/app/components/DocumentContext.tsx @@ -14,7 +14,12 @@ class DocumentContext { document?: Document; /** The editor instance for this document */ - editor?: Editor; + @observable.ref + editor: Editor | undefined = undefined; + + /** The total number of changes in the currently viewed revision diff */ + @observable + totalChanges: number = 0; /** The ID of the currently focused comment, or null if no comment is focused */ @observable @@ -67,6 +72,11 @@ class DocumentContext { this.isEditorInitialized = initialized; }; + @action + setTotalChanges = (totalChanges: number) => { + this.totalChanges = totalChanges; + }; + @action setFocusedCommentId = (commentId: string | null) => { this.focusedCommentId = commentId; diff --git a/app/scenes/Document/components/ChangesNavigation.tsx b/app/scenes/Document/components/ChangesNavigation.tsx index 6c568c6430..36fe6e1ec4 100644 --- a/app/scenes/Document/components/ChangesNavigation.tsx +++ b/app/scenes/Document/components/ChangesNavigation.tsx @@ -6,32 +6,24 @@ import { CaretDownIcon, CaretUpIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Button from "~/components/Button"; +import { useDocumentContext } from "~/components/DocumentContext"; import Tooltip from "~/components/Tooltip"; -import { type Editor } from "~/editor"; import useQuery from "~/hooks/useQuery"; -import type Revision from "~/models/Revision"; -type Props = { - revision: Revision; - editorRef: React.RefObject; -}; - -export const ChangesNavigation = observer(function ChangesNavigation_({ - editorRef, -}: Props) { +export const ChangesNavigation = observer(function ChangesNavigation_() { const { t } = useTranslation(); const query = useQuery(); - const showChanges = query.get("changes"); + const showChanges = query.has("changes"); + const { editor, totalChanges } = useDocumentContext(); if (!showChanges) { return null; } - const diffExtension = editorRef.current?.extensions.extensions.find( + const diffExtension = editor?.extensions.extensions.find( (ext) => ext instanceof Diff ) as Diff | undefined; const currentChangeIndex = diffExtension?.getCurrentChangeIndex() ?? -1; - const totalChanges = diffExtension?.getTotalChangesCount() ?? 0; return ( <> @@ -50,14 +42,16 @@ export const ChangesNavigation = observer(function ChangesNavigation_({ } - onClick={() => editorRef.current?.commands.prevChange()} + onClick={() => editor?.commands.prevChange()} + disabled={!diffExtension} aria-label={t("Previous change")} /> } - onClick={() => editorRef.current?.commands.nextChange()} + onClick={() => editor?.commands.nextChange()} + disabled={!diffExtension} aria-label={t("Next change")} /> diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index 7f8884b08c..f4eac6a1c3 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -365,7 +365,6 @@ function DocumentScene({ ) : (
; document: Document; revision: Revision | undefined; isDraft: boolean; @@ -62,7 +60,6 @@ type Props = { }; function DocumentHeader({ - editorRef, document, revision, isEditing, @@ -263,7 +260,7 @@ function DocumentHeader({ {revision && ( <> - + diff --git a/app/scenes/Document/components/RevisionViewer.tsx b/app/scenes/Document/components/RevisionViewer.tsx index b80d8cdf15..f959171c36 100644 --- a/app/scenes/Document/components/RevisionViewer.tsx +++ b/app/scenes/Document/components/RevisionViewer.tsx @@ -44,7 +44,7 @@ type Props = Omit & { function RevisionViewer(props: Props, ref: React.Ref) { const { document, children, revision } = props; const { revisions } = useStores(); - const { setEditor } = useDocumentContext(); + const { setEditor, setTotalChanges } = useDocumentContext(); const query = useQuery(); const showChanges = props.showChanges ?? query.has("changes"); const compareToParam = query.get("compareTo"); @@ -80,22 +80,38 @@ function RevisionViewer(props: Props, ref: React.Ref) { /** * Create editor extensions with the Diff extension configured to render - * the calculated changes as decorations in the editor. + * the calculated changes as decorations in the editor. The change count is + * derived from the same changeset so the indicator can render before the + * editor and its Diff extension have finished mounting. */ - const extensions = React.useMemo(() => { + const { extensions, totalChanges } = React.useMemo(() => { const changeset = ChangesetHelper.getChangeset( revision.data, comparisonData ); - return [ - CodeWordBreak, - ...withComments(richExtensions), - ...(showChanges && changeset?.changes - ? [new Diff({ changes: changeset?.changes })] - : []), - ]; + return { + extensions: [ + CodeWordBreak, + ...withComments(richExtensions), + ...(showChanges && changeset?.changes + ? [new Diff({ changes: changeset?.changes })] + : []), + ], + totalChanges: showChanges + ? Diff.countChanges(changeset?.changes ?? null) + : 0, + }; }, [revision.data, comparisonData, showChanges]); + // Publish the change count so the header indicator can render immediately, + // without waiting for the lazily-loaded editor to mount. + React.useEffect(() => { + setTotalChanges(totalChanges); + }, [totalChanges, setTotalChanges]); + + // Reset the count on unmount so it does not linger on the live document. + React.useEffect(() => () => setTotalChanges(0), [setTotalChanges]); + // The editor builds its extensions once, on mount, so it has to be remounted // whenever the diff configuration changes. Revisions are listed without their // content, so the revision being compared against — and with it the Diff diff --git a/shared/editor/extensions/Diff.ts b/shared/editor/extensions/Diff.ts index 13977ef36d..370295bf15 100644 --- a/shared/editor/extensions/Diff.ts +++ b/shared/editor/extensions/Diff.ts @@ -36,6 +36,29 @@ type DiffOptions = { }; export default class Diff extends Extension { + /** + * Count the total number of individual changes in a changeset. + * + * @param changes the set of changes, or null. + * @returns the total count of all inserted, deleted, and modified items. + */ + public static countChanges( + changes: readonly ExtendedChange[] | null + ): number { + if (!changes) { + return 0; + } + + return changes.reduce( + (total, change) => + total + + change.inserted.length + + change.deleted.length + + change.modified.length, + 0 + ); + } + get name() { return "diff"; } @@ -82,19 +105,7 @@ export default class Diff extends Extension { * @returns the total count of all inserted, deleted, and modified items. */ public getTotalChangesCount(): number { - const { changes } = this.options; - if (!changes) { - return 0; - } - - return changes.reduce( - (total, change) => - total + - change.inserted.length + - change.deleted.length + - change.modified.length, - 0 - ); + return Diff.countChanges(this.options.changes); } private goToChange(direction: number): Command { From b3a1cef0184706d3569e1f52632c493d598e8ba5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 00:51:16 -0400 Subject: [PATCH 024/368] fix: Revision view does not re-render when late-loaded content arrives (#13683) * fix: Revision view does not re-render when late content arrives Pre-define every MobX-decorated field on model instances so reads made before the data arrives are tracked. Co-Authored-By: Claude Fable 5.1 * test: Inherited base-class fields are observable on partial models Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- app/models/base/Model.test.ts | 43 +++++++++++++++++++++++++++++++++ app/models/base/Model.ts | 45 ++++++++++++++++++++++++++++++++++- 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/app/models/base/Model.test.ts b/app/models/base/Model.test.ts index 6f091a4772..1b9b72e66e 100644 --- a/app/models/base/Model.test.ts +++ b/app/models/base/Model.test.ts @@ -45,6 +45,49 @@ describe("Model observability", () => { expect(seen).toEqual([undefined, false, true]); }); + it("annotates fields inherited from base classes and omitted from the payload", () => { + const doc = stores.documents.add({ + id: "aaaaaaaa-6666-6666-6666-666666666666", + title: "partial", + }); + + expect(isObservableProp(doc, "createdAt")).toBe(true); // Model + expect(isObservableProp(doc, "deletedAt")).toBe(true); // ParanoidModel + expect(isObservableProp(doc, "archivedAt")).toBe(true); // ArchivableModel + }); + + it("annotates observable fields that are not serializable fields", () => { + // Revision content is observable but not a @Field, and list responses + // omit it entirely. + const revision = stores.revisions.add({ + id: "bbbbbbbb-1111-1111-1111-111111111111", + documentId: "aaaaaaaa-1111-1111-1111-111111111111", + title: "partial", + }); + + expect(isObservableProp(revision, "data")).toBe(true); + }); + + it("tracks reads of an omitted field made before it is populated", () => { + const revision = stores.revisions.add({ + id: "bbbbbbbb-2222-2222-2222-222222222222", + documentId: "aaaaaaaa-1111-1111-1111-111111111111", + title: "partial", + }); + const seen: Array = []; + const dispose = autorun(() => seen.push(revision.data?.type)); + + stores.revisions.add({ + id: "bbbbbbbb-2222-2222-2222-222222222222", + documentId: "aaaaaaaa-1111-1111-1111-111111111111", + title: "partial", + data: { type: "doc", content: [] }, + }); + + dispose(); + expect(seen).toEqual([undefined, "doc"]); + }); + it("reacts to changes", () => { const doc = stores.documents.add({ id: "aaaaaaaa-2222-2222-2222-222222222222", diff --git a/app/models/base/Model.ts b/app/models/base/Model.ts index e39b022c11..0f0c5dbdc7 100644 --- a/app/models/base/Model.ts +++ b/app/models/base/Model.ts @@ -8,6 +8,45 @@ import { getFieldsForModel, getFieldsForModelClass } from "../decorators/Field"; import { LifecycleManager } from "../decorators/Lifecycle"; import { getRelationsForModelClass } from "../decorators/Relation"; +/** + * MobX records decorator annotations on the prototype under a symbol with this + * description. + */ +const storedAnnotationsDescription = "mobx-stored-annotations"; + +/** + * Returns the keys of every decorated member on a model, including those + * inherited from base classes. The nearest record on the prototype chain + * already includes the parents' annotations, so the search stops there. + * + * With `useDefineForClassFields: false` a field declared without an initializer + * never exists on the instance, so MobX cannot annotate it. This helper, and + * the pre-definition in `initialize`, can be removed if that compiler option + * is enabled. + * + * @param target the model to inspect. + * @returns the keys annotated with a MobX decorator. + */ +function getAnnotatedKeysForModel(target: Model): (string | symbol)[] { + let prototype = Object.getPrototypeOf(target); + + while (prototype && prototype !== Object.prototype) { + const symbol = Object.getOwnPropertySymbols(prototype).find( + (candidate) => candidate.description === storedAnnotationsDescription + ); + if (symbol) { + const annotations: Record = Reflect.get( + prototype, + symbol + ); + return Reflect.ownKeys(annotations); + } + prototype = Object.getPrototypeOf(prototype); + } + + return []; +} + export default abstract class Model { static modelName: string; @@ -57,7 +96,11 @@ export default abstract class Model { * @param fields the data to construct the model with. */ protected initialize(fields: Record) { - for (const field of getFieldsForModel(this)) { + const declared = [ + ...getFieldsForModel(this), + ...getAnnotatedKeysForModel(this), + ]; + for (const field of declared) { if (field in this) { continue; } From bc8c8a96ec18ba6845007b7887370e6e4d8400e9 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 01:26:02 -0400 Subject: [PATCH 025/368] perf: Prefetch revision content on hover in history sidebar (#13688) * perf: Prefetch revision content on hover in history sidebar * Dedupe and cache latest revision fetches * Use await in fetchLatest --- .../components/History/RevisionListItem.tsx | 13 +++++- app/stores/RevisionsStore.ts | 40 ++++++++++++++----- 2 files changed, 43 insertions(+), 10 deletions(-) diff --git a/app/scenes/Document/components/History/RevisionListItem.tsx b/app/scenes/Document/components/History/RevisionListItem.tsx index 7155a45cfd..4c9443536e 100644 --- a/app/scenes/Document/components/History/RevisionListItem.tsx +++ b/app/scenes/Document/components/History/RevisionListItem.tsx @@ -1,7 +1,7 @@ import type { LocationDescriptor } from "history"; import { observer } from "mobx-react"; import { EditIcon, TrashIcon } from "outline-icons"; -import { useMemo, useRef } from "react"; +import { useCallback, useMemo, useRef } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; import styled, { css } from "styled-components"; @@ -22,8 +22,10 @@ import { ContextMenu } from "~/components/Menu/ContextMenu"; import Time from "~/components/Time"; import { ActionContextProvider } from "~/hooks/useActionContext"; import useBoolean from "~/hooks/useBoolean"; +import useClickIntent from "~/hooks/useClickIntent"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import { useMenuAction } from "~/hooks/useMenuAction"; +import useStores from "~/hooks/useStores"; import RevisionMenu from "~/menus/RevisionMenu"; import { documentHistoryPath } from "~/utils/routeHelpers"; import { EventItem, lineStyle } from "./EventListItem"; @@ -38,6 +40,7 @@ type Props = { const RevisionListItem = ({ item, document, ...rest }: Props) => { const { t } = useTranslation(); + const { revisions } = useStores(); const location = useLocation(); const sidebarContext = useLocationSidebarContext(); const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean(); @@ -57,6 +60,12 @@ const RevisionListItem = ({ item, document, ...rest }: Props) => { ); const contextMenuAction = useMenuAction(actions); + const handleClickIntent = useCallback(() => { + void revisions.fetch(item.id); + }, [revisions, item.id]); + const { handleMouseEnter, handleMouseLeave } = + useClickIntent(handleClickIntent); + // the time component tends to steal focus when clicked // ...so forward the focus back to the parent item const handleTimeClick = () => { @@ -149,6 +158,8 @@ const RevisionListItem = ({ item, document, ...rest }: Props) => { } + onMouseEnter={handleMouseEnter} + onMouseLeave={handleMouseLeave} ref={ref} $menuOpen={menuOpen} {...rest} diff --git a/app/stores/RevisionsStore.ts b/app/stores/RevisionsStore.ts index b7fcdb0b3a..9073956727 100644 --- a/app/stores/RevisionsStore.ts +++ b/app/stores/RevisionsStore.ts @@ -1,3 +1,4 @@ +import { runInAction } from "mobx"; import { type JSONObject } from "@shared/types"; import { RevisionHelper } from "@shared/utils/RevisionHelper"; import type RootStore from "~/stores/RootStore"; @@ -18,13 +19,14 @@ export default class RevisionsStore extends Store { * @returns A promise that resolves to the fetched revision. */ async fetch(id: string, options: JSONObject = {}): Promise { - const documentId = RevisionHelper.documentIdFromLatestId(id); - if (documentId) { - return this.fetchLatest(documentId); - } - const item = this.get(id); const force = Boolean(options.force) || (!!item && !item.data); + + const documentId = RevisionHelper.documentIdFromLatestId(id); + if (documentId) { + return item && !force ? item : this.fetchLatest(documentId); + } + return super.fetch(id, { ...options, force }); } @@ -43,9 +45,29 @@ export default class RevisionsStore extends Store { * @param documentId - the id of the document to fetch the latest revision for. * @returns A promise that resolves to the latest revision for the given document. */ - fetchLatest = async (documentId: string) => { - const res = await client.post(`/revisions.info`, { documentId }); - this.addPolicies(res.policies); - return this.add(res.data); + fetchLatest = async (documentId: string): Promise => { + const id = RevisionHelper.latestId(documentId); + const inflight = this.requests.get(id); + if (inflight) { + return inflight; + } + + const promise = this.requestLatest(documentId); + this.requests.set(id, promise); + + try { + return await promise; + } finally { + this.requests.delete(id); + } }; + + private async requestLatest(documentId: string): Promise { + const res = await client.post(`/revisions.info`, { documentId }); + + return runInAction(() => { + this.addPolicies(res.policies); + return this.add(res.data); + }); + } } From fcfab6452c59bb7bc96417d6a00db1b0b336e038 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 04:29:40 -0400 Subject: [PATCH 026/368] fix: Links in view mode ignore modifier clicks, drag and keyboard activation (#13689) * fix: Links in read-only documents follow browser behavior for modifier clicks, drag and keyboard * Address feedback --- shared/editor/marks/Link.tsx | 127 +++++++++++++++++++---------------- 1 file changed, 69 insertions(+), 58 deletions(-) diff --git a/shared/editor/marks/Link.tsx b/shared/editor/marks/Link.tsx index 0333dfbcf4..a62d63ad83 100644 --- a/shared/editor/marks/Link.tsx +++ b/shared/editor/marks/Link.tsx @@ -144,6 +144,33 @@ export default class Link extends Mark { } get plugins() { + /** + * Returns the anchor element for a mouse event on a link, or undefined if + * the event does not target a navigable link. + */ + const getLinkTarget = (event: MouseEvent) => { + if (event.button !== 0 && event.button !== 1) { + return undefined; + } + + // SVG anchors, such as those inside Mermaid diagrams, are handled by + // their own extension and have a non-string href. + const target = + event.target instanceof Element ? event.target.closest("a") : null; + if (!(target instanceof HTMLAnchorElement)) { + return undefined; + } + + if ( + target.getAttribute("role") === "button" || + target.matches(".component-attachment *") + ) { + return undefined; + } + + return target; + }; + const handleClick = (view: EditorView, pos: number) => { const { doc, tr } = view.state; const range = getMarkRange( @@ -184,60 +211,25 @@ export default class Link extends Mark { return false; }, mousedown: (view: EditorView, event: MouseEvent) => { - const target = (event.target as HTMLElement)?.closest("a"); - if ( - !(target instanceof HTMLAnchorElement) || - (event.button !== 0 && event.button !== 1) - ) { + const target = getLinkTarget(event); + if (!target || !view.editable) { return false; } - if ( - target.role === "button" || - target.matches(".component-attachment *") - ) { + // A linked image is selected by ProseMirror and handled by its + // node view while editing. + if (event.target instanceof HTMLImageElement) { return false; } - // If an image is selected in write mode, disallow navigation to its href - const selectedDOMNode = view.nodeDOM(view.state.selection.from); - if ( - view.editable && - selectedDOMNode && - selectedDOMNode instanceof HTMLSpanElement && - selectedDOMNode.classList.contains("component-image") && - event.target instanceof HTMLImageElement && - selectedDOMNode.contains(event.target) - ) { - return false; - } - - // clicking a link while editing should show the link toolbar, - // clicking in read-only will navigate - if (!view.editable || (view.editable && !view.hasFocus())) { - const href = - target.href || - (target.parentNode instanceof HTMLAnchorElement - ? target.parentNode.href - : ""); - - try { - const sanitized = sanitizeUrl(href); - if (this.options.onClickLink && sanitized) { - event.stopPropagation(); - event.preventDefault(); - this.options.onClickLink(sanitized, event); - } - } catch (_err) { - this.editor.props.onNotice?.( - t("Sorry, that type of link is not supported"), - "error" - ); - } - + // Clicking a link while editing but unfocused must not move focus + // into the editor, the click handler will navigate instead. + if (!view.hasFocus()) { + event.preventDefault(); return true; } + // Clicking a link while editing selects it to show the toolbar. const result = view.posAtCoords({ left: event.clientX, top: event.clientY, @@ -250,31 +242,50 @@ export default class Link extends Mark { return false; }, - click: (_view: EditorView, event: MouseEvent) => { - if ( - !(event.target instanceof HTMLAnchorElement) || - (event.button !== 0 && event.button !== 1) - ) { + click: (view: EditorView, event: MouseEvent) => { + const target = getLinkTarget(event); + if (!target) { return false; } - if ( - event.target.role === "button" || - event.target.matches(".component-attachment *") - ) { + // A linked image opens the lightbox rather than navigating while + // editing, the node view handles the click. + if (view.editable && event.target instanceof HTMLImageElement) { + event.preventDefault(); return false; } - // Prevent all default click behavior of links, see mousedown above - // for custom link handling. - if (this.options.onClickLink) { + if (view.editable && view.hasFocus()) { + // Links are not followed while editing. event.stopPropagation(); event.preventDefault(); + return false; } - return false; + const href = sanitizeUrl(target.href); + if (!this.options.onClickLink || !href) { + return false; + } + + event.stopPropagation(); + event.preventDefault(); + + try { + this.options.onClickLink(href, event); + } catch (_err) { + this.editor.props.onNotice?.( + t("Sorry, that type of link is not supported"), + "error" + ); + } + + return true; }, keydown: (view: EditorView, event: KeyboardEvent) => { + if (!view.editable) { + return false; + } + if (event.key !== " " && event.key !== "Enter") { return false; } From 4c9e711b7358276fc71254f9b602303d0f33adbf Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 10:58:58 -0400 Subject: [PATCH 027/368] fix: Members receive authorization error when importing a document (#13696) --- .../api/attachments/attachments.test.ts | 59 ++++++++++++++----- server/routes/api/attachments/attachments.ts | 8 +-- 2 files changed, 48 insertions(+), 19 deletions(-) diff --git a/server/routes/api/attachments/attachments.test.ts b/server/routes/api/attachments/attachments.test.ts index 7e910be918..15d50287c3 100644 --- a/server/routes/api/attachments/attachments.test.ts +++ b/server/routes/api/attachments/attachments.test.ts @@ -226,21 +226,50 @@ describe("#attachments.create", () => { } }); - it.each([AttachmentPreset.Import, AttachmentPreset.WorkspaceImport])( - "should not allow upload using %s preset", - async (preset) => { - const user = await buildUser(); - const res = await server.post("/api/attachments.create", user, { - body: { - name: "test.zip", - contentType: "application/zip", - size: 10000, - preset, - }, - }); - expect(res.status).toEqual(403); - } - ); + it("should not allow upload using workspaceImport preset", async () => { + const user = await buildUser(); + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + preset: AttachmentPreset.WorkspaceImport, + }, + }); + expect(res.status).toEqual(403); + }); + + it("should create expiring attachment using import preset", async () => { + const user = await buildUser(); + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + preset: AttachmentPreset.Import, + }, + }); + expect(res.status).toEqual(200); + + const body = await res.json(); + const attachment = await Attachment.findByPk(body.data.attachment.id, { + rejectOnEmpty: true, + }); + expect(attachment.expiresAt).toBeTruthy(); + }); + + it("should not allow viewer to upload using import preset", async () => { + const user = await buildViewer(); + const res = await server.post("/api/attachments.create", user, { + body: { + name: "test.zip", + contentType: "application/zip", + size: 10000, + preset: AttachmentPreset.Import, + }, + }); + expect(res.status).toEqual(403); + }); it("should not allow attachment creation for other documents", async () => { const user = await buildUser(); diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 2c5089f2cc..8c952c2f5a 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -103,12 +103,12 @@ router.post( if (preset === AttachmentPreset.Avatar) { assertIn(contentType, AttachmentValidation.avatarContentTypes); } else { - if ( - preset === AttachmentPreset.Import || - preset === AttachmentPreset.WorkspaceImport - ) { + if (preset === AttachmentPreset.WorkspaceImport) { authorize(user, "createImport", user.team); } + if (preset === AttachmentPreset.Import) { + authorize(user, "createDocument", user.team); + } if (preset === AttachmentPreset.Emoji) { assertIn(contentType, AttachmentValidation.emojiContentTypes); } From 959f54752d670c69b5f101a1c715f7af4d33bbdc Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 12:11:57 -0400 Subject: [PATCH 028/368] fix: stop table pagination at final page (#13697) --- app/hooks/useTableRequest.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/app/hooks/useTableRequest.ts b/app/hooks/useTableRequest.ts index 0c92f555e5..7c845b62da 100644 --- a/app/hooks/useTableRequest.ts +++ b/app/hooks/useTableRequest.ts @@ -28,7 +28,7 @@ export function useTableRequest({ reqFn, reqParams, }: Props): Response { - const [total, setTotal] = useState(); + const [hasNext, setHasNext] = useState(false); const [offset, setOffset] = useState({ value: INITIAL_OFFSET }); const prevParamsRef = useRef(reqParams); const sortRef = useRef(sort); @@ -52,14 +52,12 @@ export function useTableRequest({ ? orderBy(data, sortRef.current.id, sortRef.current.desc ? "desc" : "asc") : undefined; - const next = - !loading && total && sortedData && sortedData.length < total - ? nextPage - : undefined; + const next = !loading && hasNext ? nextPage : undefined; useEffect(() => { if (prevParamsRef.current !== reqParams) { prevParamsRef.current = reqParams; + setHasNext(false); setOffset({ value: INITIAL_OFFSET }); return; } @@ -73,7 +71,10 @@ export function useTableRequest({ } sortRef.current = sort; // Change sort once we receive a response from server - avoids flicker with stale data. - setTotal(response[PAGINATION_SYMBOL]?.total); + const pagination = response[PAGINATION_SYMBOL]; + setHasNext( + !!pagination && pagination.offset + response.length < pagination.total + ); }; void handleRequest(); From cf53932e9c399c9500d9cee25ce0b80012748214 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 12:17:32 -0400 Subject: [PATCH 029/368] fix: Table of contents clicks ignored while a search term is active (#13698) --- app/scenes/Document/components/MultiplayerEditor.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index 5dd095e824..116b39bb87 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -290,11 +290,15 @@ function MultiplayerEditor( ]; }, [remoteProvider, user, ydoc, props.extensions]); + // Read through a ref so the callback runs once per sync, not per identity. + const onSyncedRef = useRef(onSynced); + onSyncedRef.current = onSynced; + useEffect(() => { if ((!hasLocalPersistence || isLocalSynced) && isRemoteSynced) { - void onSynced?.(); + void onSyncedRef.current?.(); } - }, [onSynced, hasLocalPersistence, isLocalSynced, isRemoteSynced]); + }, [hasLocalPersistence, isLocalSynced, isRemoteSynced]); // Disconnect the realtime connection while idle. `isIdle` also checks for // page visibility and will immediately disconnect when a tab is hidden. From 110c3327270c794e64d2341a11290b0eb9f8f1b7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 7 Sep 2026 20:18:36 -0400 Subject: [PATCH 030/368] fix: Byte range handling for media in Safari (#13695) * fix: Byte range handling for media in Safari Safari loads video and audio with byte range requests. Several forms of Range header were mishandled by files.get: a suffix range fell through to a full 200 response, a single byte request served the whole file, a range past the end of the file produced an invalid Content-Range and a truncated body, and a range starting past the end returned 400 rather than 416. Also stop the service worker intercepting these requests. Partial responses cannot be stored by the Cache API, so the route only produced failed writes, and serving media through a service worker prevents playback in Safari. * Refactor to ByteRangeHelper --- plugins/storage/server/api/files.test.ts | 65 +++++++++++++ plugins/storage/server/api/files.ts | 29 ++---- .../server/utils/ByteRangeHelper.test.ts | 96 +++++++++++++++++++ .../storage/server/utils/ByteRangeHelper.ts | 67 +++++++++++++ vite.config.ts | 11 ++- 5 files changed, 244 insertions(+), 24 deletions(-) create mode 100644 plugins/storage/server/utils/ByteRangeHelper.test.ts create mode 100644 plugins/storage/server/utils/ByteRangeHelper.ts diff --git a/plugins/storage/server/api/files.test.ts b/plugins/storage/server/api/files.test.ts index e538ef2b2c..0d9604fa06 100644 --- a/plugins/storage/server/api/files.test.ts +++ b/plugins/storage/server/api/files.test.ts @@ -632,3 +632,68 @@ describe("#files.get", () => { expect(res.headers.get("Content-Type")).toEqual("application/zip"); }); }); + +describe("#files.get byte ranges", () => { + const fileName = "avatar.jpg"; + + const buildFile = async () => { + const user = await buildUser(); + const attachment = await buildAttachment( + { + teamId: user.teamId, + userId: user.id, + contentType: "image/jpeg", + acl: "public-read", + }, + fileName + ); + + const source = path.resolve(__dirname, "..", "test", "fixtures", fileName); + const destination = path.join( + env.FILE_STORAGE_LOCAL_ROOT_DIR, + attachment.key + ); + + ensureDirSync(path.dirname(destination)); + copyFileSync(source, destination); + + return { key: attachment.key, content: await readFile(source) }; + }; + + it("should serve the whole file when no range is requested", async () => { + const { key, content } = await buildFile(); + const res = await server.get(`/api/files.get?key=${key}`); + + expect(res.status).toEqual(200); + expect(res.headers.get("Accept-Ranges")).toEqual("bytes"); + expect(res.headers.get("Content-Length")).toEqual(String(content.length)); + }); + + it("should serve the requested range", async () => { + const { key, content } = await buildFile(); + const res = await server.get(`/api/files.get?key=${key}`, { + headers: { Range: "bytes=-100" }, + }); + + expect(res.status).toEqual(206); + expect(res.headers.get("Content-Length")).toEqual("100"); + expect(res.headers.get("Content-Range")).toEqual( + `bytes ${content.length - 100}-${content.length - 1}/${content.length}` + ); + expect(Buffer.from(await res.arrayBuffer())).toEqual( + content.subarray(-100) + ); + }); + + it("should fail with status 416 when the range cannot be satisfied", async () => { + const { key, content } = await buildFile(); + const res = await server.get(`/api/files.get?key=${key}`, { + headers: { Range: `bytes=${content.length}-` }, + }); + + expect(res.status).toEqual(416); + expect(res.headers.get("Content-Range")).toEqual( + `bytes */${content.length}` + ); + }); +}); diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index 7b26714598..93d2296ed4 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -23,6 +23,7 @@ import type LocalStorage from "@server/storage/files/LocalStorage"; import type { APIContext } from "@server/types"; import { RateLimiterStrategy } from "@server/utils/RateLimiter"; import { getJWTPayload } from "@server/utils/jwt"; +import { ByteRangeHelper } from "../utils/ByteRangeHelper"; import * as T from "./schema"; const router = new Router(); @@ -158,7 +159,13 @@ router.get( // Handle byte range requests // https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests const stats = await (FileStorage as LocalStorage).stat(key); - const range = getByteRange(ctx, stats.size); + const range = ByteRangeHelper.parse(ctx.headers.range, stats.size); + + if (range === ByteRangeHelper.unsatisfiable) { + ctx.status = 416; + ctx.set("Content-Range", `bytes */${stats.size}`); + return; + } if (range) { ctx.status = 206; @@ -175,26 +182,6 @@ router.get( } ); -function getByteRange( - ctx: APIContext, - size: number -): { start: number; end: number } | undefined { - const { range } = ctx.headers; - if (!range) { - return; - } - - const match = range.match(/bytes=(\d+)-(\d+)?/); - if (!match) { - return; - } - - const start = parseInt(match[1], 10); - const end = parseInt(match[2], 10) || size - 1; - - return { start, end }; -} - /** * Verifies a short-lived signature authorizing an upload to a single key. * diff --git a/plugins/storage/server/utils/ByteRangeHelper.test.ts b/plugins/storage/server/utils/ByteRangeHelper.test.ts new file mode 100644 index 0000000000..f6782236e4 --- /dev/null +++ b/plugins/storage/server/utils/ByteRangeHelper.test.ts @@ -0,0 +1,96 @@ +import { ByteRangeHelper } from "./ByteRangeHelper"; + +const { unsatisfiable } = ByteRangeHelper; + +describe("ByteRangeHelper.parse", () => { + it("should serve the whole file when no header is present", () => { + expect(ByteRangeHelper.parse(undefined, 100)).toBeUndefined(); + expect(ByteRangeHelper.parse("", 100)).toBeUndefined(); + }); + + it("should serve the whole file when the header is malformed", () => { + expect(ByteRangeHelper.parse("bytes=abc-", 100)).toBeUndefined(); + expect(ByteRangeHelper.parse("bytes=-", 100)).toBeUndefined(); + expect(ByteRangeHelper.parse("items=0-1", 100)).toBeUndefined(); + expect(ByteRangeHelper.parse("0-1", 100)).toBeUndefined(); + }); + + it("should serve the whole file when multiple ranges are requested", () => { + expect(ByteRangeHelper.parse("bytes=0-1, 10-20", 100)).toBeUndefined(); + }); + + it("should parse a closed range", () => { + expect(ByteRangeHelper.parse("bytes=0-1", 100)).toEqual({ + start: 0, + end: 1, + }); + expect(ByteRangeHelper.parse("bytes=10-20", 100)).toEqual({ + start: 10, + end: 20, + }); + }); + + it("should parse a single byte range", () => { + expect(ByteRangeHelper.parse("bytes=0-0", 100)).toEqual({ + start: 0, + end: 0, + }); + expect(ByteRangeHelper.parse("bytes=99-99", 100)).toEqual({ + start: 99, + end: 99, + }); + }); + + it("should tolerate surrounding whitespace", () => { + expect(ByteRangeHelper.parse(" bytes=0-1 ", 100)).toEqual({ + start: 0, + end: 1, + }); + }); + + it("should parse an open ended range", () => { + expect(ByteRangeHelper.parse("bytes=10-", 100)).toEqual({ + start: 10, + end: 99, + }); + }); + + it("should parse a suffix range", () => { + expect(ByteRangeHelper.parse("bytes=-10", 100)).toEqual({ + start: 90, + end: 99, + }); + }); + + it("should clamp a suffix range longer than the file", () => { + expect(ByteRangeHelper.parse("bytes=-500", 100)).toEqual({ + start: 0, + end: 99, + }); + }); + + it("should clamp a range that runs past the end of the file", () => { + expect(ByteRangeHelper.parse("bytes=0-1000", 100)).toEqual({ + start: 0, + end: 99, + }); + }); + + it("should be unsatisfiable when the range starts past the end", () => { + expect(ByteRangeHelper.parse("bytes=100-", 100)).toBe(unsatisfiable); + expect(ByteRangeHelper.parse("bytes=100-200", 100)).toBe(unsatisfiable); + }); + + it("should be unsatisfiable when the end is before the start", () => { + expect(ByteRangeHelper.parse("bytes=5-2", 100)).toBe(unsatisfiable); + }); + + it("should be unsatisfiable for a zero length suffix", () => { + expect(ByteRangeHelper.parse("bytes=-0", 100)).toBe(unsatisfiable); + }); + + it("should be unsatisfiable for an empty file", () => { + expect(ByteRangeHelper.parse("bytes=0-", 0)).toBe(unsatisfiable); + expect(ByteRangeHelper.parse("bytes=-1", 0)).toBe(unsatisfiable); + }); +}); diff --git a/plugins/storage/server/utils/ByteRangeHelper.ts b/plugins/storage/server/utils/ByteRangeHelper.ts new file mode 100644 index 0000000000..bf984b7d5d --- /dev/null +++ b/plugins/storage/server/utils/ByteRangeHelper.ts @@ -0,0 +1,67 @@ +/** A resolved byte range, inclusive at both ends. */ +export interface ByteRange { + start: number; + end: number; +} + +export class ByteRangeHelper { + /** Returned when the requested range lies entirely outside of the file. */ + static readonly unsatisfiable: unique symbol = Symbol("unsatisfiable"); + + /** + * Parses a single byte range from a Range header, resolved against the size + * of the file being requested. + * + * @param header The value of the Range header, if any. + * @param size The size of the file in bytes. + * @returns The range to serve, `unsatisfiable` if it lies outside of the + * file, or undefined if the entire file should be served. + */ + static parse( + header: string | undefined, + size: number + ): ByteRange | typeof ByteRangeHelper.unsatisfiable | undefined { + if (!header) { + return; + } + + // Only a single range is supported, requests for multiple ranges are + // served in full instead. + const match = header.trim().match(/^bytes=(\d*)-(\d*)$/); + if (!match) { + return; + } + + const [, first, last] = match; + + if (size === 0) { + return this.unsatisfiable; + } + + // A range with no start requests the final N bytes of the file. + if (first === "") { + const suffixLength = parseInt(last, 10); + if (isNaN(suffixLength)) { + return; + } + if (suffixLength === 0) { + return this.unsatisfiable; + } + return { start: Math.max(size - suffixLength, 0), end: size - 1 }; + } + + const start = parseInt(first, 10); + if (start >= size) { + return this.unsatisfiable; + } + + // A range with no end, or one that runs past the file, ends at the last + // byte. + const end = last === "" ? size - 1 : Math.min(parseInt(last, 10), size - 1); + if (end < start) { + return this.unsatisfiable; + } + + return { start, end }; + } +} diff --git a/vite.config.ts b/vite.config.ts index 1498a81502..81b7fa6899 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -103,7 +103,13 @@ export default ({ mode }: ConfigEnv) => }, }, { - urlPattern: /api\/files\.get/, + // Limited to images, as media and PDFs are loaded with byte range + // requests which Safari cannot play back when the response is + // served by a service worker. + urlPattern: ({ url, request }) => + url.pathname.endsWith("/api/files.get") && + request.destination === "image" && + !request.headers.has("range"), handler: "CacheFirst", options: { cacheName: "files-cache", @@ -112,9 +118,8 @@ export default ({ mode }: ConfigEnv) => maxAgeSeconds: 604800, // 7 days }, cacheableResponse: { - statuses: [0, 200, 206], // Include partial content for range requests + statuses: [200], }, - rangeRequests: true, // Allow range requests for partial content }, }, ], From 286c816b25a21ce1450b83d6a8459f37430ff97d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:51:15 -0400 Subject: [PATCH 031/368] chore(deps-dev): bump oxfmt from 0.55.0 to 0.66.0 (#13703) Bumps [oxfmt](https://github.com/oxc-project/oxc/tree/HEAD/npm/oxfmt) from 0.55.0 to 0.66.0. - [Release notes](https://github.com/oxc-project/oxc/releases) - [Changelog](https://github.com/oxc-project/oxc/blob/main/npm/oxfmt/CHANGELOG.md) - [Commits](https://github.com/oxc-project/oxc/commits/oxfmt_v0.66.0/npm/oxfmt) --- updated-dependencies: - dependency-name: oxfmt dependency-version: 0.66.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 162 +++++++++++++++++++++++++-------------------------- 2 files changed, 82 insertions(+), 82 deletions(-) diff --git a/package.json b/package.json index 66602cce94..cdb42102ef 100644 --- a/package.json +++ b/package.json @@ -360,7 +360,7 @@ "lint-staged": "^16.4.0", "msw": "^2.14.2", "nodemon": "^3.1.14", - "oxfmt": "0.55.0", + "oxfmt": "0.66.0", "oxlint": "1.75.0", "oxlint-tsgolint": "7.0.2001", "postinstall-postinstall": "^2.1.0", diff --git a/yarn.lock b/yarn.lock index 2c1dbf36b0..d82467d323 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3839,135 +3839,135 @@ __metadata: languageName: node linkType: hard -"@oxfmt/binding-android-arm-eabi@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-android-arm-eabi@npm:0.55.0" +"@oxfmt/binding-android-arm-eabi@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-android-arm-eabi@npm:0.66.0" conditions: os=android & cpu=arm languageName: node linkType: hard -"@oxfmt/binding-android-arm64@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-android-arm64@npm:0.55.0" +"@oxfmt/binding-android-arm64@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-android-arm64@npm:0.66.0" conditions: os=android & cpu=arm64 languageName: node linkType: hard -"@oxfmt/binding-darwin-arm64@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-darwin-arm64@npm:0.55.0" +"@oxfmt/binding-darwin-arm64@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-darwin-arm64@npm:0.66.0" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@oxfmt/binding-darwin-x64@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-darwin-x64@npm:0.55.0" +"@oxfmt/binding-darwin-x64@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-darwin-x64@npm:0.66.0" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@oxfmt/binding-freebsd-x64@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-freebsd-x64@npm:0.55.0" +"@oxfmt/binding-freebsd-x64@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-freebsd-x64@npm:0.66.0" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard -"@oxfmt/binding-linux-arm-gnueabihf@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-arm-gnueabihf@npm:0.55.0" +"@oxfmt/binding-linux-arm-gnueabihf@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-arm-gnueabihf@npm:0.66.0" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@oxfmt/binding-linux-arm-musleabihf@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-arm-musleabihf@npm:0.55.0" +"@oxfmt/binding-linux-arm-musleabihf@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-arm-musleabihf@npm:0.66.0" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@oxfmt/binding-linux-arm64-gnu@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-arm64-gnu@npm:0.55.0" +"@oxfmt/binding-linux-arm64-gnu@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-arm64-gnu@npm:0.66.0" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@oxfmt/binding-linux-arm64-musl@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-arm64-musl@npm:0.55.0" +"@oxfmt/binding-linux-arm64-musl@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-arm64-musl@npm:0.66.0" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@oxfmt/binding-linux-ppc64-gnu@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-ppc64-gnu@npm:0.55.0" +"@oxfmt/binding-linux-ppc64-gnu@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-ppc64-gnu@npm:0.66.0" conditions: os=linux & cpu=ppc64 & libc=glibc languageName: node linkType: hard -"@oxfmt/binding-linux-riscv64-gnu@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-riscv64-gnu@npm:0.55.0" +"@oxfmt/binding-linux-riscv64-gnu@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-riscv64-gnu@npm:0.66.0" conditions: os=linux & cpu=riscv64 & libc=glibc languageName: node linkType: hard -"@oxfmt/binding-linux-riscv64-musl@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-riscv64-musl@npm:0.55.0" +"@oxfmt/binding-linux-riscv64-musl@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-riscv64-musl@npm:0.66.0" conditions: os=linux & cpu=riscv64 & libc=musl languageName: node linkType: hard -"@oxfmt/binding-linux-s390x-gnu@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-s390x-gnu@npm:0.55.0" +"@oxfmt/binding-linux-s390x-gnu@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-s390x-gnu@npm:0.66.0" conditions: os=linux & cpu=s390x & libc=glibc languageName: node linkType: hard -"@oxfmt/binding-linux-x64-gnu@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-x64-gnu@npm:0.55.0" +"@oxfmt/binding-linux-x64-gnu@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-x64-gnu@npm:0.66.0" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@oxfmt/binding-linux-x64-musl@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-linux-x64-musl@npm:0.55.0" +"@oxfmt/binding-linux-x64-musl@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-linux-x64-musl@npm:0.66.0" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@oxfmt/binding-openharmony-arm64@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-openharmony-arm64@npm:0.55.0" +"@oxfmt/binding-openharmony-arm64@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-openharmony-arm64@npm:0.66.0" conditions: os=openharmony & cpu=arm64 languageName: node linkType: hard -"@oxfmt/binding-win32-arm64-msvc@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-win32-arm64-msvc@npm:0.55.0" +"@oxfmt/binding-win32-arm64-msvc@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-win32-arm64-msvc@npm:0.66.0" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@oxfmt/binding-win32-ia32-msvc@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-win32-ia32-msvc@npm:0.55.0" +"@oxfmt/binding-win32-ia32-msvc@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-win32-ia32-msvc@npm:0.66.0" conditions: os=win32 & cpu=ia32 languageName: node linkType: hard -"@oxfmt/binding-win32-x64-msvc@npm:0.55.0": - version: 0.55.0 - resolution: "@oxfmt/binding-win32-x64-msvc@npm:0.55.0" +"@oxfmt/binding-win32-x64-msvc@npm:0.66.0": + version: 0.66.0 + resolution: "@oxfmt/binding-win32-x64-msvc@npm:0.66.0" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -15716,7 +15716,7 @@ __metadata: nodemon: "npm:^3.1.14" octokit: "npm:^5.0.5" outline-icons: "npm:^4.6.0" - oxfmt: "npm:0.55.0" + oxfmt: "npm:0.66.0" oxlint: "npm:1.75.0" oxlint-tsgolint: "npm:7.0.2001" oy-vey: "npm:^0.12.1" @@ -15912,29 +15912,29 @@ __metadata: languageName: node linkType: hard -"oxfmt@npm:0.55.0": - version: 0.55.0 - resolution: "oxfmt@npm:0.55.0" +"oxfmt@npm:0.66.0": + version: 0.66.0 + resolution: "oxfmt@npm:0.66.0" dependencies: - "@oxfmt/binding-android-arm-eabi": "npm:0.55.0" - "@oxfmt/binding-android-arm64": "npm:0.55.0" - "@oxfmt/binding-darwin-arm64": "npm:0.55.0" - "@oxfmt/binding-darwin-x64": "npm:0.55.0" - "@oxfmt/binding-freebsd-x64": "npm:0.55.0" - "@oxfmt/binding-linux-arm-gnueabihf": "npm:0.55.0" - "@oxfmt/binding-linux-arm-musleabihf": "npm:0.55.0" - "@oxfmt/binding-linux-arm64-gnu": "npm:0.55.0" - "@oxfmt/binding-linux-arm64-musl": "npm:0.55.0" - "@oxfmt/binding-linux-ppc64-gnu": "npm:0.55.0" - "@oxfmt/binding-linux-riscv64-gnu": "npm:0.55.0" - "@oxfmt/binding-linux-riscv64-musl": "npm:0.55.0" - "@oxfmt/binding-linux-s390x-gnu": "npm:0.55.0" - "@oxfmt/binding-linux-x64-gnu": "npm:0.55.0" - "@oxfmt/binding-linux-x64-musl": "npm:0.55.0" - "@oxfmt/binding-openharmony-arm64": "npm:0.55.0" - "@oxfmt/binding-win32-arm64-msvc": "npm:0.55.0" - "@oxfmt/binding-win32-ia32-msvc": "npm:0.55.0" - "@oxfmt/binding-win32-x64-msvc": "npm:0.55.0" + "@oxfmt/binding-android-arm-eabi": "npm:0.66.0" + "@oxfmt/binding-android-arm64": "npm:0.66.0" + "@oxfmt/binding-darwin-arm64": "npm:0.66.0" + "@oxfmt/binding-darwin-x64": "npm:0.66.0" + "@oxfmt/binding-freebsd-x64": "npm:0.66.0" + "@oxfmt/binding-linux-arm-gnueabihf": "npm:0.66.0" + "@oxfmt/binding-linux-arm-musleabihf": "npm:0.66.0" + "@oxfmt/binding-linux-arm64-gnu": "npm:0.66.0" + "@oxfmt/binding-linux-arm64-musl": "npm:0.66.0" + "@oxfmt/binding-linux-ppc64-gnu": "npm:0.66.0" + "@oxfmt/binding-linux-riscv64-gnu": "npm:0.66.0" + "@oxfmt/binding-linux-riscv64-musl": "npm:0.66.0" + "@oxfmt/binding-linux-s390x-gnu": "npm:0.66.0" + "@oxfmt/binding-linux-x64-gnu": "npm:0.66.0" + "@oxfmt/binding-linux-x64-musl": "npm:0.66.0" + "@oxfmt/binding-openharmony-arm64": "npm:0.66.0" + "@oxfmt/binding-win32-arm64-msvc": "npm:0.66.0" + "@oxfmt/binding-win32-ia32-msvc": "npm:0.66.0" + "@oxfmt/binding-win32-x64-msvc": "npm:0.66.0" tinypool: "npm:2.1.0" peerDependencies: svelte: ^5.0.0 @@ -15985,7 +15985,7 @@ __metadata: optional: true bin: oxfmt: bin/oxfmt - checksum: 10c0/8052adf41f426d34e08ba464efeb388d8864ee00c263719d7aa5d72c96e436e8a24cd83597904387a5764e87ea2bd57e7e7f26772d6347b7181bb3bf2ab8f5bb + checksum: 10c0/add0d810b6bd62ecf7da74479d65e9f44e490ce4ed79670bdb80a3e0ecc7611192c92f3692790929003d2f8bead6d45b8457211cc3ba01e27af693233702189e languageName: node linkType: hard From c3275d1b1b40fa7e8e67f187b6638321bcaafc6e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:51:23 -0400 Subject: [PATCH 032/368] chore(deps-dev): bump @types/ioredis-mock from 8.2.7 to 8.2.8 (#13702) Bumps [@types/ioredis-mock](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ioredis-mock) from 8.2.7 to 8.2.8. - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ioredis-mock) --- updated-dependencies: - dependency-name: "@types/ioredis-mock" dependency-version: 8.2.8 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index cdb42102ef..204d7f733d 100644 --- a/package.json +++ b/package.json @@ -300,7 +300,7 @@ "@types/glob": "^8.0.1", "@types/google.analytics": "^0.0.46", "@types/invariant": "^2.2.37", - "@types/ioredis-mock": "^8.2.7", + "@types/ioredis-mock": "^8.2.8", "@types/js-yaml": "^4.0.9", "@types/jsdom": "^28.0.1", "@types/jsonwebtoken": "^8.5.9", diff --git a/yarn.lock b/yarn.lock index d82467d323..2d651faf9a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6848,12 +6848,12 @@ __metadata: languageName: node linkType: hard -"@types/ioredis-mock@npm:^8.2.7": - version: 8.2.7 - resolution: "@types/ioredis-mock@npm:8.2.7" +"@types/ioredis-mock@npm:^8.2.8": + version: 8.2.8 + resolution: "@types/ioredis-mock@npm:8.2.8" peerDependencies: - ioredis: ">=5" - checksum: 10c0/cb3b30815d099f4e4652290618a8dc84aadf101027f3b996b0045bad363e9355b05076477fbec31495faac7aae9463a30a6ae8d1a366702010dbf6acca6af1ae + ioredis: ^5 + checksum: 10c0/af7a6546b2f43f4c8af4ef1deb453d1e436d901bd9e25d23b0e100b6170712ae38e72ca022fd12fa3616b4abe8ceee5a5b483db8774a99b3403ee3d2097fb9c6 languageName: node linkType: hard @@ -15581,7 +15581,7 @@ __metadata: "@types/glob": "npm:^8.0.1" "@types/google.analytics": "npm:^0.0.46" "@types/invariant": "npm:^2.2.37" - "@types/ioredis-mock": "npm:^8.2.7" + "@types/ioredis-mock": "npm:^8.2.8" "@types/js-yaml": "npm:^4.0.9" "@types/jsdom": "npm:^28.0.1" "@types/jsonwebtoken": "npm:^8.5.9" From ed2dd33d7f44fe2d09a7954183a5548ab5ed3927 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:51:31 -0400 Subject: [PATCH 033/368] chore(deps): bump the sentry group with 2 updates (#13699) Bumps the sentry group with 2 updates: [@sentry/node](https://github.com/getsentry/sentry-javascript) and [@sentry/react](https://github.com/getsentry/sentry-javascript). Updates `@sentry/node` from 10.72.0 to 10.73.0 - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/10.73.0/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/10.72.0...10.73.0) Updates `@sentry/react` from 10.72.0 to 10.73.0 - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/10.73.0/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/10.72.0...10.73.0) --- updated-dependencies: - dependency-name: "@sentry/node" dependency-version: 10.73.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: sentry - dependency-name: "@sentry/react" dependency-version: 10.73.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: sentry ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 4 +- yarn.lock | 134 +++++++++++++++++++++++++-------------------------- 2 files changed, 69 insertions(+), 69 deletions(-) diff --git a/package.json b/package.json index 204d7f733d..f135834186 100644 --- a/package.json +++ b/package.json @@ -105,8 +105,8 @@ "@radix-ui/react-toolbar": "^1.1.19", "@radix-ui/react-tooltip": "^1.2.16", "@radix-ui/react-visually-hidden": "^1.2.11", - "@sentry/node": "^10.72.0", - "@sentry/react": "^10.72.0", + "@sentry/node": "^10.73.0", + "@sentry/react": "^10.73.0", "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.2", "@tanstack/react-table": "^8.21.3", diff --git a/yarn.lock b/yarn.lock index 2d651faf9a..8fb6c37b01 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5694,27 +5694,27 @@ __metadata: languageName: node linkType: hard -"@sentry/browser-utils@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/browser-utils@npm:10.72.0" +"@sentry/browser-utils@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/browser-utils@npm:10.73.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" - checksum: 10c0/2ec35c405a83aa24bc455178db04ec30b0784508ed129cefb7321aa7da2a4e5f966494fbac6c3a658db3dfa90d6d849784257bc82d7afe7e574d312368efd9ca + "@sentry/core": "npm:10.73.0" + checksum: 10c0/01ce6ee0f8b009560a6a05d073a244152011aea0fbdc4198f16308bace6ef80a0dd9dcf5d0dacc3bf2198da1d346159e67c17060ab6720b28f73e8766c0e784c languageName: node linkType: hard -"@sentry/browser@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/browser@npm:10.72.0" +"@sentry/browser@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/browser@npm:10.73.0" dependencies: - "@sentry/browser-utils": "npm:10.72.0" + "@sentry/browser-utils": "npm:10.73.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" - "@sentry/feedback": "npm:10.72.0" - "@sentry/replay": "npm:10.72.0" - "@sentry/replay-canvas": "npm:10.72.0" - checksum: 10c0/86facf754ab024407b12ca57e00ba8b8a1495c3f58bcdc17491209264fe6173285d9920dde7134a700a52f5d57bf4bfd860a31eab788baf07d710f76d3c549f1 + "@sentry/core": "npm:10.73.0" + "@sentry/feedback": "npm:10.73.0" + "@sentry/replay": "npm:10.73.0" + "@sentry/replay-canvas": "npm:10.73.0" + checksum: 10c0/5d6f9581ca8c142d6a4c409c9f34c6f3f5585c3006da12e952836ff83b9bf4fd6c0e0f650b245be4d5497ac4bb8f34d7c658a79300ecd2b165db262fd36c3544 languageName: node linkType: hard @@ -5725,31 +5725,31 @@ __metadata: languageName: node linkType: hard -"@sentry/core@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/core@npm:10.72.0" +"@sentry/core@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/core@npm:10.73.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - checksum: 10c0/6b923a7d89c746ac87b9f1037ab08017d3c22ca1c8d295ac19bac580f58d5c354d16bd6c017c4834ded7f7a9c124c3dd876dbf256430ee6eabfed8f808b417b9 + checksum: 10c0/553469fd82ec11f5697ab4b2881b6f811834a1036e88afe24920940f131d59ad1dfcd008b99656661c49c7c9de51678719b884b0a6cfcb696312fd58bb911495 languageName: node linkType: hard -"@sentry/feedback@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/feedback@npm:10.72.0" +"@sentry/feedback@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/feedback@npm:10.73.0" dependencies: - "@sentry/core": "npm:10.72.0" - checksum: 10c0/fcfb4820c67bf1684d46a295c60e711123be518ee5d5e917efc0da36fffe4701ffaa4fc7065d1064e58f4f5af0ef84c01f18dbbc51a7fe4705c1b0919fb09278 + "@sentry/core": "npm:10.73.0" + checksum: 10c0/7dcb318f742a9d4aa5379be889df6f55fab9e5dcbaed0a0a1c90565f8ea6047c562435616c5bbe5a78bdb3a31dc3d023b16ff082c6c8c908aaec8255da801112 languageName: node linkType: hard -"@sentry/node-core@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/node-core@npm:10.72.0" +"@sentry/node-core@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/node-core@npm:10.73.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" - "@sentry/opentelemetry": "npm:10.72.0" + "@sentry/core": "npm:10.73.0" + "@sentry/opentelemetry": "npm:10.73.0" import-in-the-middle: "npm:^3.0.0" peerDependencies: "@opentelemetry/api": ^1.9.0 @@ -5768,81 +5768,81 @@ __metadata: optional: true "@opentelemetry/sdk-trace-base": optional: true - checksum: 10c0/b1d25d00a8c6ec1f21700d9a7e4146830b66f311362fae51162be8b702990d4b883c9ed449d55c0ae57a410b6d440e8384cb65dfa9dccab6eb6ceabafb66974d + checksum: 10c0/4641120f7b0c2eb41db6134f86a5633ffa7c0a7411bf3526855065e1d8143ea4e5852f71f62bac456f3efbb691be201144a4db3e02d5b53328e65d4293d3ec3c languageName: node linkType: hard -"@sentry/node@npm:^10.72.0": - version: 10.72.0 - resolution: "@sentry/node@npm:10.72.0" +"@sentry/node@npm:^10.73.0": + version: 10.73.0 + resolution: "@sentry/node@npm:10.73.0" dependencies: "@opentelemetry/api": "npm:^1.9.1" "@opentelemetry/instrumentation": "npm:^0.220.0" "@opentelemetry/sdk-trace-base": "npm:^2.9.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" - "@sentry/node-core": "npm:10.72.0" - "@sentry/opentelemetry": "npm:10.72.0" - "@sentry/server-utils": "npm:10.72.0" + "@sentry/core": "npm:10.73.0" + "@sentry/node-core": "npm:10.73.0" + "@sentry/opentelemetry": "npm:10.73.0" + "@sentry/server-utils": "npm:10.73.0" import-in-the-middle: "npm:^3.0.0" - checksum: 10c0/5c687a074d5b16611edede72cd46276644527fd9e99265f07c5739684900c4ba6ea4b0238739859d10088bcfd494a89e860442b505c9bab92982c626445f9a88 + checksum: 10c0/8ddb8a279bf9e2c383942c240ef47abc7dd5ebbb7b89f3058edfed9105dba07a97634dae38e0820167b330dcdf4e3113999856cd3423ead0aedc80872daa338a languageName: node linkType: hard -"@sentry/opentelemetry@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/opentelemetry@npm:10.72.0" +"@sentry/opentelemetry@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/opentelemetry@npm:10.73.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" + "@sentry/core": "npm:10.73.0" peerDependencies: "@opentelemetry/api": ^1.9.0 "@opentelemetry/core": ^1.30.1 || ^2.1.0 "@opentelemetry/sdk-trace-base": ^1.30.1 || ^2.1.0 - checksum: 10c0/5e54a591ea9b361b36b95e45344c5a5c036798959bd03fe8664bda4dce3434476734be58d0e1228e0dd28b397c0ba83e022a73999363d61999abe570babce99f + checksum: 10c0/d3d6204cb5a784c9d5572bc1143c1e0f150585fe038bed9924df904a75cb365f26bb2d3cb8f953f719085eceebfa0f3904d9ae7fee08818f5cb41eb1dbd9197c languageName: node linkType: hard -"@sentry/react@npm:^10.72.0": - version: 10.72.0 - resolution: "@sentry/react@npm:10.72.0" +"@sentry/react@npm:^10.73.0": + version: 10.73.0 + resolution: "@sentry/react@npm:10.73.0" dependencies: - "@sentry/browser": "npm:10.72.0" + "@sentry/browser": "npm:10.73.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" + "@sentry/core": "npm:10.73.0" peerDependencies: react: ^16.14.0 || 17.x || 18.x || 19.x - checksum: 10c0/b593a0bd7579ef95acf94c96a129bb2156140e758635a8e3a196c01dae635f192052f98a9a00677644e08fdb5ff827edfc6858f2b86d135be1e1a31d413f522b + checksum: 10c0/84afea9290b8a59486566abc011dfee353c0427cf9a22725444a762153a10c31d61eb7b2e5c8cc458bf245e9974b9a2993dadf066e976e5c429bf324559ecefc languageName: node linkType: hard -"@sentry/replay-canvas@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/replay-canvas@npm:10.72.0" +"@sentry/replay-canvas@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/replay-canvas@npm:10.73.0" dependencies: - "@sentry/core": "npm:10.72.0" - "@sentry/replay": "npm:10.72.0" - checksum: 10c0/514081d5972dab76a09649457788ab9f58d819c62208c32f415e9531b33c246488b6135f44f12be8ceeb47f585ee48f0d08df24f66f4794553f15bebdf8e5c69 + "@sentry/core": "npm:10.73.0" + "@sentry/replay": "npm:10.73.0" + checksum: 10c0/1ba25555afaa65bfc731a2b997a73a24c0f502ef15514dca9e068bb44acb3538fafe317c6e7fb3fe58df9a6f1a7915245f61dd4ab1ee6e4ef2bb713280e2fe58 languageName: node linkType: hard -"@sentry/replay@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/replay@npm:10.72.0" +"@sentry/replay@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/replay@npm:10.73.0" dependencies: - "@sentry/browser-utils": "npm:10.72.0" - "@sentry/core": "npm:10.72.0" - checksum: 10c0/5a3dbe1c6e4aee63187a9705d824014a44121ac87c4daa297ff12ad8f91199f4d3dac3c61b467f579f400e63aa6e4e5ffaf46a3e47dc07bb9ead8cee22b70bfb + "@sentry/browser-utils": "npm:10.73.0" + "@sentry/core": "npm:10.73.0" + checksum: 10c0/f0bfaa9d824afd2abc91d594b24c75d4509908c16761bb6a62e5aeb70c0a3665b40b07e75d4bfdebaa735a4fc29057783fd7465b08b22744221ca7a3d5913ca1 languageName: node linkType: hard -"@sentry/server-utils@npm:10.72.0": - version: 10.72.0 - resolution: "@sentry/server-utils@npm:10.72.0" +"@sentry/server-utils@npm:10.73.0": + version: 10.73.0 + resolution: "@sentry/server-utils@npm:10.73.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.72.0" - checksum: 10c0/99e9133c80f280c744fe8a0507a5a07f9d34a4a064ec43e9017b2c0d2979f513079ebe0ff62957276f64591f406d1068b8cb5b782d7bd77bad66b7b2ce26afc2 + "@sentry/core": "npm:10.73.0" + checksum: 10c0/58196c7fefa4ac1ecd5f560f6de1d5dd313774cc752871c0882f2bb6a06fd0097506f2f503b167c6851425644e0ddc405121d8538a6274addd33276d8db55f9b languageName: node linkType: hard @@ -15558,8 +15558,8 @@ __metadata: "@radix-ui/react-tooltip": "npm:^1.2.16" "@radix-ui/react-visually-hidden": "npm:^1.2.11" "@relative-ci/agent": "npm:^4.3.1" - "@sentry/node": "npm:^10.72.0" - "@sentry/react": "npm:^10.72.0" + "@sentry/node": "npm:^10.73.0" + "@sentry/react": "npm:^10.73.0" "@simplewebauthn/browser": "npm:^13.3.0" "@simplewebauthn/server": "npm:^13.3.2" "@swc/cli": "npm:^0.8.1" From 10dc1572fefc342b2b16dea1a450198799452c21 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:51:39 -0400 Subject: [PATCH 034/368] chore(deps): bump the aws group with 6 updates (#13700) Bumps the aws group with 6 updates: | Package | From | To | | --- | --- | --- | | [@aws-sdk/client-s3](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/clients/client-s3) | `3.1121.0` | `3.1126.0` | | [@aws-sdk/cloudfront-signer](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/cloudfront-signer) | `3.1116.0` | `3.1125.0` | | [@aws-sdk/lib-storage](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/lib/lib-storage) | `3.1121.0` | `3.1126.0` | | [@aws-sdk/s3-presigned-post](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/s3-presigned-post) | `3.1121.0` | `3.1126.0` | | [@aws-sdk/s3-request-presigner](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/s3-request-presigner) | `3.1121.0` | `3.1126.0` | | [@aws-sdk/signature-v4-crt](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/signature-v4-crt) | `3.1121.0` | `3.1126.0` | Updates `@aws-sdk/client-s3` from 3.1121.0 to 3.1126.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/clients/client-s3/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1126.0/clients/client-s3) Updates `@aws-sdk/cloudfront-signer` from 3.1116.0 to 3.1125.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/cloudfront-signer/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1125.0/packages/cloudfront-signer) Updates `@aws-sdk/lib-storage` from 3.1121.0 to 3.1126.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/lib/lib-storage/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1126.0/lib/lib-storage) Updates `@aws-sdk/s3-presigned-post` from 3.1121.0 to 3.1126.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/s3-presigned-post/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1126.0/packages/s3-presigned-post) Updates `@aws-sdk/s3-request-presigner` from 3.1121.0 to 3.1126.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/s3-request-presigner/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1126.0/packages/s3-request-presigner) Updates `@aws-sdk/signature-v4-crt` from 3.1121.0 to 3.1126.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/signature-v4-crt/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1126.0/packages/signature-v4-crt) --- updated-dependencies: - dependency-name: "@aws-sdk/client-s3" dependency-version: 3.1126.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/cloudfront-signer" dependency-version: 3.1125.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/lib-storage" dependency-version: 3.1126.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/s3-presigned-post" dependency-version: 3.1126.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/s3-request-presigner" dependency-version: 3.1126.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/signature-v4-crt" dependency-version: 3.1126.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 12 ++++----- yarn.lock | 74 ++++++++++++++++++++++++++-------------------------- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/package.json b/package.json index f135834186..3db2d46d1c 100644 --- a/package.json +++ b/package.json @@ -52,12 +52,12 @@ "> 0.25%, not dead" ], "dependencies": { - "@aws-sdk/client-s3": "^3.1121.0", - "@aws-sdk/cloudfront-signer": "^3.1116.0", - "@aws-sdk/lib-storage": "^3.1121.0", - "@aws-sdk/s3-presigned-post": "^3.1121.0", - "@aws-sdk/s3-request-presigner": "^3.1121.0", - "@aws-sdk/signature-v4-crt": "^3.1121.0", + "@aws-sdk/client-s3": "^3.1126.0", + "@aws-sdk/cloudfront-signer": "^3.1125.0", + "@aws-sdk/lib-storage": "^3.1126.0", + "@aws-sdk/s3-presigned-post": "^3.1126.0", + "@aws-sdk/s3-request-presigner": "^3.1126.0", + "@aws-sdk/signature-v4-crt": "^3.1126.0", "@benrbray/prosemirror-math": "^0.2.2", "@bull-board/api": "^6.21.3", "@bull-board/koa": "^6.21.3", diff --git a/yarn.lock b/yarn.lock index 8fb6c37b01..5be96f4d3e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -41,13 +41,13 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/client-s3@npm:3.1121.0, @aws-sdk/client-s3@npm:^3.1121.0": - version: 3.1121.0 - resolution: "@aws-sdk/client-s3@npm:3.1121.0" +"@aws-sdk/client-s3@npm:3.1126.0, @aws-sdk/client-s3@npm:^3.1126.0": + version: 3.1126.0 + resolution: "@aws-sdk/client-s3@npm:3.1126.0" dependencies: "@aws-sdk/checksums": "npm:^3.1000.29" "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/credential-provider-node": "npm:^3.972.81" + "@aws-sdk/credential-provider-node": "npm:^3.972.82" "@aws-sdk/middleware-sdk-s3": "npm:^3.972.75" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" @@ -56,17 +56,17 @@ __metadata: "@smithy/node-http-handler": "npm:^4.11.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/ed715f4e8a25c22da391ed984d489664c3e1e575f35cda0e8c17adacedfd33b6265ec811824dadf28c2f001e55c6847369cbf9774b03dc05175e4e56f5111b45 + checksum: 10c0/1b2c3aa631f04b80f7eef8c91cd8145886a38cd7d04eb1ff3c1721693cb79f191e1e8821390e67f80661159b89b0e327306fd289decf74e603ce4ebc86a909b1 languageName: node linkType: hard -"@aws-sdk/cloudfront-signer@npm:^3.1116.0": - version: 3.1116.0 - resolution: "@aws-sdk/cloudfront-signer@npm:3.1116.0" +"@aws-sdk/cloudfront-signer@npm:^3.1125.0": + version: 3.1125.0 + resolution: "@aws-sdk/cloudfront-signer@npm:3.1125.0" dependencies: "@smithy/core": "npm:^3.33.3" tslib: "npm:^2.6.2" - checksum: 10c0/15692d584f2498c549b68cdebf4b774f0fac70c12c2a7924c2c0701665e29c9df5f3e387b5570f84712fdf9807fd0997e83310ee50c4d43d0925d067367d0e9b + checksum: 10c0/b4c3ed35cd5b0c0875cfcd1cf1851c8296d0a80b8cc7bc51321660fe392d730d9446c4dbd61ed5bc50044ed403e499b6d48e41776daa0de804d172685a232df6 languageName: node linkType: hard @@ -149,9 +149,9 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/credential-provider-node@npm:^3.972.81": - version: 3.972.81 - resolution: "@aws-sdk/credential-provider-node@npm:3.972.81" +"@aws-sdk/credential-provider-node@npm:^3.972.82": + version: 3.972.82 + resolution: "@aws-sdk/credential-provider-node@npm:3.972.82" dependencies: "@aws-sdk/credential-provider-env": "npm:^3.972.70" "@aws-sdk/credential-provider-http": "npm:^3.972.72" @@ -164,7 +164,7 @@ __metadata: "@smithy/credential-provider-imds": "npm:^4.4.16" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/b0e60a641a4648dcae0e20b3f2fe3866bb1b5aeba64617146888b4208d94878a8421cd74bbf1f8b921a50cc1e8410fa707ca30af0349ec54be43ce5e8004a748 + checksum: 10c0/c79c2381c1e76fecadb5adf9a8623946d819b20bfc0eaa236a384115027cdea3fe1f0a294c75edbb6aee1a0ccbbc4ec606c2eee8e1c4d720ed2ef281aa1175c8 languageName: node linkType: hard @@ -221,9 +221,9 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/lib-storage@npm:^3.1121.0": - version: 3.1121.0 - resolution: "@aws-sdk/lib-storage@npm:3.1121.0" +"@aws-sdk/lib-storage@npm:^3.1126.0": + version: 3.1126.0 + resolution: "@aws-sdk/lib-storage@npm:3.1126.0" dependencies: "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" @@ -232,8 +232,8 @@ __metadata: stream-browserify: "npm:3.0.0" tslib: "npm:^2.6.2" peerDependencies: - "@aws-sdk/client-s3": ^3.1121.0 - checksum: 10c0/50b139eae0d78bab254aa2fd6c1ae3a3f183e72ee1442f11b8a91cfc199437bf19da083f60752968b6dc5f7f02f44437ece1fbcc5f5bda048a34e7ab6bcd1f66 + "@aws-sdk/client-s3": ^3.1126.0 + checksum: 10c0/486623e8593e29e6eddc83ebf11e005d991072cf3251cbe6576ecf34707dfb146f2217bd11be413b7755a5a221293901691028fba0c5c8e69db79c75c44cc86f languageName: node linkType: hard @@ -267,24 +267,24 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/s3-presigned-post@npm:^3.1121.0": - version: 3.1121.0 - resolution: "@aws-sdk/s3-presigned-post@npm:3.1121.0" +"@aws-sdk/s3-presigned-post@npm:^3.1126.0": + version: 3.1126.0 + resolution: "@aws-sdk/s3-presigned-post@npm:3.1126.0" dependencies: - "@aws-sdk/client-s3": "npm:3.1121.0" + "@aws-sdk/client-s3": "npm:3.1126.0" "@aws-sdk/core": "npm:^3.977.9" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/signature-v4": "npm:^5.6.12" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/927f53e0824329ab8f1756e49d38b89a2b13ba119f2f926ae732b3b9e5bd86e4fe909f1a61b83f2537317fb7b434860e2091f917bb016bdbc27b2019804220ef + checksum: 10c0/42ffe8f738b5eed91d0d8b002f1dc21f2b7d9df7f2ddc06e742f5b9d453d798b62659ee93e8e7e531d8b3af84b4152f06d799d3fb5691bbae7dee4b9506549b8 languageName: node linkType: hard -"@aws-sdk/s3-request-presigner@npm:^3.1121.0": - version: 3.1121.0 - resolution: "@aws-sdk/s3-request-presigner@npm:3.1121.0" +"@aws-sdk/s3-request-presigner@npm:^3.1126.0": + version: 3.1126.0 + resolution: "@aws-sdk/s3-request-presigner@npm:3.1126.0" dependencies: "@aws-sdk/core": "npm:^3.977.9" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" @@ -292,13 +292,13 @@ __metadata: "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/416e9de4a9e2e7bfeb9e97d95bdb15664880b485eb429ed812641f3555878e9577948e695cf05ecdb191283033200c7ee9388c71069b34670e514d98be039b52 + checksum: 10c0/ef83d9af9767663371d09e5025f9be76bfafe51e715e0d1c916d7d74479cb7c28c50f09e1591d7dc4b471ec90fdb0ee59a12791466934304b582c1e1cfbb558d languageName: node linkType: hard -"@aws-sdk/signature-v4-crt@npm:^3.1121.0": - version: 3.1121.0 - resolution: "@aws-sdk/signature-v4-crt@npm:3.1121.0" +"@aws-sdk/signature-v4-crt@npm:^3.1126.0": + version: 3.1126.0 + resolution: "@aws-sdk/signature-v4-crt@npm:3.1126.0" dependencies: "@aws-sdk/crt-loader": "npm:^3.972.74" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" @@ -307,7 +307,7 @@ __metadata: "@smithy/signature-v4": "npm:^5.6.12" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/f4c3eddd670e30b26ef7dd9ad8995cccc885dd0fc97d1aa06da93e69d406e8a9a39b9fdf09cf5674e1ea0767a25790a899390c8a95e7efc3fcc90c75c0718a40 + checksum: 10c0/36106485a9942ae7774a47d814ee1f1a9efeb7e37d3227846650ecb097438fa4bfc6eda375809011599913e2625921d3492a7d740cb559e451bc47f124a95501 languageName: node linkType: hard @@ -15503,12 +15503,12 @@ __metadata: version: 0.0.0-use.local resolution: "outline@workspace:." dependencies: - "@aws-sdk/client-s3": "npm:^3.1121.0" - "@aws-sdk/cloudfront-signer": "npm:^3.1116.0" - "@aws-sdk/lib-storage": "npm:^3.1121.0" - "@aws-sdk/s3-presigned-post": "npm:^3.1121.0" - "@aws-sdk/s3-request-presigner": "npm:^3.1121.0" - "@aws-sdk/signature-v4-crt": "npm:^3.1121.0" + "@aws-sdk/client-s3": "npm:^3.1126.0" + "@aws-sdk/cloudfront-signer": "npm:^3.1125.0" + "@aws-sdk/lib-storage": "npm:^3.1126.0" + "@aws-sdk/s3-presigned-post": "npm:^3.1126.0" + "@aws-sdk/s3-request-presigner": "npm:^3.1126.0" + "@aws-sdk/signature-v4-crt": "npm:^3.1126.0" "@benrbray/prosemirror-math": "npm:^0.2.2" "@bull-board/api": "npm:^6.21.3" "@bull-board/koa": "npm:^6.21.3" From e15954649e6ac5d5f543e841223e9bea5aa19323 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:03:37 -0400 Subject: [PATCH 035/368] chore(deps-dev): bump oxlint from 1.75.0 to 1.81.0 (#13701) * chore(deps-dev): bump oxlint from 1.75.0 to 1.81.0 Bumps [oxlint](https://github.com/oxc-project/oxc/tree/HEAD/npm/oxlint) from 1.75.0 to 1.81.0. - [Release notes](https://github.com/oxc-project/oxc/releases) - [Changelog](https://github.com/oxc-project/oxc/blob/main/npm/oxlint/CHANGELOG.md) - [Commits](https://github.com/oxc-project/oxc/commits/oxlint_v1.81.0/npm/oxlint) --- updated-dependencies: - dependency-name: oxlint dependency-version: 1.81.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * chore: Disable no-redeclare for TypeScript files oxlint 1.79+ flags value and type declarations that share a name, which is valid TypeScript declaration merging. tsc already reports true redeclarations. --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Tom Moor --- .oxlintrc.json | 6 ++ package.json | 2 +- yarn.lock | 162 ++++++++++++++++++++++++------------------------- 3 files changed, 88 insertions(+), 82 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 5cc0cbd062..203bd0254f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -70,6 +70,12 @@ "valid-typeof": "error" }, "overrides": [ + { + "files": ["**/*.{ts,tsx}"], + "rules": { + "no-redeclare": "off" + } + }, { "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { diff --git a/package.json b/package.json index 3db2d46d1c..d9c7d3db92 100644 --- a/package.json +++ b/package.json @@ -361,7 +361,7 @@ "msw": "^2.14.2", "nodemon": "^3.1.14", "oxfmt": "0.66.0", - "oxlint": "1.75.0", + "oxlint": "1.81.0", "oxlint-tsgolint": "7.0.2001", "postinstall-postinstall": "^2.1.0", "react-refresh": "^0.18.0", diff --git a/yarn.lock b/yarn.lock index 5be96f4d3e..8f9261d967 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4014,135 +4014,135 @@ __metadata: languageName: node linkType: hard -"@oxlint/binding-android-arm-eabi@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-android-arm-eabi@npm:1.75.0" +"@oxlint/binding-android-arm-eabi@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-android-arm-eabi@npm:1.81.0" conditions: os=android & cpu=arm languageName: node linkType: hard -"@oxlint/binding-android-arm64@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-android-arm64@npm:1.75.0" +"@oxlint/binding-android-arm64@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-android-arm64@npm:1.81.0" conditions: os=android & cpu=arm64 languageName: node linkType: hard -"@oxlint/binding-darwin-arm64@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-darwin-arm64@npm:1.75.0" +"@oxlint/binding-darwin-arm64@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-darwin-arm64@npm:1.81.0" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@oxlint/binding-darwin-x64@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-darwin-x64@npm:1.75.0" +"@oxlint/binding-darwin-x64@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-darwin-x64@npm:1.81.0" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@oxlint/binding-freebsd-x64@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-freebsd-x64@npm:1.75.0" +"@oxlint/binding-freebsd-x64@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-freebsd-x64@npm:1.81.0" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard -"@oxlint/binding-linux-arm-gnueabihf@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-arm-gnueabihf@npm:1.75.0" +"@oxlint/binding-linux-arm-gnueabihf@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-arm-gnueabihf@npm:1.81.0" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@oxlint/binding-linux-arm-musleabihf@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-arm-musleabihf@npm:1.75.0" +"@oxlint/binding-linux-arm-musleabihf@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-arm-musleabihf@npm:1.81.0" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@oxlint/binding-linux-arm64-gnu@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-arm64-gnu@npm:1.75.0" +"@oxlint/binding-linux-arm64-gnu@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-arm64-gnu@npm:1.81.0" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@oxlint/binding-linux-arm64-musl@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-arm64-musl@npm:1.75.0" +"@oxlint/binding-linux-arm64-musl@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-arm64-musl@npm:1.81.0" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@oxlint/binding-linux-ppc64-gnu@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-ppc64-gnu@npm:1.75.0" +"@oxlint/binding-linux-ppc64-gnu@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-ppc64-gnu@npm:1.81.0" conditions: os=linux & cpu=ppc64 & libc=glibc languageName: node linkType: hard -"@oxlint/binding-linux-riscv64-gnu@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-riscv64-gnu@npm:1.75.0" +"@oxlint/binding-linux-riscv64-gnu@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-riscv64-gnu@npm:1.81.0" conditions: os=linux & cpu=riscv64 & libc=glibc languageName: node linkType: hard -"@oxlint/binding-linux-riscv64-musl@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-riscv64-musl@npm:1.75.0" +"@oxlint/binding-linux-riscv64-musl@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-riscv64-musl@npm:1.81.0" conditions: os=linux & cpu=riscv64 & libc=musl languageName: node linkType: hard -"@oxlint/binding-linux-s390x-gnu@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-s390x-gnu@npm:1.75.0" +"@oxlint/binding-linux-s390x-gnu@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-s390x-gnu@npm:1.81.0" conditions: os=linux & cpu=s390x & libc=glibc languageName: node linkType: hard -"@oxlint/binding-linux-x64-gnu@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-x64-gnu@npm:1.75.0" +"@oxlint/binding-linux-x64-gnu@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-x64-gnu@npm:1.81.0" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@oxlint/binding-linux-x64-musl@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-linux-x64-musl@npm:1.75.0" +"@oxlint/binding-linux-x64-musl@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-linux-x64-musl@npm:1.81.0" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@oxlint/binding-openharmony-arm64@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-openharmony-arm64@npm:1.75.0" +"@oxlint/binding-openharmony-arm64@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-openharmony-arm64@npm:1.81.0" conditions: os=openharmony & cpu=arm64 languageName: node linkType: hard -"@oxlint/binding-win32-arm64-msvc@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-win32-arm64-msvc@npm:1.75.0" +"@oxlint/binding-win32-arm64-msvc@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-win32-arm64-msvc@npm:1.81.0" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@oxlint/binding-win32-ia32-msvc@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-win32-ia32-msvc@npm:1.75.0" +"@oxlint/binding-win32-ia32-msvc@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-win32-ia32-msvc@npm:1.81.0" conditions: os=win32 & cpu=ia32 languageName: node linkType: hard -"@oxlint/binding-win32-x64-msvc@npm:1.75.0": - version: 1.75.0 - resolution: "@oxlint/binding-win32-x64-msvc@npm:1.75.0" +"@oxlint/binding-win32-x64-msvc@npm:1.81.0": + version: 1.81.0 + resolution: "@oxlint/binding-win32-x64-msvc@npm:1.81.0" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -15717,7 +15717,7 @@ __metadata: octokit: "npm:^5.0.5" outline-icons: "npm:^4.6.0" oxfmt: "npm:0.66.0" - oxlint: "npm:1.75.0" + oxlint: "npm:1.81.0" oxlint-tsgolint: "npm:7.0.2001" oy-vey: "npm:^0.12.1" pako: "npm:^2.1.0" @@ -16018,29 +16018,29 @@ __metadata: languageName: node linkType: hard -"oxlint@npm:1.75.0": - version: 1.75.0 - resolution: "oxlint@npm:1.75.0" +"oxlint@npm:1.81.0": + version: 1.81.0 + resolution: "oxlint@npm:1.81.0" dependencies: - "@oxlint/binding-android-arm-eabi": "npm:1.75.0" - "@oxlint/binding-android-arm64": "npm:1.75.0" - "@oxlint/binding-darwin-arm64": "npm:1.75.0" - "@oxlint/binding-darwin-x64": "npm:1.75.0" - "@oxlint/binding-freebsd-x64": "npm:1.75.0" - "@oxlint/binding-linux-arm-gnueabihf": "npm:1.75.0" - "@oxlint/binding-linux-arm-musleabihf": "npm:1.75.0" - "@oxlint/binding-linux-arm64-gnu": "npm:1.75.0" - "@oxlint/binding-linux-arm64-musl": "npm:1.75.0" - "@oxlint/binding-linux-ppc64-gnu": "npm:1.75.0" - "@oxlint/binding-linux-riscv64-gnu": "npm:1.75.0" - "@oxlint/binding-linux-riscv64-musl": "npm:1.75.0" - "@oxlint/binding-linux-s390x-gnu": "npm:1.75.0" - "@oxlint/binding-linux-x64-gnu": "npm:1.75.0" - "@oxlint/binding-linux-x64-musl": "npm:1.75.0" - "@oxlint/binding-openharmony-arm64": "npm:1.75.0" - "@oxlint/binding-win32-arm64-msvc": "npm:1.75.0" - "@oxlint/binding-win32-ia32-msvc": "npm:1.75.0" - "@oxlint/binding-win32-x64-msvc": "npm:1.75.0" + "@oxlint/binding-android-arm-eabi": "npm:1.81.0" + "@oxlint/binding-android-arm64": "npm:1.81.0" + "@oxlint/binding-darwin-arm64": "npm:1.81.0" + "@oxlint/binding-darwin-x64": "npm:1.81.0" + "@oxlint/binding-freebsd-x64": "npm:1.81.0" + "@oxlint/binding-linux-arm-gnueabihf": "npm:1.81.0" + "@oxlint/binding-linux-arm-musleabihf": "npm:1.81.0" + "@oxlint/binding-linux-arm64-gnu": "npm:1.81.0" + "@oxlint/binding-linux-arm64-musl": "npm:1.81.0" + "@oxlint/binding-linux-ppc64-gnu": "npm:1.81.0" + "@oxlint/binding-linux-riscv64-gnu": "npm:1.81.0" + "@oxlint/binding-linux-riscv64-musl": "npm:1.81.0" + "@oxlint/binding-linux-s390x-gnu": "npm:1.81.0" + "@oxlint/binding-linux-x64-gnu": "npm:1.81.0" + "@oxlint/binding-linux-x64-musl": "npm:1.81.0" + "@oxlint/binding-openharmony-arm64": "npm:1.81.0" + "@oxlint/binding-win32-arm64-msvc": "npm:1.81.0" + "@oxlint/binding-win32-ia32-msvc": "npm:1.81.0" + "@oxlint/binding-win32-x64-msvc": "npm:1.81.0" peerDependencies: oxlint-tsgolint: ">=7.0.2001" vite-plus: "*" @@ -16090,7 +16090,7 @@ __metadata: optional: true bin: oxlint: bin/oxlint - checksum: 10c0/3cdd0d30ddd284d3c4caab9f9a9b0c71d18aab7fc00b115c37da95d5c648d8c62686c6aad3aab4633f25beb88e75f1f9bcc42dd66cedf7bdfacbfbe048e5dcf1 + checksum: 10c0/547027fc2dae81851b61819886f36d95a694a12c457e0b740708756005da23602fbbb9579ea133341f3a45656e7d0821a042423e26267be5a1630492a88e8691 languageName: node linkType: hard From c1811ffa205748ee0e5350eaec9afaf8072f6817 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 8 Sep 2026 00:20:29 -0400 Subject: [PATCH 036/368] fix: Scroll position reset when navigating between revisions (#13704) * fix: Scroll position reset when navigating between revisions * fix: Clear revision error when returning to the live document --- app/scenes/Document/components/DataLoader.tsx | 1 + app/scenes/Document/components/Document.tsx | 1 - app/scenes/Document/components/RevisionViewer.tsx | 1 + app/scenes/Document/index.tsx | 14 +++++--------- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index a18d6b737e..3cba266554 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -137,6 +137,7 @@ function DataLoader({ match, children }: Props) { ); React.useEffect(() => { + setError(null); if (revisionId) { void fetchRevisionById(revisionId, setError); } diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index f4eac6a1c3..9e9f124d54 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -343,7 +343,6 @@ function DocumentScene({ ) { // extension — usually only arrives on a later render; without this neither // the highlights nor the change count would ever appear. const editorKey = [ + revision.id, showChanges ? "changes" : "no-changes", compareToRevisionId ?? revision.before?.id ?? "none", comparisonData ? "loaded" : "pending", diff --git a/app/scenes/Document/index.tsx b/app/scenes/Document/index.tsx index 100692742c..99d0d55dcd 100644 --- a/app/scenes/Document/index.tsx +++ b/app/scenes/Document/index.tsx @@ -30,7 +30,7 @@ export default function DocumentScene(props: Props) { const { ui } = useStores(); const history = useHistory(); const { pane, isSplitView } = useSplitView(); - const { documentSlug, revisionId } = props.match.params; + const { documentSlug } = props.match.params; const currentPath = props.location.pathname; useTrackLastVisitedPath(currentPath); @@ -63,16 +63,12 @@ export default function DocumentScene(props: Props) { const urlParts = documentSlug ? documentSlug.split("-") : []; const urlId = urlParts.length ? urlParts[urlParts.length - 1] : undefined; - // Normalize the key so that it is *stable* between renders. - // Without this, the initial value can be "/undefined" and then flip to - // "/" when React stringifies `undefined` on the next render, causing a - // full unmount/mount cycle of the document subtree. Keeping the key constant - // prevents extra network requests and preserves editor state on resize. - const key = revisionId ? `${urlId}/${revisionId}` : urlId; - + // The revision is deliberately not part of the key: remounting the subtree + // between revisions would empty the page while the next one loads and reset + // the scroll position. DataLoader refetches when the revision id changes. return ( Date: Tue, 8 Sep 2026 11:04:25 -0400 Subject: [PATCH 037/368] fix: Allow viewers with collection write access to import documents (#13707) --- server/routes/api/attachments/attachments.test.ts | 10 ++++++++-- server/routes/api/attachments/attachments.ts | 3 --- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/server/routes/api/attachments/attachments.test.ts b/server/routes/api/attachments/attachments.test.ts index 15d50287c3..7d001f7327 100644 --- a/server/routes/api/attachments/attachments.test.ts +++ b/server/routes/api/attachments/attachments.test.ts @@ -258,7 +258,7 @@ describe("#attachments.create", () => { expect(attachment.expiresAt).toBeTruthy(); }); - it("should not allow viewer to upload using import preset", async () => { + it("should allow viewer to upload using import preset", async () => { const user = await buildViewer(); const res = await server.post("/api/attachments.create", user, { body: { @@ -268,7 +268,13 @@ describe("#attachments.create", () => { preset: AttachmentPreset.Import, }, }); - expect(res.status).toEqual(403); + expect(res.status).toEqual(200); + + const body = await res.json(); + const attachment = await Attachment.findByPk(body.data.attachment.id, { + rejectOnEmpty: true, + }); + expect(attachment.expiresAt).toBeTruthy(); }); it("should not allow attachment creation for other documents", async () => { diff --git a/server/routes/api/attachments/attachments.ts b/server/routes/api/attachments/attachments.ts index 8c952c2f5a..ac70e7729d 100644 --- a/server/routes/api/attachments/attachments.ts +++ b/server/routes/api/attachments/attachments.ts @@ -106,9 +106,6 @@ router.post( if (preset === AttachmentPreset.WorkspaceImport) { authorize(user, "createImport", user.team); } - if (preset === AttachmentPreset.Import) { - authorize(user, "createDocument", user.team); - } if (preset === AttachmentPreset.Emoji) { assertIn(contentType, AttachmentValidation.emojiContentTypes); } From 68b912825cf4a4b3694a08f32f866cff39234b45 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 8 Sep 2026 11:20:39 -0400 Subject: [PATCH 038/368] perf: Skip loading document body for authorization-only lookups (#13706) Several high-traffic endpoints (views.create, views.list, comments.list, relationships.list, subscriptions.list/info, events.list, pins.info, documents.insights/users/documents) load a document purely to run a policy check, yet fetched its full content, text and state columns on every request. The read policy only inspects ownership, membership and collection fields, so pass includeContent: false to use the existing withoutContent scope. comments.list keeps the body only when anchor text is requested, which is the sole consumer of it. Claude-Session: https://claude.ai/code/session_017swPbmq4SwtkE15fcRhdcU Co-authored-by: Claude --- server/routes/api/comments/comments.ts | 6 +++++- server/routes/api/documents/documents.ts | 11 +++++++++-- server/routes/api/events/events.ts | 1 + server/routes/api/pins/pins.ts | 5 ++++- server/routes/api/relationships/relationships.ts | 1 + server/routes/api/subscriptions/subscriptions.ts | 2 ++ server/routes/api/views/views.ts | 2 ++ 7 files changed, 24 insertions(+), 4 deletions(-) diff --git a/server/routes/api/comments/comments.ts b/server/routes/api/comments/comments.ts index 50c729151f..f9bd052775 100644 --- a/server/routes/api/comments/comments.ts +++ b/server/routes/api/comments/comments.ts @@ -209,7 +209,11 @@ router.post( let comments, total; if (documentId) { - const document = await Document.findByPk(documentId, { userId: user.id }); + const document = await Document.findByPk(documentId, { + userId: user.id, + // The body is only needed to resolve anchor text for each comment. + includeContent: !!includeAnchorText, + }); authorize(user, "read", document); [comments, total] = await Promise.all([ Comment.findAll(params), diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 55f357ffb0..fca05c2b32 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -792,7 +792,10 @@ router.post( const { id, startDate, endDate } = ctx.input.body; const { user } = ctx.state.auth; - const document = await Document.findByPk(id, { userId: user.id }); + const document = await Document.findByPk(id, { + userId: user.id, + includeContent: false, + }); authorize(user, "listViews", document); if (!document.insightsEnabled) { @@ -829,6 +832,7 @@ router.post( const actor = ctx.state.auth.user; const document = await Document.findByPk(id, { userId: actor.id, + includeContent: false, }); authorize(actor, "read", document); @@ -911,7 +915,10 @@ router.post( async (ctx: APIContext) => { const { id } = ctx.input.body; const { user } = ctx.state.auth; - const document = await Document.findByPk(id, { userId: user.id }); + const document = await Document.findByPk(id, { + userId: user.id, + includeContent: false, + }); authorize(user, "read", document); diff --git a/server/routes/api/events/events.ts b/server/routes/api/events/events.ts index cef1ffbcb7..a68f1e9025 100644 --- a/server/routes/api/events/events.ts +++ b/server/routes/api/events/events.ts @@ -66,6 +66,7 @@ router.post( if (documentId) { const document = await Document.findByPk(documentId, { userId: user.id, + includeContent: false, }); authorize(user, "read", document); where = { ...where, documentId }; diff --git a/server/routes/api/pins/pins.ts b/server/routes/api/pins/pins.ts index 44bf976ae1..95669c7b6b 100644 --- a/server/routes/api/pins/pins.ts +++ b/server/routes/api/pins/pins.ts @@ -69,7 +69,10 @@ router.post( const { user } = ctx.state.auth; const { documentId, collectionId } = ctx.input.body; - const document = await Document.findByPk(documentId, { userId: user.id }); + const document = await Document.findByPk(documentId, { + userId: user.id, + includeContent: false, + }); authorize(user, "read", document); // There can be only one pin with these props. diff --git a/server/routes/api/relationships/relationships.ts b/server/routes/api/relationships/relationships.ts index eb51547a5c..43565ea049 100644 --- a/server/routes/api/relationships/relationships.ts +++ b/server/routes/api/relationships/relationships.ts @@ -74,6 +74,7 @@ router.post( const anchorDocument = await Document.findByPk(anchorId, { userId: user.id, + includeContent: false, rejectOnEmpty: true, }); authorize(user, "read", anchorDocument); diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index 0cc6ea2a75..25a22e202c 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -47,6 +47,7 @@ router.post( // documentId will be available here const document = await Document.findByPk(documentId!, { userId: user.id, + includeContent: false, }); authorize(user, "read", document); @@ -91,6 +92,7 @@ router.post( // documentId will be available here const document = await Document.findByPk(documentId!, { userId: user.id, + includeContent: false, }); authorize(user, "read", document); diff --git a/server/routes/api/views/views.ts b/server/routes/api/views/views.ts index 3e405cbf71..8475262978 100644 --- a/server/routes/api/views/views.ts +++ b/server/routes/api/views/views.ts @@ -24,6 +24,7 @@ router.post( const document = await Document.findByPk(documentId, { userId: user.id, + includeContent: false, }); authorize(user, "listViews", document); @@ -51,6 +52,7 @@ router.post( const document = await Document.findByPk(documentId, { userId: user.id, + includeContent: false, }); authorize(user, "read", document); From 4a5a616a21be800257dc11cef4263d0dd0412156 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Sep 2026 21:05:58 +0800 Subject: [PATCH 039/368] v1.10.1 --- LICENSE | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/LICENSE b/LICENSE index 3ba5896f6a..494e025dfb 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 1.10.0 +Licensed Work: Outline 1.10.1 The Licensed Work is (c) 2026 General Outline, Inc. Additional Use Grant: You may make use of the Licensed Work, provided that you may not use the Licensed Work for a Document @@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that Licensed Work by creating teams and documents controlled by such third parties. -Change Date: 2030-09-01 +Change Date: 2030-09-09 Change License: Apache License, Version 2.0 diff --git a/package.json b/package.json index d9c7d3db92..21ef330c47 100644 --- a/package.json +++ b/package.json @@ -388,6 +388,6 @@ "deepmerge-ts@npm:^7.1.5": "^8.0.1", "i18next-parser/i18next": "^23.16.8" }, - "version": "1.10.0", + "version": "1.10.1", "packageManager": "yarn@4.11.0" } From 699ac012e657d2e5fde1054ca032774b42d4d723 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:28:35 -0400 Subject: [PATCH 040/368] chore(deps): bump js-yaml from 4.3.1 to 4.3.2 (#13711) Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.3.1 to 4.3.2. - [Changelog](https://github.com/nodeca/js-yaml/blob/4.3.2/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/4.3.1...4.3.2) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 4.3.2 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 21ef330c47..6b0035ea0e 100644 --- a/package.json +++ b/package.json @@ -157,7 +157,7 @@ "ipaddr.js": "^2.4.0", "is-printable-key-event": "^1.0.0", "iso-639-3": "^3.0.1", - "js-yaml": "^4.3.1", + "js-yaml": "^4.3.2", "jsdom": "^22.1.0", "jsonwebtoken": "^9.0.3", "katex": "^0.16.45", diff --git a/yarn.lock b/yarn.lock index 8f9261d967..62ffb1f886 100644 --- a/yarn.lock +++ b/yarn.lock @@ -13416,6 +13416,17 @@ __metadata: languageName: node linkType: hard +"js-yaml@npm:^4.3.2": + version: 4.3.2 + resolution: "js-yaml@npm:4.3.2" + dependencies: + argparse: "npm:^2.0.1" + bin: + js-yaml: bin/js-yaml.js + checksum: 10c0/dedd34c2e8fef1d504687f1bc94ed0ee1311a1f78770fa2800352c6d59c635ccf555009d74e9afe529ae62199da2b1ccef30e53dc84dcd8d2d8187c22574bc97 + languageName: node + linkType: hard + "jsdom@npm:^22.1.0": version: 22.1.0 resolution: "jsdom@npm:22.1.0" @@ -15683,7 +15694,7 @@ __metadata: ipaddr.js: "npm:^2.4.0" is-printable-key-event: "npm:^1.0.0" iso-639-3: "npm:^3.0.1" - js-yaml: "npm:^4.3.1" + js-yaml: "npm:^4.3.2" jsdom: "npm:^22.1.0" jsonwebtoken: "npm:^9.0.3" katex: "npm:^0.16.45" From 0632d459cb742e79870df478a12b12453069976c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:28:46 -0400 Subject: [PATCH 041/368] chore(deps): bump nodemailer from 9.0.5 to 9.1.1 (#13710) Bumps [nodemailer](https://github.com/nodemailer/nodemailer) from 9.0.5 to 9.1.1. - [Release notes](https://github.com/nodemailer/nodemailer/releases) - [Changelog](https://github.com/nodemailer/nodemailer/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodemailer/nodemailer/compare/v9.0.5...v9.1.1) --- updated-dependencies: - dependency-name: nodemailer dependency-version: 9.1.1 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 6b0035ea0e..a99f299378 100644 --- a/package.json +++ b/package.json @@ -184,7 +184,7 @@ "mobx-utils": "^6.1.1", "natural-sort": "^1.0.0", "node-fetch": "2.7.0", - "nodemailer": "^9.0.5", + "nodemailer": "^9.1.1", "octokit": "^5.0.5", "outline-icons": "^4.6.0", "oy-vey": "^0.12.1", diff --git a/yarn.lock b/yarn.lock index 62ffb1f886..deb9906252 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15190,13 +15190,20 @@ __metadata: languageName: node linkType: hard -"nodemailer@npm:9.0.5, nodemailer@npm:^9.0.5": +"nodemailer@npm:9.0.5": version: 9.0.5 resolution: "nodemailer@npm:9.0.5" checksum: 10c0/60f7a21497c98c0d275cd12c488af581ef6aee65db575026319ac249dcac210bdab20edf77fe3158176ed3910f70d8c46d89abcd74f57a7170302727e6d05ee3 languageName: node linkType: hard +"nodemailer@npm:^9.1.1": + version: 9.1.1 + resolution: "nodemailer@npm:9.1.1" + checksum: 10c0/b213a2a906697a735f6eb21103629b7a77aeac297b6d843efd4588157999bf6d19381853ac1224e472f5a34aec2e2412444151a2c6ec6e8c52150afa3055039c + languageName: node + linkType: hard + "nodemon@npm:^3.1.14": version: 3.1.14 resolution: "nodemon@npm:3.1.14" @@ -15723,7 +15730,7 @@ __metadata: msw: "npm:^2.14.2" natural-sort: "npm:^1.0.0" node-fetch: "npm:2.7.0" - nodemailer: "npm:^9.0.5" + nodemailer: "npm:^9.1.1" nodemon: "npm:^3.1.14" octokit: "npm:^5.0.5" outline-icons: "npm:^4.6.0" From 00e20ee9c2e4472b4cfe64abcbc4761d2960b91b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:50:46 -0400 Subject: [PATCH 042/368] chore(deps): bump hono from 4.13.0 to 4.13.7 (#13712) Bumps [hono](https://github.com/honojs/hono) from 4.13.0 to 4.13.7. - [Release notes](https://github.com/honojs/hono/releases) - [Commits](https://github.com/honojs/hono/compare/v4.13.0...v4.13.7) --- updated-dependencies: - dependency-name: hono dependency-version: 4.13.7 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index deb9906252..11b032d91a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12261,9 +12261,9 @@ __metadata: linkType: hard "hono@npm:^4.11.4": - version: 4.13.0 - resolution: "hono@npm:4.13.0" - checksum: 10c0/d7cfb4d1063be19bea1982ea2a6b3cfa1840e8403a03203e86d17278e76fed11e7483974738345257543e183a935ea73ffc6d4a1e6ad7f0008451f55cdf8be7b + version: 4.13.7 + resolution: "hono@npm:4.13.7" + checksum: 10c0/29672a94a4f2be7f3f4d959ad69808dd3bbc220909ca4f9660997022ff45d48ae71e42a460e417d808809d68110196f19359aaab2b14ae6a750331d789601b5a languageName: node linkType: hard From ebe9adc1cfabd4d37428640c21b80e7787c4dfe7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 09:51:02 -0400 Subject: [PATCH 043/368] chore(deps-dev): bump vitest from 4.1.10 to 4.1.11 (#13709) Bumps [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) from 4.1.10 to 4.1.11. - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/vitest) --- updated-dependencies: - dependency-name: vitest dependency-version: 4.1.11 dependency-type: direct:development ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 108 +++++++++++++++++++++------------------------------ 2 files changed, 45 insertions(+), 65 deletions(-) diff --git a/package.json b/package.json index a99f299378..ce50722af1 100644 --- a/package.json +++ b/package.json @@ -371,7 +371,7 @@ "typescript": "^6.0.3", "unplugin-swc": "^1.5.11", "vite-tsconfig-paths": "^6.1.1", - "vitest": "^4.1.10" + "vitest": "^4.1.11" }, "resolutions": { "@types/react": "18.3.31", diff --git a/yarn.lock b/yarn.lock index 11b032d91a..da37bacd3e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7566,25 +7566,25 @@ __metadata: languageName: node linkType: hard -"@vitest/expect@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/expect@npm:4.1.10" +"@vitest/expect@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/expect@npm:4.1.11" dependencies: "@standard-schema/spec": "npm:^1.1.0" "@types/chai": "npm:^5.2.2" - "@vitest/spy": "npm:4.1.10" - "@vitest/utils": "npm:4.1.10" + "@vitest/spy": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" chai: "npm:^6.2.2" tinyrainbow: "npm:^3.1.0" - checksum: 10c0/a817ad0d9bd6a039776a7228d54fb8319c17e4af15917407f5566ac61781a8511f591d302519d6999217399915bc3c0290028189fc73f5c38f80cb01b6f19c8d + checksum: 10c0/0aa5e0973aca93a58cbdc3041c6bfed5897e976124965203b96a23b811f4ca403590c7eb15802c8d8366ec27a1db0682451e8a91c4d06617636de262baf86e4b languageName: node linkType: hard -"@vitest/mocker@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/mocker@npm:4.1.10" +"@vitest/mocker@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/mocker@npm:4.1.11" dependencies: - "@vitest/spy": "npm:4.1.10" + "@vitest/spy": "npm:4.1.11" estree-walker: "npm:^3.0.3" magic-string: "npm:^0.30.21" peerDependencies: @@ -7595,16 +7595,7 @@ __metadata: optional: true vite: optional: true - checksum: 10c0/4aa70b0df58681652e2e28093437fb2e8f4d02a6d03f5619abc266ac1c5ae5f43326148061d13ae6e071e0f6cfcf7634659af63644de8ce098a7c98949a3d1ad - languageName: node - linkType: hard - -"@vitest/pretty-format@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/pretty-format@npm:4.1.10" - dependencies: - tinyrainbow: "npm:^3.1.0" - checksum: 10c0/1a5daba730ffe23f2000bff484b4b2842f3b178d93663cb487b215516b8d3b62caa3e2bb2a3c63307b61a9fe58fb9bfff38559bc0c5e49d8aa403d6803a1d918 + checksum: 10c0/3111ea34bd5046f6c70bbd67cf8b89608ee8c41cb27ab2bd61d42f4b68810e9ea16a9a757a71bc254c105f73b407d00ebb6bab1ab0f7f5cdcc9d7d16602a3933 languageName: node linkType: hard @@ -7617,32 +7608,32 @@ __metadata: languageName: node linkType: hard -"@vitest/runner@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/runner@npm:4.1.10" +"@vitest/runner@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/runner@npm:4.1.11" dependencies: - "@vitest/utils": "npm:4.1.10" + "@vitest/utils": "npm:4.1.11" pathe: "npm:^2.0.3" - checksum: 10c0/554b72639de9694271b99be8ae273fe12ec793093ec91cce143816cd1187d40b7138a4d9d4de4f456cfca9567de986825bff97e107c05b9eb4abc130e854286d + checksum: 10c0/3c782b055e9e688e1785f7c8937bd1669bad1b0e5758cb8b844f918f30a324b1d21e174d46c941ce80ebf37f2b89b55b6d619a675025914a1ece6377b95909e2 languageName: node linkType: hard -"@vitest/snapshot@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/snapshot@npm:4.1.10" +"@vitest/snapshot@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/snapshot@npm:4.1.11" dependencies: - "@vitest/pretty-format": "npm:4.1.10" - "@vitest/utils": "npm:4.1.10" + "@vitest/pretty-format": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" magic-string: "npm:^0.30.21" pathe: "npm:^2.0.3" - checksum: 10c0/e71398725f51af5fd0c07bb4b957d0f987daf9b4c564ac24cb2a4d1afde1a6939f535ac17761a32dcc41b0a1e6d4088af66dc44df89fdebebb92aabed1a92b5f + checksum: 10c0/35d82a7c2a3e4b57529c30387d568d9106b6bf960189214e5d8cb1f5288cb042305c2e5c7b0b2f8cb56a2c814973de0310bc56d72deb79427bea272b6224190c languageName: node linkType: hard -"@vitest/spy@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/spy@npm:4.1.10" - checksum: 10c0/e5c08012560af6727fd66741c5cda25560d7c5442103d0c83e4276a9b0dd90b9da6cdf823a461195229a16c6ff87768ce788a68d0fa29dea73ee285618668178 +"@vitest/spy@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/spy@npm:4.1.11" + checksum: 10c0/06c68247a8efd21006abe7532fee17f30ba83c8cda3e0b952ef89e278d58058f4b1de69b6bbaa2ed614c568bf4f5769fcc76be42802dedf2bcdd9c0aae601740 languageName: node linkType: hard @@ -7663,17 +7654,6 @@ __metadata: languageName: node linkType: hard -"@vitest/utils@npm:4.1.10": - version: 4.1.10 - resolution: "@vitest/utils@npm:4.1.10" - dependencies: - "@vitest/pretty-format": "npm:4.1.10" - convert-source-map: "npm:^2.0.0" - tinyrainbow: "npm:^3.1.0" - checksum: 10c0/05b0ecec6997ec22fc08377e57dbd8fa37992e05961f3a7a916d98b1ab56d15c2a87dbd83d392b628242bdc156b1705e7fa60a3bf0c54bdb51158c153e05fc5d - languageName: node - linkType: hard - "@vitest/utils@npm:4.1.11": version: 4.1.11 resolution: "@vitest/utils@npm:4.1.11" @@ -15830,7 +15810,7 @@ __metadata: vite: "npm:^8.1.5" vite-plugin-pwa: "npm:1.3.0" vite-tsconfig-paths: "npm:^6.1.1" - vitest: "npm:^4.1.10" + vitest: "npm:^4.1.11" winston: "npm:^3.17.0" ws: "npm:^7.5.13" y-prosemirror: "npm:^1.3.7" @@ -20736,17 +20716,17 @@ __metadata: languageName: node linkType: hard -"vitest@npm:^4.1.10": - version: 4.1.10 - resolution: "vitest@npm:4.1.10" +"vitest@npm:^4.1.11": + version: 4.1.11 + resolution: "vitest@npm:4.1.11" dependencies: - "@vitest/expect": "npm:4.1.10" - "@vitest/mocker": "npm:4.1.10" - "@vitest/pretty-format": "npm:4.1.10" - "@vitest/runner": "npm:4.1.10" - "@vitest/snapshot": "npm:4.1.10" - "@vitest/spy": "npm:4.1.10" - "@vitest/utils": "npm:4.1.10" + "@vitest/expect": "npm:4.1.11" + "@vitest/mocker": "npm:4.1.11" + "@vitest/pretty-format": "npm:4.1.11" + "@vitest/runner": "npm:4.1.11" + "@vitest/snapshot": "npm:4.1.11" + "@vitest/spy": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" es-module-lexer: "npm:^2.0.0" expect-type: "npm:^1.3.0" magic-string: "npm:^0.30.21" @@ -20764,12 +20744,12 @@ __metadata: "@edge-runtime/vm": "*" "@opentelemetry/api": ^1.9.0 "@types/node": ^20.0.0 || ^22.0.0 || >=24.0.0 - "@vitest/browser-playwright": 4.1.10 - "@vitest/browser-preview": 4.1.10 - "@vitest/browser-webdriverio": 4.1.10 - "@vitest/coverage-istanbul": 4.1.10 - "@vitest/coverage-v8": 4.1.10 - "@vitest/ui": 4.1.10 + "@vitest/browser-playwright": 4.1.11 + "@vitest/browser-preview": 4.1.11 + "@vitest/browser-webdriverio": 4.1.11 + "@vitest/coverage-istanbul": 4.1.11 + "@vitest/coverage-v8": 4.1.11 + "@vitest/ui": 4.1.11 happy-dom: "*" jsdom: "*" vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -20800,7 +20780,7 @@ __metadata: optional: false bin: vitest: ./vitest.mjs - checksum: 10c0/ff07294a57f9c62f3b503f7cf88a52ee0753ed26389a49cda430387a3898f39d80af47180b0af19e27acab5bd11ae95706bd4b44ce8befc97d3ae49af6ca4fc1 + checksum: 10c0/3fa0948cf74adcccc8cbcdb4e6d30ada6933bdfb1816ff99200f3d3b689325b37dc483b22535b57b6d911f7a7b64eaa6a5f8da1606cfe7f2466f48000c21e296 languageName: node linkType: hard From dafda3de465f091525fb1908a501d777e5238e8a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Sep 2026 10:20:06 -0400 Subject: [PATCH 044/368] chore: update mail dependencies and dedupe js-yaml (#13714) --- package.json | 5 ++- yarn.lock | 98 +++++++++++++++++++--------------------------------- 2 files changed, 37 insertions(+), 66 deletions(-) diff --git a/package.json b/package.json index ce50722af1..768241789f 100644 --- a/package.json +++ b/package.json @@ -172,7 +172,7 @@ "koa-send": "5.0.1", "koa-sslify": "5.0.1", "koa-useragent": "^4.1.0", - "mailparser": "^3.9.15", + "mailparser": "^3.9.20", "mammoth": "^1.11.0", "markdown-it": "^14.3.0", "markdown-it-container": "^3.0.0", @@ -184,7 +184,7 @@ "mobx-utils": "^6.1.1", "natural-sort": "^1.0.0", "node-fetch": "2.7.0", - "nodemailer": "^9.1.1", + "nodemailer": "^10.0.0", "octokit": "^5.0.5", "outline-icons": "^4.6.0", "oy-vey": "^0.12.1", @@ -320,7 +320,6 @@ "@types/natural-sort": "^0.0.24", "@types/node": "20.19.43", "@types/node-fetch": "^2.6.13", - "@types/nodemailer": "^6.4.23", "@types/passport-oauth2": "^1.8.0", "@types/pluralize": "^0.0.33", "@types/png-chunks-extract": "^1.0.2", diff --git a/yarn.lock b/yarn.lock index da37bacd3e..679d65396d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7119,15 +7119,6 @@ __metadata: languageName: node linkType: hard -"@types/nodemailer@npm:^6.4.23": - version: 6.4.24 - resolution: "@types/nodemailer@npm:6.4.24" - dependencies: - "@types/node": "npm:*" - checksum: 10c0/7e500ee7f34b3e7ea88e7363a1dc9d93ca70d762db42e729604805e9ce576d25bd2f3c92342506625e09a3a9fd9788502457356e94d054c17c553ab3575091db - languageName: node - linkType: hard - "@types/oauth@npm:*": version: 0.9.6 resolution: "@types/oauth@npm:0.9.6" @@ -7794,14 +7785,14 @@ __metadata: languageName: node linkType: hard -"@zone-eu/mailsplit@npm:5.4.15": - version: 5.4.15 - resolution: "@zone-eu/mailsplit@npm:5.4.15" +"@zone-eu/mailsplit@npm:5.4.16": + version: 5.4.16 + resolution: "@zone-eu/mailsplit@npm:5.4.16" dependencies: libbase64: "npm:1.3.0" - libmime: "npm:5.4.2" + libmime: "npm:5.4.3" libqp: "npm:2.1.1" - checksum: 10c0/de5e82d8a7994cb01b2aef160ad2bf6eaad4508e1fef2cb7836a18acb448ca764dcb51fdd865ba7be15f57d7f39470f554270a529983a9cb59cd418175127ab9 + checksum: 10c0/cce6b192897b819986a07b3b82a974ad8b4694261ba88cd5119444cb6e86686df7de1a3b89b35d6610051b19297b203f7e70d6e6ea1e46264fb6c111d9458e5c languageName: node linkType: hard @@ -10536,10 +10527,10 @@ __metadata: languageName: node linkType: hard -"encoding-japanese@npm:2.2.0": - version: 2.2.0 - resolution: "encoding-japanese@npm:2.2.0" - checksum: 10c0/9d1f10dde16f59da8a8a1a04499dffa3e9926b0dbd7dfab8054570527b7e6de30c47e828851f42d2727af31586ec8049a84eeae593ad8b22eea10921fd269798 +"encoding-japanese@npm:2.3.0": + version: 2.3.0 + resolution: "encoding-japanese@npm:2.3.0" + checksum: 10c0/5c58dfbbb9bd5fa74bbd3cafb0a210848f5044320a4e50b43bd023d5e6b4aaac78a61ea7064ae4a0cffe6162d84f746f4643c2f42c9dac08e1391cd74d2b6745 languageName: node linkType: hard @@ -12277,16 +12268,16 @@ __metadata: languageName: node linkType: hard -"html-to-text@npm:10.0.0": - version: 10.0.0 - resolution: "html-to-text@npm:10.0.0" +"html-to-text@npm:10.0.1": + version: 10.0.1 + resolution: "html-to-text@npm:10.0.1" dependencies: "@selderee/plugin-htmlparser2": "npm:~0.12.0" - deepmerge-ts: "npm:^7.1.5" + deepmerge-ts: "npm:^8.0.1" dom-serializer: "npm:^2.0.0" htmlparser2: "npm:^10.1.0" selderee: "npm:~0.12.0" - checksum: 10c0/fde3b3695ff1bf8ba71b5fb388734de941cf8ccd4c0e816add07104496e21b8f9f937058b35c69554e510af72a5fb582e8966daa165a350464faf97d0aa9e066 + checksum: 10c0/e43826e0bed6baa7e168b342ccaca1376ad5fd7ae487c8fee8dd8c5a770269cd7270b40ed847e940e2487bf90a3e67036a52b7f8f8225090cd21fc86f610e830 languageName: node linkType: hard @@ -13385,18 +13376,7 @@ __metadata: languageName: node linkType: hard -"js-yaml@npm:^4.1.0, js-yaml@npm:^4.3.1": - version: 4.3.1 - resolution: "js-yaml@npm:4.3.1" - dependencies: - argparse: "npm:^2.0.1" - bin: - js-yaml: bin/js-yaml.js - checksum: 10c0/13c500ca322e0c3f8c81686e6ecda96d2ea37b45247a420c17c7db36932d6965cc27391abc2d1a104501600e7f0d947a5f8b7be6db619c4fefa87901b3512807 - languageName: node - linkType: hard - -"js-yaml@npm:^4.3.2": +"js-yaml@npm:^4.1.0, js-yaml@npm:^4.3.1, js-yaml@npm:^4.3.2": version: 4.3.2 resolution: "js-yaml@npm:4.3.2" dependencies: @@ -13917,15 +13897,15 @@ __metadata: languageName: node linkType: hard -"libmime@npm:5.4.2": - version: 5.4.2 - resolution: "libmime@npm:5.4.2" +"libmime@npm:5.4.3": + version: 5.4.3 + resolution: "libmime@npm:5.4.3" dependencies: - encoding-japanese: "npm:2.2.0" + encoding-japanese: "npm:2.3.0" iconv-lite: "npm:0.7.3" libbase64: "npm:1.3.0" libqp: "npm:2.1.1" - checksum: 10c0/207d6f148be620243d1670db8a746d33686d79e8863a692b35f9351f221cce0b25ff8b18d95d054f8e7743a165d84ac3fec5998e0410c1e6a8ed003ce788b484 + checksum: 10c0/e94e77b6404de0c57156217507db488eb48acab276777b8ebdd1badeb9a88ba749590dab412cc36acb6927bdf1757523bf70d1283f02295b5ab81abd76dfea9d languageName: node linkType: hard @@ -14386,21 +14366,21 @@ __metadata: languageName: node linkType: hard -"mailparser@npm:^3.9.15": - version: 3.9.15 - resolution: "mailparser@npm:3.9.15" +"mailparser@npm:^3.9.20": + version: 3.9.22 + resolution: "mailparser@npm:3.9.22" dependencies: - "@zone-eu/mailsplit": "npm:5.4.15" - encoding-japanese: "npm:2.2.0" + "@zone-eu/mailsplit": "npm:5.4.16" + encoding-japanese: "npm:2.3.0" he: "npm:1.2.0" - html-to-text: "npm:10.0.0" + html-to-text: "npm:10.0.1" iconv-lite: "npm:0.7.3" - libmime: "npm:5.4.2" + libmime: "npm:5.4.3" linkify-it: "npm:5.0.2" - nodemailer: "npm:9.0.5" + nodemailer: "npm:10.0.0" punycode.js: "npm:2.3.1" tlds: "npm:1.261.0" - checksum: 10c0/073681539404815d1fb3bd1b018fb7069f51f0e4cf1e0de1a0807ba4580429fb64e4b7e6413414f17942ed12330a51c31053b787c21fc9a2ff5c3b6225604d77 + checksum: 10c0/a006d9e7ee4aa47bbc0a88b06c07d172b1409bc8cce7031f1b35cf6a0a46abe0e2643e6a603363b63b20b0ee46ec1e2d0571082da6c25da35c7d860182fa0977 languageName: node linkType: hard @@ -15170,17 +15150,10 @@ __metadata: languageName: node linkType: hard -"nodemailer@npm:9.0.5": - version: 9.0.5 - resolution: "nodemailer@npm:9.0.5" - checksum: 10c0/60f7a21497c98c0d275cd12c488af581ef6aee65db575026319ac249dcac210bdab20edf77fe3158176ed3910f70d8c46d89abcd74f57a7170302727e6d05ee3 - languageName: node - linkType: hard - -"nodemailer@npm:^9.1.1": - version: 9.1.1 - resolution: "nodemailer@npm:9.1.1" - checksum: 10c0/b213a2a906697a735f6eb21103629b7a77aeac297b6d843efd4588157999bf6d19381853ac1224e472f5a34aec2e2412444151a2c6ec6e8c52150afa3055039c +"nodemailer@npm:10.0.0, nodemailer@npm:^10.0.0": + version: 10.0.0 + resolution: "nodemailer@npm:10.0.0" + checksum: 10c0/917fb3a5c75e2a86917212c3e9083713a1e9c77abbddd7ab52c94deadd5fbd3ee4fe12ce5d87c7a7bc31dc5b8a29a09532872cf08c9bc489b0b0a3f0aa12aa8b languageName: node linkType: hard @@ -15600,7 +15573,6 @@ __metadata: "@types/natural-sort": "npm:^0.0.24" "@types/node": "npm:20.19.43" "@types/node-fetch": "npm:^2.6.13" - "@types/nodemailer": "npm:^6.4.23" "@types/pako": "npm:^2.0.4" "@types/passport-oauth2": "npm:^1.8.0" "@types/pluralize": "npm:^0.0.33" @@ -15697,7 +15669,7 @@ __metadata: koa-sslify: "npm:5.0.1" koa-useragent: "npm:^4.1.0" lint-staged: "npm:^16.4.0" - mailparser: "npm:^3.9.15" + mailparser: "npm:^3.9.20" mammoth: "npm:^1.11.0" markdown-it: "npm:^14.3.0" markdown-it-container: "npm:^3.0.0" @@ -15710,7 +15682,7 @@ __metadata: msw: "npm:^2.14.2" natural-sort: "npm:^1.0.0" node-fetch: "npm:2.7.0" - nodemailer: "npm:^9.1.1" + nodemailer: "npm:^10.0.0" nodemon: "npm:^3.1.14" octokit: "npm:^5.0.5" outline-icons: "npm:^4.6.0" From cd808bcd92d61bd81c618c7ad84d06f261bed0e1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 9 Sep 2026 12:00:22 -0400 Subject: [PATCH 045/368] fix: serve service worker with no-cache header (#13716) --- server/routes/index.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/server/routes/index.ts b/server/routes/index.ts index 2ba7e35581..c9a069e4b5 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -71,9 +71,15 @@ if (env.isProduction) { // Hashed static assets get 1 year expiry plus immutable flag maxAge: Day.ms * 365, immutable: true, - setHeaders: (res) => { + setHeaders: (res, filePath) => { res.setHeader("Service-Worker-Allowed", "/"); res.setHeader("Access-Control-Allow-Origin", "*"); + + // The service worker is not hashed and must always be revalidated + // so that browsers detect and install new versions. + if (path.basename(filePath) === "sw.js") { + res.setHeader("Cache-Control", "no-cache"); + } }, }); } catch (err) { From 040e8332a7025814e0e5ad9a29f9414265687a83 Mon Sep 17 00:00:00 2001 From: UmbraCi <49011112+UmbraCi@users.noreply.github.com> Date: Thu, 10 Sep 2026 00:06:10 +0800 Subject: [PATCH 046/368] fix(editor): prevent native img drag copying selected images (#13635) --- shared/editor/components/Image.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/shared/editor/components/Image.tsx b/shared/editor/components/Image.tsx index 5539883077..cf436400fd 100644 --- a/shared/editor/components/Image.tsx +++ b/shared/editor/components/Image.tsx @@ -230,6 +230,7 @@ const Image = (props: Props) => { > Date: Thu, 10 Sep 2026 00:11:11 -0500 Subject: [PATCH 047/368] fix: pinned document cards ignore clicks and trackpad taps (#13708) The PointerSensor used a delay activation constraint, so any stationary press held 100 ms or longer started a drag; DocumentCard then sets pointer-events: none while dragging and the release lands behind the card, so the Link never navigates. Trackpad taps are held ~180 ms by libinput/macOS tap-and-drag detection and always failed. Use a distance constraint instead: a stationary press never activates, so clicks and taps of any duration navigate, while drag-to-reorder still starts after 8 px of movement. Fixes #4268 --- app/components/PinnedDocuments.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/components/PinnedDocuments.tsx b/app/components/PinnedDocuments.tsx index 79532148c7..fb7a9ebed5 100644 --- a/app/components/PinnedDocuments.tsx +++ b/app/components/PinnedDocuments.tsx @@ -82,8 +82,7 @@ function PinnedDocuments({ const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { - delay: 100, - tolerance: 5, + distance: 8, }, }), useSensor(KeyboardSensor, { From b21174ccbf7bae72737f7f598977ba64340bdb7a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Sep 2026 10:11:11 -0400 Subject: [PATCH 048/368] perf: Avoid N+1 query in share subscription notifications (#13719) --- server/models/Document.test.ts | 58 +++++++++++++++++++ server/models/Document.ts | 40 +++++++++++++ .../ShareSubscriptionNotificationsTask.ts | 19 ++---- 3 files changed, 103 insertions(+), 14 deletions(-) diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index 8c27e28490..ba4e88af27 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -15,6 +15,7 @@ import { buildGuestUser, } from "@server/test/factories"; import { withAPIContext } from "@server/test/support"; +import { sequelize } from "@server/storage/database"; import GroupMembership from "./GroupMembership"; import GroupUser from "./GroupUser"; import UserMembership from "./UserMembership"; @@ -260,6 +261,63 @@ describe("#findAllChildDocumentIds", () => { }); }); +describe("#findAllParentDocumentIds", () => { + test("should return empty array if there is no parent", async () => { + const document = await buildDocument(); + + expect(await document.findAllParentDocumentIds()).toEqual([]); + }); + + test("should return nested parent document ids in one query", async () => { + const parent = await buildDocument(); + const child = await buildDocument({ + parentDocumentId: parent.id, + collectionId: parent.collectionId, + teamId: parent.teamId, + userId: parent.createdById, + }); + const grandchild = await buildDocument({ + parentDocumentId: child.id, + collectionId: parent.collectionId, + teamId: parent.teamId, + userId: parent.createdById, + }); + + const query = sequelize.query.bind(sequelize); + const spy = vi.spyOn(sequelize, "query").mockImplementation(query); + try { + const results = await grandchild.findAllParentDocumentIds(); + + expect(results).toEqual([child.id, parent.id]); + expect(spy).toHaveBeenCalledTimes(1); + } finally { + spy.mockRestore(); + } + }); + + test("should stop at soft-deleted parents unless paranoid is false", async () => { + const parent = await buildDocument(); + const child = await buildDocument({ + parentDocumentId: parent.id, + collectionId: parent.collectionId, + teamId: parent.teamId, + userId: parent.createdById, + }); + const grandchild = await buildDocument({ + parentDocumentId: child.id, + collectionId: parent.collectionId, + teamId: parent.teamId, + userId: parent.createdById, + }); + await child.destroy(); + + expect(await grandchild.findAllParentDocumentIds()).toEqual([]); + expect( + await grandchild.findAllParentDocumentIds({ paranoid: false }) + ).toEqual([child.id, parent.id]); + }); +}); + describe("#membershipDocumentIds", () => { it("should return empty array when the user has no document memberships", async () => { const user = await buildUser(); diff --git a/server/models/Document.ts b/server/models/Document.ts index 2c8632c365..497a5628c8 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -1214,6 +1214,46 @@ class Document extends ArchivableModel< return rows.map((row) => row.id); }; + /** + * Calculate all parent document ids for this document by recursively + * following parentDocumentId references in one query. + * + * @param options the query options. + * @returns a promise that resolves to parent document ids, nearest first. + */ + findAllParentDocumentIds = async ( + options?: FindOptions + ): Promise => { + if (!this.parentDocumentId) { + return []; + } + + const paranoid = options?.paranoid ?? true; + const rows = await this.sequelize!.query<{ id: string }>( + ` + WITH RECURSIVE parents AS ( + SELECT documents.id, documents."parentDocumentId", 1 AS depth + FROM documents + WHERE documents.id = :parentDocumentId + ${paranoid ? 'AND documents."deletedAt" IS NULL' : ""} + UNION ALL + SELECT documents.id, documents."parentDocumentId", parents.depth + 1 + FROM documents + INNER JOIN parents ON documents.id = parents."parentDocumentId" + ${paranoid ? 'WHERE documents."deletedAt" IS NULL' : ""} + ) + SELECT id FROM parents ORDER BY depth + `, + { + replacements: { parentDocumentId: this.parentDocumentId }, + transaction: options?.transaction, + type: QueryTypes.SELECT, + } + ); + + return rows.map((row) => row.id); + }; + publish = async ( ctx: APIContext, { diff --git a/server/queues/tasks/ShareSubscriptionNotificationsTask.ts b/server/queues/tasks/ShareSubscriptionNotificationsTask.ts index 37717008f8..674bb652b6 100644 --- a/server/queues/tasks/ShareSubscriptionNotificationsTask.ts +++ b/server/queues/tasks/ShareSubscriptionNotificationsTask.ts @@ -14,20 +14,11 @@ export default class ShareSubscriptionNotificationsTask extends BaseTask Date: Thu, 10 Sep 2026 22:06:13 -0400 Subject: [PATCH 049/368] fix: Editor node drags show the sidebar document ghost (#13723) Native drags (ProseMirror nodes leaving the editor, text, files) are tracked by react-dnd as native item types. The sidebar drag placeholder rendered a document row for any active drag, so dragging an editor node past the editor edge showed an "Untitled" document ghost. Also makes notice blocks non-draggable. --- .../Sidebar/components/DragPlaceholder.tsx | 26 ++++++++++++++----- shared/editor/nodes/Notice.tsx | 2 +- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/app/components/Sidebar/components/DragPlaceholder.tsx b/app/components/Sidebar/components/DragPlaceholder.tsx index e7a4feba33..1631cabcc9 100644 --- a/app/components/Sidebar/components/DragPlaceholder.tsx +++ b/app/components/Sidebar/components/DragPlaceholder.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import type { XYCoord } from "react-dnd"; import { useDragLayer } from "react-dnd"; +import { NativeTypes } from "react-dnd-html5-backend"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import useStores from "~/hooks/useStores"; @@ -16,6 +17,10 @@ const layerStyles: React.CSSProperties = { height: "100%", }; +// Browser-native drags (files, text, or ProseMirror nodes leaving the editor) +// are tracked by react-dnd too, but they are not sidebar items. +const nativeItemTypes = new Set(Object.values(NativeTypes)); + // Keep the ghost beside the pointer so it never covers the drop cursor. const POINTER_OFFSET_X = 12; const POINTER_OFFSET_Y = 14; @@ -41,14 +46,21 @@ const DragPlaceholder = () => { const { t } = useTranslation(); const { ui } = useStores(); - const { isDragging, item, pointerOffset } = useDragLayer((monitor) => ({ - item: monitor.getItem(), - itemType: monitor.getItemType(), - pointerOffset: monitor.getClientOffset(), - isDragging: monitor.isDragging(), - })); + const { isDragging, item, itemType, pointerOffset } = useDragLayer( + (monitor) => ({ + item: monitor.getItem(), + itemType: monitor.getItemType(), + pointerOffset: monitor.getClientOffset(), + isDragging: monitor.isDragging(), + }) + ); - if (!isDragging || !pointerOffset) { + if ( + !isDragging || + !pointerOffset || + !itemType || + nativeItemTypes.has(itemType) + ) { return null; } diff --git a/shared/editor/nodes/Notice.tsx b/shared/editor/nodes/Notice.tsx index ed7575bba5..688041ebab 100644 --- a/shared/editor/nodes/Notice.tsx +++ b/shared/editor/nodes/Notice.tsx @@ -42,7 +42,7 @@ export default class Notice extends Node { "(list | blockquote | hr | paragraph | heading | code_block | code_fence | attachment)+", group: "block", defining: true, - draggable: true, + draggable: false, parseDOM: [ { tag: `div.${EditorStyleHelper.notice}`, From 35dd15b9718bcb8e547b86c1428d55170b49250b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 10 Sep 2026 22:07:16 -0400 Subject: [PATCH 050/368] Optimize documentCollaborativeUpdater by moving computations outside transaction (#13720) * perf: shorten row lock held while persisting collaborative documents The collaborative updater serialized the Y.js state and converted it to ProseMirror JSON while holding a FOR UPDATE lock on the document row, and loaded every column including the deprecated markdown text. Both the lock wait on the SELECT and the subsequent UPDATE are the dominant source of statement timeouts in production, and API document updates queue behind the same lock. --- .../documentCollaborativeUpdater.test.ts | 42 +++++++++++ .../commands/documentCollaborativeUpdater.ts | 72 +++++++++++-------- 2 files changed, 85 insertions(+), 29 deletions(-) diff --git a/server/commands/documentCollaborativeUpdater.test.ts b/server/commands/documentCollaborativeUpdater.test.ts index 26377526af..b322011524 100644 --- a/server/commands/documentCollaborativeUpdater.test.ts +++ b/server/commands/documentCollaborativeUpdater.test.ts @@ -47,6 +47,48 @@ describe("documentCollaborativeUpdater", () => { expect(text?.marks).toEqual([{ type: "strong" }]); }); + it("updates collaborative fields and leaves other columns untouched", async () => { + const user = await buildUser(); + const collaborator = await buildUser({ teamId: user.teamId }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + title: "Original title", + text: "Original markdown", + editorVersion: "1.0.0", + }); + const { revisionCount } = document; + + const ydoc = buildYDoc([ + { + type: "paragraph", + content: [{ type: "text", text: "Updated" }], + }, + ]); + + await documentCollaborativeUpdater({ + documentId: document.id, + ydoc, + sessionCollaboratorIds: [collaborator.id], + isLastConnection: true, + clientVersion: "2.0.0", + }); + + await document.reload(); + + expect(document.title).toEqual("Original title"); + expect(document.text).toEqual("Original markdown"); + expect(document.editorVersion).toEqual("2.0.0"); + expect(document.lastModifiedById).toEqual(collaborator.id); + expect(document.collaboratorIds).toEqual( + expect.arrayContaining([user.id, collaborator.id]) + ); + expect(document.revisionCount).toEqual(revisionCount + 1); + expect(document.content?.content?.[0]?.content?.[0]?.text).toEqual( + "Updated" + ); + }); + it("does not persist when content is unchanged", async () => { const user = await buildUser(); const content = [ diff --git a/server/commands/documentCollaborativeUpdater.ts b/server/commands/documentCollaborativeUpdater.ts index d83e858086..8941bbdd26 100644 --- a/server/commands/documentCollaborativeUpdater.ts +++ b/server/commands/documentCollaborativeUpdater.ts @@ -31,38 +31,55 @@ export default async function documentCollaborativeUpdater({ isLastConnection, clientVersion, }: Props) { + const state = Y.encodeStateAsUpdate(ydoc); + + // Round-trip through the schema so the stored JSON is canonical. The raw + // y-prosemirror output includes empty `attrs: {}` on every mark, and outputs + // properties in a different order - resulting in spurious "edits". The JSON + // round-trip additionally drops undefined-valued attrs, which are absent + // from previously stored content but present on `Node.toJSON` output. + const content = JSON.parse( + JSON.stringify( + Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default")).toJSON() + ) + ) as ProsemirrorData; + + // extract collaborators from doc user data + const pud = new Y.PermanentUserData(ydoc); + const pudIds = Array.from(pud.clients.values()); + return sequelize.transaction(async (transaction) => { await sequelize.query(`SET LOCAL lock_timeout = '15s';`, { transaction, }); - const document = await Document.unscoped() - .scope("withoutState") - .findOne({ - where: { - id: documentId, - }, - transaction, - lock: { - of: Document, - level: transaction.LOCK.UPDATE, - }, - rejectOnEmpty: true, - paranoid: false, - }); + // Only the columns read below are selected, the deprecated markdown text + // and collaborative state can each be megabytes and are not needed here. + const document = await Document.unscoped().findOne({ + attributes: [ + "id", + "title", + "content", + "collaboratorIds", + "collectionId", + "deletedAt", + "editorVersion", + "lastModifiedById", + "revisionCount", + "teamId", + ], + where: { + id: documentId, + }, + transaction, + lock: { + of: Document, + level: transaction.LOCK.UPDATE, + }, + rejectOnEmpty: true, + paranoid: false, + }); - const state = Y.encodeStateAsUpdate(ydoc); - - // Round-trip through the schema so the stored JSON is canonical. The raw - // y-prosemirror output includes empty `attrs: {}` on every mark, and outputs - // properties in a different order - resulting in spurious "edits". The JSON - // round-trip additionally drops undefined-valued attrs, which are absent - // from previously stored content but present on `Node.toJSON` output. - const content = JSON.parse( - JSON.stringify( - Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default")).toJSON() - ) - ) as ProsemirrorData; const isUnchanged = isEqual(document.content, content); const isDeleted = !!document.deletedAt; const lastModifiedById = isDeleted @@ -79,9 +96,6 @@ export default async function documentCollaborativeUpdater({ `Persisting ${documentId}, attributed to ${lastModifiedById}` ); - // extract collaborators from doc user data - const pud = new Y.PermanentUserData(ydoc); - const pudIds = Array.from(pud.clients.values()); const collaboratorIds = uniq([ ...(document.collaboratorIds ?? []), ...sessionCollaboratorIds, From ab40dda96640762d95aad99b5ff0d2ea2b42e562 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 11 Sep 2026 18:44:21 -0400 Subject: [PATCH 051/368] fix: Checklist conversion corrupts neighbouring lists (#13724) --- shared/editor/rules/checkboxes.test.ts | 42 ++++++++++++++++++++++++++ shared/editor/rules/checkboxes.ts | 8 +++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/shared/editor/rules/checkboxes.test.ts b/shared/editor/rules/checkboxes.test.ts index 5daf3ab68e..9af5538cea 100644 --- a/shared/editor/rules/checkboxes.test.ts +++ b/shared/editor/rules/checkboxes.test.ts @@ -94,3 +94,45 @@ it("converts an ordered list containing a checkbox item", () => { expect(checkboxList?.content?.[0].type).toBe("checkbox_item"); expect(checkboxList?.content?.[1].type).toBe("checkbox_item"); }); + +it("leaves neighbouring lists untouched when a checklist has multiple items", () => { + const markdown = `## Before 1 +- B1 a +- B1 b + +## Before 2 +- B2 a +- B2 b + +## Tasks +- [ ] task one +- [ ] task two + +## After 1 +- A1 a +- A1 b + +## After 2 +- A2 a`; + + const ast = parser.parse(markdown); + const json = ast?.toJSON(); + + const checkboxLists = findNodes(json, "checkbox_list"); + expect(checkboxLists).toHaveLength(1); + expect(checkboxLists[0]?.content).toHaveLength(2); + + const bulletLists = findNodes(json, "bullet_list"); + expect(bulletLists).toHaveLength(4); + for (const list of bulletLists) { + for (const item of list?.content ?? []) { + expect(item.type).toBe("list_item"); + } + } + + const output = serializer.serialize(ast); + expect(output).toContain("B2 a"); + expect(output).toContain("A1 a"); + expect(output).toContain("A1 b"); + expect(output).not.toContain("[ ] B2 a"); +}); diff --git a/shared/editor/rules/checkboxes.ts b/shared/editor/rules/checkboxes.ts index cae2539d2b..41337159e0 100644 --- a/shared/editor/rules/checkboxes.ts +++ b/shared/editor/rules/checkboxes.ts @@ -24,13 +24,17 @@ function isListItem(token: Token): boolean { function isListOpen(token: Token): boolean { return ( - token.type === "bullet_list_open" || token.type === "ordered_list_open" + token.type === "bullet_list_open" || + token.type === "ordered_list_open" || + token.type === "checkbox_list_open" ); } function isListClose(token: Token): boolean { return ( - token.type === "bullet_list_close" || token.type === "ordered_list_close" + token.type === "bullet_list_close" || + token.type === "ordered_list_close" || + token.type === "checkbox_list_close" ); } From 2507471f7c123ac2979f7b33e6bfadd8de04b65d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Sep 2026 23:23:50 -0400 Subject: [PATCH 052/368] fix: Crash when image caption blurs during node view teardown (#13731) * fix: Crash when image caption blurs during node view teardown The caption blur handler ran setNodeMarkup using a position from a node view that had already been destroyed, so the position was undefined and ProseMirror threw a RangeError walking the document. Guard that the position still resolves to the same node type before dispatching, for both image and video captions. Fixes OUTLINE-CLOUD-D6D Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Hggmor4gWv2Ei4pMNeeMh4 * chore: Remove caption blur tests --- shared/editor/nodes/Image.tsx | 9 ++++++++- shared/editor/nodes/Video.tsx | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/shared/editor/nodes/Image.tsx b/shared/editor/nodes/Image.tsx index af923b7c17..2010b631be 100644 --- a/shared/editor/nodes/Image.tsx +++ b/shared/editor/nodes/Image.tsx @@ -420,8 +420,15 @@ export default class Image extends SimpleImage { const { view } = this.editor; const { tr } = view.state; - // update meta on object + // The blur may fire while the node view is being torn down, at which + // point the position no longer refers to this image in the document. const pos = getPos(); + const current = + pos === undefined ? undefined : view.state.doc.nodeAt(pos); + if (current?.type !== node.type) { + return; + } + const transaction = tr.setNodeMarkup(pos, undefined, { ...node.attrs, alt: caption, diff --git a/shared/editor/nodes/Video.tsx b/shared/editor/nodes/Video.tsx index 189d00e93e..fe48678b3d 100644 --- a/shared/editor/nodes/Video.tsx +++ b/shared/editor/nodes/Video.tsx @@ -159,8 +159,15 @@ export default class Video extends Node { const { view } = this.editor; const { tr } = view.state; - // update meta on object + // The blur may fire while the node view is being torn down, at which + // point the position no longer refers to this video in the document. const pos = getPos(); + const current = + pos === undefined ? undefined : view.state.doc.nodeAt(pos); + if (current?.type !== node.type) { + return; + } + const transaction = tr.setNodeMarkup(pos, undefined, { ...node.attrs, title: caption, From 74a992e278eeffce661532720e174e9e5c9f09e7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 12 Sep 2026 23:23:57 -0400 Subject: [PATCH 053/368] fix: Lightbox flickers at the end of the close animation (#13730) Since the move to a concurrent React root the state update dispatched from animationend renders at default priority, and the passive effect that unmounts the lightbox runs in a later task. The browser can paint the intermediate commit, where the finished close animations have snapped back to their resting styles and the inline image has already been restored, so the lightbox briefly reappears fully open before disappearing. Keep the final keyframe of every closing animation with fill-mode forwards and keep the inline image hidden until the lightbox unmounts, so any frame painted between the animation ending and the teardown looks identical to the finished close. closes #13728 Claude-Session: https://claude.ai/code/session_01T4Pkj5VNWWu22pV113qqKS Co-authored-by: Claude --- app/components/Lightbox.tsx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/components/Lightbox.tsx b/app/components/Lightbox.tsx index 45580531b9..2d0d90a03b 100644 --- a/app/components/Lightbox.tsx +++ b/app/components/Lightbox.tsx @@ -616,12 +616,12 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { }, [status.image]); // Hide the inline image in the editor while the lightbox zoom transition is - // active, otherwise a duplicate is visible behind the fading overlay. + // active, otherwise a duplicate is visible behind the fading overlay. It stays + // hidden until unmount so the lightbox copy is the only one visible in any + // frame painted between the close animation ending and the teardown. useHideElement( activeImage.getElement(), - status.lightbox !== null && - status.lightbox !== LightboxStatus.READY_TO_OPEN && - status.lightbox !== LightboxStatus.CLOSED + status.lightbox !== null && status.lightbox !== LightboxStatus.READY_TO_OPEN ); const prev = () => { @@ -1132,7 +1132,7 @@ const StyledOverlay = styled(Dialog.Overlay)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1167,12 +1167,12 @@ const StyledImg = styled.img<{ : props.animation?.zoomOut ? css` animation: ${props.animation.zoomOut.apply()} - ${props.animation.zoomOut.duration}ms; + ${props.animation.zoomOut.duration}ms forwards; ` : props.animation?.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1220,7 +1220,7 @@ const Actions = styled(HStack)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1248,7 +1248,7 @@ const CloseAction = styled.div<{ animation: Animation | null }>` : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1282,7 +1282,7 @@ const Nav = styled.div<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1303,7 +1303,7 @@ const StyledError = styled(ImageError)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1324,7 +1324,7 @@ const CommentsSidebar = styled.div<{ props.animation?.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; From c2c7200151c8781ce61aef84cbc3b0ff2ddaf07e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 13 Sep 2026 15:42:34 -0400 Subject: [PATCH 054/368] fix: Show notice type for list selections (#13721) --- app/editor/menus/notice.tsx | 8 ++++++-- shared/editor/nodes/Notice.tsx | 27 ++++++++++++++++----------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/app/editor/menus/notice.tsx b/app/editor/menus/notice.tsx index 635e7e1644..549e0682cc 100644 --- a/app/editor/menus/notice.tsx +++ b/app/editor/menus/notice.tsx @@ -7,6 +7,7 @@ import { WarningIcon, } from "outline-icons"; import { NoticeTypes } from "@shared/editor/nodes/Notice"; +import { findParentNode } from "@shared/editor/queries/findParentNode"; import type { MenuItem, SelectionContext } from "@shared/editor/types"; /** @@ -16,8 +17,11 @@ import type { MenuItem, SelectionContext } from "@shared/editor/types"; * @returns an array of menu items. */ export default function noticeMenuItems(ctx: SelectionContext): MenuItem[] { - const node = ctx.selection.$from.node(-1); - const currentStyle = node?.attrs.style as NoticeTypes; + const notice = findParentNode( + (node) => node.type === ctx.schema.nodes.container_notice + )(ctx.selection); + const currentStyle: NoticeTypes = + notice?.node.attrs.style ?? NoticeTypes.Info; const mapping = { [NoticeTypes.Info]: t("Info notice"), diff --git a/shared/editor/nodes/Notice.tsx b/shared/editor/nodes/Notice.tsx index 688041ebab..d016da25c0 100644 --- a/shared/editor/nodes/Notice.tsx +++ b/shared/editor/nodes/Notice.tsx @@ -10,6 +10,7 @@ import type { Command, EditorState, Transaction } from "prosemirror-state"; import type { Primitive } from "utility-types"; import toggleWrap from "../commands/toggleWrap"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; +import { findParentNodeClosestToPos } from "../queries/findParentNode"; import noticesRule from "../rules/notices"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import type { ComponentProps } from "../types"; @@ -125,19 +126,23 @@ export default class Notice extends Node { ): boolean => { const { tr, selection } = state; const { $from } = selection; - const node = $from.node(-1); + const notice = findParentNodeClosestToPos( + $from, + (node) => node.type === state.schema.nodes.container_notice + ); - if (node?.type.name === this.name) { - if (dispatch) { - const transaction = tr.setNodeMarkup($from.before(-1), undefined, { - ...node.attrs, - style, - }); - dispatch(transaction); - } - return true; + if (!notice) { + return false; } - return false; + + if (dispatch) { + const transaction = tr.setNodeMarkup(notice.pos, undefined, { + ...notice.node.attrs, + style, + }); + dispatch(transaction); + } + return true; }; component = (props: ComponentProps) => { From ca9317f4ccf5d5c99438128c57c5c530655078ad Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 13 Sep 2026 15:53:34 -0400 Subject: [PATCH 055/368] fix: Clarify missing OAuth state errors (#13734) --- plugins/github/server/api/github.test.ts | 35 ++++++++++++++++++++++-- server/utils/oauth.ts | 12 ++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/plugins/github/server/api/github.test.ts b/plugins/github/server/api/github.test.ts index 85dba7e188..bea3ca199a 100644 --- a/plugins/github/server/api/github.test.ts +++ b/plugins/github/server/api/github.test.ts @@ -5,11 +5,11 @@ import { SetupAction } from "./schema"; const server = getTestServer(); describe("#github.callback", () => { - it("should reject callback when state nonce does not match cookie", async () => { + it("should reject callback when state cookie is missing", async () => { const user = await buildUser(); const state = JSON.stringify({ teamId: user.teamId, - nonce: "attacker-nonce", + nonce: "state-nonce", }); const res = await server.get( `/api/github.callback?state=${encodeURIComponent( @@ -21,6 +21,29 @@ describe("#github.callback", () => { const body = await res.json(); expect(res.status).toEqual(400); expect(body.error).toEqual("state_mismatch"); + expect(body.message).toEqual("OAuth state cookie was missing"); + }); + + it("should reject callback when state nonce does not match cookie", async () => { + const user = await buildUser(); + const state = JSON.stringify({ + teamId: user.teamId, + nonce: "attacker-nonce", + }); + const res = await server.get( + `/api/github.callback?state=${encodeURIComponent( + state + )}&code=123&setup_action=${SetupAction.install}&installation_id=1`, + user, + { + redirect: "manual", + headers: { Cookie: "githubOAuthNonce=cookie-nonce" }, + } + ); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.error).toEqual("state_mismatch"); + expect(body.message).toEqual("State returned in OAuth flow did not match"); }); it("should reject callback when nonce is missing from state", async () => { @@ -31,9 +54,15 @@ describe("#github.callback", () => { state )}&code=123&setup_action=${SetupAction.install}&installation_id=1`, user, - { redirect: "manual" } + { + redirect: "manual", + headers: { Cookie: "githubOAuthNonce=cookie-nonce" }, + } ); + const body = await res.json(); expect(res.status).toEqual(400); + expect(body.error).toEqual("state_mismatch"); + expect(body.message).toEqual("State returned in OAuth flow was missing"); }); it("should fail when state is not valid JSON", async () => { diff --git a/server/utils/oauth.ts b/server/utils/oauth.ts index 2d430578af..fd3c58abd0 100644 --- a/server/utils/oauth.ts +++ b/server/utils/oauth.ts @@ -47,8 +47,8 @@ export function generateOAuthStateNonce( * @param ctx The Koa context for the callback request. * @param cookieName The cookie used to persist the nonce, unique per provider. * @param stateNonce The nonce extracted from the parsed OAuth state. - * @throws {OAuthStateMismatchError} When the cookie is missing or does not - * match the supplied nonce. + * @throws {OAuthStateMismatchError} When the cookie or state nonce is missing, + * or when they do not match. */ export function verifyOAuthStateNonce( ctx: Context, @@ -63,6 +63,14 @@ export function verifyOAuthStateNonce( domain: getCookieDomain(ctx.hostname, env.isCloudHosted), }); + if (!cookieNonce) { + throw OAuthStateMismatchError("OAuth state cookie was missing"); + } + + if (!stateNonce) { + throw OAuthStateMismatchError("State returned in OAuth flow was missing"); + } + if (!safeEqual(cookieNonce, stateNonce)) { throw OAuthStateMismatchError(); } From b70bb4d02d3acc8b5404d2ac8bb655d1850f8332 Mon Sep 17 00:00:00 2001 From: Translate-O-Tron <75237327+outline-translations@users.noreply.github.com> Date: Sun, 13 Sep 2026 15:53:58 -0400 Subject: [PATCH 056/368] fix: New Czech translations (#13692) --- shared/i18n/locales/cs_CZ/translation.json | 66 +++++++++++----------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/shared/i18n/locales/cs_CZ/translation.json b/shared/i18n/locales/cs_CZ/translation.json index c7af2b44ee..7ab02ff28f 100644 --- a/shared/i18n/locales/cs_CZ/translation.json +++ b/shared/i18n/locales/cs_CZ/translation.json @@ -15,13 +15,13 @@ "Collection permissions": "Oprávnění kolekce", "Share this collection": "Sdílet kolekci", "Duplicate": "Duplikovat", - "Duplicate collection": "Duplicate collection", + "Duplicate collection": "Duplikovat kolekci", "Import documents": "Importovat dokumenty", "Sort in sidebar": "Seřadit v bočním panelu", "A-Z sort": "Seřadit A-Z", "Z-A sort": "Seřadit Z-A", "Manual sort": "Ruční řazení", - "Open in split view": "Open in split view", + "Open in split view": "Otevřít ve vedlejším panelu", "Search in collection": "Hledat v kolekci", "Star": "Přidat k oblíbeným", "Unstar": "Odebrat z oblíbených", @@ -76,7 +76,7 @@ "{{ count }} documents unpublished": "{{ count }} dokument zrušen z publikování", "{{ count }} documents unpublished_plural": "{{ count }} dokumentů zrušeno z publikování", "Subscription inherited from collection": "Odběr zděděn z kolekce", - "Share document": "Share document", + "Share document": "Sdílet dokument", "Markdown": "Markdown", "Download as Markdown": "Stáhnout jako Markdown", "HTML": "HTML", @@ -263,7 +263,7 @@ "{{ count }} user activated": "{{ count }} uživatel aktivován", "{{ count }} user activated_plural": "{{ count }} uživatelů aktivováno", "Resend invite": "Znovu odeslat pozvánku", - "Invite was resent to {{ userName }}": "Invite was resent to {{ userName }}", + "Invite was resent to {{ userName }}": "Pozvánka pro {{ userName }} byla znovu odeslána", "{{ count }} invite resent": "{{ count }} pozvánka znovu odeslána", "{{ count }} invite resent_plural": "{{ count }} pozvánek znovu odesláno", "Could not resend {{ count }} invite": "{{ count }} pozvánku se nepodařilo znovu odeslat", @@ -317,9 +317,9 @@ "I’m sure – Delete": "Jsem si jistý - odstranit", "Are you sure about that? Deleting the {{collectionName}} collection is permanent and cannot be restored, however all published documents within will be moved to the trash.": "Opravdu chcete pokračovat? Odstranění kolekce {{collectionName}} je trvalé a nelze jej vrátit zpět. Všechny publikované dokumenty v ní obsažené budou přesunuty do koše.", "Also, {{collectionName}} is being used as the start view – deleting it will reset the start view to the Home page.": "Kolekce {{collectionName}} je nastavena jako úvodní zobrazení – jejím odstraněním se jako úvodní stránka nastaví Domů.", - "Duplicating collection": "Duplicating collection", - "A copy of the collection and the documents within it will be created.": "A copy of the collection and the documents within it will be created.", - "Duplicating": "Duplicating", + "Duplicating collection": "Duplikování kolekce…", + "A copy of the collection and the documents within it will be created.": "Vytvoří se kopie kolekce včetně všech dokumentů.", + "Duplicating": "Duplikování…", "Type a command or search": "Zadejte příkaz nebo hledejte…", "Untitled": "Bez názvu", "New from template": "Nový ze šablony", @@ -425,7 +425,7 @@ "Filter options": "Možnosti filtru", "Filter": "Filtr", "No results": "Žádné výsledky", - "Close pane": "Close pane", + "Close pane": "Zavřít panel", "{{ count }} members": "{{ count }} člen", "{{ count }} members_plural": "{{ count }} členů", "{{authorName}} created <3>": "{{authorName}} vytvořil <3>", @@ -463,9 +463,9 @@ "Can edit": "Může upravovat", "No access": "Bez přístupu", "Permission": "Oprávnění", - "or": "or", + "or": "nebo", "plus": "plus", - "then": "then", + "then": "potom", "Change Language": "Změnit jazyk", "Dismiss": "Zavřít", "Unable to download image": "Obrázek se nepodařilo stáhnout", @@ -544,10 +544,10 @@ "All documents in this collection will be shared on the web, including any new documents added later": "Všechny dokumenty v této kolekci budou sdíleny na webu, včetně nových dokumentů přidaných později.", "Invite": "Pozvat", "{{ userName }} was added to the collection": "{{ userName }} byl přidán do kolekce", - "{{ count }} people added to the collection": "{{ count }} person added to the collection", - "{{ count }} people added to the collection_plural": "{{ count }} osob bylo přidáno do kolekce", - "{{ count }} people and {{ count2 }} groups added to the collection": "{{ count }} person and {{ count2 }} groups added to the collection", - "{{ count }} people and {{ count2 }} groups added to the collection_plural": "{{ count }} osob a {{ count2 }} skupin bylo přidáno do kolekce", + "{{ count }} people added to the collection": "Do kolekce byl přidán {{ count }} uživatel", + "{{ count }} people added to the collection_plural": "Do kolekce přidáno uživatelů: {{ count }}", + "{{ count }} people and {{ count2 }} groups added to the collection": "Do kolekce přidáno – uživatelé: {{ count }}, skupiny: {{ count2 }}", + "{{ count }} people and {{ count2 }} groups added to the collection_plural": "Do kolekce přidáno – uživatelé: {{ count }}, skupiny: {{ count2 }}", "Switch to dark": "Přepnout na tmavý režim", "Switch to light": "Přepnout na světlý režim", "Subscribe to updates": "Přihlásit se k odběru aktualizací", @@ -600,9 +600,9 @@ "Anyone with the link can access because the parent document, <2>{sharedParent.sourceTitle}, is shared": "Přístup má kdokoli s odkazem, protože nadřazený dokument <2>{sharedParent.sourceTitle} je sdílený.", "Nested documents are not shared on the web. Toggle sharing to enable access, this will be the default behavior in the future": "Vnořené dokumenty nejsou automaticky sdíleny na webu. Chcete-li k nim povolit přístup, zapněte sdílení.", "{{ userName }} was added to the document": "{{ userName }} byl přidán do dokumentu", - "{{ count }} people added to the document": "{{ count }} person added to the document", - "{{ count }} people added to the document_plural": "{{ count }} osob bylo přidáno do dokumentu", - "{{ count }} groups added to the document": "{{ count }} group added to the document", + "{{ count }} people added to the document": "Do dokumentu byl přidán {{ count }} uživatel", + "{{ count }} people added to the document_plural": "Do dokumentu přidáno uživatelů: {{ count }}", + "{{ count }} groups added to the document": "Do dokumentu byla přidána {{ count }} skupina", "{{ count }} groups added to the document_plural": "Do dokumentu přidáno skupin: {{ count }}", "Expand sidebar": "Rozbalit boční panel", "Collapse sidebar": "Sbalit boční panel", @@ -632,8 +632,8 @@ "Integrations": "Integrace", "Return to App": "Zpět do aplikace", "Installation": "Instalace", - "Split pane": "Split pane", - "Main pane": "Main pane", + "Split pane": "Vedlejší panel", + "Main pane": "Hlavní panel", "Unstar document": "Odebrat dokument z oblíbených", "Star document": "Přidat dokument k oblíbeným", "Select a color": "Vybrat barvu", @@ -643,7 +643,7 @@ "Highlight some text and use the <1> control to add placeholders that can be filled out when creating new documents": "Zvýrazněte text a pomocí prvku <1> přidejte zástupné symboly, které lze vyplnit při vytváření nových dokumentů.", "You’re editing a template": "Upravujete šablonu", "Template created, go ahead and customize it": "Šablona byla vytvořena, nyní ji můžete upravit.", - "Creating a template is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.": "Creating a template is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.", + "Creating a template is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents.": "Vytvoření šablony původní dokument nezmění. Vytvoříme jeho kopii a tu převedeme na šablonu pro nové dokumenty.", "Enable other members to use the template immediately": "Povolit ostatním členům okamžité použití šablony", "Location": "Umístění", "Admins can manage the workspace and access billing.": "Administrátoři mohou spravovat pracovní prostor a přistupovat k fakturaci.", @@ -677,7 +677,7 @@ "Last seen": "Naposledy viděn", "{{ time }} local time": "{{ time }} místního času", "Your import completed": "Import byl dokončen", - "View comment thread": "View comment thread", + "View comment thread": "Zobrazit vlákno komentářů", "Previous match": "Předchozí shoda", "Next match": "Další shoda", "Find and replace": "Najít a nahradit", @@ -881,7 +881,7 @@ "Archived by {{userName}}": "Archivoval {{userName}}", "Sorry, an error occurred saving the collection": "Při ukládání kolekce došlo k chybě.", "Add a description": "Přidat popis", - "{{ current }} of {{ count }} changes": "{{ current }} of {{ count }} change", + "{{ current }} of {{ count }} changes": "Změna {{ current }} z {{ count }}", "{{ current }} of {{ count }} changes_plural": "{{ current }} z {{ count }} změn", "{{ count }} changes": "Změny: {{ count }}", "{{ count }} changes_plural": "Změny: {{ count }}", @@ -1019,7 +1019,7 @@ "Weird, this shouldn't ever be empty": "Pole by nemělo být prázdné.", "Documents with recent activity will appear here": "Zde se zobrazí dokumenty s nedávnou aktivitou.", "You haven’t created any documents yet": "Zatím jste nevytvořili žádné dokumenty.", - "{{ count }} invites sent": "{{ count }} invite sent", + "{{ count }} invites sent": "Odeslána {{ count }} pozvánka", "{{ count }} invites sent_plural": "Odeslané pozvánky: {{ count }}", "Those email addresses are already invited": "Na tyto e-mailové adresy již pozvánka byla odeslána.", "Sorry, you can only send {{MAX_INVITES}} invites at a time": "Najednou lze odeslat maximálně {{MAX_INVITES}} pozvánek.", @@ -1334,8 +1334,8 @@ "Are you sure you want to cancel this import?": "Opravdu chcete import zrušit?", "Canceling": "Rušení…", "Canceling this import will discard any progress made. This cannot be undone.": "Zrušením importu ztratíte dosavadní postup.", - "{{ total }} document imported": "{{ total }} document imported", - "{{ total }} document imported_plural": "{{ total }} documents imported", + "{{ total }} document imported": "Importován {{ total }} dokument", + "{{ total }} document imported_plural": "Importované dokumenty: {{ total }}", "You can import a zip file that was previously exported from an Outline installation – collections, documents, and images will be imported. In Outline, open Export in the Settings sidebar and click on Export Data.": "Můžete importovat ZIP soubor dříve vyexportovaný z Outline – dojde k importu kolekcí, dokumentů i obrázků. V Outline otevřete Export v nastavení a klikněte na Exportovat data.", "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload": "Přetáhněte ZIP soubor z exportu Markdown aplikace {{appName}}, nebo jej nahrajte kliknutím.", "Configure": "Konfigurovat", @@ -1463,8 +1463,8 @@ "Show a hand cursor when hovering over interactive elements.": "Zobrazovat kurzor ruky při najetí na interaktivní prvky.", "Show line numbers": "Zobrazovat čísla řádků", "Show line numbers on code blocks in documents.": "Zobrazovat čísla řádků v blocích kódu.", - "Show comment marker": "Show comment marker", - "Display a marker beside lines in the editor that contain comments.": "Display a marker beside lines in the editor that contain comments.", + "Show comment marker": "Zobrazovat značky komentářů", + "Display a marker beside lines in the editor that contain comments.": "U řádků s komentáři zobrazovat v editoru značku.", "Display live word, character, and paragraph counts while editing.": "Během úprav zobrazovat aktuální počty slov, znaků a odstavců.", "When enabled, documents have a separate editing mode. When disabled, documents are always editable when you have permission.": "Je-li povoleno, dokumenty mají samostatný režim úprav. V opačném případě jsou přímo upravitelné (pokud máte oprávnění).", "Remember previous location": "Zapamatovat si poslední umístění", @@ -1692,9 +1692,9 @@ "You can manage your passkeys at any time": "Vaše přístupové klíče můžete kdykoli změnit", "If you have any concerns about your account security, please contact a workspace admin.": "Máte-li obavy o zabezpečení účtu, obraťte se na správce pracovního prostoru.", "Manage Passkeys": "Správa přístupových klíčů", - "Import a zip file of Markdown documents exported from Slab – collections, posts, and images will be imported. In Slab, open the admin settings and use the <1>Export option to download an archive of your content.": "Import a zip file of Markdown documents exported from Slab – collections, posts, and images will be imported. In Slab, open the admin settings and use the <1>Export option to download an archive of your content.", - "Drag and drop the zip file exported from Slab, or click to upload": "Drag and drop the zip file exported from Slab, or click to upload", - "Import a zip file of Markdown documents exported from Slab": "Import a zip file of Markdown documents exported from Slab", + "Import a zip file of Markdown documents exported from Slab – collections, posts, and images will be imported. In Slab, open the admin settings and use the <1>Export option to download an archive of your content.": "Můžete importovat ZIP soubor s dokumenty Markdown exportovanými ze Slabu. Importují se kolekce, příspěvky i obrázky. V nastavení správce ve Slabu zvolte <1>Export a stáhněte archiv svého obsahu.", + "Drag and drop the zip file exported from Slab, or click to upload": "Přetáhněte ZIP soubor exportovaný ze Slabu, nebo jej nahrajte kliknutím.", + "Import a zip file of Markdown documents exported from Slab": "Importovat ZIP soubor s dokumenty Markdown exportovanými ze Slabu", "Add to Slack": "Přidat do Slacku", "document published": "dokument zveřejněn", "document updated": "dokument aktualizován", @@ -1821,7 +1821,7 @@ "Go to export": "Přejít na export", "Here's your request data export from {{ appName }}": "Váš export dat z {{ appName }}", "Your requested data export is complete, you can download from the link below in a browser that is logged into your account.": "Export dat byl dokončen. Soubor si můžete stáhnout po přihlášení k účtu pomocí odkazu níže.", - "This export will be available to download for {{ days }} days.": "This export will be available to download for {{ days }} days.", + "This export will be available to download for {{ days }} days.": "Export bude ke stažení po dobu {{ days }} dnů.", "Download export": "Stáhnout export", "Your requested data export is complete - you can download from the link below in a browser that is logged into your account.": "Export dat byl dokončen. Soubor si můžete stáhnout po přihlášení k účtu pomocí odkazu níže.", "The {{ groupName }} group was mentioned in “{{ documentTitle }}”": "Skupina {{ groupName }} byla zmíněna v „{{ documentTitle }}“", @@ -1889,7 +1889,7 @@ "Sorry, an error occurred uploading the file": "Při nahrávání souboru došlo k chybě.", "Sorry, that type of link is not supported": "Typ odkazu není podporován.", "Caption": "Popisek", - "Click to copy": "Click to copy", + "Click to copy": "Kliknutím zkopírujete", "Empty diagram": "Prázdný diagram", "Double click to edit": "Dvojklikem upravíte", "Open": "Otevřít", @@ -1898,7 +1898,7 @@ "Show {{ count }} completed": "Zobrazit {{ count }} dokončené", "Show {{ count }} completed_plural": "Zobrazit {{ count }} dokončených", "Hide completed": "Skrýt dokončené", - "Sorry, the link could not be copied": "Sorry, the link could not be copied", + "Sorry, the link could not be copied": "Odkaz se nepodařilo zkopírovat.", "Write a caption": "Napsat popisek", "Add title": "Přidat titulek", "Add content": "Přidat obsah", From de005af894a14357ddf9d97e9e11556e7d64fc83 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 18:33:22 -0400 Subject: [PATCH 057/368] chore(deps): bump @css-inline/css-inline-wasm from 0.20.2 to 0.21.2 (#13742) Bumps [@css-inline/css-inline-wasm](https://github.com/Stranger6667/css-inline) from 0.20.2 to 0.21.2. - [Release notes](https://github.com/Stranger6667/css-inline/releases) - [Changelog](https://github.com/Stranger6667/css-inline/blob/master/CHANGELOG.md) - [Commits](https://github.com/Stranger6667/css-inline/compare/c-v0.20.2...c-v0.21.2) --- updated-dependencies: - dependency-name: "@css-inline/css-inline-wasm" dependency-version: 0.21.2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 768241789f..e3442b7c81 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,7 @@ "@bull-board/api": "^6.21.3", "@bull-board/koa": "^6.21.3", "@bull-board/ui": "^6.21.3", - "@css-inline/css-inline-wasm": "^0.20.2", + "@css-inline/css-inline-wasm": "^0.21.2", "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^6.0.1", "@dnd-kit/sortable": "^7.0.2", diff --git a/yarn.lock b/yarn.lock index 679d65396d..f774e7ee9a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1623,10 +1623,10 @@ __metadata: languageName: node linkType: hard -"@css-inline/css-inline-wasm@npm:^0.20.2": - version: 0.20.2 - resolution: "@css-inline/css-inline-wasm@npm:0.20.2" - checksum: 10c0/6d2b58850493a5613ce44c0307108d50a0e8bf23a469aa445e66b68e20883eb97ccbab16543de51c8edfb071a197787526bedaf4cc7db03472c3f3931ffe551f +"@css-inline/css-inline-wasm@npm:^0.21.2": + version: 0.21.2 + resolution: "@css-inline/css-inline-wasm@npm:0.21.2" + checksum: 10c0/4ee83b06456465a35bf48f5c804ec8043edc768e0a091ee16102c0af2e52bb1db0729f9703f2abc0ea123b4a29ea65f68ecbfc23a29afd788f1729c75ede90f1 languageName: node linkType: hard @@ -15484,7 +15484,7 @@ __metadata: "@bull-board/api": "npm:^6.21.3" "@bull-board/koa": "npm:^6.21.3" "@bull-board/ui": "npm:^6.21.3" - "@css-inline/css-inline-wasm": "npm:^0.20.2" + "@css-inline/css-inline-wasm": "npm:^0.21.2" "@dnd-kit/core": "npm:^6.3.1" "@dnd-kit/modifiers": "npm:^6.0.1" "@dnd-kit/sortable": "npm:^7.0.2" From 5414746db1aa9db68c2b5c4e441446754dfd1895 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 18:33:31 -0400 Subject: [PATCH 058/368] chore(deps): bump @vitejs/plugin-react from 6.0.5 to 6.1.1 (#13741) Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 6.0.5 to 6.1.1. - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.1/packages/plugin-react) --- updated-dependencies: - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- yarn.lock | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index e3442b7c81..0cabdca778 100644 --- a/package.json +++ b/package.json @@ -115,7 +115,7 @@ "@types/mailparser": "^3.4.6", "@types/pako": "^2.0.4", "@types/sanitize-filename": "^1.6.3", - "@vitejs/plugin-react": "^6.0.5", + "@vitejs/plugin-react": "^6.1.1", "addressparser": "^1.0.1", "async-sema": "^3.1.1", "bull": "^4.16.5", diff --git a/yarn.lock b/yarn.lock index f774e7ee9a..e5a1feb4d8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7539,21 +7539,24 @@ __metadata: languageName: node linkType: hard -"@vitejs/plugin-react@npm:^6.0.5": - version: 6.0.5 - resolution: "@vitejs/plugin-react@npm:6.0.5" +"@vitejs/plugin-react@npm:^6.1.1": + version: 6.1.1 + resolution: "@vitejs/plugin-react@npm:6.1.1" dependencies: "@rolldown/pluginutils": "npm:^1.0.1" peerDependencies: "@rolldown/plugin-babel": ^0.1.7 || ^0.2.0 babel-plugin-react-compiler: ^1.0.0 + oxc-transform-react: ^0.145.0 vite: ^8.0.0 peerDependenciesMeta: "@rolldown/plugin-babel": optional: true babel-plugin-react-compiler: optional: true - checksum: 10c0/fb02246fe3652d7fb746190bdd098b9e29918dfcf8c67b9c0c37300ce789e82331b2ba761530ac6ac9a61390b774d44f401787bd1c87a6c866d1e74a745cc1a0 + oxc-transform-react: + optional: true + checksum: 10c0/4599b37ee19ebee289782b177642e3002afa9b74cb57a2c0e2a601053c7ebb47f9ef178ab605ff1217de1d23069948a8d366447bfac0d9fb2f17afee5368acd0 languageName: node linkType: hard @@ -15603,7 +15606,7 @@ __metadata: "@types/validator": "npm:^13.15.10" "@types/yauzl": "npm:^2.10.3" "@types/yazl": "npm:^3.3.1" - "@vitejs/plugin-react": "npm:^6.0.5" + "@vitejs/plugin-react": "npm:^6.1.1" "@vitest/ui": "npm:^4.1.11" addressparser: "npm:^1.0.1" async-sema: "npm:^3.1.1" From a082cc54c8989e31c5ba0a8f903f016d412a03d3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 18:33:44 -0400 Subject: [PATCH 059/368] chore(deps): bump the aws group with 5 updates (#13740) Bumps the aws group with 5 updates: | Package | From | To | | --- | --- | --- | | [@aws-sdk/client-s3](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/clients/client-s3) | `3.1126.0` | `3.1130.0` | | [@aws-sdk/lib-storage](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/lib/lib-storage) | `3.1126.0` | `3.1130.0` | | [@aws-sdk/s3-presigned-post](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/s3-presigned-post) | `3.1126.0` | `3.1130.0` | | [@aws-sdk/s3-request-presigner](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/s3-request-presigner) | `3.1126.0` | `3.1130.0` | | [@aws-sdk/signature-v4-crt](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages/signature-v4-crt) | `3.1126.0` | `3.1130.0` | Updates `@aws-sdk/client-s3` from 3.1126.0 to 3.1130.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/clients/client-s3/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1130.0/clients/client-s3) Updates `@aws-sdk/lib-storage` from 3.1126.0 to 3.1130.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/lib/lib-storage/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1130.0/lib/lib-storage) Updates `@aws-sdk/s3-presigned-post` from 3.1126.0 to 3.1130.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/s3-presigned-post/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1130.0/packages/s3-presigned-post) Updates `@aws-sdk/s3-request-presigner` from 3.1126.0 to 3.1130.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/s3-request-presigner/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1130.0/packages/s3-request-presigner) Updates `@aws-sdk/signature-v4-crt` from 3.1126.0 to 3.1130.0 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages/signature-v4-crt/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/v3.1130.0/packages/signature-v4-crt) --- updated-dependencies: - dependency-name: "@aws-sdk/client-s3" dependency-version: 3.1130.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/lib-storage" dependency-version: 3.1130.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/s3-presigned-post" dependency-version: 3.1130.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/s3-request-presigner" dependency-version: 3.1130.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws - dependency-name: "@aws-sdk/signature-v4-crt" dependency-version: 3.1130.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: aws ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 10 +- yarn.lock | 304 +++++++++++++++++++++++++-------------------------- 2 files changed, 157 insertions(+), 157 deletions(-) diff --git a/package.json b/package.json index 0cabdca778..06b904a0a5 100644 --- a/package.json +++ b/package.json @@ -52,12 +52,12 @@ "> 0.25%, not dead" ], "dependencies": { - "@aws-sdk/client-s3": "^3.1126.0", + "@aws-sdk/client-s3": "^3.1130.0", "@aws-sdk/cloudfront-signer": "^3.1125.0", - "@aws-sdk/lib-storage": "^3.1126.0", - "@aws-sdk/s3-presigned-post": "^3.1126.0", - "@aws-sdk/s3-request-presigner": "^3.1126.0", - "@aws-sdk/signature-v4-crt": "^3.1126.0", + "@aws-sdk/lib-storage": "^3.1130.0", + "@aws-sdk/s3-presigned-post": "^3.1130.0", + "@aws-sdk/s3-request-presigner": "^3.1130.0", + "@aws-sdk/signature-v4-crt": "^3.1130.0", "@benrbray/prosemirror-math": "^0.2.2", "@bull-board/api": "^6.21.3", "@bull-board/koa": "^6.21.3", diff --git a/yarn.lock b/yarn.lock index e5a1feb4d8..146da1e011 100644 --- a/yarn.lock +++ b/yarn.lock @@ -28,27 +28,27 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/checksums@npm:^3.1000.29": - version: 3.1000.29 - resolution: "@aws-sdk/checksums@npm:3.1000.29" +"@aws-sdk/checksums@npm:^3.1001.0": + version: 3.1001.0 + resolution: "@aws-sdk/checksums@npm:3.1001.0" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/efa6dfb66366f8f1591cde5669d40153e2caff11c06b19a3aa3957e38084cc6a7df133c0485e10c3d6fdc5b6d7022e90b0c6816dd2c0c08574424f9429c4f9c0 + checksum: 10c0/daa0c0011f72cb26bf797e08704aa7d88b4f1f77b6d8c23336eac3ee0efd0ad401074dd07fa5174132b7edc7ab318269f2a71d8c87dbc343ddcbe23a802540d6 languageName: node linkType: hard -"@aws-sdk/client-s3@npm:3.1126.0, @aws-sdk/client-s3@npm:^3.1126.0": - version: 3.1126.0 - resolution: "@aws-sdk/client-s3@npm:3.1126.0" +"@aws-sdk/client-s3@npm:3.1130.0, @aws-sdk/client-s3@npm:^3.1130.0": + version: 3.1130.0 + resolution: "@aws-sdk/client-s3@npm:3.1130.0" dependencies: - "@aws-sdk/checksums": "npm:^3.1000.29" - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/credential-provider-node": "npm:^3.972.82" - "@aws-sdk/middleware-sdk-s3": "npm:^3.972.75" + "@aws-sdk/checksums": "npm:^3.1001.0" + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/credential-provider-node": "npm:^3.972.83" + "@aws-sdk/middleware-sdk-s3": "npm:^3.972.76" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" @@ -56,7 +56,7 @@ __metadata: "@smithy/node-http-handler": "npm:^4.11.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/1b2c3aa631f04b80f7eef8c91cd8145886a38cd7d04eb1ff3c1721693cb79f191e1e8821390e67f80661159b89b0e327306fd289decf74e603ce4ebc86a909b1 + checksum: 10c0/41378a30cbc37e803af1a093acd9e6722dccca9342f7481e3f905bae4481800846675103cb20df8e015b82152f6ca26f273d282bfdfee06331d8da6bfb4137a2 languageName: node linkType: hard @@ -70,9 +70,9 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/core@npm:^3.977.9": - version: 3.977.9 - resolution: "@aws-sdk/core@npm:3.977.9" +"@aws-sdk/core@npm:^3.978.0": + version: 3.978.0 + resolution: "@aws-sdk/core@npm:3.978.0" dependencies: "@aws-sdk/types": "npm:^3.974.5" "@aws-sdk/xml-builder": "npm:^3.972.40" @@ -82,148 +82,148 @@ __metadata: "@smithy/types": "npm:^4.17.2" bowser: "npm:^2.11.0" tslib: "npm:^2.6.2" - checksum: 10c0/9118a8d05b7c27fe55fb5e793840193d1b311b6c0c2958e591bcada391a71783536ed9c8f4913cc9c4b7258dba650d625ed782669a12875348544c33f35aa8d6 + checksum: 10c0/ac333ff04ce5c868eb6e5aeadeae7a02be302d95c3b6d9e753c50bc607f8fa56a26f9d96aad9866aba9c57ef8c20dec05910abac0246a8f6cf1c8c6e0f6237a9 languageName: node linkType: hard -"@aws-sdk/credential-provider-env@npm:^3.972.70": - version: 3.972.70 - resolution: "@aws-sdk/credential-provider-env@npm:3.972.70" +"@aws-sdk/credential-provider-env@npm:^3.972.71": + version: 3.972.71 + resolution: "@aws-sdk/credential-provider-env@npm:3.972.71" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/f5d8f3f1021a83911f617dd6b36277486d0bdb174c107c4f7776a7e2c609a101aa03ada1cca9d97229ac79aea7797ec6392fe449029b87f7cd013360592bddf3 + checksum: 10c0/0e7bfbb37e92c4d3e390c4e508d47fbb7ec25381a9dd0cb79c2e075a79ebe3ee173521c2f9b999b53f415a6a15ad7966c1e1451a997523caa3e1be185e7edee3 languageName: node linkType: hard -"@aws-sdk/credential-provider-http@npm:^3.972.72": - version: 3.972.72 - resolution: "@aws-sdk/credential-provider-http@npm:3.972.72" +"@aws-sdk/credential-provider-http@npm:^3.972.73": + version: 3.972.73 + resolution: "@aws-sdk/credential-provider-http@npm:3.972.73" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/fetch-http-handler": "npm:^5.7.2" "@smithy/node-http-handler": "npm:^4.11.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/aaa67dc42ce00713d92f931c620e36cb199533e6f1f892a6be76553986c86977442924e76f3743732a7b65e6f6777271789a6edbc70d5a86e0a9b6b5a3ef25f3 + checksum: 10c0/b9a8a595ed9186395fad43556638e4fb34f26395c69a619c9d406a0c803a104494622ee077c6d970f0bc15c8176a0676921b30a7e38ff093b88d0dc8d5d08f63 languageName: node linkType: hard -"@aws-sdk/credential-provider-ini@npm:^3.973.15": +"@aws-sdk/credential-provider-ini@npm:^3.973.16": + version: 3.973.16 + resolution: "@aws-sdk/credential-provider-ini@npm:3.973.16" + dependencies: + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/credential-provider-env": "npm:^3.972.71" + "@aws-sdk/credential-provider-http": "npm:^3.972.73" + "@aws-sdk/credential-provider-login": "npm:^3.972.78" + "@aws-sdk/credential-provider-process": "npm:^3.972.71" + "@aws-sdk/credential-provider-sso": "npm:^3.973.15" + "@aws-sdk/credential-provider-web-identity": "npm:^3.972.77" + "@aws-sdk/nested-clients": "npm:^3.997.45" + "@aws-sdk/types": "npm:^3.974.5" + "@smithy/core": "npm:^3.33.3" + "@smithy/credential-provider-imds": "npm:^4.4.16" + "@smithy/types": "npm:^4.17.2" + tslib: "npm:^2.6.2" + checksum: 10c0/f7acfae0c005fd9b1470a6b328719d9bf8d672c57dd22e9f57e158de3c3712ecac75190662a87e7c62b4201bfaa91a81f962772e8773789515304b2f9e26537a + languageName: node + linkType: hard + +"@aws-sdk/credential-provider-login@npm:^3.972.78": + version: 3.972.78 + resolution: "@aws-sdk/credential-provider-login@npm:3.972.78" + dependencies: + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/nested-clients": "npm:^3.997.45" + "@aws-sdk/types": "npm:^3.974.5" + "@smithy/core": "npm:^3.33.3" + "@smithy/types": "npm:^4.17.2" + tslib: "npm:^2.6.2" + checksum: 10c0/c86edd5c8cfe7e112cc9498867c6af3e12a73edea9e45ee95406d7ffc06baae42bf22cf30d00be4243a2eea6f192c13cd142669cca9a3dbcd367906018779b1b + languageName: node + linkType: hard + +"@aws-sdk/credential-provider-node@npm:^3.972.83": + version: 3.972.83 + resolution: "@aws-sdk/credential-provider-node@npm:3.972.83" + dependencies: + "@aws-sdk/credential-provider-env": "npm:^3.972.71" + "@aws-sdk/credential-provider-http": "npm:^3.972.73" + "@aws-sdk/credential-provider-ini": "npm:^3.973.16" + "@aws-sdk/credential-provider-process": "npm:^3.972.71" + "@aws-sdk/credential-provider-sso": "npm:^3.973.15" + "@aws-sdk/credential-provider-web-identity": "npm:^3.972.77" + "@aws-sdk/types": "npm:^3.974.5" + "@smithy/core": "npm:^3.33.3" + "@smithy/credential-provider-imds": "npm:^4.4.16" + "@smithy/types": "npm:^4.17.2" + tslib: "npm:^2.6.2" + checksum: 10c0/50ad40d4771d3ba46c295bb504bea470fba73237e3e01f34646fd14141428d7e4d85adb73fe73f0a6e4d84b462002cad702521b7f3cea1e6a1e75711b198e22c + languageName: node + linkType: hard + +"@aws-sdk/credential-provider-process@npm:^3.972.71": + version: 3.972.71 + resolution: "@aws-sdk/credential-provider-process@npm:3.972.71" + dependencies: + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/types": "npm:^3.974.5" + "@smithy/core": "npm:^3.33.3" + "@smithy/types": "npm:^4.17.2" + tslib: "npm:^2.6.2" + checksum: 10c0/a4d55be31ad01c2307ae6bb4b6b30b8be5690276e7c3bfc0ff194e8aa788ff81bde7f6c3641094a886dc6304ced38f03bbc72fce4598cfaa1a2952a267327cd7 + languageName: node + linkType: hard + +"@aws-sdk/credential-provider-sso@npm:^3.973.15": version: 3.973.15 - resolution: "@aws-sdk/credential-provider-ini@npm:3.973.15" + resolution: "@aws-sdk/credential-provider-sso@npm:3.973.15" dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/credential-provider-env": "npm:^3.972.70" - "@aws-sdk/credential-provider-http": "npm:^3.972.72" - "@aws-sdk/credential-provider-login": "npm:^3.972.77" - "@aws-sdk/credential-provider-process": "npm:^3.972.70" - "@aws-sdk/credential-provider-sso": "npm:^3.973.14" - "@aws-sdk/credential-provider-web-identity": "npm:^3.972.76" - "@aws-sdk/nested-clients": "npm:^3.997.44" + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/nested-clients": "npm:^3.997.45" + "@aws-sdk/token-providers": "npm:3.1129.0" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" - "@smithy/credential-provider-imds": "npm:^4.4.16" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/1fe5f8c84cb9877a62084f9cbedebaed605ecc34891c44254d979ccd1282a5e164840d6dbb340773c311c028568f9ea642649bebf4b38cebb2d6d0039ad9de12 + checksum: 10c0/0dc16806de6000795b25a933bf940af9ed9a70e129c66685ce40ddb4c84f449cc8dacafcd10103e808c7b6c1aceb7a08a00c8d3646de37d369291c4eb37a7c46 languageName: node linkType: hard -"@aws-sdk/credential-provider-login@npm:^3.972.77": +"@aws-sdk/credential-provider-web-identity@npm:^3.972.77": version: 3.972.77 - resolution: "@aws-sdk/credential-provider-login@npm:3.972.77" + resolution: "@aws-sdk/credential-provider-web-identity@npm:3.972.77" dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/nested-clients": "npm:^3.997.44" + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/nested-clients": "npm:^3.997.45" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/9be54fdf406325d462abdc0a2a182ba1ed39009fa18b60035705e6c3fae92dfe1afe5dba24a4fa3c8376f7cd2e1dad7a91152909f3b96dde0b215a88dfcd5330 + checksum: 10c0/a2ed48d01eb850a0ee5e72287f02ff1402aa2eab8042b4e237fa636a58b566ee46cb1bf235ae6d61dbb6a6b4ebd44ce1d74f8aba71a250db27557746ce1d3021 languageName: node linkType: hard -"@aws-sdk/credential-provider-node@npm:^3.972.82": - version: 3.972.82 - resolution: "@aws-sdk/credential-provider-node@npm:3.972.82" +"@aws-sdk/crt-loader@npm:^3.972.75": + version: 3.972.75 + resolution: "@aws-sdk/crt-loader@npm:3.972.75" dependencies: - "@aws-sdk/credential-provider-env": "npm:^3.972.70" - "@aws-sdk/credential-provider-http": "npm:^3.972.72" - "@aws-sdk/credential-provider-ini": "npm:^3.973.15" - "@aws-sdk/credential-provider-process": "npm:^3.972.70" - "@aws-sdk/credential-provider-sso": "npm:^3.973.14" - "@aws-sdk/credential-provider-web-identity": "npm:^3.972.76" - "@aws-sdk/types": "npm:^3.974.5" - "@smithy/core": "npm:^3.33.3" - "@smithy/credential-provider-imds": "npm:^4.4.16" - "@smithy/types": "npm:^4.17.2" - tslib: "npm:^2.6.2" - checksum: 10c0/c79c2381c1e76fecadb5adf9a8623946d819b20bfc0eaa236a384115027cdea3fe1f0a294c75edbb6aee1a0ccbbc4ec606c2eee8e1c4d720ed2ef281aa1175c8 - languageName: node - linkType: hard - -"@aws-sdk/credential-provider-process@npm:^3.972.70": - version: 3.972.70 - resolution: "@aws-sdk/credential-provider-process@npm:3.972.70" - dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/types": "npm:^3.974.5" - "@smithy/core": "npm:^3.33.3" - "@smithy/types": "npm:^4.17.2" - tslib: "npm:^2.6.2" - checksum: 10c0/87ea5f575f611461a538312b6c502baf86ce33eef6974bb2f9e85bd32147cb8f6b518e80f5a5d8ef371fceb03d517f4d3b6c07ddeb7f15d5a2f56c6dcbf8e8ba - languageName: node - linkType: hard - -"@aws-sdk/credential-provider-sso@npm:^3.973.14": - version: 3.973.14 - resolution: "@aws-sdk/credential-provider-sso@npm:3.973.14" - dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/nested-clients": "npm:^3.997.44" - "@aws-sdk/token-providers": "npm:3.1116.0" - "@aws-sdk/types": "npm:^3.974.5" - "@smithy/core": "npm:^3.33.3" - "@smithy/types": "npm:^4.17.2" - tslib: "npm:^2.6.2" - checksum: 10c0/12132e57c07277b4c115c835bb7a14b2a62e4f30a69998eca501a171d46be469439b3e7b33c970165362bd261b8689389dd06ba0a959657d97330f3e5172ec52 - languageName: node - linkType: hard - -"@aws-sdk/credential-provider-web-identity@npm:^3.972.76": - version: 3.972.76 - resolution: "@aws-sdk/credential-provider-web-identity@npm:3.972.76" - dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/nested-clients": "npm:^3.997.44" - "@aws-sdk/types": "npm:^3.974.5" - "@smithy/core": "npm:^3.33.3" - "@smithy/types": "npm:^4.17.2" - tslib: "npm:^2.6.2" - checksum: 10c0/5efcf6a4b10e49b5b3f9bf76b638ff0b0ce84d26126197f0d28cecbd01458f5d84a074a4cdc8817a7310a940a36a8ad164c1531eb031713bd1485d52bef8c877 - languageName: node - linkType: hard - -"@aws-sdk/crt-loader@npm:^3.972.74": - version: 3.972.74 - resolution: "@aws-sdk/crt-loader@npm:3.972.74" - dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" aws-crt: "npm:^1.31.0" tslib: "npm:^2.6.2" - checksum: 10c0/cc9ac8f7249c24191d614341aeb1b003b7b135f97179d6b7ba4e9765197d3e5156e36a1f0a56010855140d866770b71c4f0ccd19672a1b05ca6d1373bab45dc6 + checksum: 10c0/8f4a2724ac5118834f008c189a80f41cdfd53a114ddbd1321e412a628cda91032aebf88d32e45af48f665c8d726032f002e7e3389e2fcba4b0934afa1a6dc99e languageName: node linkType: hard -"@aws-sdk/lib-storage@npm:^3.1126.0": - version: 3.1126.0 - resolution: "@aws-sdk/lib-storage@npm:3.1126.0" +"@aws-sdk/lib-storage@npm:^3.1130.0": + version: 3.1130.0 + resolution: "@aws-sdk/lib-storage@npm:3.1130.0" dependencies: "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" @@ -232,30 +232,30 @@ __metadata: stream-browserify: "npm:3.0.0" tslib: "npm:^2.6.2" peerDependencies: - "@aws-sdk/client-s3": ^3.1126.0 - checksum: 10c0/486623e8593e29e6eddc83ebf11e005d991072cf3251cbe6576ecf34707dfb146f2217bd11be413b7755a5a221293901691028fba0c5c8e69db79c75c44cc86f + "@aws-sdk/client-s3": ^3.1130.0 + checksum: 10c0/951c3f6b810b3aaad021507565ed70b5b27f94a4b7a850c67d77b5b65c0f0400d3c75567e266643a0b2a17acefa76b1dedcab1b8625026f5319966fa53aca8db languageName: node linkType: hard -"@aws-sdk/middleware-sdk-s3@npm:^3.972.75": - version: 3.972.75 - resolution: "@aws-sdk/middleware-sdk-s3@npm:3.972.75" +"@aws-sdk/middleware-sdk-s3@npm:^3.972.76": + version: 3.972.76 + resolution: "@aws-sdk/middleware-sdk-s3@npm:3.972.76" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/a78eab5895803f3763bf09da2fdcabcd3008c35a57b339523868b84e028a836b1e065af57780975041eb8fb2d2420da5d462e3e1638a956c79777f1ec940d220 + checksum: 10c0/7baaae349411e77897b3ca49670f564d085a1e8744230578127c3b010cb35ce019601fd2c4610e0ce0f6819b53fda9d3ec78d3d84b9408c9da6cbe42c9c83e23 languageName: node linkType: hard -"@aws-sdk/nested-clients@npm:^3.997.44": - version: 3.997.44 - resolution: "@aws-sdk/nested-clients@npm:3.997.44" +"@aws-sdk/nested-clients@npm:^3.997.45": + version: 3.997.45 + resolution: "@aws-sdk/nested-clients@npm:3.997.45" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" @@ -263,51 +263,51 @@ __metadata: "@smithy/node-http-handler": "npm:^4.11.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/947c2049a69a02399f600bd448f34bcaaf3a97b5bbb9b43e9ce932e84d4e9c3131687d330b9c48391da4365582890dd72bf4b8dfafe0693c041e48aa0f5c972d + checksum: 10c0/ef65f970b8e0aa55bf7a837fefbf3a042f247dc4fd7291bc0d64c5115c825e2785d8684a62e97ea7f519ed9a4251b922fbe84e6278dd77d45f1d7cf740dd525d languageName: node linkType: hard -"@aws-sdk/s3-presigned-post@npm:^3.1126.0": - version: 3.1126.0 - resolution: "@aws-sdk/s3-presigned-post@npm:3.1126.0" +"@aws-sdk/s3-presigned-post@npm:^3.1130.0": + version: 3.1130.0 + resolution: "@aws-sdk/s3-presigned-post@npm:3.1130.0" dependencies: - "@aws-sdk/client-s3": "npm:3.1126.0" - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/client-s3": "npm:3.1130.0" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/signature-v4": "npm:^5.6.12" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/42ffe8f738b5eed91d0d8b002f1dc21f2b7d9df7f2ddc06e742f5b9d453d798b62659ee93e8e7e531d8b3af84b4152f06d799d3fb5691bbae7dee4b9506549b8 + checksum: 10c0/867e67ac53cd48c4dc57892dd06386b5db2dca0fb5eeb78a0b960302a95fa07046565000e87030d18c512883208cf9ad86d362d6845c3795b776638bfbcfa378 languageName: node linkType: hard -"@aws-sdk/s3-request-presigner@npm:^3.1126.0": - version: 3.1126.0 - resolution: "@aws-sdk/s3-request-presigner@npm:3.1126.0" +"@aws-sdk/s3-request-presigner@npm:^3.1130.0": + version: 3.1130.0 + resolution: "@aws-sdk/s3-request-presigner@npm:3.1130.0" dependencies: - "@aws-sdk/core": "npm:^3.977.9" + "@aws-sdk/core": "npm:^3.978.0" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/ef83d9af9767663371d09e5025f9be76bfafe51e715e0d1c916d7d74479cb7c28c50f09e1591d7dc4b471ec90fdb0ee59a12791466934304b582c1e1cfbb558d + checksum: 10c0/38aa3d15bbdcf6d31b55792584f954a608f7f2f489173e5ec3e97eaa994fee47a1698fc1130fff1cec5008b63c975bdb436819fd70b1ddfd8e30011c8cb94bc7 languageName: node linkType: hard -"@aws-sdk/signature-v4-crt@npm:^3.1126.0": - version: 3.1126.0 - resolution: "@aws-sdk/signature-v4-crt@npm:3.1126.0" +"@aws-sdk/signature-v4-crt@npm:^3.1130.0": + version: 3.1130.0 + resolution: "@aws-sdk/signature-v4-crt@npm:3.1130.0" dependencies: - "@aws-sdk/crt-loader": "npm:^3.972.74" + "@aws-sdk/crt-loader": "npm:^3.972.75" "@aws-sdk/signature-v4-multi-region": "npm:^3.996.46" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/signature-v4": "npm:^5.6.12" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/36106485a9942ae7774a47d814ee1f1a9efeb7e37d3227846650ecb097438fa4bfc6eda375809011599913e2625921d3492a7d740cb559e451bc47f124a95501 + checksum: 10c0/d94315254cb7f8171e89f8a3de6dd7ca83d0ab6714a268a42c40735f8b0cb5861667e049ba27c1cfa6e9c0560d5cffe0567f3735c14644ce45110bc6cc974ad7 languageName: node linkType: hard @@ -323,17 +323,17 @@ __metadata: languageName: node linkType: hard -"@aws-sdk/token-providers@npm:3.1116.0": - version: 3.1116.0 - resolution: "@aws-sdk/token-providers@npm:3.1116.0" +"@aws-sdk/token-providers@npm:3.1129.0": + version: 3.1129.0 + resolution: "@aws-sdk/token-providers@npm:3.1129.0" dependencies: - "@aws-sdk/core": "npm:^3.977.9" - "@aws-sdk/nested-clients": "npm:^3.997.44" + "@aws-sdk/core": "npm:^3.978.0" + "@aws-sdk/nested-clients": "npm:^3.997.45" "@aws-sdk/types": "npm:^3.974.5" "@smithy/core": "npm:^3.33.3" "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/e720401f6b6d5682984cf1927d3e4c86663b750086bac3b58827a3b9b8585c8b06fb93af82a03a40d5a8ca48c89c0f47c1ac48ea81822c52ddecc3e36ef7cf17 + checksum: 10c0/bbdfaa58f2d7e7f2aa11d826d604b3464896a1149d0ab83757c1f59ec1b267a2887626a1aa8ad2859f2871e442c0a46d28215d490c8a604e54ea55216d9b7621 languageName: node linkType: hard @@ -15477,12 +15477,12 @@ __metadata: version: 0.0.0-use.local resolution: "outline@workspace:." dependencies: - "@aws-sdk/client-s3": "npm:^3.1126.0" + "@aws-sdk/client-s3": "npm:^3.1130.0" "@aws-sdk/cloudfront-signer": "npm:^3.1125.0" - "@aws-sdk/lib-storage": "npm:^3.1126.0" - "@aws-sdk/s3-presigned-post": "npm:^3.1126.0" - "@aws-sdk/s3-request-presigner": "npm:^3.1126.0" - "@aws-sdk/signature-v4-crt": "npm:^3.1126.0" + "@aws-sdk/lib-storage": "npm:^3.1130.0" + "@aws-sdk/s3-presigned-post": "npm:^3.1130.0" + "@aws-sdk/s3-request-presigner": "npm:^3.1130.0" + "@aws-sdk/signature-v4-crt": "npm:^3.1130.0" "@benrbray/prosemirror-math": "npm:^0.2.2" "@bull-board/api": "npm:^6.21.3" "@bull-board/koa": "npm:^6.21.3" From f275632f0a0ef801ff168beeeb04655c1318b2bd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 18:33:51 -0400 Subject: [PATCH 060/368] chore(deps): bump the sentry group with 2 updates (#13739) Bumps the sentry group with 2 updates: [@sentry/node](https://github.com/getsentry/sentry-javascript) and [@sentry/react](https://github.com/getsentry/sentry-javascript). Updates `@sentry/node` from 10.73.0 to 10.74.0 - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/10.74.0/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/10.73.0...10.74.0) Updates `@sentry/react` from 10.73.0 to 10.74.0 - [Release notes](https://github.com/getsentry/sentry-javascript/releases) - [Changelog](https://github.com/getsentry/sentry-javascript/blob/10.74.0/CHANGELOG.md) - [Commits](https://github.com/getsentry/sentry-javascript/compare/10.73.0...10.74.0) --- updated-dependencies: - dependency-name: "@sentry/node" dependency-version: 10.74.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: sentry - dependency-name: "@sentry/react" dependency-version: 10.74.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: sentry ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 4 +- yarn.lock | 134 +++++++++++++++++++++++++-------------------------- 2 files changed, 69 insertions(+), 69 deletions(-) diff --git a/package.json b/package.json index 06b904a0a5..d77afbc69f 100644 --- a/package.json +++ b/package.json @@ -105,8 +105,8 @@ "@radix-ui/react-toolbar": "^1.1.19", "@radix-ui/react-tooltip": "^1.2.16", "@radix-ui/react-visually-hidden": "^1.2.11", - "@sentry/node": "^10.73.0", - "@sentry/react": "^10.73.0", + "@sentry/node": "^10.74.0", + "@sentry/react": "^10.74.0", "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.2", "@tanstack/react-table": "^8.21.3", diff --git a/yarn.lock b/yarn.lock index 146da1e011..8275403d84 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5694,27 +5694,27 @@ __metadata: languageName: node linkType: hard -"@sentry/browser-utils@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/browser-utils@npm:10.73.0" +"@sentry/browser-utils@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/browser-utils@npm:10.74.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" - checksum: 10c0/01ce6ee0f8b009560a6a05d073a244152011aea0fbdc4198f16308bace6ef80a0dd9dcf5d0dacc3bf2198da1d346159e67c17060ab6720b28f73e8766c0e784c + "@sentry/core": "npm:10.74.0" + checksum: 10c0/ac8989b374a7fc46298605bdc1236dbbfbdf248373a9c1d9ce53ebdf137d1040c40d435fa5b46a2da87dcad55f04b035bce10656d8669286bf793f5d2966df85 languageName: node linkType: hard -"@sentry/browser@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/browser@npm:10.73.0" +"@sentry/browser@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/browser@npm:10.74.0" dependencies: - "@sentry/browser-utils": "npm:10.73.0" + "@sentry/browser-utils": "npm:10.74.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" - "@sentry/feedback": "npm:10.73.0" - "@sentry/replay": "npm:10.73.0" - "@sentry/replay-canvas": "npm:10.73.0" - checksum: 10c0/5d6f9581ca8c142d6a4c409c9f34c6f3f5585c3006da12e952836ff83b9bf4fd6c0e0f650b245be4d5497ac4bb8f34d7c658a79300ecd2b165db262fd36c3544 + "@sentry/core": "npm:10.74.0" + "@sentry/feedback": "npm:10.74.0" + "@sentry/replay": "npm:10.74.0" + "@sentry/replay-canvas": "npm:10.74.0" + checksum: 10c0/5970e2abf5929481254a3658b4649abf6c45caaa9bbd39645466fa05248dea7c13075d0605884d754175ff1cf23f6e5ad06091cf716af9ef63e9f514b00182c3 languageName: node linkType: hard @@ -5725,31 +5725,31 @@ __metadata: languageName: node linkType: hard -"@sentry/core@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/core@npm:10.73.0" +"@sentry/core@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/core@npm:10.74.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - checksum: 10c0/553469fd82ec11f5697ab4b2881b6f811834a1036e88afe24920940f131d59ad1dfcd008b99656661c49c7c9de51678719b884b0a6cfcb696312fd58bb911495 + checksum: 10c0/3560388187db34f407f346eedea136ef36336d64140f66ff9e0a64b3a98999732cd6a9f10fd7f64e7b785c8faa7b06c4f98decc003777754dbe3f9b26f8a9cf7 languageName: node linkType: hard -"@sentry/feedback@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/feedback@npm:10.73.0" +"@sentry/feedback@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/feedback@npm:10.74.0" dependencies: - "@sentry/core": "npm:10.73.0" - checksum: 10c0/7dcb318f742a9d4aa5379be889df6f55fab9e5dcbaed0a0a1c90565f8ea6047c562435616c5bbe5a78bdb3a31dc3d023b16ff082c6c8c908aaec8255da801112 + "@sentry/core": "npm:10.74.0" + checksum: 10c0/b71718b884ac533d99cb1ac337194a7ff01e07e885f87d419c6136f4573e6253d40207e2f3352e9e8cb64e1af28c67063802635d12fceaa6549f4c140d53a08b languageName: node linkType: hard -"@sentry/node-core@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/node-core@npm:10.73.0" +"@sentry/node-core@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/node-core@npm:10.74.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" - "@sentry/opentelemetry": "npm:10.73.0" + "@sentry/core": "npm:10.74.0" + "@sentry/opentelemetry": "npm:10.74.0" import-in-the-middle: "npm:^3.0.0" peerDependencies: "@opentelemetry/api": ^1.9.0 @@ -5768,81 +5768,81 @@ __metadata: optional: true "@opentelemetry/sdk-trace-base": optional: true - checksum: 10c0/4641120f7b0c2eb41db6134f86a5633ffa7c0a7411bf3526855065e1d8143ea4e5852f71f62bac456f3efbb691be201144a4db3e02d5b53328e65d4293d3ec3c + checksum: 10c0/e2253dadd2ae89572e39e19c4220fb3b744a20d9c00c27ce6ce2e5c2c70c431b765ce97e58454dc4a3607b50579f7c75aeb1b918f3f95ef6a5a54496ec3dc174 languageName: node linkType: hard -"@sentry/node@npm:^10.73.0": - version: 10.73.0 - resolution: "@sentry/node@npm:10.73.0" +"@sentry/node@npm:^10.74.0": + version: 10.74.0 + resolution: "@sentry/node@npm:10.74.0" dependencies: "@opentelemetry/api": "npm:^1.9.1" "@opentelemetry/instrumentation": "npm:^0.220.0" "@opentelemetry/sdk-trace-base": "npm:^2.9.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" - "@sentry/node-core": "npm:10.73.0" - "@sentry/opentelemetry": "npm:10.73.0" - "@sentry/server-utils": "npm:10.73.0" + "@sentry/core": "npm:10.74.0" + "@sentry/node-core": "npm:10.74.0" + "@sentry/opentelemetry": "npm:10.74.0" + "@sentry/server-utils": "npm:10.74.0" import-in-the-middle: "npm:^3.0.0" - checksum: 10c0/8ddb8a279bf9e2c383942c240ef47abc7dd5ebbb7b89f3058edfed9105dba07a97634dae38e0820167b330dcdf4e3113999856cd3423ead0aedc80872daa338a + checksum: 10c0/2f4d525004a76348b0267d7207676db123cbf21f509d86e19f1d8ba1fe3bfe90dee584a2928f5fd10c2038248dfcc60d99d5bb87e88ac9d06ed5c4f000db3edb languageName: node linkType: hard -"@sentry/opentelemetry@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/opentelemetry@npm:10.73.0" +"@sentry/opentelemetry@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/opentelemetry@npm:10.74.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" + "@sentry/core": "npm:10.74.0" peerDependencies: "@opentelemetry/api": ^1.9.0 "@opentelemetry/core": ^1.30.1 || ^2.1.0 "@opentelemetry/sdk-trace-base": ^1.30.1 || ^2.1.0 - checksum: 10c0/d3d6204cb5a784c9d5572bc1143c1e0f150585fe038bed9924df904a75cb365f26bb2d3cb8f953f719085eceebfa0f3904d9ae7fee08818f5cb41eb1dbd9197c + checksum: 10c0/f576e12ddac1d5bd64387a79420e3cddbddabfb8f83dbf8fa4e8f7e9362d764c172941dff4e3f697b855a325f4f0bb01870f656129383b97821b02c15245891d languageName: node linkType: hard -"@sentry/react@npm:^10.73.0": - version: 10.73.0 - resolution: "@sentry/react@npm:10.73.0" +"@sentry/react@npm:^10.74.0": + version: 10.74.0 + resolution: "@sentry/react@npm:10.74.0" dependencies: - "@sentry/browser": "npm:10.73.0" + "@sentry/browser": "npm:10.74.0" "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" + "@sentry/core": "npm:10.74.0" peerDependencies: react: ^16.14.0 || 17.x || 18.x || 19.x - checksum: 10c0/84afea9290b8a59486566abc011dfee353c0427cf9a22725444a762153a10c31d61eb7b2e5c8cc458bf245e9974b9a2993dadf066e976e5c429bf324559ecefc + checksum: 10c0/b0a35ca2bf0983c0d6bf4eef82e283dba77c403c556cc5a6f5da32c1056c2eef91dd38fc225aca0452103d684f17043d98bc72f00262d1678503fcf343b3f0ea languageName: node linkType: hard -"@sentry/replay-canvas@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/replay-canvas@npm:10.73.0" +"@sentry/replay-canvas@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/replay-canvas@npm:10.74.0" dependencies: - "@sentry/core": "npm:10.73.0" - "@sentry/replay": "npm:10.73.0" - checksum: 10c0/1ba25555afaa65bfc731a2b997a73a24c0f502ef15514dca9e068bb44acb3538fafe317c6e7fb3fe58df9a6f1a7915245f61dd4ab1ee6e4ef2bb713280e2fe58 + "@sentry/core": "npm:10.74.0" + "@sentry/replay": "npm:10.74.0" + checksum: 10c0/7d3d0354a631851a737d3df7965d39b77583554d399479a785f3d318f2ce251f33a7985edca71a990a0e78a9855887d85c5a3fe3d9b6a99b0127d7d09dab376b languageName: node linkType: hard -"@sentry/replay@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/replay@npm:10.73.0" +"@sentry/replay@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/replay@npm:10.74.0" dependencies: - "@sentry/browser-utils": "npm:10.73.0" - "@sentry/core": "npm:10.73.0" - checksum: 10c0/f0bfaa9d824afd2abc91d594b24c75d4509908c16761bb6a62e5aeb70c0a3665b40b07e75d4bfdebaa735a4fc29057783fd7465b08b22744221ca7a3d5913ca1 + "@sentry/browser-utils": "npm:10.74.0" + "@sentry/core": "npm:10.74.0" + checksum: 10c0/a16a27ae6b84d81eea5237478dbe710aa5c91276a3ed933c0a98b1b72430cbcb7bfd461a534d61cc1db9482980f70e9ecbcb6500a6eff17e2bfb60b57f1090ed languageName: node linkType: hard -"@sentry/server-utils@npm:10.73.0": - version: 10.73.0 - resolution: "@sentry/server-utils@npm:10.73.0" +"@sentry/server-utils@npm:10.74.0": + version: 10.74.0 + resolution: "@sentry/server-utils@npm:10.74.0" dependencies: "@sentry/conventions": "npm:^0.16.0" - "@sentry/core": "npm:10.73.0" - checksum: 10c0/58196c7fefa4ac1ecd5f560f6de1d5dd313774cc752871c0882f2bb6a06fd0097506f2f503b167c6851425644e0ddc405121d8538a6274addd33276d8db55f9b + "@sentry/core": "npm:10.74.0" + checksum: 10c0/00f98b4d6d8500802917db790e4d505badaa3776e7c700432d58db3952984fd42118011c93e4b1f2dec2f053bfee37e669b852bf14fca3c5e142f1b0547a77b4 languageName: node linkType: hard @@ -15532,8 +15532,8 @@ __metadata: "@radix-ui/react-tooltip": "npm:^1.2.16" "@radix-ui/react-visually-hidden": "npm:^1.2.11" "@relative-ci/agent": "npm:^4.3.1" - "@sentry/node": "npm:^10.73.0" - "@sentry/react": "npm:^10.73.0" + "@sentry/node": "npm:^10.74.0" + "@sentry/react": "npm:^10.74.0" "@simplewebauthn/browser": "npm:^13.3.0" "@simplewebauthn/server": "npm:^13.3.2" "@swc/cli": "npm:^0.8.1" From 0cda530e15f76c8900a58120bdee23605555eb72 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Mon, 14 Sep 2026 18:34:08 -0400 Subject: [PATCH 061/368] fix: Scope authentication matching to the signing-in provider (#13737) --- server/commands/userProvisioner.test.ts | 35 ++++++++++++++++ server/commands/userProvisioner.ts | 54 +++++++++++++++++++------ 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/server/commands/userProvisioner.test.ts b/server/commands/userProvisioner.test.ts index eb70638626..fbd0a857ed 100644 --- a/server/commands/userProvisioner.test.ts +++ b/server/commands/userProvisioner.test.ts @@ -227,6 +227,41 @@ describe("userProvisioner", () => { expect(isNewUser).toEqual(false); }); + it("should not match an existing authentication from a different provider", async () => { + const existing = await buildUser(); + const authentications = await existing.$get("authentications"); + const existingAuth = authentications[0]; + const originalProviderId = existingAuth.authenticationProviderId; + + // A second provider of a different type, where the attacker is able to + // present the same external identifier as the existing user. + const otherAuthProvider = await AuthenticationProvider.create({ + name: "oidc", + providerId: randomString(32), + teamId: existing.teamId, + }); + + const { user, isNewUser } = await userProvisioner(ctx, { + name: "Attacker", + email: "attacker@example.com", + emailVerified: false, + teamId: existing.teamId, + authentication: { + authenticationProviderId: otherAuthProvider.id, + providerId: existingAuth.providerId, + accessToken: "123", + scopes: ["read"], + }, + }); + + expect(isNewUser).toEqual(true); + expect(user.id).not.toEqual(existing.id); + + await existingAuth.reload(); + expect(existingAuth.authenticationProviderId).toEqual(originalProviderId); + expect(existingAuth.accessToken).not.toEqual("123"); + }); + it("should create a new user", async () => { const team = await buildTeam(); const authenticationProviders = await team.$get("authenticationProviders"); diff --git a/server/commands/userProvisioner.ts b/server/commands/userProvisioner.ts index e4a7b963c6..0d3ad8f51f 100644 --- a/server/commands/userProvisioner.ts +++ b/server/commands/userProvisioner.ts @@ -8,7 +8,12 @@ import { InviteRequiredError, } from "@server/errors"; import Logger from "@server/logging/Logger"; -import { Team, User, UserAuthentication } from "@server/models"; +import { + AuthenticationProvider, + Team, + User, + UserAuthentication, +} from "@server/models"; import { sequelize } from "@server/storage/database"; import type { APIContext } from "@server/types"; import { UserFlag } from "@server/models/User"; @@ -73,22 +78,47 @@ export default async function userProvisioner( authentication, }: Props ): Promise { - const auth = authentication - ? await UserAuthentication.findOne({ + // The provider being signed in with, external user identifiers are only + // unique within the namespace of a single provider so it must be known + // before an existing authentication record can be matched. + const provider = authentication + ? await AuthenticationProvider.findOne({ where: { - providerId: String(authentication.providerId), + id: authentication.authenticationProviderId, + teamId, }, - include: [ - { - model: User, - as: "user", - where: { teamId }, - required: true, - }, - ], }) : undefined; + if (authentication && !provider) { + throw InvalidAuthenticationError(); + } + + const auth = + authentication && provider + ? await UserAuthentication.findOne({ + where: { + providerId: String(authentication.providerId), + }, + include: [ + { + model: User, + as: "user", + where: { teamId }, + required: true, + }, + { + // Restrict matching to the same type of provider, an identifier + // from one provider must never match a record from another. + model: AuthenticationProvider, + as: "authenticationProvider", + where: { name: provider.name }, + required: true, + }, + ], + }) + : undefined; + // Someone has signed in with this authentication before, we just // want to update the details instead of creating a new record if (auth && authentication) { From 0ed4a80336d906c4acac7c6b523982281473e949 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 19:31:07 -0400 Subject: [PATCH 062/368] chore(deps): bump markdown-it and @types/markdown-it (#13743) * chore(deps): bump markdown-it and @types/markdown-it Bumps [markdown-it](https://github.com/markdown-it/markdown-it) and [@types/markdown-it](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/markdown-it). These dependencies needed to be updated together. Updates `markdown-it` from 14.3.0 to 14.3.1 - [Changelog](https://github.com/markdown-it/markdown-it/blob/14.3.1/CHANGELOG.md) - [Commits](https://github.com/markdown-it/markdown-it/compare/14.3.0...14.3.1) Updates `@types/markdown-it` from 14.1.2 to 14.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/markdown-it) --- updated-dependencies: - dependency-name: markdown-it dependency-version: 14.3.1 dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: "@types/markdown-it" dependency-version: 14.2.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * fix: align markdown-it rule types --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Tom Moor --- package.json | 6 +++--- shared/editor/rules/mark.ts | 9 +++++---- yarn.lock | 30 +++++++++++++++++++++++------- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index d77afbc69f..472c59d779 100644 --- a/package.json +++ b/package.json @@ -174,7 +174,7 @@ "koa-useragent": "^4.1.0", "mailparser": "^3.9.20", "mammoth": "^1.11.0", - "markdown-it": "^14.3.0", + "markdown-it": "^14.3.1", "markdown-it-container": "^3.0.0", "markdown-it-emoji": "^3.0.0", "mermaid": "11.17.1", @@ -313,7 +313,7 @@ "@types/koa-send": "^4.1.6", "@types/koa-sslify": "^4.0.6", "@types/koa-useragent": "^2.1.2", - "@types/markdown-it": "14.1.2", + "@types/markdown-it": "14.2.0", "@types/markdown-it-container": "^2.0.11", "@types/markdown-it-emoji": "^3.0.1", "@types/mime-types": "^3.0.1", @@ -378,7 +378,7 @@ "prosemirror-transform": "1.10.5", "prismjs": "1.30.0", "zod": "^4.5.4", - "@types/markdown-it": "14.1.2", + "@types/markdown-it": "14.2.0", "ip-address@npm:10.1.0": "^10.2.0", "minimatch@npm:9.0.1": "9.0.9", "lodash@npm:4.17.21": "^4.18.1", diff --git a/shared/editor/rules/mark.ts b/shared/editor/rules/mark.ts index 619a2b6bd1..91e2338033 100644 --- a/shared/editor/rules/mark.ts +++ b/shared/editor/rules/mark.ts @@ -2,14 +2,12 @@ // https://github.com/markdown-it/markdown-it-mark/blob/master/index.js import type MarkdownIt from "markdown-it"; -import type StateInline from "markdown-it/lib/rules_inline/state_inline.mjs"; -import type { Delimiter } from "markdown-it/lib/rules_inline/state_inline.mjs"; export default function (options: { delim: string; mark: string }) { const delimCharCode = options.delim.charCodeAt(0); return function emphasisPlugin(md: MarkdownIt) { - function tokenize(state: StateInline, silent: boolean) { + function tokenize(state: MarkdownIt.StateInline, silent: boolean) { let i, token; const start = state.pos, @@ -61,7 +59,10 @@ export default function (options: { delim: string; mark: string }) { // Walk through delimiter list and replace text tokens with tags // - function postProcess(state: StateInline, delimiters: Delimiter[]) { + function postProcess( + state: MarkdownIt.StateInline, + delimiters: MarkdownIt.StateInline.Delimiter[] + ) { let i = 0, j, startDelim, diff --git a/yarn.lock b/yarn.lock index 8275403d84..e048ba18a2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7039,13 +7039,13 @@ __metadata: languageName: node linkType: hard -"@types/markdown-it@npm:14.1.2": - version: 14.1.2 - resolution: "@types/markdown-it@npm:14.1.2" +"@types/markdown-it@npm:14.2.0": + version: 14.2.0 + resolution: "@types/markdown-it@npm:14.2.0" dependencies: "@types/linkify-it": "npm:^5" "@types/mdurl": "npm:^2" - checksum: 10c0/34f709f0476bd4e7b2ba7c3341072a6d532f1f4cb6f70aef371e403af8a08a7c372ba6907ac426bc618d356dab660c5b872791ff6c1ead80c483e0d639c6f127 + checksum: 10c0/60ff1a0495ef303310744566342c49b4b3e76fbdca82c5ec28d88731fc934b0c63335d25bca6133903c877f2c41c59cdfddefb3626c6ee0780b9573ddf6aefe4 languageName: node linkType: hard @@ -14451,7 +14451,7 @@ __metadata: languageName: node linkType: hard -"markdown-it@npm:^14.0.0, markdown-it@npm:^14.3.0": +"markdown-it@npm:^14.0.0": version: 14.3.0 resolution: "markdown-it@npm:14.3.0" dependencies: @@ -14467,6 +14467,22 @@ __metadata: languageName: node linkType: hard +"markdown-it@npm:^14.3.1": + version: 14.3.1 + resolution: "markdown-it@npm:14.3.1" + dependencies: + argparse: "npm:^2.0.1" + entities: "npm:^4.5.0" + linkify-it: "npm:^5.0.2" + mdurl: "npm:^2.0.0" + punycode.js: "npm:^2.3.1" + uc.micro: "npm:^2.1.0" + bin: + markdown-it: bin/markdown-it.mjs + checksum: 10c0/806f0f5f29f1ddd9fd465f905c1f2c54d64af9023095792dd5364e5807f77454f427ee75d66083b432d0900e21836f0fff940f94f5fc93c41b2f78970469874e + languageName: node + linkType: hard + "marked@npm:^16.3.0": version: 16.4.2 resolution: "marked@npm:16.4.2" @@ -15569,7 +15585,7 @@ __metadata: "@types/koa-sslify": "npm:^4.0.6" "@types/koa-useragent": "npm:^2.1.2" "@types/mailparser": "npm:^3.4.6" - "@types/markdown-it": "npm:14.1.2" + "@types/markdown-it": "npm:14.2.0" "@types/markdown-it-container": "npm:^2.0.11" "@types/markdown-it-emoji": "npm:^3.0.1" "@types/mime-types": "npm:^3.0.1" @@ -15674,7 +15690,7 @@ __metadata: lint-staged: "npm:^16.4.0" mailparser: "npm:^3.9.20" mammoth: "npm:^1.11.0" - markdown-it: "npm:^14.3.0" + markdown-it: "npm:^14.3.1" markdown-it-container: "npm:^3.0.0" markdown-it-emoji: "npm:^3.0.0" mermaid: "npm:11.17.1" From 61aa3e43a7931365aca131d3daff0f0504a4acec Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 19:01:19 -0400 Subject: [PATCH 063/368] fix: Clean up temporary upload files (#13752) --- .../middlewares/cleanupMultipartFiles.test.ts | 77 +++++++++++++++++++ server/middlewares/cleanupMultipartFiles.ts | 37 +++++++++ server/routes/api/index.ts | 2 + 3 files changed, 116 insertions(+) create mode 100644 server/middlewares/cleanupMultipartFiles.test.ts create mode 100644 server/middlewares/cleanupMultipartFiles.ts diff --git a/server/middlewares/cleanupMultipartFiles.test.ts b/server/middlewares/cleanupMultipartFiles.test.ts new file mode 100644 index 0000000000..ff090c5bbd --- /dev/null +++ b/server/middlewares/cleanupMultipartFiles.test.ts @@ -0,0 +1,77 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { AppContext } from "@server/types"; +import cleanupMultipartFiles from "./cleanupMultipartFiles"; + +interface MockFile { + filepath: string; +} + +const createContext = (files: Record) => + ({ + request: { files }, + }) as unknown as AppContext; + +describe("cleanupMultipartFiles middleware", () => { + let temporaryDirectory: string; + + beforeEach(async () => { + temporaryDirectory = await fs.mkdtemp( + path.join(os.tmpdir(), "outline-upload-cleanup-") + ); + }); + + afterEach(async () => { + await fs.rm(temporaryDirectory, { force: true, recursive: true }); + }); + + it("removes all uploaded files after the request is handled", async () => { + const firstFilePath = path.join(temporaryDirectory, "first"); + const secondFilePath = path.join(temporaryDirectory, "second"); + await Promise.all([ + fs.writeFile(firstFilePath, "first"), + fs.writeFile(secondFilePath, "second"), + ]); + + const middleware = cleanupMultipartFiles(); + const next = vi.fn(async () => { + await expect(fs.stat(firstFilePath)).resolves.toBeDefined(); + await expect(fs.stat(secondFilePath)).resolves.toBeDefined(); + }); + + await middleware( + createContext({ + first: [{ filepath: firstFilePath }], + other: [{ filepath: secondFilePath }], + }), + next + ); + + expect(next).toHaveBeenCalledOnce(); + await expect(fs.stat(firstFilePath)).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect(fs.stat(secondFilePath)).rejects.toMatchObject({ + code: "ENOENT", + }); + }); + + it("removes uploaded files when request handling fails", async () => { + const filePath = path.join(temporaryDirectory, "failed-request"); + await fs.writeFile(filePath, "content"); + + const error = new Error("Request failed"); + const middleware = cleanupMultipartFiles(); + + await expect( + middleware( + createContext({ + file: { filepath: filePath }, + }), + vi.fn().mockRejectedValue(error) + ) + ).rejects.toBe(error); + await expect(fs.stat(filePath)).rejects.toMatchObject({ code: "ENOENT" }); + }); +}); diff --git a/server/middlewares/cleanupMultipartFiles.ts b/server/middlewares/cleanupMultipartFiles.ts new file mode 100644 index 0000000000..1ebd85ba08 --- /dev/null +++ b/server/middlewares/cleanupMultipartFiles.ts @@ -0,0 +1,37 @@ +import fs from "node:fs/promises"; +import type { Next } from "koa"; +import { toError } from "@shared/utils/error"; +import Logger from "@server/logging/Logger"; +import type { AppContext } from "@server/types"; + +/** + * Removes temporary files created while parsing a multipart request. + * + * @returns the middleware function. + */ +export default function cleanupMultipartFiles() { + return async function cleanupMultipartFilesMiddleware( + ctx: AppContext, + next: Next + ) { + const filePaths = Object.values(ctx.request.files ?? {}) + .flat() + .map((file) => file.filepath); + + try { + await next(); + } finally { + await Promise.all( + filePaths.map(async (filePath) => { + try { + await fs.rm(filePath, { force: true }); + } catch (error) { + Logger.error("Failed to remove temporary upload", toError(error), { + filePath, + }); + } + }) + ); + } + }; +} diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index 04c73a5fd0..90843c0e35 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -7,6 +7,7 @@ import userAgent from "koa-useragent"; import env from "@server/env"; import { NotFoundError } from "@server/errors"; import { apiContext } from "@server/middlewares/apiContext"; +import cleanupMultipartFiles from "@server/middlewares/cleanupMultipartFiles"; import coalesceBody from "@server/middlewares/coaleseBody"; import requestContextMiddleware from "@server/middlewares/requestContext"; import requestTracer from "@server/middlewares/requestTracer"; @@ -72,6 +73,7 @@ api.use( jsonLimit: 5 * 1024 * 1024, // 5MB limit for JSON payloads }) ); +api.use(cleanupMultipartFiles()); api.use(coalesceBody()); api.use(userAgent); api.use(requestTracer()); From 4d12b3294c8f30ba57d5d25ad3b2abb2e93649fa Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 19:13:19 -0400 Subject: [PATCH 064/368] perf: Animate loading bar with transform (#13755) --- app/components/LoadingIndicator/LoadingIndicatorBar.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx index 2985bcc13d..e15d442183 100644 --- a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx +++ b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx @@ -8,8 +8,8 @@ const LoadingIndicatorBar = () => ( ); const loadingFrame = keyframes` - from { margin-left: -100%; } - to { margin-left: 100%; } + from { transform: translateX(-100%); } + to { transform: translateX(100%); } `; const Container = styled.div` @@ -19,7 +19,7 @@ const Container = styled.div` width: 100%; animation: ${loadingFrame} 4s ease-in-out infinite; animation-delay: 250ms; - margin-left: -100%; + transform: translateX(-100%); `; const Loader = styled.div` From 33e1293ae9059eb624ced668ae9a4b3fcd50bda1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 19:17:39 -0400 Subject: [PATCH 065/368] fix: Correct shared document preview links (#13756) --- .../HoverPreview/HoverPreviewDocument.tsx | 57 ++++++++++++------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 4f5d1de441..4483d79fbe 100644 --- a/app/components/HoverPreview/HoverPreviewDocument.tsx +++ b/app/components/HoverPreview/HoverPreviewDocument.tsx @@ -19,29 +19,42 @@ const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( { url, id, title, summary, lastActivityByViewer }: Props, ref: React.Ref ) { + const parsedUrl = new URL(url, window.location.href); + const content = ( + + + + + {title} + {lastActivityByViewer && {lastActivityByViewer}} + + }> + + + + + + + + ); + + if (parsedUrl.origin !== window.location.origin) { + return ( + + {content} + + ); + } + return ( - - - - - - {title} - {lastActivityByViewer && {lastActivityByViewer}} - - }> - - - - - - - + + {content} ); }); From 2d07783af714b5734c4f2ca1a4535199a8d625cc Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 19:50:25 -0400 Subject: [PATCH 066/368] Prevent the admin service from running in production (#13758) * fix: Prevent the admin service from running in production * clarify --- server/env.ts | 1 + server/main.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/server/env.ts b/server/env.ts index d97525fef5..e4275fe2f5 100644 --- a/server/env.ts +++ b/server/env.ts @@ -342,6 +342,7 @@ export class Environment { /** * A comma list of which services should be enabled on this instance – defaults to all. + * The "admin" service is only available in development. * * If a services flag is passed it takes priority over the environment variable * for example: --services=web,worker diff --git a/server/main.ts b/server/main.ts index e6b1773def..7d0b55b8a5 100644 --- a/server/main.ts +++ b/server/main.ts @@ -101,6 +101,12 @@ export async function start(id: number, disconnect: () => void) { // must happen before the services add upgrade handlers of their own onupgrade(server); + // The admin service exposes internal queue state without authentication, + // so it is restricted to non-production environments. + if (env.SERVICES.includes("admin") && env.isProduction) { + throw new Error("The admin service cannot be run with NODE_ENV=production"); + } + // loop through requested services at startup for (const name of env.SERVICES) { if (!Object.keys(services).includes(name)) { From f852339c57d199fd84ee21f478934cc9d442ae7b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 19:58:03 -0400 Subject: [PATCH 067/368] fix: Remove source uploads after imports (#13757) * fix: Remove source uploads after imports * fix: Defer import upload cleanup * fix: Initialize import cleanup state --- server/queues/processors/ImportsProcessor.ts | 51 +++++++++++++++-- server/queues/tasks/APIImportTask.ts | 2 - server/queues/tasks/JSONAPIImportTask.test.ts | 57 ++++++++++++++++++- shared/schema.ts | 2 +- 4 files changed, 102 insertions(+), 10 deletions(-) diff --git a/server/queues/processors/ImportsProcessor.ts b/server/queues/processors/ImportsProcessor.ts index c1df1921ae..25f5d30ae8 100644 --- a/server/queues/processors/ImportsProcessor.ts +++ b/server/queues/processors/ImportsProcessor.ts @@ -25,6 +25,7 @@ import { } from "@shared/types"; import { colorPalette } from "@shared/constants"; import { UrlHelper } from "@shared/utils/UrlHelper"; +import { errToString } from "@shared/utils/error"; import { CollectionValidation } from "@shared/validations"; import { createContext } from "@server/context"; import { schema } from "@server/editor"; @@ -59,8 +60,10 @@ export default abstract class ImportsProcessor< * @param event The import event */ public async perform(event: ImportEvent) { + let sourceAttachment: Attachment | null = null; + try { - await sequelize.transaction(async (transaction) => { + sourceAttachment = await sequelize.transaction(async (transaction) => { const importModel = await Import.findByPk>(event.modelId, { rejectOnEmpty: true, paranoid: false, @@ -73,19 +76,23 @@ export default abstract class ImportsProcessor< importModel.state === ImportState.Errored || importModel.state === ImportState.Canceled ) { - return; + return null; } switch (event.name) { case "imports.create": - return this.onCreation(importModel, transaction); + await this.onCreation(importModel, transaction); + return null; case "imports.processed": return this.onProcessed(importModel, transaction); case "imports.delete": - return this.onDeletion(importModel, event, transaction); + await this.onDeletion(importModel, event, transaction); + return null; } + + return null; }); } catch (err) { if (event.name !== "imports.delete" && err instanceof Error) { @@ -99,6 +106,21 @@ export default abstract class ImportsProcessor< throw err; // throw error for retry. } + + if (!sourceAttachment) { + return; + } + + try { + await sourceAttachment.destroy(); + } catch (err) { + Logger.warn("Failed to delete source attachment after import", { + attachmentId: sourceAttachment.id, + importId: event.modelId, + message: errToString(err), + teamId: event.teamId, + }); + } } public async onFailed(event: ImportEvent) { @@ -167,9 +189,12 @@ export default abstract class ImportsProcessor< * * @param importModel Import model associated with the event. * @param transaction Sequelize transaction. - * @returns Promise that resolves when mapping and persistence is completed. + * @returns Source attachment to delete after the transaction commits. */ - private async onProcessed(importModel: Import, transaction: Transaction) { + private async onProcessed( + importModel: Import, + transaction: Transaction + ): Promise { try { const { collections } = await this.createCollectionsAndDocuments({ importModel, @@ -203,7 +228,9 @@ export default abstract class ImportsProcessor< await collection.save({ silent: true, transaction }); } + const storageKey = importModel.scratch?.storageKey; importModel.state = ImportState.Completed; + importModel.scratch = null; importModel.error = null; // unset any error from previous attempts. await importModel.saveWithCtx( createContext({ @@ -211,6 +238,18 @@ export default abstract class ImportsProcessor< transaction, }) ); + + if (storageKey) { + return Attachment.findOne({ + where: { + key: storageKey, + teamId: importModel.teamId, + }, + transaction, + }); + } + + return null; } catch (err) { if (err instanceof UniqueConstraintError) { Logger.error( diff --git a/server/queues/tasks/APIImportTask.ts b/server/queues/tasks/APIImportTask.ts index bfdd0a3b7e..455bd163e7 100644 --- a/server/queues/tasks/APIImportTask.ts +++ b/server/queues/tasks/APIImportTask.ts @@ -259,8 +259,6 @@ export default abstract class APIImportTask< await sequelize.transaction(async (transaction) => { const associatedImport = importTask.import; associatedImport.state = ImportState.Processed; - // Release any cross-phase scratch state — the import is done with it. - associatedImport.scratch = null; await associatedImport.saveWithCtx( createContext({ user: associatedImport.createdBy, diff --git a/server/queues/tasks/JSONAPIImportTask.test.ts b/server/queues/tasks/JSONAPIImportTask.test.ts index b712f63e11..2ce5af0699 100644 --- a/server/queues/tasks/JSONAPIImportTask.test.ts +++ b/server/queues/tasks/JSONAPIImportTask.test.ts @@ -7,18 +7,21 @@ import { Attachment, Collection, Document, + Import, ImportTask, User, } from "@server/models"; import FileStorage from "@server/storage/files"; import { CollectionPermission, + ImportState, ImportTaskPhase, ImportTaskState, IntegrationService, } from "@shared/types"; import { buildAdmin, + buildAttachment, buildDocument, buildImport, buildTeam, @@ -228,6 +231,7 @@ async function runImport(opts: { teamId: string; createdById: string; zipPath: string; + storageKey?: string; }): Promise<{ importId: string }> { vi.spyOn(FileStorage, "getFileHandle").mockResolvedValue({ path: opts.zipPath, @@ -242,7 +246,7 @@ async function runImport(opts: { input: [ { externalId: randomUUID(), permission: CollectionPermission.Read }, ], - scratch: { storageKey: "fixture-key" }, + scratch: { storageKey: opts.storageKey ?? "fixture-key" }, }); // Seed the bootstrap row that JSONImportsProcessor would have created. @@ -331,6 +335,57 @@ describe("JSONAPIImportTask", () => { expect(attachments.length).toBeGreaterThanOrEqual(1); }); + it("deletes the source archive after the import completes", async () => { + const admin = await buildAdmin(); + const sourceAttachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + key: `uploads/${admin.id}/${randomUUID()}/import.zip`, + }); + + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + storageKey: sourceAttachment.key, + }); + + const importModel = await Import.findByPk(importId, { + rejectOnEmpty: true, + }); + expect(importModel.scratch).toBeNull(); + expect(await Attachment.findByPk(sourceAttachment.id)).toBeNull(); + }); + + it("completes the import when source archive cleanup fails", async () => { + const admin = await buildAdmin(); + const sourceAttachment = await buildAttachment({ + teamId: admin.teamId, + userId: admin.id, + key: `uploads/${admin.id}/${randomUUID()}/import.zip`, + }); + const destroy = vi + .spyOn(Attachment.prototype, "destroy") + .mockRejectedValueOnce(new Error("Storage unavailable")); + + try { + const { importId } = await runImport({ + teamId: admin.teamId, + createdById: admin.id, + zipPath: zip.filePath, + storageKey: sourceAttachment.key, + }); + + const importModel = await Import.findByPk(importId, { + rejectOnEmpty: true, + }); + expect(importModel.state).toBe(ImportState.Completed); + expect(await Attachment.findByPk(sourceAttachment.id)).not.toBeNull(); + } finally { + destroy.mockRestore(); + } + }); + it("rewrites internal document links to the new urlIds", async () => { const admin = await buildAdmin(); // Pre-create a document with the exported urlId so the importer is diff --git a/shared/schema.ts b/shared/schema.ts index e5a00d2098..2543e6b413 100644 --- a/shared/schema.ts +++ b/shared/schema.ts @@ -129,7 +129,7 @@ export interface JSONImportScratch { * Per-importer scratch shape stored on `Import.scratch`. Holds cross-phase * state that the importer needs between bootstrap and completion but that * isn't part of any single task's input. Cleared when the import flips to - * `Processed`. + * `Completed`. */ export type ImportScratch = T extends | IntegrationService.Markdown From 11abb1c752d497cb8471dc80d612f2d3fae0d963 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 20:38:26 -0400 Subject: [PATCH 068/368] perf: Filter placeholder candidates before evaluating conditions (#13760) --- app/editor/extensions/BlockMenu.tsx | 4 +- shared/editor/nodes/Doc.ts | 4 +- shared/editor/plugins/PlaceholderPlugin.ts | 93 ++++++++++++++-------- 3 files changed, 62 insertions(+), 39 deletions(-) diff --git a/app/editor/extensions/BlockMenu.tsx b/app/editor/extensions/BlockMenu.tsx index 47a7ba24ca..4f3cc1faed 100644 --- a/app/editor/extensions/BlockMenu.tsx +++ b/app/editor/extensions/BlockMenu.tsx @@ -78,10 +78,10 @@ export default class BlockMenuExtension extends Suggestion { }), new PlaceholderPlugin([ { - condition: ({ node, $start, textContent, state }) => + condition: ({ node, $start, isDocEmpty, state }) => $start.depth === 1 && state.selection.$from.pos === $start.pos + node.content.size && - !!textContent && + !isDocEmpty && node.childCount === 0 && node.textContent === "", text: `${t("Type '/' to insert")}…`, diff --git a/shared/editor/nodes/Doc.ts b/shared/editor/nodes/Doc.ts index 5a11c07453..6dd6583c89 100644 --- a/shared/editor/nodes/Doc.ts +++ b/shared/editor/nodes/Doc.ts @@ -26,8 +26,8 @@ export default class Doc extends Node { return [ new PlaceholderPlugin([ { - condition: ({ $start, parent, node, state, textContent }) => - textContent === "" && + condition: ({ $start, parent, node, state, isDocEmpty }) => + isDocEmpty && !isNull(parent) && parent.type === state.doc.type && parent.childCount === 1 && diff --git a/shared/editor/plugins/PlaceholderPlugin.ts b/shared/editor/plugins/PlaceholderPlugin.ts index 4175679fc5..a4f2794cbb 100644 --- a/shared/editor/plugins/PlaceholderPlugin.ts +++ b/shared/editor/plugins/PlaceholderPlugin.ts @@ -1,4 +1,3 @@ -import { filter, find, map } from "es-toolkit/compat"; import type { Node, ResolvedPos } from "prosemirror-model"; import type { EditorState } from "prosemirror-state"; import { Plugin } from "prosemirror-state"; @@ -15,13 +14,19 @@ type Config = Array<{ parent: Node | null; /** Current editor state */ state: EditorState; - /** Text content of the document */ - textContent: string; + /** Whether the document has no text content, evaluated lazily */ + isDocEmpty: boolean; }) => boolean; /** Placeholder text */ text: string; }>; +/** + * The largest content size of a node that any placeholder condition can match. + * Conditions only ever target empty textblocks or a lone "/" character. + */ +const MAX_CANDIDATE_SIZE = 1; + export class PlaceholderPlugin extends Plugin { /** * @param config Placeholder conditions to evaluate against candidate nodes. @@ -58,44 +63,62 @@ export class PlaceholderPlugin extends Plugin { config: Config, nodeTypes: string[] ) { - const paras: Array<{ - node: Node; - $start: ResolvedPos; - parent: Node | null; - }> = []; + const decorations: Decoration[] = []; + let isDocEmpty: boolean | undefined; + state.doc.descendants((node, pos, parent) => { - if (nodeTypes.includes(node.type.name)) { - paras.push({ node, $start: state.doc.resolve(pos + 1), parent }); + if (!nodeTypes.includes(node.type.name)) { + return true; + } + if (node.content.size > MAX_CANDIDATE_SIZE) { return false; } - return true; - }); - const textContent = state.doc.textContent; - const decorations: Decoration[] = filter( - map(paras, (para) => { - const condMet = find(config, (conf) => - conf.condition({ - node: para.node, - $start: para.$start, - parent: para.parent, - state, - textContent, + const $start = state.doc.resolve(pos + 1); + const args = { + node, + $start, + parent, + state, + get isDocEmpty() { + isDocEmpty ??= isEmpty(state.doc); + return isDocEmpty; + }, + }; + const condMet = config.find((conf) => conf.condition(args)); + + if (condMet) { + decorations.push( + Decoration.node(pos, pos + node.nodeSize, { + class: "placeholder", + "data-empty-text": condMet.text, }) ); - return condMet - ? Decoration.node( - para.$start.pos - 1, - para.$start.pos - 1 + para.node.nodeSize, - { - class: "placeholder", - "data-empty-text": condMet.text, - } - ) - : undefined; - }), - (decoration) => decoration !== undefined - ); + } + return false; + }); + return DecorationSet.create(state.doc, decorations); } } + +/** + * Whether the document has no text content. Equivalent to checking that + * `doc.textContent` is empty, but stops at the first text-producing node + * instead of building a string of the whole document. + */ +function isEmpty(doc: Node): boolean { + let empty = true; + doc.descendants((node) => { + if (!empty) { + return false; + } + if (node.isText) { + empty = !node.text; + } else if (node.isLeaf && node.type.spec.leafText) { + empty = !node.type.spec.leafText(node); + } + return empty; + }); + return empty; +} From 07aab19000843148bd0869489e1f9725faa71cdb Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 20:44:03 -0400 Subject: [PATCH 069/368] perf: Map editor decorations through inline edits instead of rebuilding (#13759) * perf: Map editor decorations through inline edits instead of rebuilding * fix: Repair missing block ids on first edit and keep remote edits on the rebuild path * test: Add isInlineTransaction query tests --- shared/editor/nodes/CheckboxList.ts | 27 ++- shared/editor/nodes/TableCell.ts | 8 +- shared/editor/nodes/TableHeader.ts | 8 +- shared/editor/nodes/ToggleBlock.ts | 58 +++++- .../queries/isInlineTransaction.test.ts | 166 ++++++++++++++++++ shared/editor/queries/isInlineTransaction.ts | 71 ++++++++ 6 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 shared/editor/queries/isInlineTransaction.test.ts create mode 100644 shared/editor/queries/isInlineTransaction.ts diff --git a/shared/editor/nodes/CheckboxList.ts b/shared/editor/nodes/CheckboxList.ts index dfafc772dc..36fafe9bbe 100644 --- a/shared/editor/nodes/CheckboxList.ts +++ b/shared/editor/nodes/CheckboxList.ts @@ -4,7 +4,7 @@ import type { Schema, Node as ProsemirrorNode, } from "prosemirror-model"; -import { Plugin } from "prosemirror-state"; +import { Plugin, PluginKey } from "prosemirror-state"; import { v4 as generateUuid } from "uuid"; import toggleList from "../commands/toggleList"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; @@ -13,6 +13,7 @@ import { listWrappingInputRule, } from "../lib/listInputRule"; import { findBlockNodes } from "../queries/findChildren"; +import { isInlineTransaction } from "../queries/isInlineTransaction"; import { CheckboxListView } from "./CheckboxListView"; import Node from "./Node"; @@ -41,10 +42,26 @@ export default class CheckboxList extends Node { const userIdentifier = this.editor.props.userId; // Plugin to auto-assign IDs to checkbox lists - const assignIdsPlugin = new Plugin({ - appendTransaction: (txs, _oldSt, newSt) => { - const hasDocChanges = txs.some((t) => t.docChanged); - if (!hasDocChanges) { + const assignIdsPluginKey = new PluginKey("checkboxListIds"); + const assignIdsPlugin = new Plugin({ + key: assignIdsPluginKey, + state: { + // Whether any document change has been applied since load + init: () => false, + apply: (tr, hasChanged) => hasChanged || tr.docChanged, + }, + appendTransaction: (txs, oldSt, newSt) => { + if (!txs.some((t) => t.docChanged)) { + return null; + } + + // Lists loaded without ids are repaired on the first edit. After that + // only structural edits can introduce a list without an id. + const isFirstChange = !assignIdsPluginKey.getState(oldSt); + const hasStructuralChange = txs.some( + (t) => t.docChanged && !isInlineTransaction(t) + ); + if (!isFirstChange && !hasStructuralChange) { return null; } diff --git a/shared/editor/nodes/TableCell.ts b/shared/editor/nodes/TableCell.ts index 7c53fc98db..a73f7d829c 100644 --- a/shared/editor/nodes/TableCell.ts +++ b/shared/editor/nodes/TableCell.ts @@ -8,6 +8,7 @@ import type { EditorState } from "prosemirror-state"; import { Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import { TableMap } from "prosemirror-tables"; +import { isInlineTransaction } from "../queries/isInlineTransaction"; import { getCellAttrs, isValidCellAlignment, @@ -146,11 +147,16 @@ export default class TableCell extends Node { state: { init: (_, state) => createCellDecorations(state), apply: (tr, pluginState, oldState, newState) => { - // Only recompute if document changed if (!tr.docChanged) { return pluginState; } + // Inline edits cannot change the table layout, so mapping the + // existing decorations is enough. + if (isInlineTransaction(tr, (node) => !!node.type.spec.tableRole)) { + return pluginState.map(tr.mapping, tr.doc); + } + return createCellDecorations(newState); }, }, diff --git a/shared/editor/nodes/TableHeader.ts b/shared/editor/nodes/TableHeader.ts index 0386ad5895..bcf2b6d888 100644 --- a/shared/editor/nodes/TableHeader.ts +++ b/shared/editor/nodes/TableHeader.ts @@ -13,6 +13,7 @@ import { isValidCellMarks, setCellAttrs, } from "../lib/table"; +import { isInlineTransaction } from "../queries/isInlineTransaction"; import { getCellsInColumn, getCellsInRow, @@ -403,11 +404,16 @@ export default class TableHeader extends Node { state: { init: (_, state) => createHeaderDecorations(state), apply: (tr, pluginState, oldState, newState) => { - // Only recompute if document changed if (!tr.docChanged) { return pluginState; } + // Inline edits cannot change the table layout, so mapping the + // existing decorations is enough. + if (isInlineTransaction(tr, (node) => !!node.type.spec.tableRole)) { + return pluginState.map(tr.mapping, tr.doc); + } + return createHeaderDecorations(newState); }, }, diff --git a/shared/editor/nodes/ToggleBlock.ts b/shared/editor/nodes/ToggleBlock.ts index 2c3dfe9f34..2bae7e1ce3 100644 --- a/shared/editor/nodes/ToggleBlock.ts +++ b/shared/editor/nodes/ToggleBlock.ts @@ -36,6 +36,7 @@ import type { MarkdownSerializerState } from "../lib/markdown/serializer"; import { PlaceholderPlugin } from "../plugins/PlaceholderPlugin"; import { findBlockNodes } from "../queries/findChildren"; import { findCutAfterHeading } from "../queries/findCutAfterHeading"; +import { isInlineTransaction } from "../queries/isInlineTransaction"; import { isNodeActive } from "../queries/isNodeActive"; import toggleBlocksRule from "../rules/toggleBlocks"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; @@ -72,6 +73,8 @@ export const toggleFoldPluginKey = new PluginKey("toggleFold"); /** Plugin key for toggle block fold/unfold events. */ export const toggleEventPluginKey = new PluginKey("toggleBlockEvent"); +const toggleIdPluginKey = new PluginKey("toggleBlockIds"); + /** Build the localStorage key used to persist a toggle block's fold state. */ export const toggleStorageKey = (id: string) => `toggle:${id}`; @@ -117,12 +120,28 @@ export default class ToggleBlock extends Node { get plugins() { // Assign IDs and auto-fold empty - const plugin = new Plugin({ - appendTransaction: (transactions, _oldState, newState) => { + const plugin = new Plugin({ + key: toggleIdPluginKey, + state: { + // Whether any document change has been applied since load + init: () => false, + apply: (tr, hasChanged) => hasChanged || tr.docChanged, + }, + appendTransaction: (transactions, oldState, newState) => { if (!transactions.some((tr) => tr.docChanged)) { return null; } + // Blocks loaded without ids are repaired on the first edit. After + // that only structural edits can add toggle blocks or empty bodies. + const isFirstChange = !toggleIdPluginKey.getState(oldState); + if ( + !isFirstChange && + !transactions.some((tr) => this.isStructuralChange(tr, newState)) + ) { + return null; + } + // Single pass to find all toggle blocks const toggleBlocks = findBlockNodes(newState.doc, true).filter( (b) => b.node.type.name === this.name @@ -187,20 +206,23 @@ export default class ToggleBlock extends Node { }, apply: (tr, pluginState, _oldState, newState) => { - if (isRemoteTransaction(tr, newState)) { - return this.reconcileFoldState(pluginState, newState.doc); - } - const action = tr.getMeta(toggleFoldPluginKey); - // No action - just map decorations through the transaction if (!action) { if (!tr.docChanged) { return pluginState; } - // Always rebuild decorations to ensure head positions are correct - // (mapping can produce incorrect positions when first child changes) + // Inline edits only shift positions, so mapping is enough. Any + // other change may add, remove, or split toggle blocks and + // their heads, so the decorations are rebuilt from the document. + if (!this.isStructuralChange(tr, newState)) { + return { + ...pluginState, + decorations: pluginState.decorations.map(tr.mapping, tr.doc), + }; + } + return this.reconcileFoldState(pluginState, tr.doc); } @@ -470,6 +492,24 @@ export default class ToggleBlock extends Node { }; } + /** + * Check whether a transaction may change the set of toggle blocks, their + * ids, or the bounds of their heads. Local inline edits such as typing do + * not. Remote transactions always do, as their steps do not reflect the + * shape of the collaborative change. + * + * @param tr The transaction to inspect. + * @param state The editor state after the transaction. + * @return true if the toggle block decorations must be rebuilt. + */ + private isStructuralChange(tr: Transaction, state: EditorState): boolean { + return ( + tr.docChanged && + (isRemoteTransaction(tr, state) || + !isInlineTransaction(tr, (node) => node.type.name === this.name)) + ); + } + /** * Resolve the toggle blocks an action applies to: the block at the given * position, that block and every toggle block nested inside it when diff --git a/shared/editor/queries/isInlineTransaction.test.ts b/shared/editor/queries/isInlineTransaction.test.ts new file mode 100644 index 0000000000..8d951dc3c7 --- /dev/null +++ b/shared/editor/queries/isInlineTransaction.test.ts @@ -0,0 +1,166 @@ +import type { Node as ProsemirrorNode } from "prosemirror-model"; +import { TextSelection } from "prosemirror-state"; +import { + createEditorState, + doc, + heading, + p, + schema, +} from "@shared/test/editor"; +import { isInlineTransaction } from "./isInlineTransaction"; + +const { strong } = schema.marks; + +/** + * Document layout (positions are the start of each block's content): + * + * 1 paragraph "first" + * 8 heading "title" + * 15 paragraph "second" + */ +function state() { + return createEditorState(doc([p("first"), heading("title"), p("second")])); +} + +describe("isInlineTransaction", () => { + describe("inline edits", () => { + it("is true for an empty transaction", () => { + expect(isInlineTransaction(state().tr)).toBe(true); + }); + + it("is true when typing inside a paragraph", () => { + const tr = state().tr.insertText("x", 3); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true when typing at the start and end of a textblock", () => { + const s = state(); + expect(isInlineTransaction(s.tr.insertText("x", 1))).toBe(true); + expect(isInlineTransaction(s.tr.insertText("x", 6))).toBe(true); + }); + + it("is true when deleting text within one textblock", () => { + const tr = state().tr.delete(2, 4); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true when deleting all text in a textblock", () => { + const tr = state().tr.delete(1, 6); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true when replacing a text selection with text", () => { + const tr = state().tr.insertText("replacement", 2, 5); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true for mark changes", () => { + const s = state(); + expect(isInlineTransaction(s.tr.addMark(1, 6, strong.create()))).toBe( + true + ); + expect(isInlineTransaction(s.tr.removeMark(1, 6, strong))).toBe(true); + }); + + it("is true when inserting an inline node", () => { + const tr = state().tr.insert( + 3, + schema.nodes.emoji.create({ "data-name": "smile" }) + ); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true for a sequence of inline steps", () => { + const tr = state() + .tr.insertText("a", 3) + .delete(1, 2) + .addMark(1, 4, strong.create()) + .insertText("b", 16); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is true when only the selection changes", () => { + const s = state(); + const tr = s.tr.setSelection(TextSelection.create(s.doc, 3)); + expect(isInlineTransaction(tr)).toBe(true); + }); + }); + + describe("structural edits", () => { + it("is false when splitting a textblock", () => { + const tr = state().tr.split(3); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when joining two textblocks", () => { + // Delete across the boundary between the first paragraph and heading + const tr = state().tr.delete(5, 9); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when deleting a range that spans blocks", () => { + const tr = state().tr.delete(2, 17); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when inserting a block node", () => { + const tr = state().tr.insert(7, p("inserted")); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when deleting a whole block", () => { + const tr = state().tr.delete(7, 14); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when replacing the whole document", () => { + const s = state(); + const tr = s.tr.replaceWith(0, s.doc.content.size, [p("new")]); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when changing a block type", () => { + const tr = state().tr.setBlockType(1, 1, schema.nodes.heading, { + level: 2, + }); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when wrapping a block", () => { + const s = state(); + const range = s.doc.resolve(1).blockRange(s.doc.resolve(6)); + const tr = s.tr.wrap(range!, [{ type: schema.nodes.blockquote }]); + expect(isInlineTransaction(tr)).toBe(false); + }); + + it("is false when one step in a sequence is structural", () => { + const tr = state().tr.insertText("a", 3).split(4); + expect(isInlineTransaction(tr)).toBe(false); + }); + }); + + describe("attribute changes", () => { + it("is true for a node attribute change by default", () => { + const tr = state().tr.setNodeAttribute(7, "level", 3); + expect(isInlineTransaction(tr)).toBe(true); + }); + + it("is false when the predicate flags the changed node", () => { + const tr = state().tr.setNodeAttribute(7, "level", 3); + const isHeading = (node: ProsemirrorNode) => node.type.name === "heading"; + expect(isInlineTransaction(tr, isHeading)).toBe(false); + }); + + it("is true when the predicate does not match the changed node", () => { + const tr = state().tr.setNodeAttribute(7, "level", 3); + const isParagraph = (node: ProsemirrorNode) => + node.type.name === "paragraph"; + expect(isInlineTransaction(tr, isParagraph)).toBe(true); + }); + + it("is true for document attribute changes", () => { + const tr = state().tr.setDocAttribute("title", "x"); + expect(isInlineTransaction(tr)).toBe(true); + }); + }); +}); diff --git a/shared/editor/queries/isInlineTransaction.ts b/shared/editor/queries/isInlineTransaction.ts new file mode 100644 index 0000000000..d3c4854fd7 --- /dev/null +++ b/shared/editor/queries/isInlineTransaction.ts @@ -0,0 +1,71 @@ +import type { Node as ProsemirrorNode } from "prosemirror-model"; +import type { Transaction } from "prosemirror-state"; +import { + AddMarkStep, + AttrStep, + DocAttrStep, + RemoveMarkStep, + ReplaceStep, + type Step, +} from "prosemirror-transform"; + +/** + * Check whether a transaction only edits inline content, such as typing, + * deleting text within a single textblock, or changing marks. Such + * transactions never add, remove, or resize block nodes, other than the + * textblock that was edited. + * + * @param tr The transaction to inspect. + * @param isStructuralAttr Optional predicate for attribute changes that + * should be treated as structural, given the node whose attribute changed. + * @returns true if every step in the transaction is an inline edit. + */ +export function isInlineTransaction( + tr: Transaction, + isStructuralAttr?: (node: ProsemirrorNode) => boolean +): boolean { + return tr.steps.every((step, index) => + isInlineStep(step, tr.docs[index], isStructuralAttr) + ); +} + +function isInlineStep( + step: Step, + doc: ProsemirrorNode, + isStructuralAttr?: (node: ProsemirrorNode) => boolean +): boolean { + if ( + step instanceof AddMarkStep || + step instanceof RemoveMarkStep || + step instanceof DocAttrStep + ) { + return true; + } + + if (step instanceof AttrStep) { + const node = doc.nodeAt(step.pos); + return !node || !isStructuralAttr?.(node); + } + + if (!(step instanceof ReplaceStep)) { + return false; + } + + const { slice } = step; + if (slice.openStart > 0 || slice.openEnd > 0) { + return false; + } + + let inline = true; + slice.content.forEach((child) => { + if (!child.isInline) { + inline = false; + } + }); + if (!inline) { + return false; + } + + const $from = doc.resolve(step.from); + return $from.parent.isTextblock && $from.sameParent(doc.resolve(step.to)); +} From 0e054da71d0c8426cdb49bcd8ce98c0dfef79921 Mon Sep 17 00:00:00 2001 From: breken Date: Wed, 16 Sep 2026 17:50:07 -0700 Subject: [PATCH 070/368] fix(policies): let guests with edit rights duplicate documents again (#13717) #13198 (9796407) moved the duplicate gate to team-level createDocument, which guests and viewers can never hold - so the policy change silently removed duplicate for guests with edit rights on the source document. Allow duplicate when the actor can createDocument at team level (members, preserves #13198) OR update the source (guests, the pre-1.10 capability); the destination collection is still authorized separately in documents.duplicate. Includes the #13198 regression guard plus guest positive/negative cases. Fixes #13715. Co-authored-by: Instinct Agent --- server/policies/document.test.ts | 87 ++++++++++++++++++++++++++++++++ server/policies/document.ts | 8 ++- 2 files changed, 94 insertions(+), 1 deletion(-) diff --git a/server/policies/document.test.ts b/server/policies/document.test.ts index 87a22757b4..5c9e5d6172 100644 --- a/server/policies/document.test.ts +++ b/server/policies/document.test.ts @@ -317,6 +317,93 @@ describe("membership ids", () => { }); }); +describe("duplicate", () => { + it("should allow members to duplicate from a read-write collection", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + permission: CollectionPermission.ReadWrite, + }); + const doc = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + const document = await Document.findByPk(doc.id, { userId: user.id }); + const abilities = serialize(user, document); + expect(abilities.duplicate).toBeTruthy(); + }); + + it("should allow members to duplicate from a read-only collection", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + permission: CollectionPermission.Read, + }); + const doc = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + const document = await Document.findByPk(doc.id, { userId: user.id }); + const abilities = serialize(user, document); + expect(abilities.duplicate).toBeTruthy(); + }); + + it("should allow guests to duplicate documents they can update", async () => { + const team = await buildTeam(); + const user = await buildUser({ + teamId: team.id, + role: UserRole.Guest, + }); + const collection = await buildCollection({ + teamId: team.id, + permission: null, + }); + const doc = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + await UserMembership.create({ + documentId: doc.id, + userId: user.id, + createdById: user.id, + permission: DocumentPermission.ReadWrite, + }); + const document = await Document.findByPk(doc.id, { userId: user.id }); + const abilities = serialize(user, document); + expect(abilities.update).toBeTruthy(); + expect(abilities.duplicate).toBeTruthy(); + }); + + it("should not allow guests to duplicate read-only documents", async () => { + const team = await buildTeam(); + const user = await buildUser({ + teamId: team.id, + role: UserRole.Guest, + }); + const collection = await buildCollection({ + teamId: team.id, + permission: null, + }); + const doc = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + await UserMembership.create({ + documentId: doc.id, + userId: user.id, + createdById: user.id, + permission: DocumentPermission.Read, + }); + const document = await Document.findByPk(doc.id, { userId: user.id }); + const abilities = serialize(user, document); + expect(abilities.read).toBeTruthy(); + expect(abilities.update).toEqual(false); + expect(abilities.duplicate).toEqual(false); + }); +}); + describe("no collection", () => { it("should allow no permissions for team member", async () => { const team = await buildTeam(); diff --git a/server/policies/document.ts b/server/policies/document.ts index f93e176644..8c027a2197 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -129,7 +129,13 @@ allow(User, "duplicate", Document, (actor, document) => !!document?.isActive, isTeamMutable(actor), can(actor, "read", document), - can(actor, "createDocument", actor.team) + or( + can(actor, "createDocument", actor.team), + // Guests and viewers are never team-level creators (see createDocument + // on Team above), but may duplicate documents they can update - the + // destination is still authorized separately in documents.duplicate. + can(actor, "update", document) + ) ) ); From 30b8e681cf49794bf62d49ae9dd7b687a246ca75 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 21:30:57 -0400 Subject: [PATCH 071/368] Add Gmail and Outlook links after email sign-in requests (#13761) * Add inbox links after email magic-link requests * Add and align Gmail and Outlook button icons --- app/components/Icons/GmailIcon.tsx | 30 +++++++++++ app/components/Icons/OutlookIcon.tsx | 30 +++++++++++ app/hooks/useEmailInboxLinks.ts | 48 +++++++++++++++++ app/scenes/Login/Login.tsx | 2 + .../Login/components/EmailInboxButtons.tsx | 54 +++++++++++++++++++ shared/i18n/locales/en_US/translation.json | 2 + 6 files changed, 166 insertions(+) create mode 100644 app/components/Icons/GmailIcon.tsx create mode 100644 app/components/Icons/OutlookIcon.tsx create mode 100644 app/hooks/useEmailInboxLinks.ts create mode 100644 app/scenes/Login/components/EmailInboxButtons.tsx diff --git a/app/components/Icons/GmailIcon.tsx b/app/components/Icons/GmailIcon.tsx new file mode 100644 index 0000000000..f362c20b95 --- /dev/null +++ b/app/components/Icons/GmailIcon.tsx @@ -0,0 +1,30 @@ +interface GmailIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Gmail logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Gmail logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/gmail.svg + */ +export function GmailIcon({ + size = 24, + color = "currentColor", +}: GmailIconProps) { + return ( + + ); +} diff --git a/app/components/Icons/OutlookIcon.tsx b/app/components/Icons/OutlookIcon.tsx new file mode 100644 index 0000000000..bf2c83ae9a --- /dev/null +++ b/app/components/Icons/OutlookIcon.tsx @@ -0,0 +1,30 @@ +interface OutlookIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Outlook logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Outlook logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/microsoftoutlook.svg + */ +export function OutlookIcon({ + size = 24, + color = "currentColor", +}: OutlookIconProps) { + return ( + + ); +} diff --git a/app/hooks/useEmailInboxLinks.ts b/app/hooks/useEmailInboxLinks.ts new file mode 100644 index 0000000000..e8a905869a --- /dev/null +++ b/app/hooks/useEmailInboxLinks.ts @@ -0,0 +1,48 @@ +import { getBaseDomain } from "@shared/utils/domains"; +import useStores from "./useStores"; + +interface EmailInboxLink { + provider: "gmail" | "outlook"; + href: string; +} + +/** + * Builds inbox links for the likely email providers, with search where supported. + * + * @param email the address that received the sign-in link. + * @returns inbox links, including both providers when the context is unclear. + */ +export function useEmailInboxLinks(email: string): EmailInboxLink[] { + const { auth } = useStores(); + const providers = auth.config?.name ? auth.config.providers : []; + const domain = email.trim().toLowerCase().split("@").pop(); + const isGmail = domain === "gmail.com" || domain === "googlemail.com"; + const isOutlook = ["outlook.com", "hotmail.com", "live.com", "msn.com"].some( + (value) => value === domain + ); + const hasGoogle = providers.some((provider) => provider.id === "google"); + const hasMicrosoft = providers.some((provider) => provider.id === "azure"); + const links: EmailInboxLink[] = []; + const senderQuery = `from:(${getBaseDomain()})`; + + if (isGmail || (!isOutlook && (!hasMicrosoft || hasGoogle))) { + links.push({ + provider: "gmail", + href: `https://mail.google.com/mail/?authuser=${encodeURIComponent(email.trim())}#search/${encodeURIComponent(`in:anywhere ${senderQuery}`)}`, + }); + } + + if (isOutlook || (!isGmail && (!hasGoogle || hasMicrosoft))) { + const origin = isOutlook + ? "https://outlook.live.com" + : "https://outlook.office.com"; + links.push({ + provider: "outlook", + // Outlook does not support a reliable search URL. Open the recipient's + // mailbox rather than a search route that may fail or ignore the query. + href: `${origin}/mail/?login_hint=${encodeURIComponent(email.trim())}`, + }); + } + + return links; +} diff --git a/app/scenes/Login/Login.tsx b/app/scenes/Login/Login.tsx index 99d8dc2bb1..5de7d74fb7 100644 --- a/app/scenes/Login/Login.tsx +++ b/app/scenes/Login/Login.tsx @@ -39,6 +39,7 @@ import AuthenticationProvider from "./components/AuthenticationProvider"; import { BackButton } from "./components/BackButton"; import { Background } from "./components/Background"; import { Centered } from "./components/Centered"; +import { EmailInboxButtons } from "./components/EmailInboxButtons"; import { Notices } from "./components/Notices"; import { PasskeyAuthenticationProvider } from "./components/PasskeyAuthenticationProvider"; import { SigningIn } from "./components/SigningIn"; @@ -313,6 +314,7 @@ function Login({ children, onBack }: Props) { />
+ )} diff --git a/app/scenes/Login/components/EmailInboxButtons.tsx b/app/scenes/Login/components/EmailInboxButtons.tsx new file mode 100644 index 0000000000..28ecf1a833 --- /dev/null +++ b/app/scenes/Login/components/EmailInboxButtons.tsx @@ -0,0 +1,54 @@ +import { observer } from "mobx-react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import { Inner } from "~/components/Button"; +import ButtonLarge from "~/components/ButtonLarge"; +import Flex from "~/components/Flex"; +import { GmailIcon } from "~/components/Icons/GmailIcon"; +import { OutlookIcon } from "~/components/Icons/OutlookIcon"; +import { useEmailInboxLinks } from "~/hooks/useEmailInboxLinks"; + +interface EmailInboxButtonsProps { + email: string; +} + +/** + * Shows links to find the sign-in email in Gmail or Outlook. + * + * @param props the recipient email address. + * @returns the available inbox buttons. + */ +export const EmailInboxButtons = observer(function EmailInboxButtons({ + email, +}: EmailInboxButtonsProps) { + const { t } = useTranslation(); + const links = useEmailInboxLinks(email); + + return ( + + {links.map(({ provider, href }) => ( + : } + fullwidth + neutral + > + {provider === "gmail" ? t("Open in Gmail") : t("Open in Outlook")} + + ))} + + ); +}); + +const Buttons = styled(Flex)` + width: 100%; + margin-bottom: 12px; + + ${Inner} { + height: 100%; + } +`; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 16bd66767c..d0ce57beea 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continue with Email", "Continue with {{ authProviderName }}": "Continue with {{ authProviderName }}", "Back to home": "Back to home", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "The workspace could not be found", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "subdomain", From 143da3ff87fcdbf73e75892fdad2f89c3c2db320 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 21:45:20 -0400 Subject: [PATCH 072/368] fix: Address review follow-ups for mapped editor decorations (#13762) Treat checkbox list attribute changes as structural for id repair, keep remote transactions on the rebuild path for table decorations, and map column grip decorations through local inline edits. --- shared/editor/nodes/CheckboxList.ts | 4 +- shared/editor/nodes/TableCell.ts | 13 +++- shared/editor/nodes/TableHeader.ts | 47 +++++++++++---- shared/editor/queries/table.test.ts | 94 +++++++++++++++++++++++++++++ shared/editor/queries/table.ts | 38 +++++++++++- 5 files changed, 179 insertions(+), 17 deletions(-) create mode 100644 shared/editor/queries/table.test.ts diff --git a/shared/editor/nodes/CheckboxList.ts b/shared/editor/nodes/CheckboxList.ts index 36fafe9bbe..20c5f737bb 100644 --- a/shared/editor/nodes/CheckboxList.ts +++ b/shared/editor/nodes/CheckboxList.ts @@ -59,7 +59,9 @@ export default class CheckboxList extends Node { // only structural edits can introduce a list without an id. const isFirstChange = !assignIdsPluginKey.getState(oldSt); const hasStructuralChange = txs.some( - (t) => t.docChanged && !isInlineTransaction(t) + (t) => + t.docChanged && + !isInlineTransaction(t, (node) => node.type.name === this.name) ); if (!isFirstChange && !hasStructuralChange) { return null; diff --git a/shared/editor/nodes/TableCell.ts b/shared/editor/nodes/TableCell.ts index a73f7d829c..1036f52c12 100644 --- a/shared/editor/nodes/TableCell.ts +++ b/shared/editor/nodes/TableCell.ts @@ -8,6 +8,7 @@ import type { EditorState } from "prosemirror-state"; import { Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import { TableMap } from "prosemirror-tables"; +import { isRemoteTransaction } from "../lib/multiplayer"; import { isInlineTransaction } from "../queries/isInlineTransaction"; import { getCellAttrs, @@ -20,6 +21,8 @@ import { presetColors, rgbaToHex } from "@shared/utils/color"; import { parseToRgb, transparentize } from "polished"; import type { RgbaColor } from "polished/lib/types/color"; +const isTableNode = (node: ProsemirrorNode) => !!node.type.spec.tableRole; + export default class TableCell extends Node { /** The default opacity of the table cell background */ static opacity = 0.7; @@ -151,9 +154,13 @@ export default class TableCell extends Node { return pluginState; } - // Inline edits cannot change the table layout, so mapping the - // existing decorations is enough. - if (isInlineTransaction(tr, (node) => !!node.type.spec.tableRole)) { + // Local inline edits cannot change the table layout, so mapping + // the existing decorations is enough. Remote transactions do not + // reflect the shape of the change, so they always rebuild. + if ( + !isRemoteTransaction(tr, newState) && + isInlineTransaction(tr, isTableNode) + ) { return pluginState.map(tr.mapping, tr.doc); } diff --git a/shared/editor/nodes/TableHeader.ts b/shared/editor/nodes/TableHeader.ts index bcf2b6d888..d09d56a210 100644 --- a/shared/editor/nodes/TableHeader.ts +++ b/shared/editor/nodes/TableHeader.ts @@ -1,5 +1,5 @@ import type Token from "markdown-it/lib/token.mjs"; -import type { NodeSpec } from "prosemirror-model"; +import type { Node as ProsemirrorNode, NodeSpec } from "prosemirror-model"; import type { EditorState } from "prosemirror-state"; import { Plugin, PluginKey } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; @@ -7,6 +7,7 @@ import { DecorationSet, Decoration } from "prosemirror-view"; import { isInTable, moveTableColumn, TableMap } from "prosemirror-tables"; import { addColumnBefore, selectColumn } from "../commands/table"; import { isMobile } from "../../utils/browser"; +import { isRemoteTransaction } from "../lib/multiplayer"; import { getCellAttrs, isValidCellAlignment, @@ -17,6 +18,7 @@ import { isInlineTransaction } from "../queries/isInlineTransaction"; import { getCellsInColumn, getCellsInRow, + hasTableSelectionChanged, isColumnSelected, isTableSelected, } from "../queries/table"; @@ -208,6 +210,8 @@ function createColumnDragDecorations(state: EditorState): DecorationSet { return DecorationSet.create(state.doc, decorations); } +const isTableNode = (node: ProsemirrorNode) => !!node.type.spec.tableRole; + export default class TableHeader extends Node { get name() { return "th"; @@ -408,9 +412,13 @@ export default class TableHeader extends Node { return pluginState; } - // Inline edits cannot change the table layout, so mapping the - // existing decorations is enough. - if (isInlineTransaction(tr, (node) => !!node.type.spec.tableRole)) { + // Local inline edits cannot change the table layout, so mapping + // the existing decorations is enough. Remote transactions do not + // reflect the shape of the change, so they always rebuild. + if ( + !isRemoteTransaction(tr, newState) && + isInlineTransaction(tr, isTableNode) + ) { return pluginState.map(tr.mapping, tr.doc); } @@ -428,17 +436,32 @@ export default class TableHeader extends Node { state: { init: (_, state) => createColumnDecorations(state), apply: (tr, pluginState, oldState, newState) => { - // Recompute if selection, document, or drag state changed - if ( - !tr.selectionSet && - !tr.docChanged && - !tr.getMeta(columnDragPluginKey) && - !tr.getMeta(rowDragPluginKey) - ) { + const hasDragChanged = + !!tr.getMeta(columnDragPluginKey) || + !!tr.getMeta(rowDragPluginKey); + if (!tr.selectionSet && !tr.docChanged && !hasDragChanged) { return pluginState; } - return createColumnDecorations(newState); + // Rebuild for drag state, selection changes that affect the grips, + // and any change that may alter the table layout. The set is also + // empty when built before the view existed, so build it once the + // selection is in a table. + if ( + hasDragChanged || + hasTableSelectionChanged(tr, oldState, newState) || + (pluginState === DecorationSet.empty && isInTable(newState)) || + (tr.docChanged && + (isRemoteTransaction(tr, newState) || + !isInlineTransaction(tr, isTableNode))) + ) { + return createColumnDecorations(newState); + } + + // Local inline edits only shift positions, so mapping is enough. + return tr.docChanged + ? pluginState.map(tr.mapping, tr.doc) + : pluginState; }, }, props: { diff --git a/shared/editor/queries/table.test.ts b/shared/editor/queries/table.test.ts new file mode 100644 index 0000000000..f6ce89956e --- /dev/null +++ b/shared/editor/queries/table.test.ts @@ -0,0 +1,94 @@ +import { TextSelection } from "prosemirror-state"; +import { CellSelection } from "prosemirror-tables"; +import { + createEditorStateWithSelection, + doc, + p, + table, + td, + tr, +} from "@shared/test/editor"; +import { hasTableSelectionChanged } from "./table"; + +/** + * Document layout: + * + * 0 table + * 1 tr + * 2 td (content starts at 3, paragraph text at 4) + * 9 td (content starts at 10, paragraph text at 11) + * 18 paragraph "between" (text at 19) + * 27 table + * 28 tr + * 29 td (paragraph text at 31) + */ +function state(pos: number) { + return createEditorStateWithSelection( + doc([ + table([tr([td("one"), td("two")])]), + p("between"), + table([tr([td("three")])]), + ]), + pos + ); +} + +describe("hasTableSelectionChanged", () => { + it("is false when the selection is not set", () => { + const s = state(4); + const t = s.tr.insertText("x", 5); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(false); + }); + + it("is false when the cursor moves within one table", () => { + const s = state(4); + const t = s.tr.setSelection(TextSelection.create(s.doc, 12)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(false); + }); + + it("is false when typing keeps the cursor in the same table", () => { + const s = state(4); + const t = s.tr.insertText("x", 4); + t.setSelection(TextSelection.create(t.doc, 5)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(false); + }); + + it("is false when the cursor moves outside of any table", () => { + const s = state(19); + const t = s.tr.setSelection(TextSelection.create(s.doc, 22)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(false); + }); + + it("is true when the cursor moves out of a table", () => { + const s = state(4); + const t = s.tr.setSelection(TextSelection.create(s.doc, 19)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(true); + }); + + it("is true when the cursor moves into a table", () => { + const s = state(19); + const t = s.tr.setSelection(TextSelection.create(s.doc, 4)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(true); + }); + + it("is true when the cursor moves between tables", () => { + const s = state(4); + const t = s.tr.setSelection(TextSelection.create(s.doc, 31)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(true); + }); + + it("is true when cells become selected", () => { + const s = state(4); + const t = s.tr.setSelection(CellSelection.create(s.doc, 2, 9)); + expect(hasTableSelectionChanged(t, s, s.apply(t))).toBe(true); + }); + + it("is true when a cell selection is dropped", () => { + const s = state(4); + const selected = s.apply( + s.tr.setSelection(CellSelection.create(s.doc, 2, 9)) + ); + const t = selected.tr.setSelection(TextSelection.create(selected.doc, 4)); + expect(hasTableSelectionChanged(t, selected, selected.apply(t))).toBe(true); + }); +}); diff --git a/shared/editor/queries/table.ts b/shared/editor/queries/table.ts index 00519ca2ae..5c912e7f23 100644 --- a/shared/editor/queries/table.ts +++ b/shared/editor/queries/table.ts @@ -1,6 +1,7 @@ -import type { EditorState } from "prosemirror-state"; +import type { EditorState, Transaction } from "prosemirror-state"; import type { TableRect } from "prosemirror-tables"; import { CellSelection, isInTable, selectedRect } from "prosemirror-tables"; +import { findParentNodeClosestToPos } from "./findParentNode"; import { ColumnSelection } from "../selection/ColumnSelection"; import { RowSelection } from "../selection/RowSelection"; import type { EditorView } from "prosemirror-view"; @@ -659,3 +660,38 @@ export const hasNodeAttrMarkWithAttrsCellSelection = ( return attrsMatch; }; + +/** + * Checks whether the selection change in a transaction can alter table + * decorations that depend on the selection: a cell selection on either side, + * or the selection moving into, out of, or between tables. Moving the cursor + * within one table does not. + * + * @param tr The transaction. + * @param oldState The editor state before the transaction. + * @param newState The editor state after the transaction. + * @returns true if the selected table or the cell selection changed. + */ +export function hasTableSelectionChanged( + tr: Transaction, + oldState: EditorState, + newState: EditorState +): boolean { + if (!tr.selectionSet) { + return false; + } + if ( + oldState.selection instanceof CellSelection || + newState.selection instanceof CellSelection + ) { + return true; + } + + const isTable = (node: Node) => node.type.spec.tableRole === "table"; + const before = findParentNodeClosestToPos(oldState.selection.$head, isTable); + const after = findParentNodeClosestToPos(newState.selection.$head, isTable); + if (!before || !after) { + return !!before !== !!after; + } + return tr.mapping.map(before.pos) !== after.pos; +} From e43ffc061c2a7a05d8b583ef8fcc8705bb0c2347 Mon Sep 17 00:00:00 2001 From: Translate-O-Tron <75237327+outline-translations@users.noreply.github.com> Date: Wed, 16 Sep 2026 22:05:29 -0400 Subject: [PATCH 073/368] New Crowdin updates (#13763) * fix: New Czech translations * fix: New French translations * fix: New Spanish translations * fix: New Catalan translations * fix: New Danish translations * fix: New German translations * fix: New Hebrew translations * fix: New Hungarian translations * fix: New Italian translations * fix: New Japanese translations * fix: New Korean translations * fix: New Dutch translations * fix: New Polish translations * fix: New Portuguese translations * fix: New Swedish translations * fix: New Turkish translations * fix: New Ukrainian translations * fix: New Chinese Simplified translations * fix: New Chinese Traditional translations * fix: New Vietnamese translations * fix: New Portuguese, Brazilian translations * fix: New Indonesian translations * fix: New Persian translations * fix: New Thai translations * fix: New English, United Kingdom translations * fix: New Norwegian Bokmal translations --- shared/i18n/locales/ca_ES/translation.json | 2 ++ shared/i18n/locales/cs_CZ/translation.json | 2 ++ shared/i18n/locales/da_DK/translation.json | 2 ++ shared/i18n/locales/de_DE/translation.json | 2 ++ shared/i18n/locales/en_GB/translation.json | 2 ++ shared/i18n/locales/es_ES/translation.json | 2 ++ shared/i18n/locales/fa_IR/translation.json | 2 ++ shared/i18n/locales/fr_FR/translation.json | 2 ++ shared/i18n/locales/he_IL/translation.json | 2 ++ shared/i18n/locales/hu_HU/translation.json | 2 ++ shared/i18n/locales/id_ID/translation.json | 2 ++ shared/i18n/locales/it_IT/translation.json | 2 ++ shared/i18n/locales/ja_JP/translation.json | 2 ++ shared/i18n/locales/ko_KR/translation.json | 2 ++ shared/i18n/locales/nb_NO/translation.json | 2 ++ shared/i18n/locales/nl_NL/translation.json | 2 ++ shared/i18n/locales/pl_PL/translation.json | 2 ++ shared/i18n/locales/pt_BR/translation.json | 2 ++ shared/i18n/locales/pt_PT/translation.json | 2 ++ shared/i18n/locales/sv_SE/translation.json | 2 ++ shared/i18n/locales/th_TH/translation.json | 2 ++ shared/i18n/locales/tr_TR/translation.json | 2 ++ shared/i18n/locales/uk_UA/translation.json | 2 ++ shared/i18n/locales/vi_VN/translation.json | 2 ++ shared/i18n/locales/zh_CN/translation.json | 2 ++ shared/i18n/locales/zh_TW/translation.json | 2 ++ 26 files changed, 52 insertions(+) diff --git a/shared/i18n/locales/ca_ES/translation.json b/shared/i18n/locales/ca_ES/translation.json index 90db034031..1c76882a65 100644 --- a/shared/i18n/locales/ca_ES/translation.json +++ b/shared/i18n/locales/ca_ES/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continua amb el correu electrònic", "Continue with {{ authProviderName }}": "Continua amb {{ authProviderName }}", "Back to home": "Tornar a l'inici", + "Open in Gmail": "Obre al Gmail", + "Open in Outlook": "Obre a l’Outlook", "The workspace could not be found": "No s'ha pogut trobar l'espai de treball", "To continue, enter your workspace’s subdomain.": "Per continuar, entra al subdomini del teu espai de treball.", "subdomain": "subdomini", diff --git a/shared/i18n/locales/cs_CZ/translation.json b/shared/i18n/locales/cs_CZ/translation.json index 7ab02ff28f..df5f470e22 100644 --- a/shared/i18n/locales/cs_CZ/translation.json +++ b/shared/i18n/locales/cs_CZ/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Pokračovat e-mailem", "Continue with {{ authProviderName }}": "Pokračovat přes {{ authProviderName }}", "Back to home": "Zpět domů", + "Open in Gmail": "Otevřít v Gmailu", + "Open in Outlook": "Otevřít v Outlooku", "The workspace could not be found": "Pracovní prostor nebyl nalezen.", "To continue, enter your workspace’s subdomain.": "Pro pokračování zadejte subdoménu pracovního prostoru.", "subdomain": "subdoména", diff --git a/shared/i18n/locales/da_DK/translation.json b/shared/i18n/locales/da_DK/translation.json index d1c9c05b4a..bd65843d96 100644 --- a/shared/i18n/locales/da_DK/translation.json +++ b/shared/i18n/locales/da_DK/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Fortsæt med e-mail", "Continue with {{ authProviderName }}": "Fortsæt med {{ authProviderName }}", "Back to home": "Tilbage til forsiden", + "Open in Gmail": "Åbn i Gmail", + "Open in Outlook": "Åbn i Outlook", "The workspace could not be found": "Arbejdsområdet blev ikke fundet", "To continue, enter your workspace’s subdomain.": "Indtast dit arbejdsområdes underdomæne for at fortsætte.", "subdomain": "underdomæne", diff --git a/shared/i18n/locales/de_DE/translation.json b/shared/i18n/locales/de_DE/translation.json index 98caf0a473..1fc75c5f82 100644 --- a/shared/i18n/locales/de_DE/translation.json +++ b/shared/i18n/locales/de_DE/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Weiter mit E-Mail", "Continue with {{ authProviderName }}": "Weiter mit {{ authProviderName }}", "Back to home": "Zurück zu Home", + "Open in Gmail": "In Gmail öffnen", + "Open in Outlook": "In Outlook öffnen", "The workspace could not be found": "Der Arbeitsbereich konnte nicht gefunden werden", "To continue, enter your workspace’s subdomain.": "Um fortzufahren, geben Sie die Subdomain Ihres Arbeitsbereichs ein.", "subdomain": "Subdomäne", diff --git a/shared/i18n/locales/en_GB/translation.json b/shared/i18n/locales/en_GB/translation.json index 4dd12e789f..2a29842000 100644 --- a/shared/i18n/locales/en_GB/translation.json +++ b/shared/i18n/locales/en_GB/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continue with Email", "Continue with {{ authProviderName }}": "Continue with {{ authProviderName }}", "Back to home": "Back to home", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "The workspace could not be found", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "subdomain", diff --git a/shared/i18n/locales/es_ES/translation.json b/shared/i18n/locales/es_ES/translation.json index b0da4f5441..524e4c8dea 100644 --- a/shared/i18n/locales/es_ES/translation.json +++ b/shared/i18n/locales/es_ES/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continuar con el correo electrónico", "Continue with {{ authProviderName }}": "Continuar con {{ authProviderName }}", "Back to home": "Volver al inicio", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "El espacio de trabajo no se pudo encontrar", "To continue, enter your workspace’s subdomain.": "Para continuar, introduce el subdominio de tu espacio de trabajo.", "subdomain": "subdominio", diff --git a/shared/i18n/locales/fa_IR/translation.json b/shared/i18n/locales/fa_IR/translation.json index 85d917afd6..1338ebf4a9 100644 --- a/shared/i18n/locales/fa_IR/translation.json +++ b/shared/i18n/locales/fa_IR/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "ادامه با ایمیل", "Continue with {{ authProviderName }}": "با {{ authProviderName }} ادامه دهید", "Back to home": "بازگشت به خانه", + "Open in Gmail": "باز کردن در جیمیل", + "Open in Outlook": "باز کردن در اوت‌لوک", "The workspace could not be found": "فضای کاری یافت نشد", "To continue, enter your workspace’s subdomain.": "برای ادامه، زیر دامنه فضای کاری خود را وارد کنید.", "subdomain": "زیر دامنه", diff --git a/shared/i18n/locales/fr_FR/translation.json b/shared/i18n/locales/fr_FR/translation.json index 53157a9c75..2cedee9a22 100644 --- a/shared/i18n/locales/fr_FR/translation.json +++ b/shared/i18n/locales/fr_FR/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continuer avec un e-mail", "Continue with {{ authProviderName }}": "Continuer avec {{ authProviderName }}", "Back to home": "Retour à l’accueil", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "La ressource demandée est introuvable", "To continue, enter your workspace’s subdomain.": "Pour continuer, entrez le sous-domaine de votre espace de travail.", "subdomain": "sous-domaine", diff --git a/shared/i18n/locales/he_IL/translation.json b/shared/i18n/locales/he_IL/translation.json index 9ad545de19..37cf6f5e21 100644 --- a/shared/i18n/locales/he_IL/translation.json +++ b/shared/i18n/locales/he_IL/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "המשך עם אימייל", "Continue with {{ authProviderName }}": "המשך עם {{ authProviderName }}", "Back to home": "חזרה הביתה", + "Open in Gmail": "פתח ב-Gmail", + "Open in Outlook": "פתח ב-Outlook", "The workspace could not be found": "לא ניתן למצוא את סביבת העבודה", "To continue, enter your workspace’s subdomain.": "כדי להמשיך, הזן את תת-הדומיין של סביבת העבודה שלך.", "subdomain": "תת-דומיין", diff --git a/shared/i18n/locales/hu_HU/translation.json b/shared/i18n/locales/hu_HU/translation.json index 6f71c7bc2e..bd5f238763 100644 --- a/shared/i18n/locales/hu_HU/translation.json +++ b/shared/i18n/locales/hu_HU/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continue with Email", "Continue with {{ authProviderName }}": "Continue with {{ authProviderName }}", "Back to home": "Vissza a főoldalra", + "Open in Gmail": "Megnyitás a Gmailben", + "Open in Outlook": "Megnyitás az Outlookban", "The workspace could not be found": "The workspace could not be found", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "aldomain", diff --git a/shared/i18n/locales/id_ID/translation.json b/shared/i18n/locales/id_ID/translation.json index 6d0961d1a7..48253f82ea 100644 --- a/shared/i18n/locales/id_ID/translation.json +++ b/shared/i18n/locales/id_ID/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Lanjutkan dengan Surel", "Continue with {{ authProviderName }}": "Lanjutkan dengan {{ authProviderName }}", "Back to home": "Kembali ke beranda", + "Open in Gmail": "Buka di Gmail", + "Open in Outlook": "Buka di Outlook", "The workspace could not be found": "The workspace could not be found", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "subdomain", diff --git a/shared/i18n/locales/it_IT/translation.json b/shared/i18n/locales/it_IT/translation.json index 40fdb063de..e8b4146e9c 100644 --- a/shared/i18n/locales/it_IT/translation.json +++ b/shared/i18n/locales/it_IT/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continua con email", "Continue with {{ authProviderName }}": "Continua con {{ authProviderName }}", "Back to home": "Torna alla home", + "Open in Gmail": "Apri in Gmail", + "Open in Outlook": "Apri in Outlook", "The workspace could not be found": "Non è stato possibile trovare lo spazio di lavoro", "To continue, enter your workspace’s subdomain.": "Per continuare, inserisci il sottodominio del tuo spazio di lavoro.", "subdomain": "sottodominio", diff --git a/shared/i18n/locales/ja_JP/translation.json b/shared/i18n/locales/ja_JP/translation.json index 69bcb61e06..5fa2514578 100644 --- a/shared/i18n/locales/ja_JP/translation.json +++ b/shared/i18n/locales/ja_JP/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Eメール でログイン", "Continue with {{ authProviderName }}": "{{ authProviderName }} でログイン", "Back to home": "ホームへ戻る", + "Open in Gmail": "Gmailで開く", + "Open in Outlook": "Outlookで開く", "The workspace could not be found": "ワークスペースが見つかりませんでした", "To continue, enter your workspace’s subdomain.": "続行するには、ワークスペースのサブドメインを入力してください。", "subdomain": "サブドメイン", diff --git a/shared/i18n/locales/ko_KR/translation.json b/shared/i18n/locales/ko_KR/translation.json index e3d9f0f87c..272a522c17 100644 --- a/shared/i18n/locales/ko_KR/translation.json +++ b/shared/i18n/locales/ko_KR/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "이메일로 계속하기", "Continue with {{ authProviderName }}": "{{ authProviderName }} 사용하여 계속하기", "Back to home": "홈으로 돌아가기", + "Open in Gmail": "Gmail에서 열기", + "Open in Outlook": "Outlook에서 열기", "The workspace could not be found": "워크스페이스를 찾을 수 없습니다", "To continue, enter your workspace’s subdomain.": "계속하려면 워크스페이스의 서브도메인을 입력하세요.", "subdomain": "하위 도메인", diff --git a/shared/i18n/locales/nb_NO/translation.json b/shared/i18n/locales/nb_NO/translation.json index 1da025e5f0..f910f0eab3 100644 --- a/shared/i18n/locales/nb_NO/translation.json +++ b/shared/i18n/locales/nb_NO/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Fortsett med e-post", "Continue with {{ authProviderName }}": "Fortsett med {{ authProviderName }}", "Back to home": "Tilbake til hjem", + "Open in Gmail": "Åpne i Gmail", + "Open in Outlook": "Åpne i Outlook", "The workspace could not be found": "Arbeidsområdet ble ikke funnet", "To continue, enter your workspace’s subdomain.": "For å fortsette, angi arbeidsområdets underdomene.", "subdomain": "underdomene", diff --git a/shared/i18n/locales/nl_NL/translation.json b/shared/i18n/locales/nl_NL/translation.json index 3e5254997e..d21e67029d 100644 --- a/shared/i18n/locales/nl_NL/translation.json +++ b/shared/i18n/locales/nl_NL/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Verdergaan met e-mailadres", "Continue with {{ authProviderName }}": "Ga verder met {{ authProviderName }}", "Back to home": "Terug naar home", + "Open in Gmail": "Openen in Gmail", + "Open in Outlook": "Openen in Outlook", "The workspace could not be found": "De werkruimte kon niet worden gevonden", "To continue, enter your workspace’s subdomain.": "Voer het subdomein van je werkruimte in om door te gaan.", "subdomain": "subdomein", diff --git a/shared/i18n/locales/pl_PL/translation.json b/shared/i18n/locales/pl_PL/translation.json index 6cc73713cb..a54893a1d1 100644 --- a/shared/i18n/locales/pl_PL/translation.json +++ b/shared/i18n/locales/pl_PL/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Kontynuuj przy użyciu e-maila", "Continue with {{ authProviderName }}": "Kontynuuj za pomocą {{ authProviderName }}", "Back to home": "Wróć do strony głównej", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "Nie można odnaleźć projektu", "To continue, enter your workspace’s subdomain.": "Aby kontynuować, wpisz subdomenę swojego obszaru roboczego.", "subdomain": "subdomena", diff --git a/shared/i18n/locales/pt_BR/translation.json b/shared/i18n/locales/pt_BR/translation.json index 0f6a3a1d06..21323b1ff0 100644 --- a/shared/i18n/locales/pt_BR/translation.json +++ b/shared/i18n/locales/pt_BR/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continuar com E-mail", "Continue with {{ authProviderName }}": "Continuar com {{ authProviderName }}", "Back to home": "Voltar à página inicial", + "Open in Gmail": "Abrir no Gmail", + "Open in Outlook": "Abrir no Outlook", "The workspace could not be found": "Não foi possível encontrar o espaço de trabalho", "To continue, enter your workspace’s subdomain.": "Para continuar, insira o subdomínio do espaço de trabalho.", "subdomain": "subdomínio", diff --git a/shared/i18n/locales/pt_PT/translation.json b/shared/i18n/locales/pt_PT/translation.json index cc671f4407..7bafe96cd2 100644 --- a/shared/i18n/locales/pt_PT/translation.json +++ b/shared/i18n/locales/pt_PT/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continuar com Email", "Continue with {{ authProviderName }}": "Continuar com {{ authProviderName }}", "Back to home": "Voltar à vista inicial", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "Não foi possível encontrar a área de trabalho", "To continue, enter your workspace’s subdomain.": "Para continuar, insira o subdomínio da área de trabalho.", "subdomain": "subdomínio", diff --git a/shared/i18n/locales/sv_SE/translation.json b/shared/i18n/locales/sv_SE/translation.json index f89d644a9f..6ef03384cc 100644 --- a/shared/i18n/locales/sv_SE/translation.json +++ b/shared/i18n/locales/sv_SE/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Fortsätt med e-post", "Continue with {{ authProviderName }}": "Fortsätt med {{ authProviderName }}", "Back to home": "Tillbaka till startsidan", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "Arbetsytan kunde inte hittas", "To continue, enter your workspace’s subdomain.": "För att fortsätta, ange arbetsytans underdomän.", "subdomain": "subdomän", diff --git a/shared/i18n/locales/th_TH/translation.json b/shared/i18n/locales/th_TH/translation.json index c7ea4cfbd1..e9fa7fd03f 100644 --- a/shared/i18n/locales/th_TH/translation.json +++ b/shared/i18n/locales/th_TH/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Continue with Email", "Continue with {{ authProviderName }}": "Continue with {{ authProviderName }}", "Back to home": "Back to home", + "Open in Gmail": "เปิดใน Gmail", + "Open in Outlook": "เปิดใน Outlook", "The workspace could not be found": "The workspace could not be found", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "subdomain", diff --git a/shared/i18n/locales/tr_TR/translation.json b/shared/i18n/locales/tr_TR/translation.json index 7983d6c64d..0d4bf7043c 100644 --- a/shared/i18n/locales/tr_TR/translation.json +++ b/shared/i18n/locales/tr_TR/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "E-posta ile devam et", "Continue with {{ authProviderName }}": "{{ authProviderName }} ile devam et", "Back to home": "Anasayfaya geri dön", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "Çalışma alanı bulunamadı", "To continue, enter your workspace’s subdomain.": "Devam etmek için, çalışma alanınızın alt alan adını girin.", "subdomain": "alt alan adı", diff --git a/shared/i18n/locales/uk_UA/translation.json b/shared/i18n/locales/uk_UA/translation.json index a4bad9159d..0d9dcbc746 100644 --- a/shared/i18n/locales/uk_UA/translation.json +++ b/shared/i18n/locales/uk_UA/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Продовжити з електронною поштою", "Continue with {{ authProviderName }}": "Продовжити з {{ authProviderName }}", "Back to home": "Повернутися на головну", + "Open in Gmail": "Open in Gmail", + "Open in Outlook": "Open in Outlook", "The workspace could not be found": "Робоче середовище не знайдено", "To continue, enter your workspace’s subdomain.": "Щоб продовжити, введіть піддомен вашого робочого середовища.", "subdomain": "піддомен", diff --git a/shared/i18n/locales/vi_VN/translation.json b/shared/i18n/locales/vi_VN/translation.json index d243de372a..6dac73ad23 100644 --- a/shared/i18n/locales/vi_VN/translation.json +++ b/shared/i18n/locales/vi_VN/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "Tiếp tục với email", "Continue with {{ authProviderName }}": "Tiếp tục với {{ authProviderName }}", "Back to home": "Quay lại trang chủ", + "Open in Gmail": "Mở trong Gmail", + "Open in Outlook": "Mở trong Outlook", "The workspace could not be found": "Không tìm thấy không gian làm việc", "To continue, enter your workspace’s subdomain.": "To continue, enter your workspace’s subdomain.", "subdomain": "tên miền phụ", diff --git a/shared/i18n/locales/zh_CN/translation.json b/shared/i18n/locales/zh_CN/translation.json index f2b895077c..900ba838d1 100644 --- a/shared/i18n/locales/zh_CN/translation.json +++ b/shared/i18n/locales/zh_CN/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "使用电子邮箱继续", "Continue with {{ authProviderName }}": "使用 {{ authProviderName }} 继续", "Back to home": "回到主页", + "Open in Gmail": "在 Gmail 中打开", + "Open in Outlook": "在 Outlook 中打开", "The workspace could not be found": "找不到该工作区", "To continue, enter your workspace’s subdomain.": "要继续,请输入您的工作区的子域。", "subdomain": "子域", diff --git a/shared/i18n/locales/zh_TW/translation.json b/shared/i18n/locales/zh_TW/translation.json index dde5adaacd..aa5e6e0f79 100644 --- a/shared/i18n/locales/zh_TW/translation.json +++ b/shared/i18n/locales/zh_TW/translation.json @@ -1086,6 +1086,8 @@ "Continue with Email": "使用電子郵件以繼續", "Continue with {{ authProviderName }}": "使用 {{ authProviderName }} 以繼續", "Back to home": "回到首頁", + "Open in Gmail": "在 Gmail 中開啟", + "Open in Outlook": "在 Outlook 中開啟", "The workspace could not be found": "找不到工作區", "To continue, enter your workspace’s subdomain.": "若要繼續,請輸入您工作區的子網域。", "subdomain": "子網域", From 85deb8934b609eba450d6ab48c42160cbc4ab2b6 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 22:11:24 -0400 Subject: [PATCH 074/368] Fix GitLab webhook integration updates (#13764) * fix GitLab webhook integration updates * support shared GitLab webhook credentials --- .../github/server/tasks/GitHubWebhookTask.ts | 1 + plugins/gitlab/server/GitLabIssueProvider.ts | 48 +++++++++++++---- plugins/gitlab/server/api/gitlab.ts | 51 ++++++++++++++----- .../gitlab/server/tasks/GitLabWebhookTask.ts | 4 +- server/types.ts | 2 + server/utils/BaseIssueProvider.ts | 3 ++ 6 files changed, 84 insertions(+), 25 deletions(-) diff --git a/plugins/github/server/tasks/GitHubWebhookTask.ts b/plugins/github/server/tasks/GitHubWebhookTask.ts index 912413abae..d2bfc77fd5 100644 --- a/plugins/github/server/tasks/GitHubWebhookTask.ts +++ b/plugins/github/server/tasks/GitHubWebhookTask.ts @@ -21,6 +21,7 @@ export default class GitHubWebhookTask extends BaseTask { await plugin.value.handleWebhook({ headers, payload, + teamId: null, }); } } diff --git a/plugins/gitlab/server/GitLabIssueProvider.ts b/plugins/gitlab/server/GitLabIssueProvider.ts index a297947ed1..f5225eb626 100644 --- a/plugins/gitlab/server/GitLabIssueProvider.ts +++ b/plugins/gitlab/server/GitLabIssueProvider.ts @@ -79,9 +79,11 @@ export class GitLabIssueProvider extends BaseIssueProvider { async handleWebhook({ payload, headers, + teamId, }: { payload: Record; headers: Record; + teamId: string | null | undefined; }) { const hookId = headers["x-gitlab-webhook-uuid"] as string; const typedPayload = payload as GitLabWebhookPayload; @@ -94,35 +96,44 @@ export class GitLabIssueProvider extends BaseIssueProvider { return; } + if (teamId === undefined) { + Logger.warn(`Received GitLab webhook without authorization scope`); + return; + } + switch (eventName) { case "project_update": case "project_transfer": case "project_rename": - await this.updateProject(typedPayload); + await this.updateProject(typedPayload, teamId); break; case "repository_update": - await this.createProject(typedPayload); + await this.createProject(typedPayload, teamId); break; case "project_destroy": - await this.destroyProject(typedPayload); + await this.destroyProject(typedPayload, teamId); break; case "group_rename": case "user_rename": - await this.updateNamespace(typedPayload); + await this.updateNamespace(typedPayload, teamId); break; case "user_destroy": case "group_destroy": - await this.destroyNamespace(typedPayload); + await this.destroyNamespace(typedPayload, teamId); break; default: break; } } - private async updateNamespace(payload: GitLabWebhookPayload) { + private async updateNamespace( + payload: GitLabWebhookPayload, + teamId: string | null + ) { const name = payload.old_full_path ?? payload.old_username; const where = { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.literal(`"issueSources"::jsonb @> :jsonCondition`), }; const jsonCondition = JSON.stringify([{ owner: { name } }]); @@ -166,7 +177,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async destroyNamespace(payload: GitLabWebhookPayload) { + private async destroyNamespace( + payload: GitLabWebhookPayload, + teamId: string | null + ) { if (!payload.user_id && !payload.full_path) { Logger.warn( `GitLab namespace_destroy event without user_id or full_path` @@ -177,6 +191,7 @@ export class GitLabIssueProvider extends BaseIssueProvider { let replacements = {}; const whereCondition: WhereOptions = { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), ...(payload.user_id && { "settings.gitlab.installation.account.id": payload.user_id, }), @@ -224,11 +239,15 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async destroyProject(payload: GitLabWebhookPayload) { + private async destroyProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { await sequelize.transaction(async (transaction) => { const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.where( sequelize.literal(`"issueSources"::jsonb @> :projectJson`), Op.eq, @@ -260,7 +279,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async createProject(payload: GitLabWebhookPayload) { + private async createProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { const createEvent = payload.changes?.some((p: { before: string }) => /^0{40}$/.test(p.before) ); @@ -278,9 +300,11 @@ export class GitLabIssueProvider extends BaseIssueProvider { const integration = (await Integration.findOne({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), "settings.gitlab.installation.account.id": payload.user_id, }, lock: transaction.LOCK.UPDATE, + transaction, })) as Integration; if (!integration) { @@ -306,7 +330,10 @@ export class GitLabIssueProvider extends BaseIssueProvider { }); } - private async updateProject(payload: GitLabWebhookPayload) { + private async updateProject( + payload: GitLabWebhookPayload, + teamId: string | null + ) { if (!payload.name || !payload.path_with_namespace) { return; } @@ -317,6 +344,7 @@ export class GitLabIssueProvider extends BaseIssueProvider { const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, + ...(teamId ? { teamId } : {}), [Op.and]: sequelize.where( sequelize.literal(`"issueSources"::jsonb @> :projectJson`), Op.eq, diff --git a/plugins/gitlab/server/api/gitlab.ts b/plugins/gitlab/server/api/gitlab.ts index fb50b85b17..051ffe9f97 100644 --- a/plugins/gitlab/server/api/gitlab.ts +++ b/plugins/gitlab/server/api/gitlab.ts @@ -12,6 +12,7 @@ import validateWebhook from "@server/middlewares/validateWebhook"; import { IntegrationAuthentication, Integration } from "@server/models"; import { authorize } from "@server/policies"; import type { APIContext } from "@server/types"; +import { safeEqual } from "@server/utils/crypto"; import { generateOAuthStateNonce, verifyOAuthStateNonce, @@ -27,6 +28,11 @@ import * as T from "./schema"; const router = new Router(); +function getGitLabWebhookToken(ctx: APIContext): string | undefined { + const signatureHeader = ctx.request.headers["x-gitlab-token"]; + return Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader; +} + router.post( "gitlab.connect", auth(), @@ -307,7 +313,7 @@ router.post( // Self-hosted instances store their client secret in the database, // use the X-Gitlab-Instance header to find the matching integration. if (instanceUrl && instanceUrl !== "https://gitlab.com") { - const integration = await Integration.findOne({ + const integrations = await Integration.findAll({ where: { service: IntegrationService.GitLab, settings: { gitlab: { url: instanceUrl } }, @@ -320,29 +326,46 @@ router.post( }, ], }); - if (integration) { - return integration.authentication.clientSecret ?? undefined; + const token = getGitLabWebhookToken(ctx); + const teamIds = new Set(); + let clientSecret: string | undefined; + + for (const integration of integrations) { + const candidateSecret = integration.authentication.clientSecret; + + if (!candidateSecret || !safeEqual(candidateSecret, token)) { + continue; + } + + clientSecret = candidateSecret; + teamIds.add(integration.teamId); } + + if (clientSecret) { + ctx.state.webhookTeamIds = [...teamIds]; + } + + return clientSecret; } // Default GitLab.com instance uses the env secret return env.GITLAB_CLIENT_SECRET; }, - getSignatureFromHeader: (ctx) => { - const { headers } = ctx.request; - const signatureHeader = headers["x-gitlab-token"]; - return Array.isArray(signatureHeader) - ? signatureHeader[0] - : signatureHeader; - }, + getSignatureFromHeader: getGitLabWebhookToken, }), async (ctx: APIContext) => { const { headers, body } = ctx.request; + const teamIds: Array = ctx.state.webhookTeamIds ?? [null]; - await new GitLabWebhookTask().schedule({ - payload: body, - headers, - }); + await Promise.all( + teamIds.map((teamId) => + new GitLabWebhookTask().schedule({ + payload: body, + headers, + teamId, + }) + ) + ); ctx.status = 202; } diff --git a/plugins/gitlab/server/tasks/GitLabWebhookTask.ts b/plugins/gitlab/server/tasks/GitLabWebhookTask.ts index 1b54eca230..f90e257f83 100644 --- a/plugins/gitlab/server/tasks/GitLabWebhookTask.ts +++ b/plugins/gitlab/server/tasks/GitLabWebhookTask.ts @@ -5,10 +5,11 @@ import { Hook, PluginManager } from "@server/utils/PluginManager"; type Props = { headers: Record; payload: Record; + teamId: string | null; }; export default class GitLabWebhookTask extends BaseTask { - public async perform({ headers, payload }: Props): Promise { + public async perform({ headers, payload, teamId }: Props): Promise { const plugins = PluginManager.getHooks(Hook.IssueProvider); const plugin = plugins.find( (p) => p.value.service === IntegrationService.GitLab @@ -21,6 +22,7 @@ export default class GitLabWebhookTask extends BaseTask { await plugin.value.handleWebhook({ headers, payload, + teamId, }); } } diff --git a/server/types.ts b/server/types.ts index adad7772a5..43a9d4b141 100644 --- a/server/types.ts +++ b/server/types.ts @@ -74,6 +74,8 @@ export type AppState = { auth: Authentication | Record; transaction: Transaction; pagination: Pagination; + /** The teams authorized to receive an inbound webhook. */ + webhookTeamIds?: string[]; oauthClient?: OAuthClient; oauthIntent?: OAuthIntent; oauthState?: OAuthState; diff --git a/server/utils/BaseIssueProvider.ts b/server/utils/BaseIssueProvider.ts index 273c9b0cfd..49bdc7aaf2 100644 --- a/server/utils/BaseIssueProvider.ts +++ b/server/utils/BaseIssueProvider.ts @@ -19,8 +19,11 @@ export abstract class BaseIssueProvider { abstract handleWebhook({ payload, headers, + teamId, }: { payload: Record; headers: Record; + /** The authorized team, or null for a provider-wide webhook secret. */ + teamId: string | null; }): Promise; } From 35fe31e56f0f7e93484ab534a4a615d5b50d67ad Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 22:39:25 -0400 Subject: [PATCH 075/368] test: Use unique subdomains in test factories to prevent sporadic collisions (#13765) --- plugins/email/server/auth/email.test.ts | 21 +++++++----- server/commands/accountProvisioner.test.ts | 33 +++++++++++-------- server/commands/teamProvisioner.test.ts | 26 +++++++-------- server/routes/api/auth/auth.test.ts | 11 ++++--- server/routes/api/documents/documents.test.ts | 7 ++-- server/routes/oauth/oauth.test.ts | 8 ++--- server/test/factories.ts | 13 ++++++++ 7 files changed, 72 insertions(+), 47 deletions(-) diff --git a/plugins/email/server/auth/email.test.ts b/plugins/email/server/auth/email.test.ts index 5caf4dc7d0..fa92a48cc2 100644 --- a/plugins/email/server/auth/email.test.ts +++ b/plugins/email/server/auth/email.test.ts @@ -2,7 +2,12 @@ import { faker } from "@faker-js/faker"; import SigninEmail from "@server/emails/templates/SigninEmail"; import WelcomeEmail from "@server/emails/templates/WelcomeEmail"; import { AuthenticationProvider } from "@server/models"; -import { buildUser, buildGuestUser, buildTeam } from "@server/test/factories"; +import { + buildUser, + buildGuestUser, + buildTeam, + buildSubdomain, +} from "@server/test/factories"; import { getTestServer } from "@server/test/support"; const server = getTestServer(); @@ -29,7 +34,7 @@ describe("email", () => { it("should respond with redirect location when user is SSO enabled", async () => { const spy = vi.spyOn(WelcomeEmail.prototype, "schedule"); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const user = await buildUser({ teamId: team.id }); const res = await server.post("/auth/email", { @@ -49,7 +54,7 @@ describe("email", () => { it("should respond with success and email to be sent when user has SSO but disabled", async () => { const spy = vi.spyOn(SigninEmail.prototype, "schedule"); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const user = await buildUser({ teamId: team.id }); @@ -84,7 +89,7 @@ describe("email", () => { it("should not send email when user is on another subdomain but respond with success", async () => { const user = await buildUser(); const spy = vi.spyOn(WelcomeEmail.prototype, "schedule"); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ subdomain }); const res = await server.post("/auth/email", { body: { @@ -104,7 +109,7 @@ describe("email", () => { it("should respond with success and email to be sent when user is not SSO enabled", async () => { const spy = vi.spyOn(SigninEmail.prototype, "schedule"); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const user = await buildGuestUser({ teamId: team.id, @@ -126,7 +131,7 @@ describe("email", () => { it("should respond with success regardless of whether successful to prevent crawling email logins", async () => { const spy = vi.spyOn(WelcomeEmail.prototype, "schedule"); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ subdomain }); const res = await server.post("/auth/email", { body: { @@ -147,7 +152,7 @@ describe("email", () => { it("should default to current subdomain with SSO", async () => { const spy = vi.spyOn(SigninEmail.prototype, "schedule"); const email = "sso-user@example.org"; - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain, }); @@ -176,7 +181,7 @@ describe("email", () => { it("should default to current subdomain with guest email", async () => { const spy = vi.spyOn(SigninEmail.prototype, "schedule"); const email = "guest-user@example.org"; - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain, }); diff --git a/server/commands/accountProvisioner.test.ts b/server/commands/accountProvisioner.test.ts index dc135c850b..d39f4f21b9 100644 --- a/server/commands/accountProvisioner.test.ts +++ b/server/commands/accountProvisioner.test.ts @@ -4,7 +4,12 @@ import { errToString } from "@shared/utils/error"; import { Event, TeamDomain } from "@server/models"; import Collection from "@server/models/Collection"; import UserAuthentication from "@server/models/UserAuthentication"; -import { buildUser, buildTeam, buildAdmin } from "@server/test/factories"; +import { + buildUser, + buildTeam, + buildAdmin, + buildSubdomain, +} from "@server/test/factories"; import { setSelfHosted } from "@server/test/support"; import accountProvisioner from "./accountProvisioner"; import { createContext } from "@server/context"; @@ -27,7 +32,7 @@ describe("accountProvisioner", () => { team: { name: "New workspace", avatarUrl: faker.image.avatar(), - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: "google", @@ -67,7 +72,7 @@ describe("accountProvisioner", () => { team: { name: "New workspace", avatarUrl: faker.image.avatar(), - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: "google", @@ -112,7 +117,7 @@ describe("accountProvisioner", () => { team: { name: existingTeam.name, avatarUrl: existingTeam.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -134,7 +139,7 @@ describe("accountProvisioner", () => { }); it("should allow authentication by email matching", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const existingTeam = await buildTeam({ subdomain, }); @@ -177,7 +182,7 @@ describe("accountProvisioner", () => { }); it("should not allow authentication by email matching when email is unverified", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const existingTeam = await buildTeam({ subdomain, }); @@ -250,7 +255,7 @@ describe("accountProvisioner", () => { team: { name: existingTeam.name, avatarUrl: existingTeam.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -298,7 +303,7 @@ describe("accountProvisioner", () => { team: { name: existingTeam.name, avatarUrl: existingTeam.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -343,7 +348,7 @@ describe("accountProvisioner", () => { }, team: { avatarUrl: existingTeam.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -385,7 +390,7 @@ describe("accountProvisioner", () => { }, team: { avatarUrl: team.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -429,7 +434,7 @@ describe("accountProvisioner", () => { team: { name: team.name, avatarUrl: team.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: authenticationProvider.name, @@ -469,7 +474,7 @@ describe("accountProvisioner", () => { team: { name: "New workspace", avatarUrl: faker.image.avatar(), - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: "google", @@ -556,7 +561,7 @@ describe("accountProvisioner", () => { teamId: team.id, name: team.name, avatarUrl: team.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), }, authenticationProvider: { name: "google", @@ -588,7 +593,7 @@ describe("accountProvisioner", () => { teamId: team.id, name: team.name, avatarUrl: team.avatarUrl, - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), domain, }, authenticationProvider: { diff --git a/server/commands/teamProvisioner.test.ts b/server/commands/teamProvisioner.test.ts index 1505e7cc82..bf5b1b0430 100644 --- a/server/commands/teamProvisioner.test.ts +++ b/server/commands/teamProvisioner.test.ts @@ -1,6 +1,6 @@ import { faker } from "@faker-js/faker"; import TeamDomain from "@server/models/TeamDomain"; -import { buildTeam, buildUser } from "@server/test/factories"; +import { buildTeam, buildUser, buildSubdomain } from "@server/test/factories"; import { setSelfHosted } from "@server/test/support"; import teamProvisioner from "./teamProvisioner"; import { createContext } from "@server/context"; @@ -11,7 +11,7 @@ describe("teamProvisioner", () => { describe("hosted", () => { it("should create team and authentication provider", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const result = await teamProvisioner(ctx, { name: "Test team", subdomain, @@ -30,7 +30,7 @@ describe("teamProvisioner", () => { }); it("should set subdomain append if unavailable", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ subdomain, @@ -51,7 +51,7 @@ describe("teamProvisioner", () => { }); it("should increment subdomain append if unavailable", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ subdomain, }); @@ -72,7 +72,7 @@ describe("teamProvisioner", () => { }); it("should return existing team", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const authenticationProvider = { name: "google", providerId: `${subdomain}.com`, @@ -94,7 +94,7 @@ describe("teamProvisioner", () => { }); it("should return non-deleted team if multiple matches", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const authenticationProvider = { name: "google", providerId: `${subdomain}.com`, @@ -124,7 +124,7 @@ describe("teamProvisioner", () => { }); it("should error on mismatched team and authentication provider", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const exampleTeam = await buildTeam({ subdomain, @@ -138,7 +138,7 @@ describe("teamProvisioner", () => { let error; try { - const testSubdomain = faker.internet.domainWord(); + const testSubdomain = buildSubdomain(); await teamProvisioner(ctx, { teamId: exampleTeam.id, name: "name", @@ -161,7 +161,7 @@ describe("teamProvisioner", () => { beforeEach(setSelfHosted); it("should allow creating first team", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const { team, isNewTeam } = await teamProvisioner(ctx, { name: "Test team", subdomain, @@ -178,7 +178,7 @@ describe("teamProvisioner", () => { it("should not allow creating multiple teams in installation", async () => { const team = await buildTeam(); - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); let error; try { @@ -212,7 +212,7 @@ describe("teamProvisioner", () => { }); const result = await teamProvisioner(ctx, { name: "Updated name", - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), domain, teamId: existing.id, authenticationProvider: { @@ -247,7 +247,7 @@ describe("teamProvisioner", () => { try { await teamProvisioner(ctx, { name: "Updated name", - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), domain: otherDomain, teamId: existing.id, authenticationProvider: { @@ -267,7 +267,7 @@ describe("teamProvisioner", () => { name: "google", providerId: faker.internet.domainName(), }; - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const existing = await buildTeam({ subdomain, authenticationProviders: [authenticationProvider], diff --git a/server/routes/api/auth/auth.test.ts b/server/routes/api/auth/auth.test.ts index 46d616528c..267caeea1e 100644 --- a/server/routes/api/auth/auth.test.ts +++ b/server/routes/api/auth/auth.test.ts @@ -7,6 +7,7 @@ import { buildUser, buildTeam, buildUserPasskey, + buildSubdomain, } from "@server/test/factories"; import { getTestServer, setSelfHosted } from "@server/test/support"; @@ -130,7 +131,7 @@ describe("#auth.config", () => { }); it("should return available providers for team subdomain", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ guestSignin: false, subdomain, @@ -176,7 +177,7 @@ describe("#auth.config", () => { }); it("should return email provider for team when guest signin enabled", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ guestSignin: true, subdomain, @@ -200,7 +201,7 @@ describe("#auth.config", () => { }); it("should not return provider when disabled", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ guestSignin: false, subdomain, @@ -223,7 +224,7 @@ describe("#auth.config", () => { }); it("should not return passkeys provider when passkeysEnabled but no passkeys exist", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); await buildTeam({ guestSignin: false, passkeysEnabled: true, @@ -247,7 +248,7 @@ describe("#auth.config", () => { }); it("should return passkeys provider when passkeysEnabled and passkeys exist", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ guestSignin: false, passkeysEnabled: true, diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 5164d9f3fe..fa1b8d50a5 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -42,6 +42,7 @@ import { buildAdmin, buildTemplate, buildAttachment, + buildSubdomain, } from "@server/test/factories"; import { getTestServer, @@ -3173,7 +3174,7 @@ describe("#documents.search", () => { }); it("should return results using shareId", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const findableDocument = await buildDocument({ title: "search term", @@ -3974,7 +3975,7 @@ describe("#documents.search", () => { }); it("should scope results to a documentId filter combined with shareId", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const parent = await buildDocument({ title: "search term", @@ -4021,7 +4022,7 @@ describe("#documents.search", () => { }); it("should scope results to the legacy documentId param combined with shareId", async () => { - const subdomain = faker.internet.domainWord(); + const subdomain = buildSubdomain(); const team = await buildTeam({ subdomain }); const parent = await buildDocument({ title: "search term", diff --git a/server/routes/oauth/oauth.test.ts b/server/routes/oauth/oauth.test.ts index c3d73975a8..6e2a14c38c 100644 --- a/server/routes/oauth/oauth.test.ts +++ b/server/routes/oauth/oauth.test.ts @@ -1,4 +1,3 @@ -import { faker } from "@faker-js/faker"; import sharedEnv from "@shared/env"; import { TeamPreference } from "@shared/types"; import { OAuthClientValidation } from "@shared/validations"; @@ -9,6 +8,7 @@ import { buildOAuthClient, buildTeam, buildUser, + buildSubdomain, } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; @@ -19,7 +19,7 @@ describe("#oauth.register", () => { let subdomain: string; beforeEach(async () => { - subdomain = faker.internet.domainWord(); + subdomain = buildSubdomain(); team = await buildTeam({ subdomain }); }); @@ -272,7 +272,7 @@ describe("#oauth.register management (RFC 7592)", () => { let subdomain: string; beforeEach(async () => { - subdomain = faker.internet.domainWord(); + subdomain = buildSubdomain(); await buildTeam({ subdomain }); }); @@ -555,7 +555,7 @@ describe("GET /.well-known/oauth-protected-resource", () => { it("should return 404 when MCP is disabled", async () => { const team = await buildTeam({ - subdomain: faker.internet.domainWord(), + subdomain: buildSubdomain(), preferences: { [TeamPreference.MCP]: false }, }); diff --git a/server/test/factories.ts b/server/test/factories.ts index 098b707640..a4496fd9b8 100644 --- a/server/test/factories.ts +++ b/server/test/factories.ts @@ -148,6 +148,19 @@ export async function buildSubscription(overrides: Partial = {}) { }); } +/** + * Builds a random team subdomain that is unique across parallel test files. + * + * @returns a valid, unique subdomain string. + */ +export function buildSubdomain() { + return `${faker.word.noun().toLowerCase()}-${randomString({ + length: 8, + charset: "alphanumeric", + capitalization: "lowercase", + })}`; +} + export function buildTeam( overrides: Omit, "authenticationProviders"> & { authenticationProviders?: Partial[]; From 324b2b94ef86567ce25a5a81292f62fc6c2d7578 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 22:43:57 -0400 Subject: [PATCH 076/368] fix: Validate share id on public share endpoints (#13766) * fix: Validate share id on shares.sitemap, shares.info, and shares.subscribe Fixes OUTLINE-CLOUD-CWY * test: Add regression tests for invalid share ids on shares.info and shares.subscribe * test: Use an id that fails share slug validation and assert the message --- server/routes/api/documents/documents.test.ts | 2 +- server/routes/api/shares/schema.ts | 8 +-- server/routes/api/shares/shares.test.ts | 55 +++++++++++++++++++ server/utils/zod.ts | 4 +- 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index fa1b8d50a5..b62ec0912a 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -607,7 +607,7 @@ describe("#documents.info", () => { }); const body = await res.json(); expect(res.status).toEqual(400); - expect(body.message).toEqual("shareId: Invalid input"); + expect(body.message).toEqual("shareId: Must be a valid UUID or share slug"); }); }); diff --git a/server/routes/api/shares/schema.ts b/server/routes/api/shares/schema.ts index 8d88baf764..7c3afce136 100644 --- a/server/routes/api/shares/schema.ts +++ b/server/routes/api/shares/schema.ts @@ -5,13 +5,13 @@ import { UrlHelper } from "@shared/utils/UrlHelper"; import { ShareValidation } from "@shared/validations"; import { Share } from "@server/models"; import { ValidateURL } from "@server/validation"; -import { zodIdType } from "@server/utils/zod"; +import { zodIdType, zodShareIdType } from "@server/utils/zod"; import { BaseSchema } from "../schema"; export const SharesInfoSchema = BaseSchema.extend({ body: z .object({ - id: z.string().optional(), + id: zodShareIdType().optional(), collectionId: zodIdType().optional(), documentId: zodIdType().optional(), }) @@ -120,7 +120,7 @@ export type SharesRevokeReq = z.infer; export const SharesSitemapSchema = BaseSchema.extend({ query: z.object({ - id: z.string(), + id: zodShareIdType(), }), }); @@ -128,7 +128,7 @@ export type SharesSitemapReq = z.infer; export const SharesSubscribeSchema = BaseSchema.extend({ body: z.object({ - shareId: z.string(), + shareId: zodShareIdType(), documentId: z.uuid(), email: z.string().email(), }), diff --git a/server/routes/api/shares/shares.test.ts b/server/routes/api/shares/shares.test.ts index 96a9716f2c..480e70cc83 100644 --- a/server/routes/api/shares/shares.test.ts +++ b/server/routes/api/shares/shares.test.ts @@ -673,6 +673,18 @@ describe("#shares.info", () => { expect(body.message).toEqual("documentId: Must be a valid UUID or slug"); }); + it("should fail with status 400 bad request when id is invalid", async () => { + const user = await buildUser(); + const res = await server.post("/api/shares.info", user, { + body: { + id: "Foo!", + }, + }); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("id: Must be a valid UUID or share slug"); + }); + it("should not find share by documentId in private collection", async () => { const admin = await buildAdmin(); const collection = await buildCollection({ @@ -1397,7 +1409,50 @@ describe("#shares.revoke", () => { }); }); +describe("#shares.sitemap", () => { + it("should fail with status 400 bad request when id is empty", async () => { + const res = await server.get("/api/shares.sitemap?id="); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("id: Must be a valid UUID or share slug"); + }); + + it("should fail with status 400 bad request when id is invalid", async () => { + const res = await server.get("/api/shares.sitemap?id=Foo!"); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("id: Must be a valid UUID or share slug"); + }); + + it("should return a sitemap for an indexable share", async () => { + const share = await buildShare({ allowIndexing: true }); + const res = await server.get(`/api/shares.sitemap?id=${share.id}`); + expect(res.status).toEqual(200); + expect(res.headers.get("content-type")).toContain("application/xml"); + }); + + it("should return 404 when share does not allow indexing", async () => { + const share = await buildShare({ allowIndexing: false }); + const res = await server.get(`/api/shares.sitemap?id=${share.id}`); + expect(res.status).toEqual(404); + }); +}); + describe("#shares.subscribe", () => { + it("should fail with status 400 bad request when shareId is invalid", async () => { + const share = await buildShare(); + const res = await server.post("/api/shares.subscribe", { + body: { + shareId: "Foo!", + documentId: share.documentId!, + email: "subscriber@example.com", + }, + }); + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toEqual("shareId: Must be a valid UUID or share slug"); + }); + it("should create a subscription for a published share", async () => { const share = await buildShare(); const res = await server.post("/api/shares.subscribe", { diff --git a/server/utils/zod.ts b/server/utils/zod.ts index ae7e152462..39b52e8686 100644 --- a/server/utils/zod.ts +++ b/server/utils/zod.ts @@ -53,7 +53,9 @@ export const zodEmojiType = () => * @returns a zod schema for share identifiers. */ export const zodShareIdType = () => - z.union([z.uuid(), z.string().regex(UrlHelper.SHARE_URL_SLUG_REGEX)]); + z.union([z.uuid(), z.string().regex(UrlHelper.SHARE_URL_SLUG_REGEX)], { + error: "Must be a valid UUID or share slug", + }); /** * Returns a zod schema that validates an IANA timezone name. From 9eb49d76b7f277c2182d8f159ab2c3d848d9e2c5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 23:19:19 -0400 Subject: [PATCH 077/368] fix: Selection lands after a newly inserted notice instead of inside it (#13768) --- app/editor/components/ComponentView.tsx | 32 +++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/app/editor/components/ComponentView.tsx b/app/editor/components/ComponentView.tsx index e55a68fd15..944c5a00bc 100644 --- a/app/editor/components/ComponentView.tsx +++ b/app/editor/components/ComponentView.tsx @@ -164,12 +164,15 @@ export default class ComponentView { */ handleContentRef = (element: HTMLElement | null) => { if ( - element && - this.contentDOM && - element !== this.contentDOM.parentElement + !element || + !this.contentDOM || + element === this.contentDOM.parentElement ) { - element.appendChild(this.contentDOM); + return; } + + element.appendChild(this.contentDOM); + this.syncSelection(); }; stopEvent(event: Event) { @@ -211,4 +214,25 @@ export default class ComponentView { contentRef: this.handleContentRef, } as ComponentProps; } + + /** + * Re-apply the editor selection to the DOM once the content is mounted. React + * mounts the content after ProseMirror has already synced the selection, so a + * selection inside a freshly created node lands on a detached element and the + * browser leaves the caret after the node instead. + */ + private syncSelection() { + const { view } = this; + if (!this.dom || !view.hasFocus()) { + return; + } + + const pos = this.getPos(); + const { from, to } = view.state.selection; + if (from <= pos || to >= pos + this.node.nodeSize) { + return; + } + + view.focus(); + } } From 1a0c7f47c8470aa972262558bc7409795e0ecc6b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 16 Sep 2026 23:48:02 -0400 Subject: [PATCH 078/368] fix: Backspace inside a notice orphans the emptied paragraph in Chrome (#13770) --- app/editor/components/ComponentView.tsx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/editor/components/ComponentView.tsx b/app/editor/components/ComponentView.tsx index 944c5a00bc..fa0357a502 100644 --- a/app/editor/components/ComponentView.tsx +++ b/app/editor/components/ComponentView.tsx @@ -22,6 +22,9 @@ type ComponentViewConstructor = { }; export default class ComponentView { + /** The class name applied to the editable content element of every node view. */ + static readonly contentClassName = "component-content"; + /** The React component to render. */ component: FunctionComponent; /** The editor instance. */ @@ -76,6 +79,10 @@ export default class ComponentView { this.contentDOM = document.createElement( node.type.spec.inline ? "span" : "div" ); + // Chrome unwraps an attribute-less div that is the only child of its + // parent when a deletion empties a block inside it, which orphans the + // content from ProseMirror. Any attribute prevents this. + this.contentDOM.className = ComponentView.contentClassName; } this.className = `component-${node.type.name}`; From 06a62f096c72ed437674ed743e2fd2013242927d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 07:29:42 -0400 Subject: [PATCH 079/368] fix: Hide scrollbars on the suggestion menu (#13779) --- app/editor/components/SuggestionsMenu.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/editor/components/SuggestionsMenu.tsx b/app/editor/components/SuggestionsMenu.tsx index 1547ca4d8f..23c93ba620 100644 --- a/app/editor/components/SuggestionsMenu.tsx +++ b/app/editor/components/SuggestionsMenu.tsx @@ -13,7 +13,7 @@ import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators"; import { findParentNode } from "@shared/editor/queries/findParentNode"; import type { MenuItem } from "@shared/editor/types"; import { toastNotice } from "~/editor/toastNotice"; -import { s } from "@shared/styles"; +import { hideScrollbars, s } from "@shared/styles"; import { getEventFiles } from "@shared/utils/files"; import { AttachmentValidation } from "@shared/validations"; import { @@ -1269,12 +1269,15 @@ const bouncyFadeIn = keyframes` `; const BouncyPopoverContent = styled(PopoverContent)` + ${hideScrollbars()} + &[data-state="open"] { animation: ${bouncyFadeIn} 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275); } `; const SubmenuPopoverContent = styled(PopoverContent)` + ${hideScrollbars()} max-height: min(324px, var(--radix-popover-content-available-height)); `; From d195e2965111a4447ba75565ab7ac1f60a0440c1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 07:31:06 -0400 Subject: [PATCH 080/368] feat: Show file extensions and print shortcut in the export menu (#13778) --- app/actions/definitions/documents.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index c411207a5e..fee4f951fb 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -719,10 +719,20 @@ export const shareDocument = createAction({ }, }); +/** + * Shows a file extension in the shortcut slot of menu items only, the command + * bar would otherwise register it as a key sequence. + */ +const fileExtensionHint = + (extension: string) => + ({ isMenu }: ActionContext) => + isMenu ? [extension] : undefined; + export const downloadDocumentAsMarkdown = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")), analyticsName: "Download document as Markdown", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".md"), keywords: "md markdown export download", icon: , iconInContextMenu: false, @@ -744,6 +754,7 @@ export const downloadDocumentAsHTML = createAction({ name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")), analyticsName: "Download document as HTML", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".html"), keywords: "xml html export download", icon: , iconInContextMenu: false, @@ -766,6 +777,7 @@ export const downloadDocumentAsTextBundle = createAction({ isMenu ? t("TextBundle") : t("Download as TextBundle"), analyticsName: "Download document as TextBundle", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".textpack"), keywords: "textbundle textpack bear ulysses export download", icon: , iconInContextMenu: false, @@ -787,6 +799,7 @@ export const downloadDocumentAsPDF = createAction({ name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")), analyticsName: "Download document as PDF", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".pdf"), keywords: "pdf export download", icon: , iconInContextMenu: false, @@ -1150,6 +1163,7 @@ export const printDocument = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Print") : t("Print document")), analyticsName: "Print document", section: ActiveDocumentSection, + shortcut: ["Meta+P"], icon: , iconInContextMenu: false, visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print), From 29287f6e1e1e5539f8ff1fbedd78e3a83a92f820 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 07:39:00 -0400 Subject: [PATCH 081/368] fix: Table of contents closes immediately when another tab's header is under 700px (#13781) --- app/scenes/Document/components/Document.tsx | 7 ++++++- app/scenes/Document/components/Header.tsx | 6 ------ app/scenes/Document/components/SharedHeader.tsx | 6 ------ app/stores/UiStore.ts | 4 ++-- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index 9e9f124d54..cce30ff169 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -25,6 +25,7 @@ import { MeasuredContainer } from "~/components/MeasuredContainer"; import type { Editor as TEditor } from "~/editor"; import type { Properties } from "~/types"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; +import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; import isTextInput from "~/utils/isTextInput"; import { client } from "~/utils/ApiClient"; @@ -82,6 +83,7 @@ function DocumentScene({ children, }: Props) { const { auth, ui, dialogs } = useStores(); + const isMobile = useMobile(); const { t } = useTranslation(); const history = useHistory(); const location = useLocation(); @@ -304,8 +306,11 @@ function DocumentScene({ tocPosition ?? ((team?.getPreference(TeamPreference.TocPosition) as TOCPosition) || TOCPosition.Left); + // Hide on mobile at render time so the stored preference is kept intact. const showContents = - tocPos && (isShare ? ui.tocVisible !== false : ui.tocVisible === true); + tocPos && + !isMobile && + (isShare ? ui.tocVisible !== false : ui.tocVisible === true); const tocOffset = tocPos === TOCPosition.Left ? EditorStyleHelper.tocWidth / -2 diff --git a/app/scenes/Document/components/Header.tsx b/app/scenes/Document/components/Header.tsx index 76bd87d012..df64165613 100644 --- a/app/scenes/Document/components/Header.tsx +++ b/app/scenes/Document/components/Header.tsx @@ -111,12 +111,6 @@ function DocumentHeader({ const canToggleEmbeds = team?.documentEmbeds; const showContents = ui.tocVisible === true; - useEffect(() => { - if (isMobile && showContents) { - ui.set({ tocVisible: false }); - } - }, [isMobile, showContents, ui]); - const toc = ( { - if (isMobile && showContents) { - ui.set({ tocVisible: false }); - } - }, [isMobile, showContents, ui]); - useKeyDown( (event) => event.ctrlKey && event.altKey && event.code === "KeyH", handleToggle, diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index d2e164add1..fb3c3f4b57 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -211,11 +211,11 @@ class UiStore { return; } - // Note: we do not sync all properties here, sidebar widths cause fighting between windows + // Note: we do not sync all properties here, sidebar widths and TOC + // visibility cause fighting between windows this.theme = newData.theme; this.languagePromptDismissed = newData.languagePromptDismissed; this.sidebarCollapsed = !!newData.sidebarCollapsed; - this.tocVisible = newData.tocVisible; } }); From 9f7069d083da986142c11ce696db806d8ec1bc99 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 07:59:27 -0400 Subject: [PATCH 082/368] fix: Reduce gap between archived/deleted banner and document title (#13780) * fix: Reduce gap between archived/deleted banner and document title * refactor: Move notice spacing rule to the editor container --- app/scenes/Document/components/Document.tsx | 7 ++++++- app/scenes/Document/components/DocumentTitle.tsx | 4 ++-- app/scenes/Document/components/Notices.tsx | 15 +++++++++++---- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index cce30ff169..976811c252 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -36,7 +36,7 @@ import Container from "./Container"; import Contents from "./Contents"; import Editor from "./Editor"; import Header from "./Header"; -import Notices from "./Notices"; +import Notices, { DocumentNotice } from "./Notices"; import References from "./References"; import RevisionViewer from "./RevisionViewer"; import SharedHeader from "./SharedHeader"; @@ -546,6 +546,11 @@ const EditorContainer = styled.div` // Adds space to the gutter to make room for icon & heading annotations padding: 0 32px; + // A notice above the editor already provides the space from the header + &:has(> ${DocumentNotice}) { + --document-title-margin-top: 0; + } + ${breakpoint("tablet")` padding: 0 44px; grid-row: 1; diff --git a/app/scenes/Document/components/DocumentTitle.tsx b/app/scenes/Document/components/DocumentTitle.tsx index e8a431401f..afbaae1255 100644 --- a/app/scenes/Document/components/DocumentTitle.tsx +++ b/app/scenes/Document/components/DocumentTitle.tsx @@ -292,7 +292,7 @@ const StyledIconPicker = styled(IconPicker)` const Title = styled(ContentEditable)` position: relative; line-height: ${lineHeight}; - margin-top: 8vh; + margin-top: var(--document-title-margin-top, 8vh); margin-bottom: 0.5em; font-size: ${fontSize}; font-weight: 600; @@ -327,7 +327,7 @@ const Title = styled(ContentEditable)` } ${breakpoint("tablet")` - margin-top: 6vh; + margin-top: var(--document-title-margin-top, 6vh); margin-left: 0; &:hover { diff --git a/app/scenes/Document/components/Notices.tsx b/app/scenes/Document/components/Notices.tsx index e6db1e735a..7cb17a38d4 100644 --- a/app/scenes/Document/components/Notices.tsx +++ b/app/scenes/Document/components/Notices.tsx @@ -1,11 +1,18 @@ import { differenceInDays } from "date-fns"; import { TrashIcon, ArchiveIcon } from "outline-icons"; import { Trans, useTranslation } from "react-i18next"; +import styled from "styled-components"; import type Document from "~/models/Document"; import ErrorBoundary from "~/components/ErrorBoundary"; import Notice from "~/components/Notice"; import Time from "~/components/Time"; +/** + * A notice shown above the document title, for example when the document is + * archived or deleted. + */ +export const DocumentNotice = styled(Notice)``; + type Props = { document: Document; readOnly: boolean; @@ -51,16 +58,16 @@ export default function Notices({ document }: Props) { return ( {document.archivedAt && !document.deletedAt && ( - }> + }> {t("Archived by {{userName}}", { userName: document.updatedBy?.name ?? t("Unknown"), })}   + )} {document.deletedAt && ( - } description={permanentlyDeletedDescription()} > @@ -69,7 +76,7 @@ export default function Notices({ document }: Props) { })}   + )} ); From da6cbc123e97d3c359a9aebf516db574520d65ed Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 08:04:21 -0400 Subject: [PATCH 083/368] feat: Multi-select controls on the child document list (#13782) * feat: Multi-select controls on the child document list * Remove redundant selectable gate --- .../Document/components/ReferenceListItem.tsx | 136 ++++++++++++++++-- app/scenes/Document/components/References.tsx | 58 +++++--- 2 files changed, 166 insertions(+), 28 deletions(-) diff --git a/app/scenes/Document/components/ReferenceListItem.tsx b/app/scenes/Document/components/ReferenceListItem.tsx index d6c252008a..17259c84cc 100644 --- a/app/scenes/Document/components/ReferenceListItem.tsx +++ b/app/scenes/Document/components/ReferenceListItem.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { DocumentIcon, PlusIcon } from "outline-icons"; +import { CheckmarkIcon, DocumentIcon, PlusIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled, { css } from "styled-components"; @@ -14,6 +14,7 @@ import useShare from "@shared/hooks/useShare"; import Document from "~/models/Document"; import Flex from "~/components/Flex"; import { ContextMenu } from "~/components/Menu/ContextMenu"; +import { useModelSelection } from "~/components/ModelSelectionContext"; import NudeButton from "~/components/NudeButton"; import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext"; import { ActionContextProvider } from "~/hooks/useActionContext"; @@ -22,8 +23,9 @@ import DocumentMenu from "~/menus/DocumentMenu"; import { newNestedDocumentPath, sharedModelPath } from "~/utils/routeHelpers"; import useBoolean from "~/hooks/useBoolean"; import useClickIntent from "~/hooks/useClickIntent"; +import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; -import { useCallback } from "react"; +import { useCallback, useRef } from "react"; import useCurrentUser from "~/hooks/useCurrentUser"; type Props = { @@ -88,7 +90,53 @@ const Actions = styled(EventBoundary)` `}; `; -const DocumentLink = styled(Link)<{ $menuOpen?: boolean }>` +const IconWrapper = styled.span` + position: relative; + flex-shrink: 0; + display: flex; + width: 24px; + height: 24px; +`; + +const DocumentIconWrapper = styled.span<{ $dimmed: boolean }>` + display: flex; + transition: opacity 100ms ease; + opacity: ${(props) => (props.$dimmed ? 0 : 1)}; +`; + +const SelectButton = styled(NudeButton)<{ + $checked: boolean; + $visible: boolean; +}>` + position: absolute; + top: 3px; + left: 3px; + width: 18px; + height: 18px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 4px; + border: 2px solid ${s("inputBorder")}; + color: ${(props) => props.theme.accentText}; + opacity: ${(props) => (props.$visible ? 1 : 0)}; + transition: + opacity 100ms ease, + background 100ms ease, + border-color 100ms ease; + + ${(props) => + props.$checked && + css` + background: ${props.theme.accent}; + border-color: ${props.theme.accent}; + `} +`; + +const DocumentLink = styled(Link)<{ + $menuOpen?: boolean; + $selectable?: boolean; +}>` display: flex; align-items: center; margin: 2px -8px; @@ -115,6 +163,27 @@ const DocumentLink = styled(Link)<{ $menuOpen?: boolean }>` } } + /* Revealing the checkbox is a hover affordance only – on touch devices the + equivalent states (active, focus) are triggered by tapping the item to + navigate. There, the checkbox appears once a selection is underway. */ + @media (hover: hover) { + &:hover, + &:focus, + &:focus-within { + ${(props) => + props.$selectable && + css` + ${SelectButton} { + opacity: 1; + } + + ${DocumentIconWrapper} { + opacity: 0; + } + `} + } + } + ${(props) => props.$menuOpen && css` @@ -154,9 +223,12 @@ function ReferenceListItem({ sidebarContext, ...rest }: Props) { + const { t } = useTranslation(); const { documents } = useStores(); const { shareId } = useShare(); const user = useCurrentUser({ rejectOnEmpty: false }); + const selection = useModelSelection(); + const iconRef = useRef(null); const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean(); const prefetchDocument = useCallback(async () => { await documents.prefetchDocument(document.id); @@ -170,11 +242,43 @@ function ReferenceListItem({ const initial = title.charAt(0).toUpperCase(); const showContextMenu = document instanceof Document && !!user; + // Multi-select is only offered for documents the user can update. + const can = usePolicy(document.id); + const selectable = !!selection && !!can.update; + const isSelected = selection?.isSelected(document.id) ?? false; + const isSelecting = + selectable && ((selection?.isActive ?? false) || isSelected); + + const inSelectArea = (event: React.MouseEvent) => + selectable && !!iconRef.current?.contains(event.target as Node); + + // Handled on the link so preventDefault reliably suppresses navigation. + const handleLinkClick = (event: React.MouseEvent) => { + if (selection && inSelectArea(event)) { + event.preventDefault(); + if (event.shiftKey) { + selection.selectRange(document.id); + } else { + selection.toggle(document.id); + } + } + }; + + // Suppress the browser's text selection when shift-clicking to select a range. + const handleLinkMouseDown = (event: React.MouseEvent) => { + if (event.shiftKey && inSelectArea(event)) { + event.preventDefault(); + } + }; + const link = ( - {icon ? ( - - ) : ( - - )} + + {selectable && ( + + {isSelected && } + + )} + + {icon ? ( + + ) : ( + + )} + + {isEmoji ? title.replace(icon!, "") : title} {showContextMenu && ( diff --git a/app/scenes/Document/components/References.tsx b/app/scenes/Document/components/References.tsx index 74dc3458c0..f55e4bc185 100644 --- a/app/scenes/Document/components/References.tsx +++ b/app/scenes/Document/components/References.tsx @@ -3,7 +3,9 @@ import { useEffect, useRef, Fragment, useMemo, useState } from "react"; import { Trans } from "react-i18next"; import styled from "styled-components"; import type Document from "~/models/Document"; +import DocumentSelectionToolbar from "~/components/DocumentSelectionToolbar"; import Fade from "~/components/Fade"; +import { ModelSelectionProvider } from "~/components/ModelSelectionContext"; import { determineSidebarContext } from "~/components/Sidebar/components/SidebarContext"; import { Tab, Tabs } from "~/components/Tabs"; import useCurrentUser from "~/hooks/useCurrentUser"; @@ -24,7 +26,7 @@ type Props = { type TabType = "children" | "backlinks"; function References({ document }: Props) { - const { documents } = useStores(); + const { documents, policies } = useStores(); const user = useCurrentUser({ rejectOnEmpty: false }); const locationSidebarContext = useLocationSidebarContext(); const { sharedTree, isShare } = useShare(); @@ -43,6 +45,17 @@ function References({ document }: Props) { const children = useChildren(document, sharedTree); const backlinks = useBacklinks(document, sharedTree); + // Only updatable children are selectable, so that is what feeds range and + // select-all; per-item checkboxes are gated on the same ability. + const selectableChildIds = useMemo( + () => + isShare + ? [] + : children + .filter((node) => policies.abilities(node.id).update) + .map((node) => node.id), + [isShare, children, policies] + ); const can = usePolicy(document); const showBacklinks = !!backlinks.length; const showChildDocuments = !!children.length; @@ -107,27 +120,32 @@ function References({ document }: Props) { )} {showChildDocuments && ( - - {children.map((node) => { - // If we have the document in the store already then use it to get the extra - // contextual info, otherwise the collection node will do (only has title and id) - const document = documents.get(node.id); - return ( - } + > + + {children.map((node) => { + // If we have the document in the store already then use it to get the extra + // contextual info, otherwise the collection node will do (only has title and id) + const document = documents.get(node.id); + return ( + + ); + })} + {showNewChildDocument && ( + - ); - })} - {showNewChildDocument && ( - - )} - + )} + + )} From cc15b088ecc9c162a8ed0831904fd594650d7fe1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 19:36:47 -0400 Subject: [PATCH 084/368] feat: Show a toast with actions when a file download completes in the desktop app (#13769) * Show toast with actions when a file download completes In the desktop app a toast is now displayed when a file finishes downloading, with the option to open the file or reveal it in the file manager of the operating system. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Kat47mueTm3CUZSbDVfBas * Guard download bridge calls for older desktop apps Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Kat47mueTm3CUZSbDVfBas * Change protocol in dev for easier testing * Use standard buttons stacked below the file name in download toast --------- Co-authored-by: Claude --- app/components/DesktopEventHandler.tsx | 3 + app/components/DownloadToast.tsx | 71 ++++++++++++++++++++++ app/scenes/DesktopRedirect.tsx | 3 +- app/typings/window.d.ts | 21 +++++++ app/utils/Desktop.ts | 6 ++ app/utils/routeHelpers.ts | 5 +- server/middlewares/passport.ts | 6 +- shared/i18n/locales/en_US/translation.json | 6 +- 8 files changed, 116 insertions(+), 5 deletions(-) create mode 100644 app/components/DownloadToast.tsx diff --git a/app/components/DesktopEventHandler.tsx b/app/components/DesktopEventHandler.tsx index 28ca23249c..0243f014b5 100644 --- a/app/components/DesktopEventHandler.tsx +++ b/app/components/DesktopEventHandler.tsx @@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; +import { showDownloadToast } from "~/components/DownloadToast"; import { useDesktopTitlebar } from "~/hooks/useDesktopTitlebar"; import useStores from "~/hooks/useStores"; import Desktop from "~/utils/Desktop"; @@ -41,6 +42,8 @@ export default function DesktopEventHandler() { }); }); + Desktop.bridge?.onDownloadComplete?.(showDownloadToast); + Desktop.bridge?.focus(() => { window.document.body.classList.remove("backgrounded"); }); diff --git a/app/components/DownloadToast.tsx b/app/components/DownloadToast.tsx new file mode 100644 index 0000000000..d13cf9b5d3 --- /dev/null +++ b/app/components/DownloadToast.tsx @@ -0,0 +1,71 @@ +import { t } from "i18next"; +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import Desktop from "~/utils/Desktop"; + +type DownloadedFile = { + /** The user facing name of the downloaded file. */ + fileName: string; + /** The absolute path the file was saved to. */ + filePath: string; +}; + +/** + * Displays a toast notifying that a file finished downloading, with the file + * name and actions to open the file or reveal it in the file manager. Desktop + * app only. + * + * @param file the name and path of the downloaded file. + */ +export function showDownloadToast(file: DownloadedFile) { + const toastId = `download-${file.filePath}`; + + toast.message(t("Download complete"), { + id: toastId, + description: , + }); +} + +function DownloadToastDescription({ + file, + toastId, +}: { + file: DownloadedFile; + toastId: string; +}) { + const { t } = useTranslation(); + + const handleOpen = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.openDownload?.(file.filePath); + }, [file.filePath, toastId]); + + const handleShowInFolder = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.showDownloadInFolder?.(file.filePath); + }, [file.filePath, toastId]); + + // The name given to the file manager differs by operating system. + const showInFolderLabel = Desktop.isMacApp() + ? t("Show in Finder") + : Desktop.isWindowsApp() + ? t("Show in Explorer") + : t("Show in folder"); + + return ( + + {file.fileName} + + + + + + ); +} diff --git a/app/scenes/DesktopRedirect.tsx b/app/scenes/DesktopRedirect.tsx index 9cdc2b6c5a..5d681ca3f8 100644 --- a/app/scenes/DesktopRedirect.tsx +++ b/app/scenes/DesktopRedirect.tsx @@ -2,6 +2,7 @@ import { useEffect } from "react"; import styled from "styled-components"; import Flex from "~/components/Flex"; import useQuery from "~/hooks/useQuery"; +import Desktop from "~/utils/Desktop"; import { SigningIn } from "./Login/components/SigningIn"; const DesktopRedirect = () => { @@ -11,7 +12,7 @@ const DesktopRedirect = () => { useEffect(() => { if (token) { window.open( - `outline://${window.location.host}/auth/redirect?token=${token}`, + `${Desktop.protocol}://${window.location.host}/auth/redirect?token=${token}`, "_self" ); diff --git a/app/typings/window.d.ts b/app/typings/window.d.ts index a14e960737..3045f5c3fd 100644 --- a/app/typings/window.d.ts +++ b/app/typings/window.d.ts @@ -142,6 +142,27 @@ declare global { */ onReplaceInPage: (callback: () => void) => void; + /** + * Registers a callback to be called when a file download completes. The + * callback receives the name and saved path of the file, which can be + * passed back to `openDownload` or `showDownloadInFolder`. + */ + onDownloadComplete: ( + callback: (file: { fileName: string; filePath: string }) => void + ) => void; + + /** + * Opens a downloaded file with the default application for its type. + * Resolves with whether the file was opened. + */ + openDownload: (filePath: string) => Promise; + + /** + * Reveals a downloaded file in the file manager of the operating system. + * Resolves with whether the file was revealed. + */ + showDownloadInFolder: (filePath: string) => Promise; + /** * Get whether the app is configured to launch at login. */ diff --git a/app/utils/Desktop.ts b/app/utils/Desktop.ts index 462a3607c1..e5b05935b6 100644 --- a/app/utils/Desktop.ts +++ b/app/utils/Desktop.ts @@ -1,10 +1,16 @@ import { isMac, isWindows } from "@shared/utils/browser"; +import env from "~/env"; /** * Helper methods for detecting and interacting with the desktop application * wrapper. */ export default class Desktop { + /** + * The custom protocol scheme registered by the desktop application. + */ + static protocol = env.isDevelopment ? "outline-dev" : "outline"; + /** * Returns true if the client has inset/floating window controls. */ diff --git a/app/utils/routeHelpers.ts b/app/utils/routeHelpers.ts index 3a7519eaa9..9f5f19328c 100644 --- a/app/utils/routeHelpers.ts +++ b/app/utils/routeHelpers.ts @@ -3,6 +3,7 @@ import type Collection from "~/models/Collection"; import type Comment from "~/models/Comment"; import type Document from "~/models/Document"; import env from "~/env"; +import Desktop from "~/utils/Desktop"; /** * Returns the path to the home screen. @@ -320,14 +321,14 @@ export function urlify( } /** - * Converts a path to a desktop app URL using the outline:// protocol. + * Converts a path to a desktop app URL using the desktop app's custom protocol. * * @param path The path to convert. * @param origin Optional origin to use instead of `window.location.origin`. * @returns The desktop app URL. */ export function desktopify(path: string, origin?: string): string { - return urlify(path, origin).replace(/^https?:\/\//, "outline://"); + return urlify(path, origin).replace(/^https?:\/\//, `${Desktop.protocol}://`); } /** Route matcher for a collection slug. */ diff --git a/server/middlewares/passport.ts b/server/middlewares/passport.ts index 470b9955bb..667077d620 100644 --- a/server/middlewares/passport.ts +++ b/server/middlewares/passport.ts @@ -92,7 +92,11 @@ export default function createMiddleware(providerName: string) { // form a URL object with the err.redirectPath and replace the host const reqProtocol = - oauthState?.client === Client.Desktop ? "outline" : ctx.protocol; + oauthState?.client === Client.Desktop + ? env.isDevelopment + ? "outline-dev" + : "outline" + : ctx.protocol; const requestHost = await getValidatedHost( oauthState?.host ?? ctx.hostname diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index d0ce57beea..f1c60e19c6 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -383,6 +383,11 @@ "Currently editing": "Currently editing", "Currently viewing": "Currently viewing", "Viewed {{ timeAgo }}": "Viewed {{ timeAgo }}", + "Download complete": "Download complete", + "Show in Finder": "Show in Finder", + "Show in Explorer": "Show in Explorer", + "Show in folder": "Show in folder", + "Open": "Open", "Uploading… {{ progress }}%": "Uploading… {{ progress }}%", "File type not supported. Please use PNG, JPG, GIF, or WebP.": "File type not supported. Please use PNG, JPG, GIF, or WebP.", "File size too large. Maximum size is {{ size }}.": "File size too large. Maximum size is {{ size }}.", @@ -1894,7 +1899,6 @@ "Click to copy": "Click to copy", "Empty diagram": "Empty diagram", "Double click to edit": "Double click to edit", - "Open": "Open", "Loading": "Loading", "Error loading data": "Error loading data", "Show {{ count }} completed": "Show {{ count }} completed", From d281e991d95c636b709ef6e19125150bcec02d1c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 20:45:01 -0400 Subject: [PATCH 085/368] fix: Sidebar selection changes when a Prompt blocks navigation (#13785) --- app/components/Sidebar/components/NavLink.tsx | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/components/Sidebar/components/NavLink.tsx b/app/components/Sidebar/components/NavLink.tsx index a7749de327..b47b80382c 100644 --- a/app/components/Sidebar/components/NavLink.tsx +++ b/app/components/Sidebar/components/NavLink.tsx @@ -188,7 +188,16 @@ const NavLink = observer(function NavLink({ // Wait a frame until following the link requestAnimationFrame(() => { - requestAnimationFrame(navigateTo); + requestAnimationFrame(() => { + navigateTo(); + + // A may block the navigation, in which case the location + // is unchanged and the pending target must be released. + const value = pendingNavigation.get(); + if (value && value.from === history.location) { + setPendingNavigation(null); + } + }); element.blur(); }); } From fe409306f4ffad4c47a06e7f9b626e5c8fdf501d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 17 Sep 2026 20:54:06 -0400 Subject: [PATCH 086/368] fix: Warn before leaving a document with unsynced edits (#13738) * fix: Warn before leaving a document with unsynced edits * refactor: Move unsynced change tracking into CollaborationProvider * refactor: Move collaboration event types next to CollaborationProvider * fix: Pending changes stuck after the collaboration connection is restored * chore: Log collaboration sync state changes in development * fix: Report lost local persistence in the leave prompt * fix: Stop local persistence when the initial read fails * fix: Stop local persistence when a write aborts * Remove test --- app/components/DocumentContext.tsx | 32 ++++ .../Document/components/ConnectionStatus.tsx | 12 +- app/scenes/Document/components/Document.tsx | 38 +++- .../Document/components/MultiplayerEditor.tsx | 60 +++--- app/stores/UiStore.ts | 15 -- .../multiplayer/CollaborationProvider.test.ts | 146 ++++++++++++++ .../multiplayer/CollaborationProvider.ts | 179 ++++++++++++++++++ .../{ => multiplayer}/IndexeddbPersistence.ts | 55 +++++- shared/i18n/locales/en_US/translation.json | 2 + yarn.lock | 18 +- 10 files changed, 484 insertions(+), 73 deletions(-) create mode 100644 app/utils/multiplayer/CollaborationProvider.test.ts create mode 100644 app/utils/multiplayer/CollaborationProvider.ts rename app/utils/{ => multiplayer}/IndexeddbPersistence.ts (82%) diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx index 8633969aa4..a69333b7a8 100644 --- a/app/components/DocumentContext.tsx +++ b/app/components/DocumentContext.tsx @@ -8,6 +8,7 @@ import type { TextStats } from "~/hooks/useTextStats"; import { getTextStats } from "~/hooks/useTextStats"; import type Document from "~/models/Document"; import type { Editor } from "~/editor"; +import type { ConnectionStatus } from "~/utils/multiplayer/CollaborationProvider"; class DocumentContext { /** The current document */ @@ -33,6 +34,22 @@ class DocumentContext { @observable headings: Heading[] = []; + /** The connection status of the collaboration provider */ + @observable + multiplayerStatus: ConnectionStatus | undefined = undefined; + + /** The close code of the collaboration connection, when it was closed with an error */ + @observable + multiplayerErrorCode?: number = undefined; + + /** Whether there are local edits the collaboration server has not confirmed */ + @observable + hasUnsyncedChanges = false; + + /** Whether edits are also stored in the browser, so they survive a reload */ + @observable + hasLocalPersistence = true; + constructor() { makeObservable(this); } @@ -82,6 +99,21 @@ class DocumentContext { this.focusedCommentId = commentId; }; + @action + setMultiplayerStatus = (status: ConnectionStatus, errorCode?: number) => { + this.multiplayerStatus = status; + this.multiplayerErrorCode = errorCode; + }; + + @action + setMultiplayerSyncState = ( + hasUnsyncedChanges: boolean, + hasLocalPersistence: boolean + ) => { + this.hasUnsyncedChanges = hasUnsyncedChanges; + this.hasLocalPersistence = hasLocalPersistence; + }; + @action updateState = () => { this.editorDoc = this.editor?.view.state.doc; diff --git a/app/scenes/Document/components/ConnectionStatus.tsx b/app/scenes/Document/components/ConnectionStatus.tsx index 44700fab55..bde1b5e073 100644 --- a/app/scenes/Document/components/ConnectionStatus.tsx +++ b/app/scenes/Document/components/ConnectionStatus.tsx @@ -10,13 +10,13 @@ import { EditorUpdateError, TooManyConnections, } from "@shared/collaboration/CloseEvents"; +import { useDocumentContext } from "~/components/DocumentContext"; import Fade from "~/components/Fade"; import NudeButton from "~/components/NudeButton"; import Tooltip from "~/components/Tooltip"; -import useStores from "~/hooks/useStores"; function ConnectionStatus() { - const { ui } = useStores(); + const { multiplayerStatus, multiplayerErrorCode } = useDocumentContext(); const { t } = useTranslation(); const codeToMessage = { @@ -44,12 +44,12 @@ function ConnectionStatus() { }, }; - const message = ui.multiplayerErrorCode - ? codeToMessage[ui.multiplayerErrorCode as keyof typeof codeToMessage] + const message = multiplayerErrorCode + ? codeToMessage[multiplayerErrorCode as keyof typeof codeToMessage] : undefined; - return ui.multiplayerStatus === "connecting" || - ui.multiplayerStatus === "disconnected" ? ( + return multiplayerStatus === "connecting" || + multiplayerStatus === "disconnected" ? ( { + if (hasUnsyncedChanges) { + return documentContext.hasLocalPersistence + ? t( + `Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?` + ) + : t( + `Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?` + ); + } + if (isUploading && !isEditorDirty) { + return t( + `Images are still uploading.\nAre you sure you want to discard them?` + ); + } + return true; + }; + + const handleUnload = (event: BeforeUnloadEvent) => { + if (hasUnsyncedChanges) { + event.preventDefault(); + event.returnValue = ""; + } + }; + + useEventListener("beforeunload", handleUnload); + const hasEmojiInTitle = determineIconType(document.icon) === IconType.Emoji; const pageTitle = hasEmojiInTitle ? document.titleWithDefault.replace(document.icon!, "") @@ -359,10 +391,8 @@ function DocumentScene({ {!readOnly && ( )} {isShare ? ( diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index 116b39bb87..818fd4312a 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -1,4 +1,4 @@ -import { HocuspocusProvider, WebSocketStatus } from "@hocuspocus/provider"; +import { WebSocketStatus } from "@hocuspocus/provider"; import { throttle } from "es-toolkit/compat"; import { Node as ProsemirrorNode } from "prosemirror-model"; import { @@ -20,6 +20,7 @@ import EDITOR_VERSION from "@shared/editor/version"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; import { supportsPassiveListener } from "@shared/utils/browser"; import type { Props as EditorProps } from "~/components/Editor"; +import { useDocumentContext } from "~/components/DocumentContext"; import Editor from "~/components/Editor"; import type { Editor as SharedEditor } from "~/editor"; import MultiplayerExtension from "~/editor/extensions/Multiplayer"; @@ -30,8 +31,13 @@ import useIsMounted from "~/hooks/useIsMounted"; import usePageVisibility from "~/hooks/usePageVisibility"; import useStores from "~/hooks/useStores"; import type { AwarenessChangeEvent } from "~/types"; -import { IndexeddbPersistence } from "~/utils/IndexeddbPersistence"; import Logger from "~/utils/Logger"; +import { + CollaborationProvider, + type ConnectionMessageEvent, + type ConnectionStatusEvent, +} from "~/utils/multiplayer/CollaborationProvider"; +import { IndexeddbPersistence } from "~/utils/multiplayer/IndexeddbPersistence"; import { homePath } from "~/utils/routeHelpers"; import { sleep } from "@shared/utils/timers"; @@ -40,21 +46,6 @@ type Props = EditorProps & { onSynced?: () => Promise; }; -export type ConnectionStatus = - | "connecting" - | "connected" - | "disconnected" - | void; - -type ConnectionStatusEvent = { status: ConnectionStatus }; - -type MessageEvent = { - message: string; - event: Event & { - code?: number; - }; -}; - function MultiplayerEditor( { onSynced, ...props }: Props, ref: ForwardedRef @@ -65,9 +56,10 @@ function MultiplayerEditor( const currentUser = useCurrentUser(); const retryCount = useRef(0); const { presence, auth, ui } = useStores(); + const documentContext = useDocumentContext(); const [editorVersionBehind, setEditorVersionBehind] = useState(false); const [showCursorNames, setShowCursorNames] = useState(false); - const [remoteProvider, setRemoteProvider] = useState(); + const [remoteProvider, setRemoteProvider] = useState(); const [hasLocalPersistence, setHasLocalPersistence] = useState(true); const [isLocalSynced, setLocalSynced] = useState(false); const [isRemoteSynced, setRemoteSynced] = useState(false); @@ -96,7 +88,7 @@ function MultiplayerEditor( setHasLocalPersistence(false); } - const provider = new HocuspocusProvider({ + const provider = new CollaborationProvider({ parameters: { editorVersion: EDITOR_VERSION, }, @@ -104,6 +96,7 @@ function MultiplayerEditor( name, document: ydoc, token, + localProvider, }); const syncScrollPosition = throttle(() => { @@ -175,6 +168,17 @@ function MultiplayerEditor( }; provider.on("awarenessChange", showCursorNames); + + const syncState = () => { + documentContext.setMultiplayerSyncState( + provider.hasPendingChanges, + provider.hasLocalPersistence + ); + }; + + provider.on("syncStateChange", syncState); + syncState(); + localProvider?.whenSynced .then(() => { if (!isActive || !localProvider.synced) { @@ -198,14 +202,14 @@ function MultiplayerEditor( retryCount.current = 0; }); - provider.on("close", (ev: MessageEvent) => { + provider.on("close", (ev: ConnectionMessageEvent) => { if ("code" in ev.event) { // Note other close code are handled internally by the library if (ev.event.code === EditorUpdateError.code) { provider.shouldConnect = false; } - ui.setMultiplayerStatus("disconnected", ev.event.code); + documentContext.setMultiplayerStatus("disconnected", ev.event.code); if (ev.event.code === EditorUpdateError.code) { setEditorVersionBehind(true); @@ -214,15 +218,15 @@ function MultiplayerEditor( }); if (debug) { - provider.on("close", (ev: MessageEvent) => + provider.on("close", (ev: ConnectionMessageEvent) => Logger.debug("collaboration", "close", ev) ); - provider.on("message", (ev: MessageEvent) => + provider.on("message", (ev: ConnectionMessageEvent) => Logger.debug("collaboration", "incoming", { message: ev.message, }) ); - provider.on("outgoingMessage", (ev: MessageEvent) => + provider.on("outgoingMessage", (ev: ConnectionMessageEvent) => Logger.debug("collaboration", "outgoing", { message: ev.message, }) @@ -230,8 +234,8 @@ function MultiplayerEditor( } provider.on("status", (ev: ConnectionStatusEvent) => { - if (ui.multiplayerStatus !== ev.status) { - ui.setMultiplayerStatus(ev.status, undefined); + if (documentContext.multiplayerStatus !== ev.status) { + documentContext.setMultiplayerStatus(ev.status, undefined); } }); @@ -245,7 +249,8 @@ function MultiplayerEditor( provider?.destroy(); void localProvider?.destroy(); setRemoteProvider(undefined); - ui.setMultiplayerStatus(undefined, undefined); + documentContext.setMultiplayerStatus(undefined, undefined); + documentContext.setMultiplayerSyncState(false, true); }; // `token` is intentionally omitted, it is only read when establishing the // connection and a refreshed token must not tear down the provider. @@ -255,6 +260,7 @@ function MultiplayerEditor( t, documentId, ui, + documentContext, presence, ydoc, currentUser.id, diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index fb3c3f4b57..410ff39eba 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -9,7 +9,6 @@ import Storage from "@shared/utils/Storage"; import Document from "~/models/Document"; import type Model from "~/models/base/Model"; import Collection from "~/models/Collection"; -import type { ConnectionStatus } from "~/scenes/Document/components/MultiplayerEditor"; import type { SplitViewPane } from "~/utils/splitView"; import { isTruthyQueryValue } from "~/utils/urls"; import { startViewTransition } from "~/utils/viewTransition"; @@ -110,11 +109,6 @@ class UiStore { @observable sidebarIsResizing = false; - @observable - multiplayerStatus: ConnectionStatus | undefined = undefined; - - @observable - multiplayerErrorCode?: number = undefined; @observable debugSafeArea = false; @@ -359,15 +353,6 @@ class UiStore { } }; - @action - setMultiplayerStatus = ( - status: ConnectionStatus, - errorCode?: number - ): void => { - this.multiplayerStatus = status; - this.multiplayerErrorCode = errorCode; - }; - @action setSidebarResizing = (sidebarIsResizing: boolean): void => { this.sidebarIsResizing = sidebarIsResizing; diff --git a/app/utils/multiplayer/CollaborationProvider.test.ts b/app/utils/multiplayer/CollaborationProvider.test.ts new file mode 100644 index 0000000000..90ae64ebbd --- /dev/null +++ b/app/utils/multiplayer/CollaborationProvider.test.ts @@ -0,0 +1,146 @@ +import * as Y from "yjs"; +import { + CollaborationProvider, + type SyncStateEvent, +} from "./CollaborationProvider"; + +describe("CollaborationProvider", () => { + let doc: Y.Doc; + let provider: CollaborationProvider; + let events: SyncStateEvent[]; + + const edit = (origin?: unknown) => { + doc.transact(() => doc.getText("default").insert(0, "a"), origin); + }; + + beforeEach(() => { + vi.useFakeTimers(); + doc = new Y.Doc(); + events = []; + provider = new CollaborationProvider({ + url: "ws://localhost", + name: "test", + document: doc, + connect: false, + }); + provider.on("syncStateChange", (event: SyncStateEvent) => { + events.push(event); + }); + }); + + afterEach(() => { + provider.destroy(); + vi.useRealTimers(); + }); + + it("starts without pending changes", () => { + expect(provider.hasPendingChanges).toBe(false); + expect(provider.hasLocalPersistence).toBe(false); + }); + + it("reports an edit made while disconnected immediately", () => { + edit(); + + expect(provider.hasPendingChanges).toBe(true); + expect(events).toEqual([ + { hasUnsyncedChanges: true, hasLocalPersistence: false }, + ]); + }); + + it("ignores updates that came from the provider itself", () => { + edit(provider); + + expect(provider.hasPendingChanges).toBe(false); + expect(events).toEqual([]); + }); + + it("waits for the grace period while connected", () => { + provider.synced = true; + edit(); + + expect(provider.hasPendingChanges).toBe(false); + + vi.advanceTimersByTime(2000); + + expect(provider.hasPendingChanges).toBe(true); + expect(events).toHaveLength(1); + }); + + it("clears pending changes once the server confirms a full sync", () => { + edit(); + edit(); + expect(provider.hasPendingChanges).toBe(true); + + provider.synced = true; + + expect(provider.hasPendingChanges).toBe(false); + expect(events.at(-1)).toEqual({ + hasUnsyncedChanges: false, + hasLocalPersistence: false, + }); + + vi.advanceTimersByTime(2000); + + expect(provider.hasPendingChanges).toBe(false); + }); + + it("keeps pending changes while the connection is down", () => { + provider.synced = true; + edit(); + vi.advanceTimersByTime(2000); + expect(provider.hasPendingChanges).toBe(true); + + provider.synced = false; + + expect(provider.hasPendingChanges).toBe(true); + expect(events).toHaveLength(1); + }); + + it("reports when local persistence stops", () => { + provider.destroy(); + const listeners = new Set<() => void>(); + const localProvider = { + stopped: false, + onStop: (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; + provider = new CollaborationProvider({ + url: "ws://localhost", + name: "test", + document: doc, + connect: false, + localProvider, + }); + provider.on("syncStateChange", (event: SyncStateEvent) => { + events.push(event); + }); + expect(provider.hasLocalPersistence).toBe(true); + + edit(); + expect(events.at(-1)).toEqual({ + hasUnsyncedChanges: true, + hasLocalPersistence: true, + }); + + listeners.forEach((listener) => listener()); + expect(provider.hasLocalPersistence).toBe(false); + expect(events.at(-1)).toEqual({ + hasUnsyncedChanges: true, + hasLocalPersistence: false, + }); + }); + + it("does not report after being destroyed", () => { + provider.synced = true; + edit(); + provider.destroy(); + + vi.advanceTimersByTime(2000); + + expect(provider.hasPendingChanges).toBe(false); + }); +}); diff --git a/app/utils/multiplayer/CollaborationProvider.ts b/app/utils/multiplayer/CollaborationProvider.ts new file mode 100644 index 0000000000..02544d992c --- /dev/null +++ b/app/utils/multiplayer/CollaborationProvider.ts @@ -0,0 +1,179 @@ +import { + HocuspocusProvider, + type HocuspocusProviderConfiguration, +} from "@hocuspocus/provider"; +import { Second } from "@shared/utils/time"; +import Logger from "~/utils/Logger"; +import type { IndexeddbPersistence } from "./IndexeddbPersistence"; + +/** How long a local change may await the server echo before it is unsynced. */ +const unsyncedGracePeriod = 2 * Second.ms; + +/** The part of local persistence the provider relies on. */ +type LocalProvider = Pick; + +export type CollaborationProviderConfiguration = + HocuspocusProviderConfiguration & { + /** Local persistence for the same document, if available. */ + localProvider?: LocalProvider; + }; + +/** The state of the connection to the collaboration server. */ +export type ConnectionStatus = + | "connecting" + | "connected" + | "disconnected" + | void; + +/** Emitted when the connection status changes. */ +export interface ConnectionStatusEvent { + status: ConnectionStatus; +} + +/** Emitted for incoming, outgoing and close messages of the connection. */ +export interface ConnectionMessageEvent { + message: string; + event: Event & { + code?: number; + }; +} + +export interface SyncStateEvent { + /** Whether there are local edits the server has not confirmed. */ + hasUnsyncedChanges: boolean; + /** Whether edits are also stored in the browser, so they survive a reload. */ + hasLocalPersistence: boolean; +} + +/** + * A Hocuspocus provider that also tracks whether local edits have reached the + * server, and emits a "syncStateChange" event whenever that changes. + */ +export class CollaborationProvider extends HocuspocusProvider { + constructor(configuration: CollaborationProviderConfiguration) { + const { localProvider, ...rest } = configuration; + super(rest); + this.localProvider = localProvider; + this.localPersistence = !!localProvider && !localProvider.stopped; + this.stopLocalProviderListener = localProvider?.onStop(() => + this.setLocalPersistence(false) + ); + + this.document.on("update", this.handleDocumentUpdate); + this.on("synced", this.handleSynced); + this.updateSyncState(); + } + + /** Whether there are local edits the server has not confirmed. */ + get hasPendingChanges(): boolean { + return this.syncState.hasUnsyncedChanges; + } + + /** Whether edits are also stored in the browser, so they survive a reload. */ + get hasLocalPersistence(): boolean { + return this.localPersistence; + } + + onMessage(event: Parameters[0]) { + super.onMessage(event); + this.updateSyncState(); + } + + destroy() { + this.clearUnsyncedTimeout(); + this.stopLocalProviderListener?.(); + this.document.off("update", this.handleDocumentUpdate); + super.destroy(); + } + + private localProvider?: LocalProvider; + + private localPersistence: boolean; + + private stopLocalProviderListener?: () => void; + + /** The last state reported to listeners. */ + private syncState: SyncStateEvent = { + hasUnsyncedChanges: false, + hasLocalPersistence: true, + }; + + /** Whether an edit was made since the server last confirmed a full sync. */ + private editedSinceSync = false; + + private unsyncedTimeout?: ReturnType; + + private handleDocumentUpdate = (_update: Uint8Array, origin: unknown) => { + if (origin !== this && origin !== this.localProvider) { + this.editedSinceSync = true; + } + this.updateSyncState(); + }; + + // The sync handshake delivers every local edit, so the inherited count only + // covers edits made from here on. It would otherwise keep counting edits + // made while reconnecting, which are never echoed individually. + private handleSynced = ({ state }: { state: boolean }) => { + Logger.debug("collaboration", "synced", { + state, + unsyncedChanges: this.unsyncedChanges, + editedSinceSync: this.editedSinceSync, + }); + if (state) { + this.unsyncedChanges = 0; + } + this.updateSyncState(); + }; + + // While synced the inherited count is reliable, as the server echoes every + // update back. Otherwise fall back to whether an edit was made since the + // last confirmed sync. + private updateSyncState = () => { + if (this.synced && !this.hasUnsyncedChanges) { + this.editedSinceSync = false; + } + const hasUnsyncedChanges = this.synced + ? this.hasUnsyncedChanges + : this.editedSinceSync; + + // A connected server echoes each update within milliseconds, so only + // report changes as unsynced once they have been pending for a while. + if (hasUnsyncedChanges && this.synced) { + this.unsyncedTimeout ??= setTimeout(() => { + this.unsyncedTimeout = undefined; + this.emitSyncState(true); + }, unsyncedGracePeriod); + return; + } + this.clearUnsyncedTimeout(); + this.emitSyncState(hasUnsyncedChanges); + }; + + private emitSyncState(hasUnsyncedChanges: boolean) { + const next: SyncStateEvent = { + hasUnsyncedChanges, + hasLocalPersistence: this.localPersistence, + }; + if ( + next.hasUnsyncedChanges === this.syncState.hasUnsyncedChanges && + next.hasLocalPersistence === this.syncState.hasLocalPersistence + ) { + return; + } + this.syncState = next; + Logger.debug("collaboration", "sync state", next); + this.emit("syncStateChange", next); + } + + private setLocalPersistence(value: boolean) { + this.localPersistence = value; + this.updateSyncState(); + } + + private clearUnsyncedTimeout() { + if (this.unsyncedTimeout !== undefined) { + clearTimeout(this.unsyncedTimeout); + this.unsyncedTimeout = undefined; + } + } +} diff --git a/app/utils/IndexeddbPersistence.ts b/app/utils/multiplayer/IndexeddbPersistence.ts similarity index 82% rename from app/utils/IndexeddbPersistence.ts rename to app/utils/multiplayer/IndexeddbPersistence.ts index 7d64223ac1..cdda289b73 100644 --- a/app/utils/IndexeddbPersistence.ts +++ b/app/utils/multiplayer/IndexeddbPersistence.ts @@ -1,4 +1,5 @@ import * as Y from "yjs"; +import Logger from "~/utils/Logger"; /** * Persists a Y.Doc to IndexedDB so documents can be loaded instantly from the @@ -21,6 +22,12 @@ export class IndexeddbPersistence { /** Whether the state stored in the database has been applied to the document. */ public synced = false; + /** + * Whether persisting has stopped for good, because the database could not + * be opened or the connection was closed underneath us. + */ + public stopped = false; + /** * Resolves once the state stored in the database has been applied to the * document, or immediately if the instance is destroyed beforehand – check @@ -47,10 +54,24 @@ export class IndexeddbPersistence { return this; }); + this.whenSynced.catch((error) => this.stop(error)); doc.on("update", this.handleDocUpdate); doc.on("destroy", this.destroy); } + /** + * Registers a listener that is called once persisting stops, see `stopped`. + * + * @param listener the function to call. + * @returns a function that removes the listener. + */ + public onStop(listener: () => void): () => void { + this.stopListeners.add(listener); + return () => { + this.stopListeners.delete(listener); + }; + } + /** * Merges all stored update rows into a single row containing the current * document state. @@ -99,6 +120,8 @@ export class IndexeddbPersistence { private destroyed = false; + private stopListeners = new Set<() => void>(); + /** * Number of stored updates after which they are merged into a single * database row containing the entire document state, keeping loads fast. @@ -119,7 +142,13 @@ export class IndexeddbPersistence { return; } - this.updatesStore(this.db).add(update); + try { + this.updatesStore(this.db).add(update); + } catch (error) { + // A throw here would break every later Y.Doc transaction. + this.stop(error); + return; + } if (++this.dbsize >= this.preferredTrimSize) { if (this.storeTimeoutId !== undefined) { @@ -188,10 +217,28 @@ export class IndexeddbPersistence { } } + private stop(error: unknown) { + if (this.stopped) { + return; + } + this.stopped = true; + this.db = null; + + if (!this.destroyed) { + Logger.warn("Local document persistence stopped", { error }); + } + this.stopListeners.forEach((listener) => listener()); + this.stopListeners.clear(); + } + + /** + * Opens a read-write transaction on the updates store. Writes report + * failures such as a full quota asynchronously by aborting the transaction. + */ private updatesStore(db: IDBDatabase): IDBObjectStore { - return db - .transaction(updatesStoreName, "readwrite") - .objectStore(updatesStoreName); + const transaction = db.transaction(updatesStoreName, "readwrite"); + transaction.onabort = () => this.stop(transaction.error); + return transaction.objectStore(updatesStoreName); } } diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index f1c60e19c6..667bb7b54f 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -922,6 +922,8 @@ "Edits you make will sync once you’re online": "Edits you make will sync once you’re online", "Offline": "Offline", "Document restored": "Document restored", + "Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?": "Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?", + "Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?": "Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?", "Images are still uploading.\nAre you sure you want to discard them?": "Images are still uploading.\nAre you sure you want to discard them?", "{{ count }} comment": "{{ count }} comment", "{{ count }} comment_plural": "{{ count }} comments", diff --git a/yarn.lock b/yarn.lock index e048ba18a2..734baa469c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14451,23 +14451,7 @@ __metadata: languageName: node linkType: hard -"markdown-it@npm:^14.0.0": - version: 14.3.0 - resolution: "markdown-it@npm:14.3.0" - dependencies: - argparse: "npm:^2.0.1" - entities: "npm:^4.5.0" - linkify-it: "npm:^5.0.2" - mdurl: "npm:^2.0.0" - punycode.js: "npm:^2.3.1" - uc.micro: "npm:^2.1.0" - bin: - markdown-it: bin/markdown-it.mjs - checksum: 10c0/b2dea908968109d6e9088ac972254bca842157d85d2e6838d0eb263cd8106e7e6a72663b138366cc98f57441d9f3f2ebfb842bf7b2f9e1c13187ebe70e0af8f9 - languageName: node - linkType: hard - -"markdown-it@npm:^14.3.1": +"markdown-it@npm:^14.0.0, markdown-it@npm:^14.3.1": version: 14.3.1 resolution: "markdown-it@npm:14.3.1" dependencies: From 3c655d55a39672eba00304cb812dad98f0b16692 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 08:00:03 -0400 Subject: [PATCH 087/368] fix: Store group description on creation (#13791) --- server/routes/api/groups/groups.test.ts | 3 +++ server/routes/api/groups/groups.ts | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/server/routes/api/groups/groups.test.ts b/server/routes/api/groups/groups.test.ts index 032a6aae48..968915078b 100644 --- a/server/routes/api/groups/groups.test.ts +++ b/server/routes/api/groups/groups.test.ts @@ -14,16 +14,19 @@ const server = getTestServer(); describe("#groups.create", () => { it("should create a group", async () => { const name = "hello I am a group"; + const description = "A group description"; const user = await buildAdmin(); const res = await server.post("/api/groups.create", user, { body: { name, + description, externalId: "123", }, }); const body = await res.json(); expect(res.status).toEqual(200); expect(body.data.name).toEqual(name); + expect(body.data.description).toEqual(description); expect(body.data.externalId).toEqual("123"); }); }); diff --git a/server/routes/api/groups/groups.ts b/server/routes/api/groups/groups.ts index a570b8baca..6fc322f3b0 100644 --- a/server/routes/api/groups/groups.ts +++ b/server/routes/api/groups/groups.ts @@ -233,12 +233,13 @@ router.post( validate(T.GroupsCreateSchema), transaction(), async (ctx: APIContext) => { - const { name, externalId, disableMentions } = ctx.input.body; + const { name, description, externalId, disableMentions } = ctx.input.body; const { user } = ctx.state.auth; authorize(user, "createGroup", user.team); const group = await Group.createWithCtx(ctx, { name, + description, externalId, disableMentions, teamId: user.teamId, From 9839ad8182cdd533845d7005efdcf0e995af9c0a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 08:58:01 -0400 Subject: [PATCH 088/368] fix: Send analytics events through gtag and track WebMCP tool registration (#13792) * fix: Send analytics events through gtag and track WebMCP tool registration * Track WebMCP registration without a tool count --- app/actions/index.ts | 33 +++++++++++++++------------------ app/hooks/useWebMCPActions.ts | 3 +++ app/utils/Analytics.ts | 9 +++------ 3 files changed, 21 insertions(+), 24 deletions(-) diff --git a/app/actions/index.ts b/app/actions/index.ts index 46decda4fb..f9e3c9a8f3 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -46,24 +46,7 @@ export function createAction( ...definition, type: "action", variant: "action", - perform: definition.perform - ? (context) => { - // We must use the specific analytics name here as the action name is - // translated and potentially contains user strings. - if (definition.analyticsName) { - Analytics.track("perform_action", definition.analyticsName, { - context: context.isButton - ? "button" - : context.isCommandBar - ? "commandbar" - : context.isMCP - ? "webmcp" - : "contextmenu", - }); - } - return definition.perform(context); - } - : () => {}, + perform: definition.perform ?? (() => {}), id: definition.id ?? uuidv4(), }; } @@ -353,6 +336,20 @@ export async function performAction( ? () => history.push(resolve(action.to, context)) : () => window.open(action.url, action.target); + // We must use the specific analytics name here as the action name is + // translated and potentially contains user strings. + if (action.analyticsName) { + Analytics.track("perform_action", action.analyticsName, { + context: context.isButton + ? "button" + : context.isCommandBar + ? "commandbar" + : context.isMCP + ? "webmcp" + : "contextmenu", + }); + } + const result = perform(); if (result instanceof Promise) { diff --git a/app/hooks/useWebMCPActions.ts b/app/hooks/useWebMCPActions.ts index 0d1b00a438..03527d48b2 100644 --- a/app/hooks/useWebMCPActions.ts +++ b/app/hooks/useWebMCPActions.ts @@ -11,6 +11,7 @@ import type { ActionVariant, ActionWithChildren, } from "~/types"; +import Analytics from "~/utils/Analytics"; import { isModelContextSupported, registerModelContextTool, @@ -104,6 +105,8 @@ export default function useWebMCPActions( ); } + Analytics.track("webmcp", "register"); + return () => controller.abort(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [enabled, toolNames.join(","), location.pathname, ...additionalDeps]); diff --git a/app/utils/Analytics.ts b/app/utils/Analytics.ts index 3d260f7502..4eb4bf8416 100644 --- a/app/utils/Analytics.ts +++ b/app/utils/Analytics.ts @@ -7,6 +7,7 @@ export default class Analytics { * * @param event The event name * @param action The action name + * @param metadata Additional parameters to attach to the event */ public static track = ( event: string, @@ -19,12 +20,8 @@ export default class Analytics { } // GA4 - if (window.dataLayer) { - window.dataLayer.push({ - event, - action, - ...metadata, - }); + if (window.gtag) { + window.gtag("event", event, { action, ...metadata }); } }; } From 3a446d1e37bb971a746c45fbab81a08dd36664ff Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 17:45:25 -0400 Subject: [PATCH 089/368] chore: Speed up CI (#13797) * chore: Speed up CI with TypeScript 7 and Blacksmith runners Upgrade TypeScript to 7.0.2, the native compiler, which cuts a full type check from ~57s to ~12s locally. Yarn is bumped to 4.18.0 because older versions fail to apply the builtin compat patch to TypeScript 7. Fix two type errors the stricter compiler surfaces: the collection drop target used unrelated item and monitor types, and Store.add relied on the error type of an abstract construct call to satisfy the generic return. Move CI jobs to Blacksmith runners, with a fallback to GitHub-hosted runners for forks. * chore: Match enterprise CI runner sizes * chore: Persist node_modules on a sticky disk and use more test workers * chore: Use the preinstalled PostgreSQL in CI instead of a service container * chore: Skip the setup-node yarn cache when a sticky disk is mounted * chore: Persist the Node.js toolcache and run server tests in 6 shards * chore: Disable the setup-node package manager cache on Blacksmith * chore: Keep pull requests from forks off Blacksmith runners and sticky disks --- .github/actions/install/action.yml | 22 +- .github/workflows/ci.yml | 45 ++- .../components/DraggableCollectionLink.tsx | 18 +- app/stores/base/Store.ts | 2 +- package.json | 4 +- yarn.lock | 290 +++++++++++++++++- 6 files changed, 334 insertions(+), 47 deletions(-) diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml index 3cd311d501..cc2d710782 100644 --- a/.github/actions/install/action.yml +++ b/.github/actions/install/action.yml @@ -1,8 +1,15 @@ name: Install description: Set up Node.js, Corepack, and install dependencies with yarn cache +# The Blacksmith condition must match the runner selection in workflows/ci.yml. runs: using: composite steps: + - name: Mount Node.js toolcache + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-node-toolcache + path: /opt/hostedtoolcache/node - name: Enable Corepack shell: bash run: corepack enable @@ -10,7 +17,20 @@ runs: uses: actions/setup-node@v5 with: node-version: 26.x - cache: "yarn" + # Blacksmith jobs persist the yarn cache on a sticky disk instead. + package-manager-cache: ${{ !(github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) }} + - name: Mount yarn cache + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-yarn-cache + path: ~/.yarn/berry/cache + - name: Mount node_modules + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-node-modules + path: ./node_modules - name: Install dependencies shell: bash run: yarn install --immutable diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba95754024..d763a546ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,12 @@ env: jobs: changes: - runs-on: ubuntu-latest + # Blacksmith runners are only available to the outline organization, and are + # not used for pull requests from forks so that fork-controlled code cannot + # write to the shared sticky disks. Keep in sync with actions/install. + runs-on: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} outputs: + runner: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} code: ${{ steps.filter.outputs.code }} config: ${{ steps.filter.outputs.config }} server: ${{ steps.filter.outputs.server }} @@ -60,7 +64,7 @@ jobs: lint: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -79,7 +83,7 @@ jobs: types: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -88,7 +92,7 @@ jobs: audit: needs: changes if: ${{ needs.changes.outputs.deps == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -97,7 +101,7 @@ jobs: test: needs: changes if: ${{ needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: test-group: [app, shared] @@ -109,37 +113,30 @@ jobs: test-server: needs: changes if: ${{ needs.changes.outputs.server == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest - services: - postgres: - image: postgres:14.2 - env: - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: outline_test - ports: - - 5432:5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5, 6] steps: - uses: actions/checkout@v5 + # The runner image ships with PostgreSQL preinstalled, starting it is much + # faster than pulling and initializing a service container. + - name: Start PostgreSQL + run: | + sudo systemctl start postgresql.service + until pg_isready -h localhost; do sleep 1; done + sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'password';" + sudo -u postgres createdb outline_test - uses: ./.github/actions/install - run: yarn sequelize db:migrate - name: Run server tests - run: yarn test:server --maxWorkers=2 --shard=${{ matrix.shard }}/4 + run: yarn test:server --maxWorkers=4 --shard=${{ matrix.shard }}/6 bundle-size: needs: changes if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index 192a3e7046..d2caac6c30 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -2,7 +2,6 @@ import fractionalIndex from "fractional-index"; import { observer } from "mobx-react"; import type * as React from "react"; import { useState, useEffect, useCallback } from "react"; -import type { DropTargetMonitor } from "react-dnd"; import { useDrop, useDrag } from "react-dnd"; import { getEmptyImage } from "react-dnd-html5-backend"; import styled from "styled-components"; @@ -11,7 +10,6 @@ import type Document from "~/models/Document"; import CollectionIcon from "~/components/Icons/CollectionIcon"; import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useStores from "~/hooks/useStores"; -import type { DragObject } from "../hooks/useDragAndDrop"; import CollectionLink from "./CollectionLink"; import DropCursor from "./DropCursor"; import SidebarDisclosureContext, { @@ -26,6 +24,12 @@ type Props = { belowCollection: Collection | void; }; +interface CollectionDragItem { + id: string; + title: string; + icon: React.ReactNode; +} + function DraggableCollectionLink({ collection, activeDocument, @@ -48,9 +52,13 @@ function DraggableCollectionLink({ const [ { isCollectionDropping, isDraggingAnyCollection }, dropToReorderCollection, - ] = useDrop({ + ] = useDrop< + CollectionDragItem, + void, + { isCollectionDropping: boolean; isDraggingAnyCollection: boolean } + >({ accept: "collection", - drop: (item: DragObject) => { + drop: (item) => { void collections.move( item.id, fractionalIndex(collection.index, belowCollectionIndex) @@ -60,7 +68,7 @@ function DraggableCollectionLink({ collection.id !== item.id && (!belowCollection || item.id !== belowCollection.id) && !!policies.abilities(item.id).move, - collect: (monitor: DropTargetMonitor) => ({ + collect: (monitor) => ({ isCollectionDropping: monitor.isOver(), isDraggingAnyCollection: monitor.canDrop(), }), diff --git a/app/stores/base/Store.ts b/app/stores/base/Store.ts index 1409157e3e..73c6f47990 100644 --- a/app/stores/base/Store.ts +++ b/app/stores/base/Store.ts @@ -249,7 +249,7 @@ export default abstract class Store { } // @ts-expect-error TS thinks that we're instantiating an abstract class here - const newModel = new ModelClass(item, this); + const newModel: T = new ModelClass(item, this); this.data.set(newModel.id, newModel); this.persistence?.persist(newModel.id); return newModel; diff --git a/package.json b/package.json index 472c59d779..7574742858 100644 --- a/package.json +++ b/package.json @@ -367,7 +367,7 @@ "rimraf": "^6.1.3", "rollup-plugin-webpack-stats": "^3.1.3", "terser": "^5.49.0", - "typescript": "^6.0.3", + "typescript": "^7.0.2", "unplugin-swc": "^1.5.11", "vite-tsconfig-paths": "^6.1.1", "vitest": "^4.1.11" @@ -388,5 +388,5 @@ "i18next-parser/i18next": "^23.16.8" }, "version": "1.10.1", - "packageManager": "yarn@4.11.0" + "packageManager": "yarn@4.18.0" } diff --git a/yarn.lock b/yarn.lock index 734baa469c..777e291791 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,7 +2,7 @@ # Manual changes might be lost - proceed with caution! __metadata: - version: 8 + version: 10 cacheKey: 10c0 "@antfu/install-pkg@npm:^1.1.0": @@ -7524,6 +7524,146 @@ __metadata: languageName: node linkType: hard +"@typescript/typescript-aix-ppc64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-aix-ppc64@npm:7.0.2" + conditions: os=aix & cpu=ppc64 + languageName: node + linkType: hard + +"@typescript/typescript-darwin-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-darwin-arm64@npm:7.0.2" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-darwin-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-darwin-x64@npm:7.0.2" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-freebsd-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-freebsd-arm64@npm:7.0.2" + conditions: os=freebsd & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-freebsd-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-freebsd-x64@npm:7.0.2" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-linux-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-arm64@npm:7.0.2" + conditions: os=linux & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-linux-arm@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-arm@npm:7.0.2" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@typescript/typescript-linux-loong64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-loong64@npm:7.0.2" + conditions: os=linux & cpu=loong64 + languageName: node + linkType: hard + +"@typescript/typescript-linux-mips64el@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-mips64el@npm:7.0.2" + conditions: os=linux & cpu=mips64el + languageName: node + linkType: hard + +"@typescript/typescript-linux-ppc64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-ppc64@npm:7.0.2" + conditions: os=linux & cpu=ppc64 + languageName: node + linkType: hard + +"@typescript/typescript-linux-riscv64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-riscv64@npm:7.0.2" + conditions: os=linux & cpu=riscv64 + languageName: node + linkType: hard + +"@typescript/typescript-linux-s390x@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-s390x@npm:7.0.2" + conditions: os=linux & cpu=s390x + languageName: node + linkType: hard + +"@typescript/typescript-linux-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-linux-x64@npm:7.0.2" + conditions: os=linux & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-netbsd-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-netbsd-arm64@npm:7.0.2" + conditions: os=netbsd & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-netbsd-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-netbsd-x64@npm:7.0.2" + conditions: os=netbsd & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-openbsd-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-openbsd-arm64@npm:7.0.2" + conditions: os=openbsd & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-openbsd-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-openbsd-x64@npm:7.0.2" + conditions: os=openbsd & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-sunos-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-sunos-x64@npm:7.0.2" + conditions: os=sunos & cpu=x64 + languageName: node + linkType: hard + +"@typescript/typescript-win32-arm64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-win32-arm64@npm:7.0.2" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@typescript/typescript-win32-x64@npm:7.0.2": + version: 7.0.2 + resolution: "@typescript/typescript-win32-x64@npm:7.0.2" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@upsetjs/venn.js@npm:^2.0.0": version: 2.0.0 resolution: "@upsetjs/venn.js@npm:2.0.0" @@ -15774,7 +15914,7 @@ __metadata: tiny-cookie: "npm:^2.5.1" tmp: "npm:^0.2.6" tunnel-agent: "npm:^0.6.0" - typescript: "npm:^6.0.3" + typescript: "npm:^7.0.2" ukkonen: "npm:^2.2.0" umzug: "npm:^3.8.3" unplugin-swc: "npm:^1.5.11" @@ -17874,7 +18014,7 @@ __metadata: "resolve@patch:resolve@npm%3A^1.22.1#optional!builtin, resolve@patch:resolve@npm%3A^1.22.11#optional!builtin, resolve@patch:resolve@npm%3A~1.22.1#optional!builtin": version: 1.22.12 - resolution: "resolve@patch:resolve@npm%3A1.22.12#optional!builtin::version=1.22.12&hash=c3c19d" + resolution: "resolve@patch:resolve@npm%3A1.22.12#optional!builtin::version=1.22.12&hash=9bd1a5" dependencies: es-errors: "npm:^1.3.0" is-core-module: "npm:^2.16.1" @@ -17882,7 +18022,7 @@ __metadata: supports-preserve-symlinks-flag: "npm:^1.0.0" bin: resolve: bin/resolve - checksum: 10c0/fc6519984ae1f894d877c0060ba8b1f5ba3bc0e85a02f74e141929c118c23d74d9735619a9cc2965397387e514884245c65d72a40731dcb6cfc84c7bcdc8321e + checksum: 10c0/e12af106e16e652bd83060e8afacece4ee3dcbd0f4cf028e3d9ad178e6ced9ecb1c87ee60158b239582313902a717f8adc57a9b76ea54b1994141ba15f420c65 languageName: node linkType: hard @@ -20034,13 +20174,74 @@ __metadata: languageName: node linkType: hard -"typescript@npm:^6.0.3": - version: 6.0.3 - resolution: "typescript@npm:6.0.3" +"typescript@npm:^7.0.2": + version: 7.0.2 + resolution: "typescript@npm:7.0.2" + dependencies: + "@typescript/typescript-aix-ppc64": "npm:7.0.2" + "@typescript/typescript-darwin-arm64": "npm:7.0.2" + "@typescript/typescript-darwin-x64": "npm:7.0.2" + "@typescript/typescript-freebsd-arm64": "npm:7.0.2" + "@typescript/typescript-freebsd-x64": "npm:7.0.2" + "@typescript/typescript-linux-arm": "npm:7.0.2" + "@typescript/typescript-linux-arm64": "npm:7.0.2" + "@typescript/typescript-linux-loong64": "npm:7.0.2" + "@typescript/typescript-linux-mips64el": "npm:7.0.2" + "@typescript/typescript-linux-ppc64": "npm:7.0.2" + "@typescript/typescript-linux-riscv64": "npm:7.0.2" + "@typescript/typescript-linux-s390x": "npm:7.0.2" + "@typescript/typescript-linux-x64": "npm:7.0.2" + "@typescript/typescript-netbsd-arm64": "npm:7.0.2" + "@typescript/typescript-netbsd-x64": "npm:7.0.2" + "@typescript/typescript-openbsd-arm64": "npm:7.0.2" + "@typescript/typescript-openbsd-x64": "npm:7.0.2" + "@typescript/typescript-sunos-x64": "npm:7.0.2" + "@typescript/typescript-win32-arm64": "npm:7.0.2" + "@typescript/typescript-win32-x64": "npm:7.0.2" + dependenciesMeta: + "@typescript/typescript-aix-ppc64": + optional: true + "@typescript/typescript-darwin-arm64": + optional: true + "@typescript/typescript-darwin-x64": + optional: true + "@typescript/typescript-freebsd-arm64": + optional: true + "@typescript/typescript-freebsd-x64": + optional: true + "@typescript/typescript-linux-arm": + optional: true + "@typescript/typescript-linux-arm64": + optional: true + "@typescript/typescript-linux-loong64": + optional: true + "@typescript/typescript-linux-mips64el": + optional: true + "@typescript/typescript-linux-ppc64": + optional: true + "@typescript/typescript-linux-riscv64": + optional: true + "@typescript/typescript-linux-s390x": + optional: true + "@typescript/typescript-linux-x64": + optional: true + "@typescript/typescript-netbsd-arm64": + optional: true + "@typescript/typescript-netbsd-x64": + optional: true + "@typescript/typescript-openbsd-arm64": + optional: true + "@typescript/typescript-openbsd-x64": + optional: true + "@typescript/typescript-sunos-x64": + optional: true + "@typescript/typescript-win32-arm64": + optional: true + "@typescript/typescript-win32-x64": + optional: true bin: tsc: bin/tsc - tsserver: bin/tsserver - checksum: 10c0/4a25ff5045b984370f48f196b3a0120779b1b343d40b9a68d114ea5e5fff099809b2bb777576991a63a5cd59cf7bffd96ff6fe10afcefbcb8bd6fb96ad4b6606 + checksum: 10c0/3dcee51ec8c332492325bcdbf7df48b66668751f127e622ae7d41b6c716eb19184424a45e14f7750f50f340232388b69e6287859155f06a5ce2df76f12cb31cf languageName: node linkType: hard @@ -20054,13 +20255,74 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@npm%3A^6.0.3#optional!builtin": - version: 6.0.3 - resolution: "typescript@patch:typescript@npm%3A6.0.3#optional!builtin::version=6.0.3&hash=5786d5" +"typescript@patch:typescript@npm%3A^7.0.2#optional!builtin": + version: 7.0.2 + resolution: "typescript@patch:typescript@npm%3A7.0.2#optional!builtin::version=7.0.2&hash=3bafbf" + dependencies: + "@typescript/typescript-aix-ppc64": "npm:7.0.2" + "@typescript/typescript-darwin-arm64": "npm:7.0.2" + "@typescript/typescript-darwin-x64": "npm:7.0.2" + "@typescript/typescript-freebsd-arm64": "npm:7.0.2" + "@typescript/typescript-freebsd-x64": "npm:7.0.2" + "@typescript/typescript-linux-arm": "npm:7.0.2" + "@typescript/typescript-linux-arm64": "npm:7.0.2" + "@typescript/typescript-linux-loong64": "npm:7.0.2" + "@typescript/typescript-linux-mips64el": "npm:7.0.2" + "@typescript/typescript-linux-ppc64": "npm:7.0.2" + "@typescript/typescript-linux-riscv64": "npm:7.0.2" + "@typescript/typescript-linux-s390x": "npm:7.0.2" + "@typescript/typescript-linux-x64": "npm:7.0.2" + "@typescript/typescript-netbsd-arm64": "npm:7.0.2" + "@typescript/typescript-netbsd-x64": "npm:7.0.2" + "@typescript/typescript-openbsd-arm64": "npm:7.0.2" + "@typescript/typescript-openbsd-x64": "npm:7.0.2" + "@typescript/typescript-sunos-x64": "npm:7.0.2" + "@typescript/typescript-win32-arm64": "npm:7.0.2" + "@typescript/typescript-win32-x64": "npm:7.0.2" + dependenciesMeta: + "@typescript/typescript-aix-ppc64": + optional: true + "@typescript/typescript-darwin-arm64": + optional: true + "@typescript/typescript-darwin-x64": + optional: true + "@typescript/typescript-freebsd-arm64": + optional: true + "@typescript/typescript-freebsd-x64": + optional: true + "@typescript/typescript-linux-arm": + optional: true + "@typescript/typescript-linux-arm64": + optional: true + "@typescript/typescript-linux-loong64": + optional: true + "@typescript/typescript-linux-mips64el": + optional: true + "@typescript/typescript-linux-ppc64": + optional: true + "@typescript/typescript-linux-riscv64": + optional: true + "@typescript/typescript-linux-s390x": + optional: true + "@typescript/typescript-linux-x64": + optional: true + "@typescript/typescript-netbsd-arm64": + optional: true + "@typescript/typescript-netbsd-x64": + optional: true + "@typescript/typescript-openbsd-arm64": + optional: true + "@typescript/typescript-openbsd-x64": + optional: true + "@typescript/typescript-sunos-x64": + optional: true + "@typescript/typescript-win32-arm64": + optional: true + "@typescript/typescript-win32-x64": + optional: true bin: tsc: bin/tsc - tsserver: bin/tsserver - checksum: 10c0/2f25c74e65663c248fa1ade2b8459d9ce5372ff9dad07067310f132966ebec1d93f6c42f0baf77a6b6a7a91460463f708e6887013aaade22111037457c6b25df + checksum: 10c0/6b3cdc369cd829d46e00734ea64233ee84419c2825ad8fe408915adde77abced4b7a2401f7eed517d54a7a4f5d1c1869753cb99018df1c2159c761d9f33483a6 languageName: node linkType: hard From 6ac407de84cf32c0bd72f73f7c32da634a182d70 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 17:45:39 -0400 Subject: [PATCH 090/368] chore: Run server tests with a shared module registry (#13799) Adds a server-shared Vitest project with isolate disabled and moves every server test into it by default. Files that mock or reset modules opt out with a header marker and stay in the isolated project. Restores env values that leaked between files: the test URL is reset after each file, and tests that mutate env restore the previous value. The test server no longer closes the shared sequelize pool. --- AGENTS.md | 1 + package.json | 2 +- .../ConnectionLimitExtension.test.ts | 1 + server/commands/documentImporter.test.ts | 1 + server/converters/PdfConverter.test.ts | 1 + .../models/helpers/ProseMirrorHelper.test.ts | 1 + server/models/helpers/TextHelper.test.ts | 1 + server/onerror.test.ts | 1 + .../api/attachments/attachments.test.ts | 1 + server/routes/api/auth/auth.test.ts | 1 + .../api/fileOperations/fileOperations.test.ts | 1 + server/routes/api/urls/urls.test.ts | 1 + server/storage/files/BaseStorage.test.ts | 6 ++ .../files/S3Storage.cloudfront.test.ts | 1 + server/storage/files/presignedPut.test.ts | 1 + server/test/setup.ts | 9 +++ server/test/support.ts | 7 +-- server/utils/environment.test.ts | 1 + server/utils/url.test.ts | 4 +- vitest.config.ts | 58 +++++++++++++++---- 20 files changed, 81 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7618999693..0fe213fa37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,6 +168,7 @@ yarn test:shared # All shared code tests ``` - Write unit tests for utilities and business logic in a collocated .test.ts file. +- Server tests share a module registry between files. A server test that uses `vi.mock` or `vi.resetModules` must start with `// @vitest-isolate true` so it runs isolated. - Do not create new test directories - Mock external dependencies appropriately in **mocks** folder. - Aim for high code coverage but focus on critical paths. diff --git a/package.json b/package.json index 7574742858..9195488ed8 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "test": "TZ=UTC vitest run", "test:app": "TZ=UTC vitest run --project app", "test:shared": "TZ=UTC vitest run --project shared-node --project shared-jsdom", - "test:server": "TZ=UTC vitest run --project server", + "test:server": "TZ=UTC vitest run --project \"server*\"", "test:watch": "TZ=UTC vitest", "vite:dev": "VITE_CJS_IGNORE_WARNING=true vite", "vite:build": "VITE_CJS_IGNORE_WARNING=true vite build", diff --git a/server/collaboration/ConnectionLimitExtension.test.ts b/server/collaboration/ConnectionLimitExtension.test.ts index 60fd2aa538..7bee8b458d 100644 --- a/server/collaboration/ConnectionLimitExtension.test.ts +++ b/server/collaboration/ConnectionLimitExtension.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { Server } from "@hocuspocus/server"; import WebSocket from "ws"; import EDITOR_VERSION from "@shared/editor/version"; diff --git a/server/commands/documentImporter.test.ts b/server/commands/documentImporter.test.ts index b5bd20d9a7..695854cfc3 100644 --- a/server/commands/documentImporter.test.ts +++ b/server/commands/documentImporter.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import path from "node:path"; import fs from "fs-extra"; import { errToString } from "@shared/utils/error"; diff --git a/server/converters/PdfConverter.test.ts b/server/converters/PdfConverter.test.ts index 4720146ff9..66238eb312 100644 --- a/server/converters/PdfConverter.test.ts +++ b/server/converters/PdfConverter.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { PdfConverter } from "./PdfConverter"; const processPdf = vi.hoisted(() => vi.fn()); diff --git a/server/models/helpers/ProseMirrorHelper.test.ts b/server/models/helpers/ProseMirrorHelper.test.ts index aa55c6dec6..f51dc10118 100644 --- a/server/models/helpers/ProseMirrorHelper.test.ts +++ b/server/models/helpers/ProseMirrorHelper.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { faker } from "@faker-js/faker"; import { Node } from "prosemirror-model"; import type { DeepPartial } from "utility-types"; diff --git a/server/models/helpers/TextHelper.test.ts b/server/models/helpers/TextHelper.test.ts index 3259882332..a547d6f1f7 100644 --- a/server/models/helpers/TextHelper.test.ts +++ b/server/models/helpers/TextHelper.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { createContext } from "@server/context"; import { buildProseMirrorDoc, buildUser } from "@server/test/factories"; import { ProsemirrorHelper } from "./ProsemirrorHelper"; diff --git a/server/onerror.test.ts b/server/onerror.test.ts index c5357d728e..43a313800a 100644 --- a/server/onerror.test.ts +++ b/server/onerror.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import type Koa from "koa"; import { DatabaseError } from "sequelize"; import type { Mock } from "vitest"; diff --git a/server/routes/api/attachments/attachments.test.ts b/server/routes/api/attachments/attachments.test.ts index 7d001f7327..79cdf7d39e 100644 --- a/server/routes/api/attachments/attachments.test.ts +++ b/server/routes/api/attachments/attachments.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { randomUUID } from "node:crypto"; import { AttachmentPreset, CollectionPermission } from "@shared/types"; import env from "@server/env"; diff --git a/server/routes/api/auth/auth.test.ts b/server/routes/api/auth/auth.test.ts index 267caeea1e..21f256e6d6 100644 --- a/server/routes/api/auth/auth.test.ts +++ b/server/routes/api/auth/auth.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { faker } from "@faker-js/faker"; import { randomUUID } from "node:crypto"; import { Scope } from "@shared/types"; diff --git a/server/routes/api/fileOperations/fileOperations.test.ts b/server/routes/api/fileOperations/fileOperations.test.ts index ab82128bdb..d67cb70af8 100644 --- a/server/routes/api/fileOperations/fileOperations.test.ts +++ b/server/routes/api/fileOperations/fileOperations.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { CollectionPermission, FileOperationState, diff --git a/server/routes/api/urls/urls.test.ts b/server/routes/api/urls/urls.test.ts index 0e162728f6..dd41378a42 100644 --- a/server/routes/api/urls/urls.test.ts +++ b/server/routes/api/urls/urls.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import type { Mock } from "vitest"; import { randomString } from "@shared/random"; import { UnfurlResourceType } from "@shared/types"; diff --git a/server/storage/files/BaseStorage.test.ts b/server/storage/files/BaseStorage.test.ts index f0e45a0bdb..8d94d65ecf 100644 --- a/server/storage/files/BaseStorage.test.ts +++ b/server/storage/files/BaseStorage.test.ts @@ -145,12 +145,18 @@ describe("BaseStorage", () => { describe("storeFromUrl", () => { let storage: MockStorage; + const originalMaxSize = env.FILE_STORAGE_UPLOAD_MAX_SIZE; + beforeEach(() => { storage = new MockStorage(); storage.storedFiles = []; env.FILE_STORAGE_UPLOAD_MAX_SIZE = 500; }); + afterEach(() => { + env.FILE_STORAGE_UPLOAD_MAX_SIZE = originalMaxSize; + }); + describe("base64 URL size validation", () => { it("should enforce maxUploadSize option for base64 URLs", async () => { const largeDataSize = 1000; diff --git a/server/storage/files/S3Storage.cloudfront.test.ts b/server/storage/files/S3Storage.cloudfront.test.ts index b6204b4bfe..c4f518e0d1 100644 --- a/server/storage/files/S3Storage.cloudfront.test.ts +++ b/server/storage/files/S3Storage.cloudfront.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import type S3Storage from "./S3Storage"; const { mockEnv, mockGetS3SignedUrl, mockGetCloudFrontSignedUrl } = vi.hoisted( diff --git a/server/storage/files/presignedPut.test.ts b/server/storage/files/presignedPut.test.ts index ca544e1318..806c61eba0 100644 --- a/server/storage/files/presignedPut.test.ts +++ b/server/storage/files/presignedPut.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import { AttachmentPreset } from "@shared/types"; import env from "@server/env"; import { buildUser, buildDocument } from "@server/test/factories"; diff --git a/server/test/setup.ts b/server/test/setup.ts index 1f7bc08a82..9e7bbfa320 100644 --- a/server/test/setup.ts +++ b/server/test/setup.ts @@ -69,6 +69,15 @@ void pluginModules; const { BaseTask: BaseTaskClass } = await import("@server/queues/tasks/base/BaseTask"); +// Module-level code in a test file, such as building the web service, must +// see the same environment whether or not the module registry is shared with +// the previous file in the worker, so the URL is restored after each file. +const defaultUrl = env.URL; + +afterAll(() => { + env.URL = sharedEnv.URL = defaultUrl; +}); + beforeEach(() => { env.URL = sharedEnv.URL = "https://app.outline.dev"; diff --git a/server/test/support.ts b/server/test/support.ts index 66c0a1b350..bc369331b1 100644 --- a/server/test/support.ts +++ b/server/test/support.ts @@ -24,12 +24,7 @@ export function getTestServer() { onerror(app); const server = new TestServer(app); - const disconnect = async () => { - await sequelize.close(); - return server.close(); - }; - - afterAll(disconnect); + afterAll(() => server.close()); return server; } diff --git a/server/utils/environment.test.ts b/server/utils/environment.test.ts index 81ff2f6b44..bbc639bc61 100644 --- a/server/utils/environment.test.ts +++ b/server/utils/environment.test.ts @@ -1,3 +1,4 @@ +// @vitest-isolate true import fs from "node:fs"; import os from "node:os"; import path from "node:path"; diff --git a/server/utils/url.test.ts b/server/utils/url.test.ts index 2629a91efc..3c8c67ec93 100644 --- a/server/utils/url.test.ts +++ b/server/utils/url.test.ts @@ -5,15 +5,17 @@ import { isInvalidAppPath, validateUrlNotPrivate } from "./url"; describe("validateUrlNotPrivate", () => { let lookupSpy: MockInstance; + const originalAllowedPrivateIps = env.ALLOWED_PRIVATE_IP_ADDRESSES; beforeEach(() => { + env.ALLOWED_PRIVATE_IP_ADDRESSES = undefined; lookupSpy = vi.spyOn(dns.promises, "lookup"); lookupSpy.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]); }); afterEach(() => { lookupSpy.mockRestore(); - env.ALLOWED_PRIVATE_IP_ADDRESSES = undefined; + env.ALLOWED_PRIVATE_IP_ADDRESSES = originalAllowedPrivateIps; }); it("should allow public IP addresses", async () => { diff --git a/vitest.config.ts b/vitest.config.ts index bc729ac2e0..7428658199 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,6 +1,8 @@ +import fs from "node:fs"; import path from "node:path"; +import { globSync } from "glob"; import swc from "unplugin-swc"; -import { defineConfig } from "vitest/config"; +import { configDefaults, defineConfig } from "vitest/config"; // SSL_CERT_FILE is OpenSSL's CA bundle variable and may be present in the // host environment running the tests; clear it so it is not resolved into @@ -54,6 +56,38 @@ const aliasesAsArray = Object.entries(aliases).map(([find, replacement]) => ({ const fileMockAlias = { find: /\.(gif|ttf|eot|svg)$/, replacement: fileMock }; +const serverTestFiles = [ + "server/**/*.test.{ts,tsx}", + "plugins/**/*.test.{ts,tsx}", +]; + +// Server tests share a module registry between files in a worker. A file that +// mocks or resets modules must opt out with this marker in its header so it +// runs isolated. +const ISOLATED_MARKER = "@vitest-isolate true"; + +const isolatedServerTestFiles = globSync(serverTestFiles, { + cwd: __dirname, + posix: true, +}).filter((file) => { + const header = fs + .readFileSync(path.join(__dirname, file), "utf8") + .slice(0, 512); + return header.includes(ISOLATED_MARKER); +}); + +const serverTestConfig = { + globals: true, + environment: "node" as const, + setupFiles: [ + "./__mocks__/console.js", + "./server/test/setupMocks.ts", + "./server/test/setup.ts", + ], + globalSetup: ["./server/test/globalTeardown.ts"], + fileParallelism: true, +}; + export default defineConfig({ ...sharedConfig, test: { @@ -65,17 +99,19 @@ export default defineConfig({ { ...sharedConfig, test: { + ...serverTestConfig, name: "server", - globals: true, - environment: "node", - include: ["server/**/*.test.{ts,tsx}", "plugins/**/*.test.{ts,tsx}"], - setupFiles: [ - "./__mocks__/console.js", - "./server/test/setupMocks.ts", - "./server/test/setup.ts", - ], - globalSetup: ["./server/test/globalTeardown.ts"], - fileParallelism: true, + include: isolatedServerTestFiles, + }, + }, + { + ...sharedConfig, + test: { + ...serverTestConfig, + name: "server-shared", + include: serverTestFiles, + exclude: [...configDefaults.exclude, ...isolatedServerTestFiles], + isolate: false, }, }, { From f0f85535218cfb06d09c238e02a99621893661bd Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 17:52:16 -0400 Subject: [PATCH 091/368] feat: Section header menus in the sidebar (#13801) * wip * feat: Share sidebar actions overlay between headers and links, add quick create button --- .../Sidebar/components/Collections.tsx | 9 +- .../Sidebar/components/DraggableSection.tsx | 124 +++++++++++++++++- app/components/Sidebar/components/Header.tsx | 111 +++++++++++++--- .../Sidebar/components/SidebarActions.tsx | 76 +++++++++++ .../Sidebar/components/SidebarLink.tsx | 75 ++--------- shared/i18n/locales/en_US/translation.json | 5 +- 6 files changed, 308 insertions(+), 92 deletions(-) create mode 100644 app/components/Sidebar/components/SidebarActions.tsx diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx index e215dbbef9..a15b7d598b 100644 --- a/app/components/Sidebar/components/Collections.tsx +++ b/app/components/Sidebar/components/Collections.tsx @@ -22,6 +22,8 @@ import SidebarLink from "./SidebarLink"; import Text from "@shared/components/Text"; import usePolicy from "~/hooks/usePolicy"; +const headerActions = [createCollection]; + function Collections() { const { documents, auth, collections, policies } = useStores(); const { t } = useTranslation(); @@ -58,7 +60,12 @@ function Collections() { return ( -
+
options={params} diff --git a/app/components/Sidebar/components/DraggableSection.tsx b/app/components/Sidebar/components/DraggableSection.tsx index b4a634f8bc..7b8d68dcf7 100644 --- a/app/components/Sidebar/components/DraggableSection.tsx +++ b/app/components/Sidebar/components/DraggableSection.tsx @@ -1,10 +1,21 @@ import { observer } from "mobx-react"; -import { createContext, useEffect, useState, type ReactNode } from "react"; +import { + createContext, + useCallback, + useEffect, + useMemo, + useState, + type ReactNode, +} from "react"; import type { ConnectDragSource } from "react-dnd"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { SidebarSection, UserPreference } from "@shared/types"; +import { createAction } from "~/actions"; +import { NavigationSection } from "~/actions/sections"; +import { ArrowDownIcon, ArrowUpIcon } from "~/components/Icons/ArrowIcon"; import useCurrentUser from "~/hooks/useCurrentUser"; +import type { Action } from "~/types"; import { useDragSidebarSection, useDropToReorderSidebarSection, @@ -12,11 +23,19 @@ import { import DropCursor from "./DropCursor"; import Section from "./Section"; +type SidebarSectionContextValue = { + /** Drag connector so the section header can register as the drag handle. */ + dragRef: ConnectDragSource; + /** Actions offered in the section header's context menu. */ + menuActions: Action[]; +}; + /** - * Carries the drag connector for a sidebar section so the section header can - * register itself as the drag handle. + * Carries the drag connector and the context menu actions for a sidebar + * section to its header. */ -export const SectionDragContext = createContext(null); +export const SidebarSectionContext = + createContext(null); /** * Normalizes a persisted sidebar section order — unknown values and @@ -64,6 +83,16 @@ export function moveSidebarSection( return result.every((s, i) => s === order[i]) ? undefined : result; } +/** + * Type guard for sidebar section identifiers. + * + * @param value The value to check. + * @returns true if the value names a sidebar section. + */ +function isSidebarSection(value: string): value is SidebarSection { + return Object.values(SidebarSection).includes(value); +} + type Props = { /** The section being rendered. */ section: SidebarSection; @@ -89,6 +118,82 @@ function DraggableSection({ section, children }: Props) { user.getPreference(UserPreference.SidebarSectionOrder, []) ); + const [wrapper, setWrapper] = useState(null); + + // Hidden sections are collapsed with CSS, so the nearest visible neighbour + // is read from the DOM rather than from the persisted order. + const findVisibleSibling = useCallback( + (direction: "previous" | "next"): SidebarSection | undefined => { + let element = + direction === "previous" + ? wrapper?.previousElementSibling + : wrapper?.nextElementSibling; + + while (element instanceof HTMLElement) { + const sibling = element.dataset.section; + if ( + sibling && + isSidebarSection(sibling) && + getComputedStyle(element).display !== "none" + ) { + return sibling; + } + element = + direction === "previous" + ? element.previousElementSibling + : element.nextElementSibling; + } + + return undefined; + }, + [wrapper] + ); + + const handleMove = useCallback( + (direction: "previous" | "next") => { + const target = findVisibleSibling(direction); + if (!target) { + return; + } + + const newOrder = moveSidebarSection( + normalizeSidebarSectionOrder( + user.getPreference(UserPreference.SidebarSectionOrder, []) + ), + section, + direction === "previous" ? "before" : "after", + target + ); + if (newOrder) { + user.setPreference(UserPreference.SidebarSectionOrder, newOrder); + void user.save(); + } + }, + [findVisibleSibling, section, user] + ); + + const menuActions = useMemo( + () => [ + createAction({ + name: ({ t }) => t("Move up"), + analyticsName: "Move sidebar section up", + section: NavigationSection, + icon: , + visible: () => !!findVisibleSibling("previous"), + perform: () => handleMove("previous"), + }), + createAction({ + name: ({ t }) => t("Move down"), + analyticsName: "Move sidebar section down", + section: NavigationSection, + icon: , + visible: () => !!findVisibleSibling("next"), + perform: () => handleMove("next"), + }), + ], + [findVisibleSibling, handleMove] + ); + const [{ isDragging }, dragRef] = useDragSidebarSection( section, titles[section] @@ -106,8 +211,13 @@ function DraggableSection({ section, children }: Props) { const showCursors = useDeferredFlag(bottomProps.isDragging); const isDraggingDeferred = useDeferredFlag(isDragging); + const contextValue = useMemo( + () => ({ dragRef, menuActions }), + [dragRef, menuActions] + ); + return ( - + {showCursors && ( )} - + {children} - + {showCursors && ( = ({ id, title, children }: Props) => { +export const Header: React.FC = ({ + id, + title, + actions, + primaryAction, + children, +}: Props) => { + const { t } = useTranslation(); + const actionContext = useActionContext({ isButton: true }); const [firstRender, setFirstRender] = React.useState(true); - const dragRef = React.useContext(SectionDragContext); + const sectionContext = React.useContext(SidebarSectionContext); + const sectionActions = sectionContext?.menuActions; + const hasMenu = !!(actions?.length || sectionActions?.length); + + // Dangling separators are trimmed when the menu items are rendered. + const menuAction = React.useMemo( + () => + createRootMenuAction([ + ...(actions ?? []), + ActionSeparator, + ...(sectionActions ?? []), + ]), + [actions, sectionActions] + ); const [expanded, setExpanded] = usePersistedState( getHeaderExpandedKey(id ?? ""), true @@ -40,12 +78,40 @@ export const Header: React.FC = ({ id, title, children }: Props) => { return ( <> -

- -

+ +

+ + {hasMenu && ( + + {primaryAction && ( + (primaryAction.name, actionContext), + delay: 500, + }} + > + {resolve(primaryAction.icon, actionContext)} + + )} + + + + + )} +

+
{expanded && (firstRender ? children : {children})} ); @@ -79,7 +145,7 @@ const Button = styled.button` letter-spacing: 0.03em; margin: 0; padding-block: 4px; - padding-inline: 12px 2px; + padding-inline: 12px 32px; border: 0; background: none; border-radius: 4px; @@ -87,16 +153,9 @@ const Button = styled.button` transition: all 100ms ease; ${undraggableOnDesktop()} - &:not(:disabled):hover, - &:not(:disabled):active { - background: ${s("sidebarHoverBackground")}; + &:not(:disabled) { cursor: var(--pointer); - } - - @media (hover: hover) { - &:not(:disabled):hover { - color: ${s("text")}; - } + background: var(--background); } `; @@ -114,14 +173,26 @@ const Disclosure = styled(CollapsedIcon)<{ $expanded?: boolean }>` `; const H3 = styled.h3` + position: relative; margin: 0; + ${revealActionsOnHover} - &:hover, + ${hoveredOrMenuOpen}, &:focus-within { + --background: ${s("sidebarHoverBackground")}; + ${Disclosure} { opacity: 1; } } + + @media (hover: hover) { + ${hoveredOrMenuOpen} { + ${Button}:not(:disabled) { + color: ${s("text")}; + } + } + } `; export default Header; diff --git a/app/components/Sidebar/components/SidebarActions.tsx b/app/components/Sidebar/components/SidebarActions.tsx new file mode 100644 index 0000000000..aa305f6134 --- /dev/null +++ b/app/components/Sidebar/components/SidebarActions.tsx @@ -0,0 +1,76 @@ +import styled, { css } from "styled-components"; +import EventBoundary from "@shared/components/EventBoundary"; +import { s } from "@shared/styles"; +import NudeButton from "~/components/NudeButton"; + +/** + * Selector list matching a sidebar row that is hovered, pressed, or has one + * of its menus open. Radix marks the open trigger with `data-state="open"`: + * the row itself for a context menu, a descendant button for a dropdown. + */ +export const hoveredOrMenuOpen = `&:hover, &:active, &[data-state="open"], &:has([data-state="open"])`; + +/** + * Trailing action buttons for a sidebar row. Hidden until the row reveals + * them, see `revealActionsOnHover`. The parent must be positioned. + */ +export const SidebarActions = styled(EventBoundary)<{ + $showActions?: boolean; +}>` + display: inline-flex; + visibility: ${(props) => (props.$showActions ? "visible" : "hidden")}; + position: absolute; + inset-block: 0; + inset-inline-end: 4px; + margin-block: auto; + height: 24px; + color: ${s("textTertiary")}; + background: var(--background); + transition: opacity 50ms; + + [data-drag-active] & { + display: none; + } + + svg { + color: ${s("textSecondary")}; + fill: currentColor; + opacity: 0.5; + } + + &:hover { + visibility: visible; + + svg { + opacity: 0.75; + } + } + + ${NudeButton} { + background: transparent; + + &:hover, + &[aria-expanded="true"] { + background: ${s("sidebarControlHoverBackground")}; + } + } +`; + +/** + * Mixin for a sidebar row that reveals its `SidebarActions` while hovered, + * focused, or while one of its menus is open. + */ +export const revealActionsOnHover = css` + @media (hover: hover) { + ${hoveredOrMenuOpen}, + &:focus-within { + ${SidebarActions} { + visibility: visible; + + svg { + opacity: 0.75; + } + } + } + } +`; diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 7b1e24a376..35ac4f5ae7 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -2,16 +2,19 @@ import type { LocationDescriptor } from "history"; import * as React from "react"; import styled, { useTheme, css } from "styled-components"; import breakpoint from "styled-components-breakpoint"; -import EventBoundary from "@shared/components/EventBoundary"; import { ellipsis, hover, s } from "@shared/styles"; import { isMobile } from "@shared/utils/browser"; -import NudeButton from "~/components/NudeButton"; import { UnreadBadge } from "~/components/UnreadBadge"; import useClickIntent from "~/hooks/useClickIntent"; import { undraggableOnDesktop } from "~/styles"; import Disclosure from "./Disclosure"; import type { Props as NavLinkProps } from "./NavLink"; import NavLink from "./NavLink"; +import { + SidebarActions, + hoveredOrMenuOpen, + revealActionsOnHover, +} from "./SidebarActions"; import type { ActionFactory, ActionWithChildren } from "~/types"; import { ContextMenu } from "~/components/Menu/ContextMenu"; import { useTranslation } from "react-i18next"; @@ -177,7 +180,9 @@ function SidebarLink( {unreadBadge && } - {menu && {menu}} + {menu && ( + {menu} + )} ); @@ -245,38 +250,6 @@ const Content = styled.span` min-width: 0; `; -const Actions = styled(EventBoundary)<{ $showActions?: boolean }>` - display: inline-flex; - visibility: ${(props) => (props.$showActions ? "visible" : "hidden")}; - - [data-drag-active] & { - display: none; - } - - position: absolute; - top: 3px; - inset-inline-end: 4px; - gap: 4px; - color: ${s("textTertiary")}; - transition: opacity 50ms; - height: 24px; - background: var(--background); - - svg { - color: ${s("textSecondary")}; - fill: currentColor; - opacity: 0.5; - } - - &:hover { - visibility: visible; - - svg { - opacity: 0.75; - } - } -`; - const HiddenDisclosure = styled(Disclosure)` position: inherit; inset-inline-start: initial; @@ -290,13 +263,11 @@ const Link = styled(NavLink)<{ $isDraft?: boolean; $disabled?: boolean; }>` - &:hover, - &:active, - &:has([data-state="open"]) { + ${hoveredOrMenuOpen} { --background: ${s("sidebarHoverBackground")}; } - &[aria-current="page"] ${Actions} { + &[aria-current="page"] ${SidebarActions} { --background: ${s("sidebarActiveBackground")}; } @@ -364,34 +335,14 @@ const Link = styled(NavLink)<{ font-size: 14px; `} + ${revealActionsOnHover} + @media (hover: hover) { - &:hover ${Actions}, - &:active ${Actions}, - &:has([data-state="open"]) ${Actions} { - visibility: visible; - - svg { - opacity: 0.75; - } - } - - &:hover, - &:has([data-state="open"]) { + ${hoveredOrMenuOpen} { color: ${(props) => props.$isActiveDrop ? props.theme.white : props.theme.text}; } } - - & ${Actions} { - ${NudeButton} { - background: transparent; - - &:hover, - &[aria-expanded="true"] { - background: ${s("sidebarControlHoverBackground")}; - } - } - } `; const Label = styled.div<{ $ellipsis: boolean }>` diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 667bb7b54f..7871ba232a 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -619,7 +619,10 @@ "Hide": "Hide", "Starred": "Starred", "Shared with me": "Shared with me", + "Move up": "Move up", + "Move down": "Move down", "Import files": "Import files", + "Section options": "Section options", "Recent": "Recent", "Go back": "Go back", "Go forward": "Go forward", @@ -786,8 +789,6 @@ "Insert before": "Insert before", "Move left": "Move left", "Move right": "Move right", - "Move up": "Move up", - "Move down": "Move down", "Could not import file": "Could not import file", "Unsubscribed from document": "Unsubscribed from document", "Unsubscribed from collection": "Unsubscribed from collection", From ed7a1e9ffc1c14657a84638b0cf624c247fd63a7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 17:52:22 -0400 Subject: [PATCH 092/368] fix: Validate custom theme colors (#13800) --- app/hooks/useBuildTheme.ts | 25 +++++++++++++++------ server/routes/api/teams/schema.ts | 5 +++-- server/routes/api/teams/teams.test.ts | 31 +++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/app/hooks/useBuildTheme.ts b/app/hooks/useBuildTheme.ts index 1d1842f847..054c924da7 100644 --- a/app/hooks/useBuildTheme.ts +++ b/app/hooks/useBuildTheme.ts @@ -1,3 +1,4 @@ +import { pickBy } from "es-toolkit"; import { useEffect, useMemo } from "react"; import { breakpoints } from "@shared/styles"; import { @@ -6,6 +7,7 @@ import { buildPitchBlackTheme, } from "@shared/styles/theme"; import type { CustomTheme } from "@shared/types"; +import { validateColorHex } from "@shared/utils/color"; import { Theme } from "~/stores/UiStore"; import useMediaQuery from "~/hooks/useMediaQuery"; import useStores from "./useStores"; @@ -41,18 +43,29 @@ export default function useBuildTheme( const resolvedTheme = overrideTheme ?? ui.resolvedTheme; + // Drop any stored color that is not valid hex so a bad value cannot break rendering. + const safeTheme = useMemo( + () => + pickBy( + customTheme, + (value): value is string => + typeof value === "string" && validateColorHex(value) + ), + [customTheme] + ); + const theme = useMemo( () => isPrinting - ? buildLightTheme(customTheme) + ? buildLightTheme(safeTheme) : isMobile ? resolvedTheme === "dark" - ? buildPitchBlackTheme(customTheme) - : buildLightTheme(customTheme) + ? buildPitchBlackTheme(safeTheme) + : buildLightTheme(safeTheme) : resolvedTheme === "dark" - ? buildDarkTheme(customTheme) - : buildLightTheme(customTheme), - [customTheme, isMobile, isPrinting, resolvedTheme] + ? buildDarkTheme(safeTheme) + : buildLightTheme(safeTheme), + [safeTheme, isMobile, isPrinting, resolvedTheme] ); return theme; diff --git a/server/routes/api/teams/schema.ts b/server/routes/api/teams/schema.ts index e7fb51db0e..1f3439f26f 100644 --- a/server/routes/api/teams/schema.ts +++ b/server/routes/api/teams/schema.ts @@ -6,6 +6,7 @@ import { TOCPosition, UserRole, } from "@shared/types"; +import { validateColorHex } from "@shared/utils/color"; import { TeamValidation } from "@shared/validations"; import { BaseSchema } from "@server/routes/api/schema"; @@ -63,8 +64,8 @@ export const TeamsUpdateSchema = BaseSchema.extend({ /** The custom theme for the team. */ [TeamPreference.CustomTheme]: z .strictObject({ - accent: z.string().min(4).max(7).regex(/^#/), - accentText: z.string().min(4).max(7).regex(/^#/), + accent: z.string().min(4).max(7).refine(validateColorHex), + accentText: z.string().min(4).max(7).refine(validateColorHex), }) .partial(), /** Side to display the document's table of contents in relation to the main content. */ diff --git a/server/routes/api/teams/teams.test.ts b/server/routes/api/teams/teams.test.ts index e3152d5b62..1bd39d535d 100644 --- a/server/routes/api/teams/teams.test.ts +++ b/server/routes/api/teams/teams.test.ts @@ -91,6 +91,37 @@ describe("#team.update", () => { expect(res.status).toEqual(400); }); + it("should fail upon sending an invalid custom theme color", async () => { + const admin = await buildAdmin(); + const res = await server.post("/api/team.update", admin, { + body: { + preferences: { + customTheme: { + accent: "#qqqq", + }, + }, + }, + }); + expect(res.status).toEqual(400); + }); + + it("should accept a valid custom theme color", async () => { + const admin = await buildAdmin(); + const res = await server.post("/api/team.update", admin, { + body: { + preferences: { + customTheme: { + accent: "#0366d6", + accentText: "#fff", + }, + }, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.preferences.customTheme.accent).toEqual("#0366d6"); + }); + it("should add avatar", async () => { const team = await buildTeam(); const admin = await buildAdmin({ teamId: team.id }); From b57d02c4fc34bc94740a6397115e40bdba0f2f74 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 18:28:26 -0400 Subject: [PATCH 093/368] fix: Enforce maxLength for all input paths in `ContentEditable` (#13793) * fix: Enforce maxLength on paste, drop and IME input in ContentEditable * fix: Count code points and hold over-limit change during IME composition --- app/components/ContentEditable.tsx | 76 ++++++++++++++++++++++++++++-- shared/utils/TextHelper.test.ts | 26 ++++++++++ shared/utils/TextHelper.ts | 23 +++++++++ 3 files changed, 121 insertions(+), 4 deletions(-) diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 20b3948e81..14cd0ddf97 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -2,6 +2,7 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { TextHelper } from "@shared/utils/TextHelper"; import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { @@ -13,6 +14,7 @@ type Props = Omit, "ref" | "onChange"> & { onBlur?: React.FocusEventHandler | undefined; onInput?: React.FormEventHandler | undefined; onKeyDown?: React.KeyboardEventHandler | undefined; + onCompositionEnd?: React.CompositionEventHandler | undefined; placeholder?: string; maxLength?: number; autoFocus?: boolean; @@ -39,6 +41,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onFocus, onBlur, onKeyDown, + onCompositionEnd, value, children, className, @@ -95,18 +98,32 @@ const ContentEditable = React.forwardRef(function ContentEditable_( return; } - const text = event.currentTarget.textContent || ""; + let text = event.currentTarget.textContent || ""; + const overLimit = + !!maxLength && TextHelper.codePointLength(text) > maxLength; if ( maxLength && event.nativeEvent instanceof KeyboardEvent && isPrintableKeyEvent(event.nativeEvent) && - text.length >= maxLength + TextHelper.codePointLength(text) >= maxLength ) { event.preventDefault(); return; } + // Paste, drop, IME and other non-keyboard input paths bypass the check + // above, so clamp whatever landed in the DOM. Editing the DOM would + // break an active IME session, so wait for composition end and do not + // publish the over-limit buffer in the meantime. + if (overLimit && maxLength) { + if (isComposing(event)) { + callback?.(event); + return; + } + text = truncateContent(event.currentTarget, maxLength); + } + if (text !== lastValue.current) { lastValue.current = text; onChange?.(text); @@ -146,10 +163,21 @@ const ContentEditable = React.forwardRef(function ContentEditable_( const handlePaste = React.useCallback( (event: React.ClipboardEvent) => { event.preventDefault(); - const text = event.clipboardData.getData("text/plain"); + let text = event.clipboardData.getData("text/plain"); + + if (maxLength) { + const current = event.currentTarget.textContent || ""; + const selected = window.getSelection()?.toString() || ""; + const remaining = + maxLength - + (TextHelper.codePointLength(current) - + TextHelper.codePointLength(selected)); + text = TextHelper.truncate(text, remaining); + } + window.document.execCommand("insertText", false, text); }, - [] + [maxLength] ); const contentEditable = !disabled && !readOnly; @@ -163,6 +191,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onFocus={wrappedEvent(onFocus)} onBlur={wrappedEvent(onBlur)} onKeyDown={wrappedEvent(onKeyDown)} + onCompositionEnd={wrappedEvent(onCompositionEnd)} onPaste={handlePaste} data-placeholder={placeholder} suppressContentEditableWarning @@ -175,6 +204,45 @@ const ContentEditable = React.forwardRef(function ContentEditable_( ); }); +function isComposing(event: React.SyntheticEvent) { + const native = event.nativeEvent; + return ( + (native instanceof InputEvent || native instanceof KeyboardEvent) && + native.isComposing + ); +} + +/** + * Truncates the text content of an element to the given number of code points + * while keeping the caret at its current position where possible. + */ +function truncateContent(element: HTMLElement, maxLength: number): string { + const selection = window.getSelection(); + const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined; + let offset = Number.MAX_SAFE_INTEGER; + + if (range && element.contains(range.startContainer)) { + const before = range.cloneRange(); + before.selectNodeContents(element); + before.setEnd(range.startContainer, range.startOffset); + offset = before.toString().length; + } + + const text = TextHelper.truncate(element.textContent || "", maxLength); + element.textContent = text; + + const textNode = element.firstChild; + if (textNode && selection) { + const caret = document.createRange(); + caret.setStart(textNode, Math.min(offset, text.length)); + caret.collapse(true); + selection.removeAllRanges(); + selection.addRange(caret); + } + + return text; +} + function placeCaret(element: HTMLElement, atStart: boolean) { if ( typeof window.getSelection !== "undefined" && diff --git a/shared/utils/TextHelper.test.ts b/shared/utils/TextHelper.test.ts index bdbbab52ed..745f21b0e8 100644 --- a/shared/utils/TextHelper.test.ts +++ b/shared/utils/TextHelper.test.ts @@ -28,4 +28,30 @@ describe("TextHelper", () => { expect(result).toBe("Hello January 1, 2021"); }); }); + + describe("codePointLength", () => { + it("should count code points rather than UTF-16 units", () => { + expect(TextHelper.codePointLength("abc")).toBe(3); + expect(TextHelper.codePointLength("😀")).toBe(1); + expect(TextHelper.codePointLength("a😀b")).toBe(3); + expect(TextHelper.codePointLength("")).toBe(0); + }); + }); + + describe("truncate", () => { + it("should not split surrogate pairs", () => { + expect(TextHelper.truncate("😀", 1)).toBe("😀"); + expect(TextHelper.truncate("a😀b", 2)).toBe("a😀"); + expect(TextHelper.truncate("abc", 2)).toBe("ab"); + }); + + it("should return the text unchanged when within the limit", () => { + expect(TextHelper.truncate("abc", 5)).toBe("abc"); + }); + + it("should return an empty string for a non-positive limit", () => { + expect(TextHelper.truncate("abc", 0)).toBe(""); + expect(TextHelper.truncate("abc", -1)).toBe(""); + }); + }); }); diff --git a/shared/utils/TextHelper.ts b/shared/utils/TextHelper.ts index 39987f7c16..6b14aeb7c4 100644 --- a/shared/utils/TextHelper.ts +++ b/shared/utils/TextHelper.ts @@ -29,4 +29,27 @@ export class TextHelper { .replace(/{datetime}/g, getCurrentDateTimeAsString(locales)) .replace(/{author}/g, user.name); } + + /** + * Returns the length of the text in Unicode code points rather than UTF-16 + * code units, matching the server-side length validation. + * + * @param text The text to measure + * @returns The number of code points in the text + */ + static codePointLength(text: string): number { + return Array.from(text).length; + } + + /** + * Truncates the text to a maximum number of Unicode code points without + * splitting surrogate pairs. + * + * @param text The text to truncate + * @param maxLength The maximum number of code points to keep + * @returns The truncated text + */ + static truncate(text: string, maxLength: number): string { + return Array.from(text).slice(0, Math.max(0, maxLength)).join(""); + } } From 7f00defd626c5dbe3afc5f7da9d0b0202a7ba650 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 21:09:35 -0400 Subject: [PATCH 094/368] feat: Add archive and deletion reasons (#13784) * feat: Add reasons for archived and deleted documents * feat: Add deprecation reasons to archived collections * fix: Refine deprecation reason display for readers * feat: Accept reasons when archiving or deleting * Support reasons in archive and delete MCP tools * Fix placeholder after clearing content editable text * Keep the caret before content editable placeholders * Remove test * feat: Add archive reasons to the confirmation dialog --- app/actions/definitions/documents.tsx | 19 +- app/components/ContentEditable.tsx | 22 +- app/components/DeprecatedReason.tsx | 93 ++++++ app/components/DeprecationNotice.tsx | 15 + app/components/DocumentArchiveDialog.tsx | 53 ++++ app/components/Notice.tsx | 3 +- app/models/Collection.ts | 4 + app/models/Document.ts | 13 +- app/scenes/Collection/components/Notices.tsx | 12 +- app/scenes/Document/components/Notices.tsx | 17 +- app/stores/DocumentsStore.ts | 10 +- server/commands/documentUpdater.ts | 19 +- ...ted-reason-to-documents-and-collections.js | 23 ++ server/models/Collection.test.ts | 23 ++ server/models/Collection.ts | 43 ++- server/models/Document.test.ts | 32 +++ server/models/Document.ts | 13 +- server/policies/collection.ts | 10 + server/policies/document.ts | 7 + server/presenters/collection.ts | 1 + server/presenters/document.ts | 1 + .../api/collections/collections.test.ts | 253 ++++++++++++++++- server/routes/api/collections/collections.ts | 39 ++- server/routes/api/collections/schema.ts | 25 +- server/routes/api/documents/documents.test.ts | 268 +++++++++++++++++- server/routes/api/documents/documents.ts | 28 +- server/routes/api/documents/schema.ts | 24 +- server/tools/collections.test.ts | 107 +++++++ server/tools/collections.ts | 64 +++-- server/tools/documents.test.ts | 121 ++++++++ server/tools/documents.ts | 64 +++-- shared/i18n/locales/en_US/translation.json | 9 +- shared/validations.ts | 5 + 33 files changed, 1348 insertions(+), 92 deletions(-) create mode 100644 app/components/DeprecatedReason.tsx create mode 100644 app/components/DeprecationNotice.tsx create mode 100644 app/components/DocumentArchiveDialog.tsx create mode 100644 server/migrations/20260917003126-add-deprecated-reason-to-documents-and-collections.js diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index fee4f951fb..15015c2e58 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -62,6 +62,7 @@ import DocumentPublish from "~/scenes/DocumentPublish"; import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInTrash"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import { DialogTitle } from "~/components/DialogTitle"; +import { DocumentArchiveDialog } from "~/components/DocumentArchiveDialog"; import DocumentCopy from "~/components/DocumentExplorer/DocumentCopy"; import MarkdownIcon from "~/components/Icons/MarkdownIcon"; import { ImportDocumentDialog } from "~/components/ImportDocumentDialog"; @@ -1464,10 +1465,11 @@ export const archiveDocument = createAction({ }) ), content: ( - { + { const succeeded = await performBatch(documents, (document) => - document.archive() + document.archive({ reason }) ); if (succeeded) { toast.success( @@ -1477,16 +1479,7 @@ export const archiveDocument = createAction({ ); } }} - savingText={`${t("Archiving")}…`} - > - {documents.length === 1 - ? t( - "Archiving this document will remove it from the collection and search results." - ) - : t( - "Archiving these documents will remove them from their collections and search results." - )} - + /> ), }); }, diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 14cd0ddf97..a5f3109c2a 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -57,6 +57,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( ) { const contentRef = React.useRef(null); const [innerValue, setInnerValue] = React.useState(value); + const [isEmpty, setIsEmpty] = React.useState(value.length === 0); const lastValue = React.useRef(value); React.useImperativeHandle(ref, () => ({ @@ -99,6 +100,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( } let text = event.currentTarget.textContent || ""; + setIsEmpty(text.length === 0); const overLimit = !!maxLength && TextHelper.codePointLength(text) > maxLength; @@ -145,8 +147,17 @@ const ContentEditable = React.forwardRef(function ContentEditable_( }, [autoFocus, disabled, isVisible, readOnly, contentRef]); React.useEffect(() => { - if (contentRef.current && value !== contentRef.current.textContent) { - if (document.activeElement === contentRef.current) { + if (!contentRef.current) { + return; + } + + const isFocused = document.activeElement === contentRef.current; + setIsEmpty( + isFocused ? !contentRef.current.textContent : value.length === 0 + ); + + if (value !== contentRef.current.textContent) { + if (isFocused) { // Don't reset content while the user is actively editing. Update // lastValue so that the next input or blur event will push the // current DOM text back to the model via onChange. @@ -194,6 +205,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onCompositionEnd={wrappedEvent(onCompositionEnd)} onPaste={handlePaste} data-placeholder={placeholder} + data-empty={isEmpty} suppressContentEditableWarning role={contentEditable ? "textbox" : undefined} {...rest} @@ -266,12 +278,14 @@ const Content = styled.span` cursor: text; word-break: anywhere; - &:empty { + /* Browsers can leave line breaks behind after all text is deleted. */ + &[data-empty="true"] { display: inline-block; } - &:empty::before { + &[data-empty="true"]::before { display: inline-block; + float: inline-start; color: ${s("placeholder")}; -webkit-text-fill-color: ${s("placeholder")}; content: attr(data-placeholder); diff --git a/app/components/DeprecatedReason.tsx b/app/components/DeprecatedReason.tsx new file mode 100644 index 0000000000..f90a96cfab --- /dev/null +++ b/app/components/DeprecatedReason.tsx @@ -0,0 +1,93 @@ +import { observer } from "mobx-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import styled from "styled-components"; +import { DeprecationValidation } from "@shared/validations"; +import type Collection from "~/models/Collection"; +import type Document from "~/models/Document"; +import ContentEditable from "~/components/ContentEditable"; +import usePolicy from "~/hooks/usePolicy"; + +interface Props { + model: Document | Collection; +} + +/** + * Displays an editable reason for archiving or deleting a document or collection. + * + * @param props the model to describe. + * @returns the reason field, in read-only mode for readers. + */ +export const DeprecatedReason = observer(function DeprecatedReason({ + model, +}: Props) { + const { t } = useTranslation(); + const can = usePolicy(model); + const readOnly = !can.updateDeprecatedReason; + const [draft, setDraft] = useState(); + const value = draft ?? model.deprecatedReason ?? ""; + + const handleSave = async () => { + if (readOnly || model.isSaving || draft === undefined) { + return; + } + + const deprecatedReason = draft.trim() || null; + if (deprecatedReason === model.deprecatedReason) { + setDraft(undefined); + return; + } + + try { + await model.save({ deprecatedReason }); + setDraft(undefined); + toast.success(t("Reason saved")); + } catch { + toast.error(t("The reason could not be saved. Please try again.")); + } + }; + + if (readOnly && !model.deprecatedReason) { + return null; + } + + return ( + { + if ( + event.key === "Enter" && + !event.shiftKey && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + event.currentTarget.blur(); + } + }} + /> + ); +}); + +const Input = styled(ContentEditable)` + margin-top: 4px; + + > span { + display: block; + background: transparent; + color: inherit; + -webkit-text-fill-color: currentColor; + white-space: pre-wrap; + + &[data-empty="true"] { + display: block; + } + } +`; diff --git a/app/components/DeprecationNotice.tsx b/app/components/DeprecationNotice.tsx new file mode 100644 index 0000000000..16cec7baad --- /dev/null +++ b/app/components/DeprecationNotice.tsx @@ -0,0 +1,15 @@ +import styled from "styled-components"; +import { s } from "@shared/styles"; +import Notice from "./Notice"; + +/** A deprecation notice with a focus border around its editable reason. */ +export const DeprecationNotice = styled(Notice)` + &:has([contenteditable="true"]:focus) { + outline: 1px solid ${s("inputBorderFocused")}; + } + + > span > span { + flex: 1; + min-width: 0; + } +`; diff --git a/app/components/DocumentArchiveDialog.tsx b/app/components/DocumentArchiveDialog.tsx new file mode 100644 index 0000000000..a6d95d7b2f --- /dev/null +++ b/app/components/DocumentArchiveDialog.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { DeprecationValidation } from "@shared/validations"; +import ConfirmationDialog from "~/components/ConfirmationDialog"; +import Flex from "~/components/Flex"; +import Input from "~/components/Input"; + +interface Props { + count: number; + onSubmit: (reason?: string) => Promise; +} + +/** + * Confirms document archival with an optional reason. + * + * @param props the document count and archive callback. + * @returns the archive confirmation form. + */ +export function DocumentArchiveDialog({ count, onSubmit }: Props) { + const { t } = useTranslation(); + const [reason, setReason] = useState(""); + + const handleSubmit = () => onSubmit(reason.trim() || undefined); + + return ( + + +
+ {count === 1 + ? t( + "Archiving this document will remove it from the collection and search results." + ) + : t( + "Archiving these documents will remove them from their collections and search results." + )} +
+ setReason(event.currentTarget.value)} + maxLength={DeprecationValidation.maxReasonLength} + margin={0} + /> +
+
+ ); +} diff --git a/app/components/Notice.tsx b/app/components/Notice.tsx index 6f8f59be9e..a9d33a5ee3 100644 --- a/app/components/Notice.tsx +++ b/app/components/Notice.tsx @@ -34,13 +34,14 @@ const Notice: React.FC = ({ ); const Title = styled.span` + color: ${s("textSecondary")}; font-weight: 500; font-size: 16px; `; const Container = styled(Text)` background: ${s("sidebarBackground")}; - color: ${s("sidebarText")}; + color: ${s("textTertiary")}; padding: 10px 12px; border-radius: 4px; position: relative; diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 34dc4924f3..228cac21ff 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -38,6 +38,10 @@ export default class Collection extends ParanoidModel { @observable name: string; + /** The reason this collection is archived. */ + @observable + deprecatedReason: string | null = null; + /** Collection description in Prosemirror format. */ @Field @observable.shallow diff --git a/app/models/Document.ts b/app/models/Document.ts index d11cd36925..8256c06742 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -142,6 +142,10 @@ export default class Document extends ArchivableModel implements Searchable { @observable title: string; + /** The reason this document is archived or deleted. */ + @observable + deprecatedReason: string | null = null; + /** The likely language of the document, in ISO 639-1 format. */ language: string | undefined; @@ -519,7 +523,14 @@ export default class Document extends ArchivableModel implements Searchable { }; } - archive = () => this.store.archive(this); + /** + * Archives the document with an optional reason. + * + * @param options the archive options. + * @returns a promise that resolves when the document is archived. + */ + archive = (options?: { reason?: string }) => + this.store.archive(this, options); restore = (options?: { revisionId?: string; collectionId?: string }) => this.store.restore(this, options); diff --git a/app/scenes/Collection/components/Notices.tsx b/app/scenes/Collection/components/Notices.tsx index 81d680a45c..db067efc08 100644 --- a/app/scenes/Collection/components/Notices.tsx +++ b/app/scenes/Collection/components/Notices.tsx @@ -2,7 +2,8 @@ import { ArchiveIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import type Collection from "~/models/Collection"; import ErrorBoundary from "~/components/ErrorBoundary"; -import Notice from "~/components/Notice"; +import { DeprecationNotice } from "~/components/DeprecationNotice"; +import { DeprecatedReason } from "~/components/DeprecatedReason"; import Time from "~/components/Time"; type Props = { @@ -15,13 +16,18 @@ export default function Notices({ collection }: Props) { return ( {collection.isArchived && !collection.isDeleted && ( - }> + } + description={ + + } + > {t("Archived by {{userName}}", { userName: collection.archivedBy?.name ?? t("Unknown"), })}   + )} ); diff --git a/app/scenes/Document/components/Notices.tsx b/app/scenes/Document/components/Notices.tsx index 7cb17a38d4..d2f3ae1e67 100644 --- a/app/scenes/Document/components/Notices.tsx +++ b/app/scenes/Document/components/Notices.tsx @@ -4,14 +4,15 @@ import { Trans, useTranslation } from "react-i18next"; import styled from "styled-components"; import type Document from "~/models/Document"; import ErrorBoundary from "~/components/ErrorBoundary"; -import Notice from "~/components/Notice"; +import { DeprecationNotice } from "~/components/DeprecationNotice"; +import { DeprecatedReason } from "~/components/DeprecatedReason"; import Time from "~/components/Time"; /** * A notice shown above the document title, for example when the document is * archived or deleted. */ -export const DocumentNotice = styled(Notice)``; +export const DocumentNotice = styled(DeprecationNotice)``; type Props = { document: Document; @@ -58,7 +59,10 @@ export default function Notices({ document }: Props) { return ( {document.archivedAt && !document.deletedAt && ( - }> + } + description={} + > {t("Archived by {{userName}}", { userName: document.updatedBy?.name ?? t("Unknown"), })} @@ -69,7 +73,12 @@ export default function Notices({ document }: Props) { {document.deletedAt && ( } - description={permanentlyDeletedDescription()} + description={ + <> + {permanentlyDeletedDescription()} + + + } > {t("Deleted by {{userName}}", { userName: document.deletedBy?.name ?? t("Unknown"), diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts index 7051367dd1..6151502530 100644 --- a/app/stores/DocumentsStore.ts +++ b/app/stores/DocumentsStore.ts @@ -664,10 +664,18 @@ export default class DocumentsStore extends Store { } } + /** + * Archives a document and updates its local state. + * + * @param document the document to archive. + * @param options the archive options. + * @returns a promise that resolves when local state is updated. + */ @action - archive = async (document: Document) => { + archive = async (document: Document, options: { reason?: string } = {}) => { const res = await client.post("/documents.archive", { id: document.id, + reason: options.reason, }); runInAction(() => { invariant(res?.data, "Data should be available"); diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index bad733337e..90d9ddbbff 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -1,5 +1,5 @@ import type { DocumentPreferences, TextEditMode } from "@shared/types"; -import { DocumentConflictError } from "@server/errors"; +import { DocumentConflictError, ValidationError } from "@server/errors"; import { Event, Document } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { TextHelper } from "@server/models/helpers/TextHelper"; @@ -38,6 +38,8 @@ type Props = { publish?: boolean; /** The ID of the collection to publish the document to */ collectionId?: string | null; + /** The reason the document is archived or deleted. */ + deprecatedReason?: string | null; }; /** @@ -65,6 +67,7 @@ export default async function documentUpdater( lastRevision, publish, collectionId, + deprecatedReason, done, }: Props ): Promise { @@ -131,6 +134,20 @@ export default async function documentUpdater( } } + if (deprecatedReason !== undefined) { + // Reload under the lock so a concurrent restore cannot leave a stale note. + await document.reload({ transaction, paranoid: false }); + if (document.isActive) { + throw ValidationError("The document must be archived or deleted"); + } + document.deprecatedReason = deprecatedReason?.trim() || null; + // Keep the archive attribution and time shown in the banner unchanged. + if (document.changed("deprecatedReason")) { + await document.saveWithCtx(ctx, { silent: true }); + } + return document; + } + const changed = document.changed(); const eventData = done !== undefined ? { done } : undefined; diff --git a/server/migrations/20260917003126-add-deprecated-reason-to-documents-and-collections.js b/server/migrations/20260917003126-add-deprecated-reason-to-documents-and-collections.js new file mode 100644 index 0000000000..6701571837 --- /dev/null +++ b/server/migrations/20260917003126-add-deprecated-reason-to-documents-and-collections.js @@ -0,0 +1,23 @@ +module.exports = { + up: async (queryInterface, Sequelize) => { + await queryInterface.sequelize.transaction(async (transaction) => { + for (const table of ["documents", "collections"]) { + await queryInterface.addColumn( + table, + "deprecatedReason", + { type: Sequelize.TEXT, allowNull: true }, + { transaction } + ); + } + }); + }, + down: async (queryInterface) => { + await queryInterface.sequelize.transaction(async (transaction) => { + for (const table of ["collections", "documents"]) { + await queryInterface.removeColumn(table, "deprecatedReason", { + transaction, + }); + } + }); + }, +}; diff --git a/server/models/Collection.test.ts b/server/models/Collection.test.ts index fbc868af8f..bfce9113d0 100644 --- a/server/models/Collection.test.ts +++ b/server/models/Collection.test.ts @@ -17,6 +17,29 @@ beforeEach(() => { vi.resetAllMocks(); }); +describe("#updateDeprecatedReason", () => { + it("should reject a reason when a stale collection has already been restored", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + }); + await Collection.update( + { archivedAt: null }, + { where: { id: collection.id } } + ); + + await expect( + withAPIContext(user, (ctx) => + collection.updateDeprecatedReason(ctx, "Outdated") + ) + ).rejects.toThrow("The collection must be archived"); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + }); +}); + describe("#url", () => { it("should return correct url for the collection", () => { const collection = new Collection({ diff --git a/server/models/Collection.ts b/server/models/Collection.ts index e3ed2fc796..bb0b2858d6 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -55,7 +55,10 @@ import { CollectionPermission, NavigationNodeType } from "@shared/types"; import { UrlHelper } from "@shared/utils/UrlHelper"; import { sortNavigationNodes } from "@shared/utils/collections"; import slugify from "@shared/utils/slugify"; -import { CollectionValidation } from "@shared/validations"; +import { + CollectionValidation, + DeprecationValidation, +} from "@shared/validations"; import { parser } from "@server/editor"; import { ValidationError } from "@server/errors"; import type { APIContext } from "@server/types"; @@ -233,6 +236,11 @@ class Collection extends ParanoidModel< @Column(DataType.STRING) description: string | null; + /** The reason this collection is archived. */ + @Length({ max: DeprecationValidation.maxReasonLength }) + @Column(DataType.TEXT) + deprecatedReason: string | null; + /** * The content of the collection as JSON, this is a snapshot at the last time the state was saved. */ @@ -868,6 +876,39 @@ class Collection extends ParanoidModel< return this; }; + /** + * Updates the reason for archiving the collection. + * + * @param ctx the API context, including the acting user and transaction. + * @param reason the reason to save, or null to clear it. + * @returns the updated collection. + * @throws ValidationError if the collection is no longer archived. + */ + updateDeprecatedReason = async (ctx: APIContext, reason: string | null) => { + const { transaction } = ctx.state; + + if (transaction) { + await Collection.unscoped().findOne({ + attributes: ["id"], + where: { id: this.id }, + transaction, + lock: transaction.LOCK.UPDATE, + rejectOnEmpty: true, + }); + } + + await this.reload({ transaction }); + if (!this.archivedAt || this.deletedAt) { + throw ValidationError("The collection must be archived"); + } + + this.deprecatedReason = reason?.trim() || null; + if (this.changed("deprecatedReason")) { + await this.saveWithCtx(ctx, { silent: true }); + } + return this; + }; + /** * Removes a document from this collection's structure and soft deletes it * along with all of its descendants. diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index ba4e88af27..0aa8acad56 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -24,6 +24,38 @@ beforeEach(() => { vi.resetAllMocks(); }); +describe("#restoreTo", () => { + it.each(["archived", "deleted"])( + "should clear a reason saved after an %s document was loaded", + async (status) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + collectionId: collection.id, + archivedAt: status === "archived" ? new Date() : null, + deletedAt: status === "deleted" ? new Date() : null, + }); + + // Simulate another request saving a reason after the restore loaded its model. + await Document.update( + { deprecatedReason: "Outdated" }, + { where: { id: document.id }, paranoid: false } + ); + await withAPIContext(user, (ctx) => + document.restoreTo(ctx, { collectionId: collection.id }) + ); + await document.reload(); + expect(document.isActive).toBe(true); + expect(document.deprecatedReason).toBeNull(); + } + ); +}); + describe("#getSummary", () => { test("should strip markdown", async () => { const document = await buildDocument({ diff --git a/server/models/Document.ts b/server/models/Document.ts index 497a5628c8..2ea07a872f 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -56,7 +56,7 @@ import { DocumentPreferenceDefaults } from "@shared/constants"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { UrlHelper } from "@shared/utils/UrlHelper"; import slugify from "@shared/utils/slugify"; -import { DocumentValidation } from "@shared/validations"; +import { DeprecationValidation, DocumentValidation } from "@shared/validations"; import { InvalidRequestError, ValidationError } from "@server/errors"; import { CacheHelper } from "@server/utils/CacheHelper"; import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper"; @@ -330,6 +330,11 @@ class Document extends ArchivableModel< @SkipChangeset summary: string; + /** The reason this document is archived or deleted. */ + @Length({ max: DeprecationValidation.maxReasonLength }) + @Column(DataType.TEXT) + deprecatedReason: string | null; + @Column(DataType.ARRAY(DataType.STRING)) previousTitles: string[]; @@ -1465,6 +1470,8 @@ class Document extends ArchivableModel< if (this.deletedAt) { await this.restore({ transaction }); + this.deprecatedReason = null; + this.changed("deprecatedReason", true); this.collectionId = collectionId; await this.saveWithCtx(ctx, undefined, { name: "restore" }); } @@ -1598,6 +1605,8 @@ class Document extends ArchivableModel< for (const child of childDocuments) { await restoreChildren(child.id); child.archivedAt = null; + child.deprecatedReason = null; + child.changed("deprecatedReason", true); child.lastModifiedById = user.id; child.updatedBy = user; child.collectionId = collectionId; @@ -1607,6 +1616,8 @@ class Document extends ArchivableModel< await restoreChildren(this.id); this.archivedAt = null; + this.deprecatedReason = null; + this.changed("deprecatedReason", true); this.lastModifiedById = user.id; this.updatedBy = user; this.collectionId = collectionId; diff --git a/server/policies/collection.ts b/server/policies/collection.ts index 805e31d0c7..a7aeef58ec 100644 --- a/server/policies/collection.ts +++ b/server/policies/collection.ts @@ -237,6 +237,16 @@ allow(User, "restore", Collection, (user, collection) => ) ); +allow(User, "updateDeprecatedReason", Collection, (actor, collection) => + and( + !!collection?.archivedAt, + !collection?.deletedAt, + isTeamModel(actor, collection), + isTeamMutable(actor), + can(actor, "restore", collection) + ) +); + function includesMembership( collection: Collection | null, permissions: CollectionPermission[] diff --git a/server/policies/document.ts b/server/policies/document.ts index 8c027a2197..2063f0a477 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -256,6 +256,13 @@ allow( (document, revision) => document.id === revision?.documentId ); +allow(User, "updateDeprecatedReason", Document, (actor, document) => + and( + isTeamMutable(actor), + or(can(actor, "unarchive", document), can(actor, "restore", document)) + ) +); + allow(User, "unpublish", Document, (user, document) => { if ( !document || diff --git a/server/presenters/collection.ts b/server/presenters/collection.ts index a562eff464..04db5e46aa 100644 --- a/server/presenters/collection.ts +++ b/server/presenters/collection.ts @@ -66,6 +66,7 @@ export default async function presentCollection( res.permission = collection.permission; res.deletedAt = collection.deletedAt; res.archivedAt = collection.archivedAt; + res.deprecatedReason = collection.deprecatedReason; res.archivedBy = collection.archivedBy && presentUser(collection.archivedBy); res.sourceMetadata = collection.sourceMetadata diff --git a/server/presenters/document.ts b/server/presenters/document.ts index 00a43a43b2..b4e6f1b90a 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -80,6 +80,7 @@ async function presentDocument( updatedBy: undefined, publishedAt: document.publishedAt, archivedAt: document.archivedAt, + deprecatedReason: document.deprecatedReason, deletedAt: document.deletedAt, deletedBy: undefined, collaboratorIds: [], diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index cc0e4fb76a..219231dd2f 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -1,7 +1,9 @@ import { CollectionPermission, CollectionStatusFilter } from "@shared/types"; +import { DeprecationValidation } from "@shared/validations"; import { Document, UserMembership, GroupMembership } from "@server/models"; import { buildUser, + buildViewer, buildAdmin, buildGroup, buildCollection, @@ -1899,6 +1901,161 @@ describe("#collections.duplicate", () => { }); describe("#collections.update", () => { + describe("deprecatedReason", () => { + it.each(["admin", "manager"])( + "should let a collection %s save a reason without changing archive attribution", + async (role) => { + const owner = await buildUser(); + const editor = + role === "admin" ? await buildAdmin({ teamId: owner.teamId }) : owner; + const collection = await buildCollection({ + userId: owner.id, + teamId: owner.teamId, + archivedAt: new Date(), + }); + const updatedAt = collection.updatedAt.toISOString(); + const archivedAt = collection.archivedAt?.toISOString(); + const res = await server.post("/api/collections.update", editor, { + body: { + id: collection.id, + deprecatedReason: " Replaced by the new collection. ", + }, + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.data.deprecatedReason).toBe( + "Replaced by the new collection." + ); + expect(body.data.archivedAt).toBe(archivedAt); + expect(body.data.archivedBy.id).toBe(owner.id); + expect(body.data.updatedAt).toBe(updatedAt); + expect(body.policies[0].abilities.updateDeprecatedReason).toBeTruthy(); + await collection.reload(); + expect(collection.deprecatedReason).toBe( + "Replaced by the new collection." + ); + } + ); + + it.each([null, "", " "])( + "should clear the reason with %j", + async (value) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + deprecatedReason: "Outdated", + }); + const res = await server.post("/api/collections.update", user, { + body: { id: collection.id, deprecatedReason: value }, + }); + expect(res.status).toBe(200); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + } + ); + + it.each(["member", "viewer", "other team"])( + "should deny edits by a %s without collection management access", + async (role) => { + const owner = await buildUser(); + const editor = + role === "viewer" + ? await buildViewer({ teamId: owner.teamId }) + : await buildUser( + role === "other team" ? {} : { teamId: owner.teamId } + ); + const collection = await buildCollection({ + userId: owner.id, + teamId: owner.teamId, + archivedAt: new Date(), + deprecatedReason: "Outdated", + }); + const res = await server.post("/api/collections.update", editor, { + body: { id: collection.id, deprecatedReason: "Changed" }, + }); + expect(res.status).toBe(403); + await collection.reload(); + expect(collection.deprecatedReason).toBe("Outdated"); + } + ); + + it("should show the reason to readers", async () => { + const owner = await buildUser(); + const reader = await buildViewer({ teamId: owner.teamId }); + const collection = await buildCollection({ + userId: owner.id, + teamId: owner.teamId, + archivedAt: new Date(), + deprecatedReason: "Outdated", + }); + const res = await server.post("/api/collections.info", reader, { + body: { id: collection.id }, + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.data.deprecatedReason).toBe("Outdated"); + expect(body.policies[0].abilities.updateDeprecatedReason).toBeFalsy(); + }); + + it.each([ + { name: "Changed" }, + { description: "Changed" }, + { permission: null }, + ])( + "should reject updates to other fields with a reason: %j", + async (fields) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + }); + const res = await server.post("/api/collections.update", user, { + body: { id: collection.id, deprecatedReason: "Outdated", ...fields }, + }); + expect(res.status).toBe(403); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + } + ); + + it.each(["active", "deleted"])( + "should reject a reason on an %s collection", + async (status) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + deletedAt: status === "deleted" ? new Date() : null, + }); + const res = await server.post("/api/collections.update", user, { + body: { id: collection.id, deprecatedReason: "Outdated" }, + }); + expect(res.status).toBe(403); + } + ); + + it("should validate the reason length", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + }); + const res = await server.post("/api/collections.update", user, { + body: { + id: collection.id, + deprecatedReason: "x".repeat( + DeprecationValidation.maxReasonLength + 1 + ), + }, + }); + expect(res.status).toBe(400); + }); + }); + it("should require authentication", async () => { const collection = await buildCollection(); const res = await server.post("/api/collections.update", { @@ -2230,6 +2387,47 @@ describe("#collections.update", () => { }); describe("#collections.delete", () => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "should delete with reason %j", + async (reason) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + deprecatedReason: "Archived reason", + }); + await buildCollection({ teamId: user.teamId }); + const res = await server.post("/api/collections.delete", user, { + body: { id: collection.id, reason }, + }); + expect(res.status).toBe(200); + await collection.reload({ paranoid: false }); + expect(collection.deletedAt).not.toBeNull(); + const expectedReason = + reason === undefined ? "Archived reason" : reason?.trim() || null; + expect(collection.deprecatedReason).toBe(expectedReason); + } + ); + + it("should reject an oversized reason before delete", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/collections.delete", user, { + body: { + id: collection.id, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }, + }); + expect(res.status).toBe(400); + await collection.reload(); + expect(collection.isActive).toBe(true); + expect(collection.deprecatedReason).toBeNull(); + }); + it("should require authentication", async () => { const res = await server.post("/api/collections.delete"); const body = await res.json(); @@ -2255,9 +2453,13 @@ describe("#collections.delete", () => { const res = await server.post("/api/collections.delete", admin, { body: { id: collection.id, + reason: "No longer needed", }, }); expect(res.status).toEqual(400); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + expect(collection.isActive).toBe(true); }); it("should delete collection", async () => { @@ -2269,11 +2471,14 @@ describe("#collections.delete", () => { const res = await server.post("/api/collections.delete", admin, { body: { id: collection.id, + reason: "No longer needed", }, }); const body = await res.json(); expect(res.status).toEqual(200); expect(body.success).toBe(true); + await collection.reload({ paranoid: false }); + expect(collection.deprecatedReason).toBe("No longer needed"); }); it("should delete published documents", async () => { @@ -2342,6 +2547,46 @@ describe("#collections.delete", () => { }); describe("#collections.archive", () => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "should archive with reason %j", + async (reason) => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/collections.archive", user, { + body: { id: collection.id, reason }, + }); + expect(res.status).toBe(200); + await collection.reload({ paranoid: false }); + expect(collection.archivedAt).not.toBeNull(); + const expectedReason = + reason === undefined ? null : reason?.trim() || null; + expect(collection.deprecatedReason).toBe(expectedReason); + const body = await res.json(); + expect(body.data.deprecatedReason).toBe(expectedReason); + } + ); + + it("should reject an oversized reason before archive", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/collections.archive", user, { + body: { + id: collection.id, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }, + }); + expect(res.status).toBe(400); + await collection.reload(); + expect(collection.isActive).toBe(true); + expect(collection.deprecatedReason).toBeNull(); + }); + it("should archive collection", async () => { const team = await buildTeam(); const admin = await buildAdmin({ teamId: team.id }); @@ -2380,7 +2625,7 @@ describe("#collections.restore", () => { const collection = await buildCollection({ teamId: team.id, }); - await buildDocument({ + const document = await buildDocument({ collectionId: collection.id, teamId: team.id, publishedAt: new Date(), @@ -2399,6 +2644,8 @@ describe("#collections.restore", () => { ]); expect(archiveRes.status).toEqual(200); expect(archiveBody.data.archivedAt).not.toBe(null); + await document.update({ deprecatedReason: "Outdated" }); + await collection.update({ deprecatedReason: "Collection is outdated" }); const res = await server.post("/api/collections.restore", admin, { body: { id: collection.id, @@ -2407,6 +2654,10 @@ describe("#collections.restore", () => { const [, body] = await Promise.all([collection.reload(), res.json()]); expect(res.status).toEqual(200); expect(body.data.archivedAt).toBe(null); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + expect(collection.deprecatedReason).toBeNull(); + expect(body.data.deprecatedReason).toBeNull(); expect(collection.documentStructure).not.toBe(null); }); diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 4a9e186e70..5ac700bc30 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -620,14 +620,36 @@ router.post( sharing, commenting, templateManagement, + deprecatedReason, } = ctx.input.body; + const updatingDeprecatedReason = + deprecatedReason !== undefined && + Object.keys(ctx.input.body).every( + (key) => key === "id" || key === "deprecatedReason" + ); + const { user } = ctx.state.auth; const collection = await Collection.findByPk(id, { userId: user.id, + includeArchivedBy: updatingDeprecatedReason, transaction, }); - authorize(user, "update", collection); + authorize( + user, + updatingDeprecatedReason ? "updateDeprecatedReason" : "update", + collection + ); + + if (deprecatedReason !== undefined) { + authorize(user, "updateDeprecatedReason", collection); + await collection.updateDeprecatedReason(ctx, deprecatedReason); + ctx.body = { + data: await presentCollection(ctx, collection), + policies: presentPolicies(user, [collection]), + }; + return; + } // we're making this collection have no default access, ensure that the // current user has an admin membership so that at least they can manage it. @@ -853,7 +875,7 @@ router.post( transaction(), async (ctx: APIContext) => { const { transaction } = ctx.state; - const { id } = ctx.input.body; + const { id, reason } = ctx.input.body; const { user } = ctx.state.auth; const collection = await Collection.findByPk(id, { @@ -863,6 +885,10 @@ router.post( authorize(user, "delete", collection); + if (reason !== undefined) { + collection.deprecatedReason = reason || null; + } + await collection.destroyWithCtx(ctx); ctx.body = { @@ -878,7 +904,7 @@ router.post( transaction(), async (ctx: APIContext) => { const { transaction } = ctx.state; - const { id } = ctx.input.body; + const { id, reason } = ctx.input.body; const { user } = ctx.state.auth; const collection = await Collection.findByPk(id, { @@ -889,6 +915,10 @@ router.post( authorize(user, "archive", collection); + if (reason !== undefined) { + collection.deprecatedReason = reason || null; + } + await collection.archiveWithCtx(ctx); ctx.body = { @@ -921,6 +951,7 @@ router.post( { lastModifiedById: user.id, archivedAt: null, + deprecatedReason: null, }, { where: { @@ -934,6 +965,8 @@ router.post( collection.archivedAt = null; collection.archivedById = null; + collection.deprecatedReason = null; + collection.changed("deprecatedReason", true); collection = await collection.saveWithCtx(ctx, undefined, { name: "restore", }); diff --git a/server/routes/api/collections/schema.ts b/server/routes/api/collections/schema.ts index 47e7923d37..f5a7c7e743 100644 --- a/server/routes/api/collections/schema.ts +++ b/server/routes/api/collections/schema.ts @@ -6,6 +6,7 @@ import { CollectionStatusFilter, FileOperationFormat, } from "@shared/types"; +import { DeprecationValidation } from "@shared/validations"; import { Collection } from "@server/models"; import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod"; import { ValidateColor, ValidateIndex } from "@server/validation"; @@ -191,6 +192,12 @@ export type CollectionsExportAllReq = z.infer< export const CollectionsUpdateSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ + /** The reason the collection is archived. */ + deprecatedReason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), name: z.string().optional(), description: z.string().nullish(), data: ProsemirrorSchema({ allowEmpty: true }).nullish(), @@ -261,13 +268,27 @@ export const CollectionsListSchema = BaseSchema.extend({ export type CollectionsListReq = z.infer; export const CollectionsDeleteSchema = BaseSchema.extend({ - body: BaseIdSchema, + body: BaseIdSchema.extend({ + /** The reason for deleting the collection. */ + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), + }), }); export type CollectionsDeleteReq = z.infer; export const CollectionsArchiveSchema = BaseSchema.extend({ - body: BaseIdSchema, + body: BaseIdSchema.extend({ + /** The reason for archiving the collection. */ + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), + }), }); export type CollectionsArchiveReq = z.infer; diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index b62ec0912a..7584009331 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -12,7 +12,7 @@ import { UserRole, } from "@shared/types"; import { TextHelper } from "@shared/utils/TextHelper"; -import { DocumentValidation } from "@shared/validations"; +import { DeprecationValidation, DocumentValidation } from "@shared/validations"; import { createContext } from "@server/context"; import { parser } from "@server/editor"; import type { Group, User } from "@server/models"; @@ -5451,6 +5451,7 @@ describe("#documents.restore", () => { const document = await buildDocument({ userId: user.id, teamId: user.teamId, + deprecatedReason: "Outdated", }); await document.destroy(); const res = await server.post("/api/documents.restore", user, { @@ -5461,6 +5462,9 @@ describe("#documents.restore", () => { const body = await res.json(); expect(res.status).toEqual(200); expect(body.data.deletedAt).toEqual(null); + expect(body.data.deprecatedReason).toBeNull(); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); }); it("should allow restore of trashed documents with collectionId", async () => { @@ -5599,6 +5603,7 @@ describe("#documents.restore", () => { const document = await buildDocument({ userId: user.id, teamId: user.teamId, + deprecatedReason: "Outdated", }); await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); const res = await server.post("/api/documents.restore", user, { @@ -5609,6 +5614,41 @@ describe("#documents.restore", () => { const body = await res.json(); expect(res.status).toEqual(200); expect(body.data.archivedAt).toEqual(null); + expect(body.data.deprecatedReason).toBeNull(); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + }); + + it("should clear reasons from archived descendants when restoring", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const child = await buildDocument({ + userId: user.id, + teamId: user.teamId, + collectionId: document.collectionId, + parentDocumentId: document.id, + deprecatedReason: "Child is outdated", + }); + const grandchild = await buildDocument({ + userId: user.id, + teamId: user.teamId, + collectionId: document.collectionId, + parentDocumentId: child.id, + deprecatedReason: "Grandchild is outdated", + }); + await withAPIContext(user, (ctx) => document.archiveWithCtx(ctx)); + const res = await server.post("/api/documents.restore", user, { + body: { id: document.id }, + }); + expect(res.status).toBe(200); + await Promise.all([child.reload(), grandchild.reload()]); + for (const descendant of [child, grandchild]) { + expect(descendant.archivedAt).toBeNull(); + expect(descendant.deprecatedReason).toBeNull(); + } }); it("should restore archived when previous parent is archived", async () => { @@ -6297,6 +6337,149 @@ describe("#documents.create", () => { }); describe("#documents.update", () => { + describe("deprecatedReason", () => { + it.each(["archived", "deleted"])( + "should update the reason for an %s document without changing attribution", + async (status) => { + const user = await buildUser(); + const editor = await buildUser({ teamId: user.teamId }); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + archivedAt: status === "archived" ? new Date() : null, + deletedAt: status === "deleted" ? new Date() : null, + }); + const updatedAt = document.updatedAt.toISOString(); + const res = await server.post("/api/documents.update", editor, { + body: { + id: document.id, + deprecatedReason: " Replaced by the new guide. ", + }, + }); + const body = await res.json(); + expect(res.status).toBe(200); + expect(body.data.deprecatedReason).toBe("Replaced by the new guide."); + expect(body.data.updatedBy.id).toBe(user.id); + expect(body.data.updatedAt).toBe(updatedAt); + await document.reload({ paranoid: false }); + expect(document.deprecatedReason).toBe("Replaced by the new guide."); + expect(document.isActive).toBe(false); + } + ); + + it.each([null, "", " "])( + "should clear the reason with %j", + async (value) => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + deprecatedReason: "Outdated", + }); + const res = await server.post("/api/documents.update", user, { + body: { id: document.id, deprecatedReason: value }, + }); + expect(res.status).toBe(200); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + } + ); + + it.each(["archived", "deleted"])( + "should reject changes to other fields on an %s document", + async (status) => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + archivedAt: status === "archived" ? new Date() : null, + deletedAt: status === "deleted" ? new Date() : null, + }); + for (const fields of [ + { title: "Changed" }, + { text: "Changed" }, + { publish: true }, + { fullWidth: true }, + ]) { + const res = await server.post("/api/documents.update", user, { + body: { + id: document.id, + deprecatedReason: "Outdated", + ...fields, + }, + }); + expect([403, 404]).toContain(res.status); + } + await document.reload({ paranoid: false }); + expect(document.deprecatedReason).toBeNull(); + } + ); + + it.each(["viewer", "other team", "private collection"])( + "should deny a user with no edit access: %s", + async (access) => { + const owner = await buildUser(); + const user = + access === "viewer" + ? await buildViewer({ teamId: owner.teamId }) + : await buildUser( + access === "other team" ? {} : { teamId: owner.teamId } + ); + const collection = await buildCollection({ + userId: owner.id, + teamId: owner.teamId, + permission: + access === "private collection" + ? null + : CollectionPermission.ReadWrite, + }); + const document = await buildDocument({ + userId: owner.id, + teamId: owner.teamId, + collectionId: collection.id, + archivedAt: new Date(), + }); + const res = await server.post("/api/documents.update", user, { + body: { id: document.id, deprecatedReason: "Outdated" }, + }); + expect(res.status).toBe(403); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + } + ); + + it("should reject a reason on an active document", 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, deprecatedReason: "Outdated" }, + }); + expect(res.status).toBe(403); + }); + + it("should validate the reason length", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + }); + const res = await server.post("/api/documents.update", user, { + body: { + id: document.id, + deprecatedReason: "x".repeat( + DeprecationValidation.maxReasonLength + 1 + ), + }, + }); + expect(res.status).toBe(400); + }); + }); + it("should update document details in the root", async () => { const user = await buildUser(); const document = await buildDocument({ @@ -6893,6 +7076,46 @@ describe("#documents.update", () => { }); describe("#documents.archive", () => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "should archive with reason %j", + async (reason) => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/documents.archive", user, { + body: { id: document.id, reason }, + }); + expect(res.status).toBe(200); + await document.reload({ paranoid: false }); + expect(document.archivedAt).not.toBeNull(); + const expectedReason = + reason === undefined ? null : reason?.trim() || null; + expect(document.deprecatedReason).toBe(expectedReason); + const body = await res.json(); + expect(body.data.deprecatedReason).toBe(expectedReason); + } + ); + + it("should reject an oversized reason before archive", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/documents.archive", user, { + body: { + id: document.id, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }, + }); + expect(res.status).toBe(400); + await document.reload(); + expect(document.isActive).toBe(true); + expect(document.deprecatedReason).toBeNull(); + }); + it("should require id", async () => { const user = await buildUser(); const res = await server.post("/api/documents.archive", user); @@ -6936,6 +7159,46 @@ describe("#documents.archive", () => { }); describe("#documents.delete", () => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "should delete with reason %j", + async (reason) => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + archivedAt: new Date(), + deprecatedReason: "Archived reason", + }); + const res = await server.post("/api/documents.delete", user, { + body: { id: document.id, reason }, + }); + expect(res.status).toBe(200); + await document.reload({ paranoid: false }); + expect(document.deletedAt).not.toBeNull(); + const expectedReason = + reason === undefined ? "Archived reason" : reason?.trim() || null; + expect(document.deprecatedReason).toBe(expectedReason); + } + ); + + it("should reject an oversized reason before delete", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const res = await server.post("/api/documents.delete", user, { + body: { + id: document.id, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }, + }); + expect(res.status).toBe(400); + await document.reload(); + expect(document.isActive).toBe(true); + expect(document.deprecatedReason).toBeNull(); + }); + it("should require id", async () => { const user = await buildUser(); const res = await server.post("/api/documents.delete", user); @@ -6953,11 +7216,14 @@ describe("#documents.delete", () => { const res = await server.post("/api/documents.delete", user, { body: { id: document.id, + reason: "No longer needed", }, }); const body = await res.json(); expect(res.status).toEqual(200); expect(body.success).toEqual(true); + await document.reload({ paranoid: false }); + expect(document.deprecatedReason).toBe("No longer needed"); }); it("should delete a draft without collection", async () => { diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index fca05c2b32..12859a3acd 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1461,6 +1461,11 @@ router.post( const { transaction } = ctx.state; const { id, insightsEnabled, publish, collectionId, ...input } = ctx.input.body; + const updatingDeprecatedReason = + input.deprecatedReason !== undefined && + Object.keys(ctx.input.body).every( + (key) => key === "id" || key === "deprecatedReason" + ); const editorVersion = ctx.headers["x-editor-version"] as string | undefined; const { user } = ctx.state.auth; @@ -1469,10 +1474,19 @@ router.post( let document = await Document.findByPk(id, { userId: user.id, includeState: true, + paranoid: !updatingDeprecatedReason, transaction, }); collection = document?.collection; - authorize(user, "update", document); + authorize( + user, + updatingDeprecatedReason ? "updateDeprecatedReason" : "update", + document + ); + + if (!updatingDeprecatedReason && input.deprecatedReason !== undefined) { + authorize(user, "updateDeprecatedReason", document); + } if (collection && insightsEnabled !== undefined) { authorize(user, "updateInsights", document); @@ -1639,7 +1653,7 @@ router.post( validate(T.DocumentsArchiveSchema), transaction(), async (ctx: APIContext) => { - const { id } = ctx.input.body; + const { id, reason } = ctx.input.body; const { user } = ctx.state.auth; const { transaction } = ctx.state; @@ -1650,6 +1664,10 @@ router.post( }); authorize(user, "archive", document); + if (reason !== undefined) { + document.deprecatedReason = reason || null; + } + await document.archiveWithCtx(ctx); ctx.body = { @@ -1667,7 +1685,7 @@ router.post( transaction(), async (ctx: APIContext) => { const { transaction } = ctx.state; - const { id, permanent } = ctx.input.body; + const { id, permanent, reason } = ctx.input.body; const { user } = ctx.state.auth; if (permanent) { @@ -1695,6 +1713,10 @@ router.post( authorize(user, "delete", document); + if (reason !== undefined) { + document.deprecatedReason = reason || null; + } + await document.destroyWithCtx(ctx); } diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 815683423d..4c059689ef 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -10,7 +10,7 @@ import { TextEditMode, SortFilter, } from "@shared/types"; -import { DocumentValidation } from "@shared/validations"; +import { DeprecationValidation, DocumentValidation } from "@shared/validations"; import { BaseSchema } from "@server/routes/api/schema"; import { zodIconType, zodIdType, zodShareIdType } from "@server/utils/zod"; import { ValidateColor } from "@server/validation"; @@ -380,6 +380,13 @@ export type DocumentsTemplatizeReq = z.infer; export const DocumentsUpdateSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ + /** The reason the document is archived or deleted. */ + deprecatedReason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), + /** Doc title to be updated */ title: z.string().optional(), @@ -493,13 +500,26 @@ export const DocumentsMoveSchema = BaseSchema.extend({ export type DocumentsMoveReq = z.infer; export const DocumentsArchiveSchema = BaseSchema.extend({ - body: BaseIdSchema, + body: BaseIdSchema.extend({ + /** The reason for archiving the document. */ + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), + }), }); export type DocumentsArchiveReq = z.infer; export const DocumentsDeleteSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ + /** The reason for deleting the document. */ + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish(), /** Whether to permanently delete the doc as opposed to soft-delete */ permanent: z.boolean().optional(), }), diff --git a/server/tools/collections.test.ts b/server/tools/collections.test.ts index f5f2b2be8c..813c795522 100644 --- a/server/tools/collections.test.ts +++ b/server/tools/collections.test.ts @@ -1,3 +1,4 @@ +import { DeprecationValidation } from "@shared/validations"; import { Collection } from "@server/models"; import { buildCollection, buildUser } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; @@ -151,3 +152,109 @@ describe("collection tools", () => { ); }); }); + +describe.each([false, true])("delete_collection with archive=%s", (archive) => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "saves reason %j with the status change", + async (reason) => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + await buildCollection({ teamId: user.teamId }); + + const res = await callMcpTool(server, accessToken, "delete_collection", { + id: collection.id, + archive, + reason, + }); + + expect(res?.result?.isError).toBeFalsy(); + expect(JSON.parse(res?.result?.content?.[0]?.text ?? "{}").success).toBe( + true + ); + await collection.reload({ paranoid: false }); + expect(collection.deprecatedReason).toBe(reason?.trim() || null); + expect( + archive ? collection.archivedAt : collection.deletedAt + ).not.toBeNull(); + } + ); + + it("rejects an oversized reason without changing the item", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + await buildCollection({ teamId: user.teamId }); + + const res = await callMcpTool(server, accessToken, "delete_collection", { + id: collection.id, + archive, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }); + + expect(res?.result?.isError).toBe(true); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + expect(collection.archivedAt).toBeNull(); + expect(collection.deletedAt).toBeNull(); + }); + + it("checks permissions before saving the reason", async () => { + const { user } = await buildOAuthUser(); + const { accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + await buildCollection({ teamId: user.teamId }); + + const res = await callMcpTool(server, accessToken, "delete_collection", { + id: collection.id, + archive, + reason: "No longer needed", + }); + + expect(res?.result?.isError).toBe(true); + await collection.reload(); + expect(collection.deprecatedReason).toBeNull(); + expect(collection.archivedAt).toBeNull(); + expect(collection.deletedAt).toBeNull(); + }); +}); + +describe("delete_collection", () => { + it.each([undefined, null, " "])( + "preserves or clears the archive reason when deleting with reason %j", + async (reason) => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + await buildCollection({ teamId: user.teamId }); + await collection.update({ + archivedAt: new Date(), + deprecatedReason: "Archived reason", + }); + + const res = await callMcpTool(server, accessToken, "delete_collection", { + id: collection.id, + reason, + }); + + expect(res?.result?.isError).toBeFalsy(); + expect(JSON.parse(res?.result?.content?.[0]?.text ?? "{}").success).toBe( + true + ); + await collection.reload({ paranoid: false }); + expect(collection.deletedAt).not.toBeNull(); + expect(collection.deprecatedReason).toBe( + reason === undefined ? "Archived reason" : null + ); + } + ); +}); diff --git a/server/tools/collections.ts b/server/tools/collections.ts index 5ddcdc411e..a29a478eff 100644 --- a/server/tools/collections.ts +++ b/server/tools/collections.ts @@ -8,6 +8,7 @@ import { authorize } from "@server/policies"; import { presentCollection as presentCollectionBase } from "@server/presenters"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { UrlHelper } from "@shared/utils/UrlHelper"; +import { DeprecationValidation } from "@shared/validations"; import { success, error, @@ -332,37 +333,52 @@ export function collectionTools(server: McpServer, scopes: string[]) { .describe( "Set to true to archive the collection instead of deleting it. All documents within the collection will also be archived." ), + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish() + .describe( + "A plain text reason for archiving or deleting the collection. Omit to keep the existing reason, or use null or an empty string to clear it." + ), }, }, - withTracing("delete_collection", async ({ id, archive }, context) => { - try { - const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + withTracing( + "delete_collection", + async ({ id, archive, reason }, context) => { + try { + const ctx = buildAPIContext(context); + const { user } = ctx.state.auth; - await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + await sequelize.transaction(async (transaction) => { + ctx.state.transaction = transaction; + ctx.context.transaction = transaction; - const collection = await Collection.findByPk(id, { - userId: user.id, - rejectOnEmpty: true, - transaction, + const collection = await Collection.findByPk(id, { + userId: user.id, + rejectOnEmpty: true, + transaction, + }); + + authorize(user, archive ? "archive" : "delete", collection); + + if (reason !== undefined) { + collection.deprecatedReason = reason || null; + } + + if (archive) { + await collection.archiveWithCtx(ctx); + } else { + await collection.destroyWithCtx(ctx); + } }); - if (archive) { - authorize(user, "archive", collection); - await collection.archiveWithCtx(ctx); - } else { - authorize(user, "delete", collection); - await collection.destroyWithCtx(ctx); - } - }); - - return success({ success: true }); - } catch (message) { - return error(message); + return success({ success: true }); + } catch (message) { + return error(message); + } } - }) + ) ); } } diff --git a/server/tools/documents.test.ts b/server/tools/documents.test.ts index ae82fd9f53..2c3063f180 100644 --- a/server/tools/documents.test.ts +++ b/server/tools/documents.test.ts @@ -1,3 +1,4 @@ +import { DeprecationValidation } from "@shared/validations"; import { CollectionPermission, DocumentPermission, Scope } from "@shared/types"; import { buildUser, @@ -990,3 +991,123 @@ describe("restore_document", () => { expect(res?.result?.isError).toBe(true); }); }); + +describe.each([false, true])("delete_document with archive=%s", (archive) => { + it.each([undefined, " Replaced by a new guide. ", null, " "])( + "saves reason %j with the status change", + async (reason) => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "delete_document", { + id: document.id, + archive, + reason, + }); + + expect(res?.result?.isError).toBeFalsy(); + expect(JSON.parse(res?.result?.content?.[0]?.text ?? "{}").success).toBe( + true + ); + await document.reload({ paranoid: false }); + expect(document.deprecatedReason).toBe(reason?.trim() || null); + expect(archive ? document.archivedAt : document.deletedAt).not.toBeNull(); + } + ); + + it("rejects an oversized reason without changing the item", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "delete_document", { + id: document.id, + archive, + reason: "x".repeat(DeprecationValidation.maxReasonLength + 1), + }); + + expect(res?.result?.isError).toBe(true); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + expect(document.archivedAt).toBeNull(); + expect(document.deletedAt).toBeNull(); + }); + + it("checks permissions before saving the reason", async () => { + const { user } = await buildOAuthUser(); + const { accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "delete_document", { + id: document.id, + archive, + reason: "No longer needed", + }); + + expect(res?.result?.isError).toBe(true); + await document.reload(); + expect(document.deprecatedReason).toBeNull(); + expect(document.archivedAt).toBeNull(); + expect(document.deletedAt).toBeNull(); + }); +}); + +describe("delete_document", () => { + it.each([undefined, null, " "])( + "preserves or clears the archive reason when deleting with reason %j", + async (reason) => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + await document.update({ + archivedAt: new Date(), + deprecatedReason: "Archived reason", + }); + + const res = await callMcpTool(server, accessToken, "delete_document", { + id: document.id, + reason, + }); + + expect(res?.result?.isError).toBeFalsy(); + expect(JSON.parse(res?.result?.content?.[0]?.text ?? "{}").success).toBe( + true + ); + await document.reload({ paranoid: false }); + expect(document.deletedAt).not.toBeNull(); + expect(document.deprecatedReason).toBe( + reason === undefined ? "Archived reason" : null + ); + } + ); +}); diff --git a/server/tools/documents.ts b/server/tools/documents.ts index 8bae887be0..f73e80cea6 100644 --- a/server/tools/documents.ts +++ b/server/tools/documents.ts @@ -20,6 +20,7 @@ import { } from "@server/presenters"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { UrlHelper } from "@shared/utils/UrlHelper"; +import { DeprecationValidation } from "@shared/validations"; import { error, success, @@ -788,37 +789,52 @@ export function documentTools(server: McpServer, scopes: string[]) { .describe( "Set to true to archive the document instead of deleting it. Archived documents remain searchable in the archive view." ), + reason: z + .string() + .trim() + .max(DeprecationValidation.maxReasonLength) + .nullish() + .describe( + "A plain text reason for archiving or deleting the document. Omit to keep the existing reason, or use null or an empty string to clear it." + ), }, }, - withTracing("delete_document", async ({ id, archive }, context) => { - try { - const ctx = buildAPIContext(context); - const { user } = ctx.state.auth; + withTracing( + "delete_document", + async ({ id, archive, reason }, context) => { + try { + const ctx = buildAPIContext(context); + const { user } = ctx.state.auth; - await sequelize.transaction(async (transaction) => { - ctx.state.transaction = transaction; - ctx.context.transaction = transaction; + await sequelize.transaction(async (transaction) => { + ctx.state.transaction = transaction; + ctx.context.transaction = transaction; - const document = await Document.findByPk(id, { - userId: user.id, - rejectOnEmpty: true, - transaction, + const document = await Document.findByPk(id, { + userId: user.id, + rejectOnEmpty: true, + transaction, + }); + + authorize(user, archive ? "archive" : "delete", document); + + if (reason !== undefined) { + document.deprecatedReason = reason || null; + } + + if (archive) { + await document.archiveWithCtx(ctx); + } else { + await document.destroyWithCtx(ctx); + } }); - if (archive) { - authorize(user, "archive", document); - await document.archiveWithCtx(ctx); - } else { - authorize(user, "delete", document); - await document.destroyWithCtx(ctx); - } - }); - - return success({ success: true }); - } catch (message) { - return error(message); + return success({ success: true }); + } catch (message) { + return error(message); + } } - }) + ) ); } diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 7871ba232a..2c3734e120 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -121,8 +121,6 @@ "Document archived": "Document archived", "{{ count }} documents archived": "{{ count }} documents archived", "{{ count }} documents archived_plural": "{{ count }} documents archived", - "Archiving this document will remove it from the collection and search results.": "Archiving this document will remove it from the collection and search results.", - "Archiving these documents will remove them from their collections and search results.": "Archiving these documents will remove them from their collections and search results.", "{{ documentName }} restored": "{{ documentName }} restored", "{{ count }} documents restored": "{{ count }} documents restored", "{{ count }} documents restored_plural": "{{ count }} documents restored", @@ -337,7 +335,14 @@ "Moving the document {{ title }} to the {{ newCollectionName }} collection will change permission for all workspace members from {{ prevPermission }} to {{ newPermission }}.": "Moving the document {{ title }} to the {{ newCollectionName }} collection will change permission for all workspace members from {{ prevPermission }} to {{ newPermission }}.", "Collections could not be loaded, please reload the app": "Collections could not be loaded, please reload the app", "Start view": "Start view", + "Reason saved": "Reason saved", + "The reason could not be saved. Please try again.": "The reason could not be saved. Please try again.", + "Reason for archiving or deleting": "Reason for archiving or deleting", + "Add a reason": "Add a reason", "Install now": "Install now", + "Archiving this document will remove it from the collection and search results.": "Archiving this document will remove it from the collection and search results.", + "Archiving these documents will remove them from their collections and search results.": "Archiving these documents will remove them from their collections and search results.", + "Reason (optional)": "Reason (optional)", "Deleted Collection": "Deleted Collection", "Collection options": "Collection options", "Document options": "Document options", diff --git a/shared/validations.ts b/shared/validations.ts index 074381e3c0..d72e3854bb 100644 --- a/shared/validations.ts +++ b/shared/validations.ts @@ -68,6 +68,11 @@ export const CommentValidation = { maxLength: 1000, }; +export const DeprecationValidation = { + /** The maximum length of an archive or deletion reason. */ + maxReasonLength: 2000, +}; + export const DocumentValidation = { /** The maximum length of the document title */ maxTitleLength: 100, From 4b4c7d32817420dab96801e7be3b88f1cee76700 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 18 Sep 2026 22:22:50 -0400 Subject: [PATCH 095/368] chore: React 19 upgrade (#13562) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * React 19 upgrade Bumps react and react-dom to 19.2.8, with the dependency changes React 19 requires: react-is 19, @types/react 19, @types/react-dom 19, react-helmet-async 3 and react-avatar-editor 15 (which now ships its own types). framer-motion moves to 13 — its v6 types reference React.ReactHTML, removed from @types/react 19. The type changes fall into a few classes: - The global JSX namespace is gone, so JSX.Element becomes React.JSX.Element and the custom element declarations move into a module augmentation. - useRef() now requires an initial value. - A ref created with a null initial value is typed nullable, so consumers that accept one are widened to RefObject. - React.ReactChild was removed; tooltips take React.ReactNode. - Ref callbacks may only return a cleanup function. react-dnd connectors return the connected node, so useDragRef and useDropRef wrap useDrag and useDrop and hand back a ref callback. react-i18next stays on v12: i18next 23 drops compatibilityJSON "v3", which would rewrite all 64 _plural keys across every locale. outline-icons, oy-vey and react-waypoint have no release that lists React 19 as a peer. All three render correctly under it; the install reports them as unmet peers. Co-Authored-By: Claude Opus 5 (1M context) * Remove react-helmet and forwardRef --------- Co-authored-by: Claude Opus 5 (1M context) --- app/actions/index.ts | 2 +- app/components/ActionButton.tsx | 121 +++-- app/components/ArrowKeyNavigation.tsx | 14 +- app/components/Authenticated.tsx | 2 +- app/components/Avatar/Avatar.tsx | 10 +- app/components/Avatar/AvatarWithHoverCard.tsx | 13 +- app/components/Breadcrumb.tsx | 14 +- app/components/Button.tsx | 13 +- app/components/ColorButton.tsx | 18 +- app/components/CommandBar/CommandBarItem.tsx | 8 +- app/components/CommandBar/useSearchIndex.ts | 2 +- app/components/ContentEditable.tsx | 45 +- app/components/CopyToClipboard.ts | 27 +- app/components/DelayedMount.ts | 2 +- app/components/DocumentBreadcrumb.tsx | 14 +- .../DocumentExplorer/DocumentExplorer.tsx | 16 +- .../DocumentExplorer/DocumentExplorerNode.tsx | 36 +- app/components/DocumentListItem.tsx | 21 +- app/components/EditableTitle.tsx | 16 +- app/components/Editor.tsx | 8 +- app/components/Fade.tsx | 2 +- app/components/Header.tsx | 8 +- app/components/HoverPreview/HoverPreview.tsx | 6 +- .../HoverPreview/HoverPreviewDocument.tsx | 18 +- .../HoverPreview/HoverPreviewGroup.tsx | 17 +- .../HoverPreview/HoverPreviewIssue.tsx | 21 +- .../HoverPreview/HoverPreviewLink.tsx | 14 +- .../HoverPreview/HoverPreviewMention.tsx | 17 +- .../HoverPreview/HoverPreviewProject.tsx | 21 +- .../HoverPreview/HoverPreviewPullRequest.tsx | 102 ++-- app/components/IconPicker/components/Grid.tsx | 18 +- .../IconPicker/components/GridTemplate.tsx | 28 +- app/components/Input.tsx | 17 +- app/components/InputSearch.tsx | 9 +- app/components/InputSelect.tsx | 440 +++++++++--------- app/components/InputSelectPermission.tsx | 80 ++-- app/components/Layout.tsx | 72 +-- app/components/Lightbox.tsx | 55 +-- app/components/List/Item.tsx | 42 +- app/components/Menu/DropdownMenu.tsx | 217 +++++---- app/components/Menu/OverflowMenuButton.tsx | 26 +- app/components/NavLink.tsx | 16 +- app/components/Notice.tsx | 4 +- .../Notifications/Notifications.tsx | 9 +- .../OAuthClient/InputClientType.tsx | 15 +- app/components/OneTimePasswordInput.tsx | 45 +- app/components/PageTitle.tsx | 46 +- app/components/PaginatedDocumentList.tsx | 2 +- app/components/PaginatedList.tsx | 10 +- app/components/ResizingHeightContainer.tsx | 61 +-- app/components/ScrollContext.ts | 2 +- app/components/ScrollToTop.ts | 2 +- app/components/Scrollable.tsx | 31 +- .../Sharing/Collection/PublicAccess.tsx | 9 +- .../Sharing/Document/PublicAccess.tsx | 9 +- .../Sharing/components/CopyLinkButton.tsx | 2 +- .../Sharing/components/SearchInput.tsx | 16 +- .../Sharing/components/Suggestions.tsx | 380 ++++++++------- app/components/Sharing/components/index.tsx | 3 +- app/components/Sidebar/Aside.tsx | 3 +- app/components/Sidebar/Sidebar.tsx | 22 +- .../Sidebar/components/CollectionRow.tsx | 3 +- .../Sidebar/components/Collections.tsx | 5 +- .../Sidebar/components/DocumentRow.tsx | 3 +- .../components/DraggableCollectionLink.tsx | 6 +- .../Sidebar/components/DraggableSection.tsx | 4 +- .../Sidebar/components/DropToImport.tsx | 2 +- app/components/Sidebar/components/NavLink.tsx | 2 +- .../Sidebar/components/SharedDocumentLink.tsx | 27 +- .../Sidebar/components/SidebarButton.tsx | 81 ++-- .../Sidebar/components/SidebarLink.tsx | 54 +-- .../Sidebar/components/TrashLink.tsx | 5 +- .../Sidebar/hooks/useDragAndDrop.tsx | 121 ++++- app/components/Switch.tsx | 37 +- app/components/Tabs/Tab.tsx | 15 +- app/components/Tooltip.tsx | 2 +- app/components/primitives/Drawer.tsx | 26 +- app/components/primitives/Form.tsx | 2 +- app/components/primitives/InputSelect.tsx | 82 ++-- app/components/primitives/Menu/index.tsx | 148 +++--- app/components/primitives/Popover.tsx | 28 +- .../primitives/components/InputSelect.tsx | 36 +- app/editor/components/FindAndReplace.tsx | 4 +- app/editor/components/FloatingToolbar.tsx | 10 +- app/editor/components/MediaDimension.tsx | 11 +- app/editor/components/StickyBlockToolbar.tsx | 9 +- app/editor/components/SuggestionsMenu.tsx | 6 +- app/editor/index.tsx | 35 +- app/editor/menus/block.tsx | 2 +- app/hooks/useClickIntent.ts | 2 +- app/hooks/useEventListener.ts | 2 +- app/hooks/useHover.ts | 4 +- app/hooks/useIdle.ts | 2 +- app/hooks/useInterval.ts | 2 +- app/hooks/useKeyboardStickyOffset.ts | 2 +- app/hooks/useLastVisitedPath.tsx | 2 +- app/hooks/useLocaleTime.ts | 2 +- app/hooks/useMenuAction.ts | 2 +- app/hooks/useOnScreen.ts | 2 +- app/hooks/usePrevious.ts | 2 +- app/hooks/useRovingTabIndex.ts | 24 + app/hooks/useSwipe.tsx | 8 +- app/index.tsx | 59 ++- .../components/Comments/CommentEditor.tsx | 8 +- .../components/Comments/CommentForm.tsx | 5 +- app/scenes/Document/components/Contents.tsx | 4 +- .../Document/components/DocumentTitle.tsx | 34 +- app/scenes/Document/components/Editor.tsx | 6 +- .../components/History/PaginatedEventList.tsx | 2 +- .../Document/components/MarkAsViewed.ts | 2 +- .../Document/components/MultiplayerEditor.tsx | 11 +- .../Document/components/ObservingBanner.tsx | 3 +- .../Document/components/RevisionViewer.tsx | 7 +- app/scenes/Login/OAuthAuthorize.tsx | 2 +- .../components/RecentSearchListItem.tsx | 6 +- .../Search/components/RecentSearches.tsx | 8 +- app/scenes/Search/components/SearchInput.tsx | 8 +- app/scenes/Settings/CustomEmojis.tsx | 3 - .../Settings/components/ApiKeyListItem.tsx | 4 +- .../Settings/components/ConnectedButton.tsx | 2 +- app/scenes/Settings/components/CopyButton.tsx | 4 +- .../Settings/components/DropToImport.tsx | 2 +- .../Settings/components/ImageUpload.tsx | 4 +- app/scenes/Shared/index.tsx | 11 +- app/types.ts | 12 +- app/typings/index.d.ts | 7 - app/typings/react.d.ts | 12 + package.json | 19 +- .../figma/client/components/FigmaButton.tsx | 2 +- .../github/client/components/GitHubButton.tsx | 2 +- .../gitlab/client/components/GitLabButton.tsx | 2 +- .../linear/client/components/LinearButton.tsx | 2 +- plugins/zapier/client/Settings.tsx | 23 +- server/emails/mailer.tsx | 2 +- server/emails/templates/BaseEmail.tsx | 2 +- shared/components/EmojiText.tsx | 2 +- shared/editor/components/ColorSwatch.tsx | 2 +- shared/editor/components/Frame.tsx | 16 +- shared/editor/components/Image.tsx | 2 +- .../editor/components/hooks/useDragResize.ts | 2 +- shared/editor/embeds/YouTube.tsx | 11 +- yarn.lock | 346 ++++---------- 142 files changed, 1912 insertions(+), 1890 deletions(-) create mode 100644 app/hooks/useRovingTabIndex.ts create mode 100644 app/typings/react.d.ts diff --git a/app/actions/index.ts b/app/actions/index.ts index f9e3c9a8f3..37cbcca3e7 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -165,7 +165,7 @@ export function actionToMenuItem( icon, visible, disabled, - tooltip: resolve(action.tooltip, context), + tooltip: resolve(action.tooltip, context), selected: resolve(action.selected, context), dangerous: action.dangerous, shortcut, diff --git a/app/components/ActionButton.tsx b/app/components/ActionButton.tsx index e42f45bfba..f1650bbc1d 100644 --- a/app/components/ActionButton.tsx +++ b/app/components/ActionButton.tsx @@ -22,68 +22,67 @@ export type Props = React.HTMLAttributes & { /** * Button that can be used to trigger an action definition. */ -const ActionButton = React.forwardRef( - function ActionButton_( - { action, tooltip, hideOnActionDisabled, ...rest }: Props, - ref: React.Ref - ) { - const actionContext = useActionContext({ - isButton: true, - }); - const isMounted = useIsMounted(); - const [executing, setExecuting] = React.useState(false); +function ActionButton({ + action, + tooltip, + hideOnActionDisabled, + ref, + ...rest +}: Props & { ref?: React.Ref }) { + const actionContext = useActionContext({ + isButton: true, + }); + const isMounted = useIsMounted(); + const [executing, setExecuting] = React.useState(false); - if (!actionContext || !action) { - return - ); - - if (tooltip) { - return {button}; - } - - return button; + if (!actionContext || !action) { + return + ); + + if (tooltip) { + return {button}; + } + + return button; +} export default observer(ActionButton); diff --git a/app/components/ArrowKeyNavigation.tsx b/app/components/ArrowKeyNavigation.tsx index 7834efd5aa..7e520998b3 100644 --- a/app/components/ArrowKeyNavigation.tsx +++ b/app/components/ArrowKeyNavigation.tsx @@ -6,12 +6,16 @@ type Props = Omit, "children"> & { children: () => React.ReactNode; onEscape?: (ev: React.KeyboardEvent) => void; items: unknown[]; + ref?: React.Ref; }; -function ArrowKeyNavigation( - { children, onEscape, items, ...rest }: Props, - ref: React.RefObject -) { +function ArrowKeyNavigation({ + children, + onEscape, + items, + ref, + ...rest +}: Props) { const handleKeyDown = React.useCallback( (ev: React.KeyboardEvent) => { if (onEscape) { @@ -48,4 +52,4 @@ function ArrowKeyNavigation( ); } -export default observer(React.forwardRef(ArrowKeyNavigation)); +export default observer(ArrowKeyNavigation); diff --git a/app/components/Authenticated.tsx b/app/components/Authenticated.tsx index 9a50239400..734904f6ee 100644 --- a/app/components/Authenticated.tsx +++ b/app/components/Authenticated.tsx @@ -8,7 +8,7 @@ import { changeLanguage } from "~/utils/language"; import LoadingIndicator from "./LoadingIndicator"; type Props = { - children: JSX.Element; + children: React.JSX.Element; }; const Authenticated = ({ children }: Props) => { diff --git a/app/components/Avatar/Avatar.tsx b/app/components/Avatar/Avatar.tsx index 18abcd4b9f..34edf124cd 100644 --- a/app/components/Avatar/Avatar.tsx +++ b/app/components/Avatar/Avatar.tsx @@ -49,16 +49,16 @@ export type AvatarProps = { showTooltip?: boolean; /** Whether to show a profile card on hover for users, defaults to true */ showHoverCard?: boolean; + /** Ref to the outer element */ + ref?: React.Ref; } & Omit< React.ComponentPropsWithoutRef<"div">, "onClick" | "className" | "style" >; -const Avatar = React.forwardRef(function Avatar_( - props: AvatarProps, - ref: React.Ref -) { +function Avatar(props: AvatarProps) { const { + ref, model, style, variant = AvatarVariant.Round, @@ -111,7 +111,7 @@ const Avatar = React.forwardRef(function Avatar_( ) : ( content ); -}); +} const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>` position: relative; diff --git a/app/components/Avatar/AvatarWithHoverCard.tsx b/app/components/Avatar/AvatarWithHoverCard.tsx index 64f8000bfc..8ffb3c3a70 100644 --- a/app/components/Avatar/AvatarWithHoverCard.tsx +++ b/app/components/Avatar/AvatarWithHoverCard.tsx @@ -1,5 +1,4 @@ import { observer } from "mobx-react"; -import * as React from "react"; import { UserHoverCard } from "~/components/UserHoverCard"; import User from "~/models/User"; import type { AvatarProps } from "./Avatar"; @@ -9,10 +8,12 @@ import Avatar from "./Avatar"; * An avatar that additionally displays a profile card on hover when the model * it represents is a user. */ -const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( - { showTooltip, showHoverCard = true, ...props }: AvatarProps, - ref: React.Ref -) { +function AvatarWithHoverCard({ + showTooltip, + showHoverCard = true, + ref, + ...props +}: AvatarProps) { const { model } = props; if (!showHoverCard || !(model instanceof User)) { @@ -24,6 +25,6 @@ const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( ); -}); +} export default observer(AvatarWithHoverCard); diff --git a/app/components/Breadcrumb.tsx b/app/components/Breadcrumb.tsx index 7a9296ddd3..4a4b98aeb7 100644 --- a/app/components/Breadcrumb.tsx +++ b/app/components/Breadcrumb.tsx @@ -20,12 +20,16 @@ type Props = React.PropsWithChildren<{ actions: InternalLinkAction[]; max?: number; highlightFirstItem?: boolean; + ref?: React.Ref; }>; -function Breadcrumb( - { actions, highlightFirstItem, children, max = 2 }: Props, - ref: React.RefObject | null -) { +function Breadcrumb({ + actions, + highlightFirstItem, + children, + max = 2, + ref, +}: Props) { const actionContext = useActionContext({ isMenu: true }); const visibleActions = useComputed( @@ -141,4 +145,4 @@ const Title = styled.span` min-width: 0; `; -export default observer(React.forwardRef(Breadcrumb)); +export default observer(Breadcrumb); diff --git a/app/components/Button.tsx b/app/components/Button.tsx index 75a2b0b622..6bb3d8c9ad 100644 --- a/app/components/Button.tsx +++ b/app/components/Button.tsx @@ -158,13 +158,14 @@ export type Props = ActionButtonProps & { "data-on"?: string; "data-event-category"?: string; "data-event-action"?: string; + ref?: React.Ref; }; -const Button = ( - props: Props & React.ComponentPropsWithoutRef, - ref: React.Ref -) => { +function Button( + props: Props & React.ComponentPropsWithoutRef +) { const { + ref, type, children, value, @@ -200,10 +201,10 @@ const Button = ( ); -}; +} const StyledDisclosureIcon = styled(DisclosureIcon)` opacity: 0.8; `; -export default React.forwardRef(Button); +export default Button; diff --git a/app/components/ColorButton.tsx b/app/components/ColorButton.tsx index 1c3b359a87..67b4f76d06 100644 --- a/app/components/ColorButton.tsx +++ b/app/components/ColorButton.tsx @@ -10,13 +10,17 @@ type Props = React.HTMLAttributes & { active?: boolean; /** The size of the button in pixels */ size?: number; + ref?: React.Ref; }; -export const ColorButton = React.forwardRef( - ( - { color, active = false, size = 24, ...rest }: Props, - ref: React.Ref - ) => ( +export function ColorButton({ + color, + active = false, + size = 24, + ref, + ...rest +}: Props) { + return ( - ) -); + ); +} /** Highlight for the hovered or selected swatch, falls back for the gradient. */ const ring = css`2px solid var(--color, ${s("textTertiary")})`; diff --git a/app/components/CommandBar/CommandBarItem.tsx b/app/components/CommandBar/CommandBarItem.tsx index edb163fb2c..5af103303e 100644 --- a/app/components/CommandBar/CommandBarItem.tsx +++ b/app/components/CommandBar/CommandBarItem.tsx @@ -14,6 +14,7 @@ type Props = { action: CommandBarActionImpl; active: boolean; currentRootActionId: string | null | undefined; + ref?: React.Ref; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -24,10 +25,7 @@ function replaceResultMarks(tag: string) { return tag.replace(/]*>(.*?)<\/b>/gi, "$1"); } -function CommandBarItem( - { action, active, currentRootActionId }: Props, - ref: React.RefObject -) { +function CommandBarItem({ action, active, currentRootActionId, ref }: Props) { const theme = useTheme(); const ancestors = React.useMemo(() => { if (!currentRootActionId || !action.ancestors) { @@ -168,4 +166,4 @@ const ForwardIcon = styled(BackIcon)` flex-shrink: 0; `; -export default React.forwardRef(CommandBarItem); +export default CommandBarItem; diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index 7ca8ec263e..d81900984c 100644 --- a/app/components/CommandBar/useSearchIndex.ts +++ b/app/components/CommandBar/useSearchIndex.ts @@ -90,7 +90,7 @@ export interface UseSearchIndex { * @returns the current results and functions to feed or reset the index. */ export function useSearchIndex(query: string): UseSearchIndex { - const indexRef = useRef(); + const indexRef = useRef(undefined); if (!indexRef.current) { indexRef.current = new SearchIndex(); } diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index a5f3109c2a..c3ad930c27 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -20,6 +20,7 @@ type Props = Omit, "ref" | "onChange"> & { autoFocus?: boolean; children?: React.ReactNode; value: string; + ref?: React.Ref; }; export type RefHandle = { @@ -33,28 +34,26 @@ export type RefHandle = { * Defines a content editable component with the same interface as a native * HTMLInputElement (or, as close as we can get). */ -const ContentEditable = React.forwardRef(function ContentEditable_( - { - disabled, - onChange, - onInput, - onFocus, - onBlur, - onKeyDown, - onCompositionEnd, - value, - children, - className, - maxLength, - autoFocus, - placeholder, - readOnly, - dir, - onClick, - ...rest - }: Props, - ref: React.RefObject -) { +function ContentEditable({ + disabled, + onChange, + onInput, + onFocus, + onBlur, + onKeyDown, + onCompositionEnd, + value, + children, + className, + maxLength, + autoFocus, + placeholder, + readOnly, + dir, + onClick, + ref, + ...rest +}: Props) { const contentRef = React.useRef(null); const [innerValue, setInnerValue] = React.useState(value); const [isEmpty, setIsEmpty] = React.useState(value.length === 0); @@ -214,7 +213,7 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
); -}); +} function isComposing(event: React.SyntheticEvent) { const native = event.nativeEvent; diff --git a/app/components/CopyToClipboard.ts b/app/components/CopyToClipboard.ts index 5dc70b7cd4..92068f1cf1 100644 --- a/app/components/CopyToClipboard.ts +++ b/app/components/CopyToClipboard.ts @@ -3,15 +3,21 @@ import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import env from "~/env"; -type Props = { - text: string; - children?: React.ReactElement; - onClick?: React.MouseEventHandler; - onCopy?: () => void; +type ChildProps = { + onClick?: React.MouseEventHandler; + ref?: React.Ref; }; -function CopyToClipboard(props: Props, ref: React.Ref) { - const { text, onCopy, children, ...rest } = props; +type Props = { + text: string; + children?: React.ReactElement; + onClick?: React.MouseEventHandler; + onCopy?: () => void; + ref?: React.Ref; +}; + +function CopyToClipboard(props: Props) { + const { text, onCopy, children, ref, ...rest } = props; const onClick = React.useCallback( (ev: React.MouseEvent) => { @@ -45,12 +51,9 @@ function CopyToClipboard(props: Props, ref: React.Ref) { return React.cloneElement(elem, { ...rest, - ref: - "ref" in elem - ? mergeRefs([elem.ref as React.MutableRefObject, ref]) - : ref, + ref: elem.props.ref ? mergeRefs([elem.props.ref, ref]) : ref, onClick, }); } -export default React.forwardRef(CopyToClipboard); +export default CopyToClipboard; diff --git a/app/components/DelayedMount.ts b/app/components/DelayedMount.ts index 40a806a165..0fc403d6ba 100644 --- a/app/components/DelayedMount.ts +++ b/app/components/DelayedMount.ts @@ -2,7 +2,7 @@ import { useState, useEffect } from "react"; type Props = { delay?: number; - children: JSX.Element; + children: React.JSX.Element; }; export default function DelayedMount({ delay = 250, children }: Props) { diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index a64161ae92..9a9922440f 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -83,12 +83,16 @@ type Props = { * ancestors are shown. If less than or equal to 0, no items are shown. */ maxDepth?: number; + ref?: React.Ref; }; -function DocumentBreadcrumb( - { document, children, onlyText, maxDepth }: Props, - ref: React.RefObject | null -) { +function DocumentBreadcrumb({ + document, + children, + onlyText, + maxDepth, + ref, +}: Props) { const { collections } = useStores(); const { t } = useTranslation(); const sidebarContext = useLocationSidebarContext(); @@ -334,4 +338,4 @@ const SmallSlash = styled(GoToIcon)` opacity: 0.5; `; -export default observer(React.forwardRef(DocumentBreadcrumb)); +export default observer(DocumentBreadcrumb); diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index daa6dccde1..9fe7304bd5 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -45,13 +45,13 @@ type Props = { const VERTICAL_PADDING = 6; const HORIZONTAL_PADDING = 24; -const innerElementType = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(function innerElementType( - { style, ...rest }: React.HTMLAttributes, - ref -) { +function innerElementType({ + style, + ref, + ...rest +}: React.HTMLAttributes & { + ref?: React.Ref; +}) { return (
); -}); +} function DocumentExplorer({ onSubmit, diff --git a/app/components/DocumentExplorer/DocumentExplorerNode.tsx b/app/components/DocumentExplorer/DocumentExplorerNode.tsx index a47984d48c..9dfc313e8d 100644 --- a/app/components/DocumentExplorer/DocumentExplorerNode.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerNode.tsx @@ -33,25 +33,25 @@ type Props = { onClick: (ev: React.MouseEvent) => void; /** Fired when the node is double-clicked to submit the current selection. */ onDoubleClick: (ev: React.MouseEvent) => void; + /** Ref to the node element. */ + ref?: React.Ref; }; -function DocumentExplorerNode( - { - selected, - active, - style, - expanded, - icon, - title, - depth, - hasChildren, - onDisclosureClick, - onPointerMove, - onClick, - onDoubleClick, - }: Props, - ref: React.RefObject -) { +function DocumentExplorerNode({ + selected, + active, + style, + expanded, + icon, + title, + depth, + hasChildren, + onDisclosureClick, + onPointerMove, + onClick, + onDoubleClick, + ref, +}: Props) { const { t } = useTranslation(); const DISCLOSURE = 24; const width = (depth + 2) * DISCLOSURE; @@ -148,4 +148,4 @@ export const Node = styled.span<{ `} `; -export default observer(React.forwardRef(DocumentExplorerNode)); +export default observer(DocumentExplorerNode); diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index eeb3f79f0e..fa473f7c05 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -1,7 +1,3 @@ -import { - useFocusEffect, - useRovingTabIndex, -} from "@getoutline/react-roving-tabindex"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; @@ -35,6 +31,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import { ContextMenu } from "./Menu/ContextMenu"; import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels"; +import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; type Props = { document: Document; @@ -44,6 +41,7 @@ type Props = { showCollection?: boolean; showPublished?: boolean; showDraft?: boolean; + ref?: React.RefObject; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -53,10 +51,7 @@ function replaceResultMarks(tag: string) { return tag.replace(new RegExp(SEARCH_RESULT_REGEX.source), "$1"); } -function DocumentListItem( - props: Props, - ref: React.RefObject -) { +function DocumentListItem(props: Props) { const { t } = useTranslation(); const user = useCurrentUser(); const theme = useTheme(); @@ -66,14 +61,13 @@ function DocumentListItem( const selection = useModelSelection(); const iconRef = React.useRef(null); - let itemRef: React.Ref = + let itemRef: React.RefObject = React.useRef(null); - if (ref) { - itemRef = ref; + if (props.ref) { + itemRef = props.ref; } const { focused, ...rovingTabIndex } = useRovingTabIndex(itemRef, false); - useFocusEffect(focused, itemRef); const { document, @@ -83,6 +77,7 @@ function DocumentListItem( showDraft = true, highlight, context, + ref: _ref, ...rest } = props; const queryIsInTitle = @@ -445,4 +440,4 @@ const ResultContext = styled(Highlight)` overflow: hidden; `; -export default observer(React.forwardRef(DocumentListItem)); +export default observer(DocumentListItem); diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx index 2a9bcfdce6..9709f3eead 100644 --- a/app/components/EditableTitle.tsx +++ b/app/components/EditableTitle.tsx @@ -20,6 +20,7 @@ type Props = Omit, "onSubmit"> & { maxLength?: number; /** The default editing state. */ isEditing?: boolean; + ref?: React.Ref; }; export type RefHandle = { @@ -27,10 +28,15 @@ export type RefHandle = { setIsEditing: (isEditing: boolean) => void; }; -function EditableTitle( - { title, onSubmit, canUpdate, onEditing, onCancel, ...rest }: Props, - ref: React.RefObject -) { +function EditableTitle({ + title, + onSubmit, + canUpdate, + onEditing, + onCancel, + ref, + ...rest +}: Props) { const [isEditing, setIsEditing] = React.useState(rest.isEditing || false); const [originalValue, setOriginalValue] = React.useState(title); const [value, setValue] = React.useState(title); @@ -190,4 +196,4 @@ const Input = styled.input` } `; -export default React.forwardRef(EditableTitle); +export default EditableTitle; diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index fd127de3c3..e0b0dcd73c 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -32,7 +32,7 @@ export type Props = Optional< editorStyle?: React.CSSProperties; }; -function Editor(props: Props, ref: React.RefObject | null) { +function Editor({ ref, ...props }: Props & { ref?: React.Ref }) { const { id, onChange, @@ -45,9 +45,9 @@ function Editor(props: Props, ref: React.RefObject | null) { const { shareId } = useShare(); const { t } = useTranslation(); const embeds = useEmbeds(!shareId); - const localRef = React.useRef(); + const localRef = React.useRef(undefined); const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences; - const previousCommentIds = React.useRef(); + const previousCommentIds = React.useRef(undefined); // Upload progress tracking for delayed toast const progressMap = React.useMemo(() => new Map(), []); @@ -265,4 +265,4 @@ function Editor(props: Props, ref: React.RefObject | null) { ); } -export default observer(React.forwardRef(Editor)); +export default observer(Editor); diff --git a/app/components/Fade.tsx b/app/components/Fade.tsx index a3de3c4eb4..8e0aeccfd2 100644 --- a/app/components/Fade.tsx +++ b/app/components/Fade.tsx @@ -12,7 +12,7 @@ const Fade = styled.span<{ timing?: number | string }>` `; type Props = { - children?: JSX.Element | null; + children?: React.JSX.Element | null; /** If true, children will be animated. */ animate: boolean; }; diff --git a/app/components/Header.tsx b/app/components/Header.tsx index 1d7ad66ce8..bbf3e640ef 100644 --- a/app/components/Header.tsx +++ b/app/components/Header.tsx @@ -35,12 +35,10 @@ type Props = { | React.ReactNode; hasSidebar?: boolean; className?: string; + ref?: React.Ref; }; -function Header( - { left, title, actions, hasSidebar, className }: Props, - ref: React.RefObject | null -) { +function Header({ left, title, actions, hasSidebar, className, ref }: Props) { const { ui } = useStores(); const { t } = useTranslation(); const { pane, isSplitView } = useSplitView(); @@ -251,4 +249,4 @@ const CloseSplitPaneButton = styled(Button)` pointer-events: auto; `; -export default observer(React.forwardRef(Header)); +export default observer(Header); diff --git a/app/components/HoverPreview/HoverPreview.tsx b/app/components/HoverPreview/HoverPreview.tsx index 00965d055c..e0c8419338 100644 --- a/app/components/HoverPreview/HoverPreview.tsx +++ b/app/components/HoverPreview/HoverPreview.tsx @@ -44,7 +44,9 @@ const HoverPreviewDesktop = observer( ({ element, unfurlId, dataLoading, onClose }: Props) => { const { unfurls } = useStores(); const [isVisible, setVisible] = React.useState(false); - const timerClose = React.useRef>(); + const timerClose = React.useRef | undefined>( + undefined + ); const cardRef = React.useRef(null); const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } = useHoverPosition({ @@ -248,7 +250,7 @@ function useHoverPosition({ element, isVisible, }: { - cardRef: React.RefObject; + cardRef: React.RefObject; element: HTMLElement | null; isVisible: boolean; }) { diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 4483d79fbe..2979d3187d 100644 --- a/app/components/HoverPreview/HoverPreviewDocument.tsx +++ b/app/components/HoverPreview/HoverPreviewDocument.tsx @@ -13,12 +13,18 @@ import { Description, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( - { url, id, title, summary, lastActivityByViewer }: Props, - ref: React.Ref -) { +function HoverPreviewDocument({ + url, + id, + title, + summary, + lastActivityByViewer, + ref, +}: Props) { const parsedUrl = new URL(url, window.location.href); const content = ( @@ -57,6 +63,6 @@ const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( {content} ); -}); +} export default HoverPreviewDocument; diff --git a/app/components/HoverPreview/HoverPreviewGroup.tsx b/app/components/HoverPreview/HoverPreviewGroup.tsx index 55177186e7..e056d34f7a 100644 --- a/app/components/HoverPreview/HoverPreviewGroup.tsx +++ b/app/components/HoverPreview/HoverPreviewGroup.tsx @@ -15,12 +15,17 @@ import { } from "./Components"; import ErrorBoundary from "../ErrorBoundary"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( - { name, description, memberCount, users }: Props, - ref: React.Ref -) { +function HoverPreviewGroup({ + name, + description, + memberCount, + users, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -65,6 +70,6 @@ const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( ); -}); +} export default HoverPreviewGroup; diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index bc7baef6d0..2fd4ba3c9b 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -21,12 +21,21 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( - { url, id, title, description, author, labels, state, createdAt }: Props, - ref: React.Ref -) { +function HoverPreviewIssue({ + url, + id, + title, + description, + author, + labels, + state, + createdAt, + ref, +}: Props) { const authorName = author.name; const urlObj = new URL(url); const service = @@ -88,7 +97,7 @@ const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( ); -}); +} const StyledIssueStatusIcon = styled(IssueStatusIcon)` margin-top: 2px; diff --git a/app/components/HoverPreview/HoverPreviewLink.tsx b/app/components/HoverPreview/HoverPreviewLink.tsx index b5ef796948..868c4605a7 100644 --- a/app/components/HoverPreview/HoverPreviewLink.tsx +++ b/app/components/HoverPreview/HoverPreviewLink.tsx @@ -18,12 +18,16 @@ type Props = { thumbnailUrl: string; /** Some description about the link provider */ description: string; + ref?: React.Ref; }; -const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( - { url, thumbnailUrl, title, description }: Props, - ref: React.Ref -) { +function HoverPreviewLink({ + url, + thumbnailUrl, + title, + description, + ref, +}: Props) { return ( @@ -39,6 +43,6 @@ const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( ); -}); +} export default HoverPreviewLink; diff --git a/app/components/HoverPreview/HoverPreviewMention.tsx b/app/components/HoverPreview/HoverPreviewMention.tsx index e05ccbcbcc..2db4b88079 100644 --- a/app/components/HoverPreview/HoverPreviewMention.tsx +++ b/app/components/HoverPreview/HoverPreviewMention.tsx @@ -4,12 +4,17 @@ import { Avatar, AvatarSize } from "~/components/Avatar"; import Flex from "~/components/Flex"; import { Preview, Title, Info, Card, CardContent } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( - { avatarUrl, name, lastActive, color }: Props, - ref: React.Ref -) { +function HoverPreviewMention({ + avatarUrl, + name, + lastActive, + color, + ref, +}: Props) { return ( @@ -32,6 +37,6 @@ const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( ); -}); +} export default HoverPreviewMention; diff --git a/app/components/HoverPreview/HoverPreviewProject.tsx b/app/components/HoverPreview/HoverPreviewProject.tsx index 9cfb43a83a..f45b6a6b97 100644 --- a/app/components/HoverPreview/HoverPreviewProject.tsx +++ b/app/components/HoverPreview/HoverPreviewProject.tsx @@ -30,12 +30,21 @@ type Props = Pick< | "state" | "targetDate" | "description" ->; +> & { + ref?: React.Ref; +}; -const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( - { url, name, color, lead, labels, state, description, targetDate }: Props, - ref: React.Ref -) { +function HoverPreviewProject({ + url, + name, + color, + lead, + labels, + state, + description, + targetDate, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -116,7 +125,7 @@ const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( ); -}); +} const StyledSquircle = styled(Squircle)` flex-shrink: 0; diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx index e9a4f41eca..d0b11c5343 100644 --- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx +++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx @@ -19,57 +19,63 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewPullRequest = React.forwardRef( - function HoverPreviewPullRequest_( - { url, title, id, description, author, state, createdAt }: Props, - ref: React.Ref - ) { - const authorName = author.name; +function HoverPreviewPullRequest({ + url, + title, + id, + description, + author, + state, + createdAt, + ref, +}: Props) { + const authorName = author.name; - return ( - - - - - - - <StyledPullRequestIcon size={18} state={state} /> - <span> - <Backticks content={title} /> -  <Text type="tertiary">{id}</Text> - </span> - - - - - - {{ authorName }} opened{" "} - - - - {description && ( - - }> - - - - )} + return ( + + + + + + + <StyledPullRequestIcon size={18} state={state} /> + <span> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> + </span> + + + + + + {{ authorName }} opened{" "} + + - - - - - ); - } -); + {description && ( + + }> + + + + )} + + + + + + ); +} const StyledPullRequestIcon = styled(PullRequestIcon)` margin-top: 2px; diff --git a/app/components/IconPicker/components/Grid.tsx b/app/components/IconPicker/components/Grid.tsx index 9be2b95de9..b82ac48bfc 100644 --- a/app/components/IconPicker/components/Grid.tsx +++ b/app/components/IconPicker/components/Grid.tsx @@ -10,12 +10,18 @@ type Props = { columns: number; itemWidth: number; onOverflowChange?: (hasMoreBelow: boolean) => void; + ref?: React.Ref; }; -const Grid = ( - { width, height, data, columns, itemWidth, onOverflowChange }: Props, - ref: React.Ref -) => { +function Grid({ + width, + height, + data, + columns, + itemWidth, + onOverflowChange, + ref, +}: Props) { const offsetRef = React.useRef(0); const maxOffset = Math.max(0, data.length * itemWidth - height); @@ -47,7 +53,7 @@ const Grid = ( {Row} ); -}; +} type RowProps = { data: React.ReactNode[][]; @@ -82,4 +88,4 @@ const RowContainer = styled.div<{ columns: number }>` align-content: center; `; -export default React.forwardRef(Grid); +export default Grid; diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx index 27f1df6ae0..2d0238a9b2 100644 --- a/app/components/IconPicker/components/GridTemplate.tsx +++ b/app/components/IconPicker/components/GridTemplate.tsx @@ -58,20 +58,20 @@ type Props = { onIconActive?: (icon: IconNode) => void; /** Callback when whether the grid has content below the fold changes */ onOverflowChange?: (hasMoreBelow: boolean) => void; + /** Ref to the scrolling container */ + ref?: React.Ref; }; -const GridTemplate = ( - { - width, - height, - data, - empty, - onIconSelect, - onIconActive, - onOverflowChange, - }: Props, - ref: React.Ref -) => { +function GridTemplate({ + width, + height, + data, + empty, + onIconSelect, + onIconActive, + onOverflowChange, + ref, +}: Props) { const isMobile = useMobile(); const buttonSize = isMobile ? BUTTON_SIZE_MOBILE : BUTTON_SIZE_DESKTOP; const iconSize = isMobile ? ICON_SIZE_MOBILE : ICON_SIZE_DESKTOP; @@ -159,7 +159,7 @@ const GridTemplate = ( onOverflowChange={onOverflowChange} /> ); -}; +} const CategoryName = styled(Text)` grid-column: 1 / -1; @@ -173,4 +173,4 @@ const Icon = styled.svg` transition-delay: var(--delay); `; -export default React.forwardRef(GridTemplate); +export default GridTemplate; diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 99c5cf8c42..1a75fa77ba 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -192,10 +192,11 @@ export interface Props extends Omit< } function Input( - props: Props, - ref: React.RefObject + props: Props & { ref?: React.Ref } ) { - const internalRef = React.useRef(); + const internalRef = React.useRef< + HTMLInputElement | HTMLTextAreaElement | undefined + >(undefined); const [focused, setFocused] = React.useState(false); const [charCount, setCharCount] = React.useState(() => { if (typeof props.value === "string") { @@ -282,6 +283,7 @@ function Input( onChange, onRequestSubmit, children, + ref, ...rest } = props; @@ -322,7 +324,7 @@ function Input( , + ref as React.Ref, ])} onBlur={handleBlur} onFocus={handleFocus} @@ -340,10 +342,7 @@ function Input( /> ) : ( , - ])} + ref={mergeRefs([internalRef, ref as React.Ref])} onBlur={handleBlur} onFocus={handleFocus} hasIcon={!!icon} @@ -384,4 +383,4 @@ export const TextWrapper = styled.span` margin-top: -16px; `; -export default React.forwardRef(Input); +export default Input; diff --git a/app/components/InputSearch.tsx b/app/components/InputSearch.tsx index 5cba7ab023..0b185c5958 100644 --- a/app/components/InputSearch.tsx +++ b/app/components/InputSearch.tsx @@ -12,12 +12,10 @@ type Props = InputProps & { onFocus?: (event: React.FocusEvent) => unknown; onChange?: (event: React.ChangeEvent) => unknown; onKeyDown?: (event: React.KeyboardEvent) => unknown; + ref?: React.Ref; }; -function InputSearch( - props: Props, - ref: React.RefObject -) { +function InputSearch(props: Props) { const { t } = useTranslation(); const theme = useTheme(); const [isFocused, setIsFocused] = React.useState(false); @@ -26,6 +24,7 @@ function InputSearch( onKeyDown, onBlur, onFocus, + ref, ...rest } = props; @@ -65,4 +64,4 @@ function InputSearch( ); } -export default React.forwardRef(InputSearch); +export default InputSearch; diff --git a/app/components/InputSelect.tsx b/app/components/InputSelect.tsx index 7111993fcb..aace4093af 100644 --- a/app/components/InputSelect.tsx +++ b/app/components/InputSelect.tsx @@ -77,139 +77,138 @@ type Props = Omit, "onChange"> & { help?: string; /** Render function to override the selected value shown in the trigger. Receives the currently selected option, or undefined when none is selected. */ displayValue?: (selectedOption: Item | undefined) => React.ReactNode; + ref?: React.Ref; } & TriggerButtonProps; -export const InputSelect = React.forwardRef( - (props, ref) => { - const { - options, - value, - onChange, - label, - labelHidden, - short, - help, - displayValue, - ...triggerProps - } = props; +export function InputSelect(props: Props) { + const { + ref, + options, + value, + onChange, + label, + labelHidden, + short, + help, + displayValue, + ...triggerProps + } = props; - const [localValue, setLocalValue] = React.useState(value); - const [open, setOpen] = React.useState(false); + const [localValue, setLocalValue] = React.useState(value); + const [open, setOpen] = React.useState(false); - const contentRef = - React.useRef>(null); + const contentRef = + React.useRef>(null); - const isMobile = useMobile(); + const isMobile = useMobile(); - const placeholder = `Select a ${label.toLowerCase()}`; - const optionsHaveIcon = options.some( - (opt) => opt.type === "item" && !!opt.icon - ); + const placeholder = `Select a ${label.toLowerCase()}`; + const optionsHaveIcon = options.some( + (opt) => opt.type === "item" && !!opt.icon + ); - const selectedOption = React.useMemo( - () => - localValue - ? (options.find( - (opt) => opt.type === "item" && opt.value === localValue - ) as Item | undefined) - : undefined, - [localValue, options] - ); + const selectedOption = React.useMemo( + () => + localValue + ? (options.find( + (opt) => opt.type === "item" && opt.value === localValue + ) as Item | undefined) + : undefined, + [localValue, options] + ); - const resolvedDisplayValue = displayValue - ? displayValue(selectedOption) - : undefined; + const resolvedDisplayValue = displayValue + ? displayValue(selectedOption) + : undefined; - const renderOption = React.useCallback( - (option: Option, idx: number) => { - if (option.type === "separator") { - return ; - } - - if (option.type === "heading") { - return ( - - {option.label} - - ); - } + const renderOption = React.useCallback( + (option: Option, idx: number) => { + if (option.type === "separator") { + return ; + } + if (option.type === "heading") { return ( - - + + {option.label} + ); - }, - [optionsHaveIcon] - ); - - const onValueChange = React.useCallback( - async (val: string) => { - setLocalValue(val); - onChange(val); - }, - [onChange, setLocalValue] - ); - - const enablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "auto"; } - }, []); - const disablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "none"; - } - }, []); - - React.useEffect(() => { - setLocalValue(value); - }, [value]); - - if (isMobile) { return ( - + + ); - } + }, + [optionsHaveIcon] + ); + const onValueChange = React.useCallback( + async (val: string) => { + setLocalValue(val); + onChange(val); + }, + [onChange, setLocalValue] + ); + + const enablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "auto"; + } + }, []); + + const disablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "none"; + } + }, []); + + React.useEffect(() => { + setLocalValue(value); + }, [value]); + + if (isMobile) { return ( - - + ); } -); -InputSelect.displayName = "InputSelect"; + + return ( + + + ); +} type MobileSelectProps = Props & { placeholder: string; @@ -217,125 +216,124 @@ type MobileSelectProps = Props & { resolvedDisplayValue?: React.ReactNode; }; -const MobileSelect = React.forwardRef( - (props, ref) => { - const { - options, - value, - onChange, - label, - labelHidden, - disabled, - short, - placeholder, - optionsHaveIcon, - displayValue: _displayValue, - resolvedDisplayValue, - ...triggerProps - } = props; +function MobileSelect(props: MobileSelectProps) { + const { + ref, + options, + value, + onChange, + label, + labelHidden, + disabled, + short, + placeholder, + optionsHaveIcon, + displayValue: _displayValue, + resolvedDisplayValue, + ...triggerProps + } = props; - const [open, setOpen] = React.useState(false); - const contentRef = - React.useRef>(null); + const [open, setOpen] = React.useState(false); + const contentRef = + React.useRef>(null); - const selectedOption = React.useMemo( - () => - value - ? options.find((opt) => opt.type === "item" && opt.value === value) - : undefined, - [value, options] - ); + const selectedOption = React.useMemo( + () => + value + ? options.find((opt) => opt.type === "item" && opt.value === value) + : undefined, + [value, options] + ); - const handleSelect = React.useCallback( - async (val: string) => { - setOpen(false); - onChange(val); - }, - [onChange] - ); + const handleSelect = React.useCallback( + async (val: string) => { + setOpen(false); + onChange(val); + }, + [onChange] + ); - const renderOption = React.useCallback( - (option: Option, idx: number) => { - if (option.type === "separator") { - return ; - } - - if (option.type === "heading") { - return ( - - {option.label} - - ); - } - - const isSelected = option === selectedOption; + const renderOption = React.useCallback( + (option: Option, idx: number) => { + if (option.type === "separator") { + return ; + } + if (option.type === "heading") { return ( - handleSelect(option.value)} - data-state={isSelected ? "checked" : "unchecked"} - > - + + {option.label} + ); - }, - [handleSelect, selectedOption, optionsHaveIcon] - ); - - const enablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "auto"; } - }, []); - const disablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "none"; - } - }, []); + const isSelected = option === selectedOption; - return ( - - - ); - } -); + {resolvedDisplayValue !== undefined ? ( + resolvedDisplayValue + ) : selectedOption ? ( +
@@ -246,7 +246,7 @@ export const AccessControlList = observer( } return true; }} - disabled={!can.update} + disabled={!can.manageUsers} value={membership.permission} />
diff --git a/app/components/Sharing/Collection/SharePopover.tsx b/app/components/Sharing/Collection/SharePopover.tsx index 89c6d3427b..d498ad498b 100644 --- a/app/components/Sharing/Collection/SharePopover.tsx +++ b/app/components/Sharing/Collection/SharePopover.tsx @@ -364,7 +364,7 @@ function SharePopover({ return ( - {can.update && ( + {can.manageUsers && ( { + if (ownerId && !owner) { + void users.fetch(ownerId); + } + }, [ownerId, owner, users]); const containerRef = React.useRef(null); const publicAccessRef = React.useRef(null); @@ -137,7 +145,7 @@ export const AccessControlList = observer( ) : usersInCollection ? ( } - title={collection.name} + title={collection.displayName} subtitle={t("Everyone in the collection")} actions={{t("Can view")}} /> @@ -160,6 +168,20 @@ export const AccessControlList = observer( ) : ( <> + {owner && ( + } + title={owner.name} + subtitle={t("Owner")} + actions={ + + {t("Can edit")} + + } + /> + )} {showLoading ? ( ) : ( @@ -168,22 +190,24 @@ export const AccessControlList = observer( invitedInSession={invitedInSession} /> )} - - - - } - title={t("Other people")} - subtitle={t("Other workspace members may have access")} - actions={ - - } - /> + {!ownerId && ( + + + + } + title={t("Other people")} + subtitle={t("Other workspace members may have access")} + actions={ + + } + /> + )} )} diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index 92c8e0e6f1..c7b0b5c02c 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -32,6 +32,7 @@ import { DraftsLink } from "./components/DraftsLink"; import DragPlaceholder from "./components/DragPlaceholder"; import { DismissableSidebarAction } from "./components/DismissableSidebarAction"; import HistoryNavigation from "./components/HistoryNavigation"; +import { PersonalDocs } from "./components/PersonalDocs"; import Section from "./components/Section"; import SharedWithMe from "./components/SharedWithMe"; import SidebarButton from "./components/SidebarButton"; @@ -79,6 +80,7 @@ function AppSidebar() { [SidebarSection.Starred]: , [SidebarSection.SharedWithMe]: , [SidebarSection.Collections]: , + [SidebarSection.Personal]: , }; return ( diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index a07b8ae95a..75697700bf 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -117,7 +117,7 @@ const CollectionLink: React.FC = ({ onDisclosureClick={onDisclosureClick} onExpand={handleExpand} canEdit={can.update} - labelText={collection.name} + labelText={collection.displayName} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} contextAction={contextMenuAction} diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx index 3ccbe06cdc..cbde050b87 100644 --- a/app/components/Sidebar/components/CollectionLinkChildren.tsx +++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx @@ -30,6 +30,8 @@ type Props = { expanded: boolean; /** Indentation depth of the parent collection. */ depth?: number; + /** Indentation depth of the child documents, defaults to below the collection. */ + childDepth?: number; /** Function to prefetch a document by ID. */ prefetchDocument?: (documentId: string) => Promise; /** Element to display above the child documents */ @@ -40,12 +42,13 @@ function CollectionLinkChildren({ collection, expanded, depth = 0, + childDepth: childDepthProp, prefetchDocument, children, }: Props) { // Documents sit one level below the collection, with a minimum that leaves // room for their own disclosure to the left of the label. - const childDepth = Math.max(depth + 1, 2); + const childDepth = childDepthProp ?? Math.max(depth + 1, 2); const { documents } = useStores(); const { t } = useTranslation(); // Scoped to this collection so that other collections do not re-render when @@ -90,17 +93,19 @@ function CollectionLinkChildren({ prefetchDocument={prefetchDocument} /> )} - {childDocuments?.length === 0 && !children && ( - - {t("Empty")} - - } - onClick={() => history.push(collection.url)} - depth={childDepth} - /> - )} + {childDocuments?.length === 0 && + !children && + !collection.isPersonal && ( + + {t("Empty")} + + } + onClick={() => history.push(collection.url)} + depth={childDepth} + /> + )} diff --git a/app/components/Sidebar/components/CollectionRow.tsx b/app/components/Sidebar/components/CollectionRow.tsx index 443dd3d27c..99a73f9fc8 100644 --- a/app/components/Sidebar/components/CollectionRow.tsx +++ b/app/components/Sidebar/components/CollectionRow.tsx @@ -165,7 +165,7 @@ function CollectionRow({ const labelElement = canEdit ? ( undefined)} isEditing={isEditing} onEditing={setIsEditing} @@ -174,7 +174,7 @@ function CollectionRow({ ref={editableTitleRef} /> ) : ( - collection.name + collection.displayName ); const iconElement = icon ?? ( @@ -212,7 +212,7 @@ function CollectionRow({ { id: collection.id, url: collection.path, - title: collection.name, + title: collection.displayName, sidebarContext, collapsedChildren: expanded ? undefined : collection.sortedDocuments, }, diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 37f35d2c7b..7f5d45a8c7 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -1,5 +1,6 @@ import type { Location } from "history"; import { observer } from "mobx-react"; +import { DocumentIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import type { match } from "react-router"; @@ -31,7 +32,7 @@ import { import { useSidebarExpansion } from "./SidebarExpansionContext"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; -import { indentForDepth } from "./SidebarLink"; +import { childDepthFor, indentForDepth } from "./SidebarLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; @@ -172,10 +173,16 @@ const DocumentLink = observer(function DocumentLink({ const color = document?.color || node.color; const initial = document?.initial || node.title.charAt(0).toUpperCase(); + // Rows at the top level of a section show the default icon, so that they + // align with the other rows in the sidebar. const iconElement = React.useMemo( () => - icon ? : undefined, - [icon, color, initial] + icon ? ( + + ) : depth === 0 ? ( + + ) : undefined, + [icon, color, initial, depth, isDraft] ); const [{ isDragging }, drag] = useDragDocument( @@ -207,7 +214,9 @@ const DocumentLink = observer(function DocumentLink({ // dragged skips the position after itself, which would be a no-op. const targetsBelow = React.useMemo(() => { if (expanded && hasChildren) { - return [{ parentDocumentId: node.id, index: 0, depth: depth + 1 }]; + return [ + { parentDocumentId: node.id, index: 0, depth: childDepthFor(depth) }, + ]; } const afterSelf = isDragging ? [] diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx index 256575b1c6..8889543abd 100644 --- a/app/components/Sidebar/components/DocumentTree.tsx +++ b/app/components/Sidebar/components/DocumentTree.tsx @@ -6,7 +6,10 @@ import * as React from "react"; import scrollIntoView from "scroll-into-view-if-needed"; import type { NavigationNode } from "@shared/types"; import { sortNavigationNodes } from "@shared/utils/collections"; -import { flattenExpandedTree } from "@shared/utils/tree"; +import { + flattenExpandedTree, + type FlattenedTreeNode, +} from "@shared/utils/tree"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import type GroupMembership from "~/models/GroupMembership"; @@ -79,27 +82,30 @@ export const DocumentTree = observer(function DocumentTree({ const rows = useComputed( () => - flattenExpandedTree({ - nodes, - depth, - parentId, - isExpanded: (nodeId) => expansion.isExpanded(nodeId), - getChildren: (node) => { - // Show an unpublished draft below its parent while it is open. - if ( - collection && - activeDraft && - activeDraft.parentDocumentId === node.id - ) { - return sortNavigationNodes( - [activeDraft.asNavigationNode, ...node.children], - collection.sort, - false - ); - } - return node.children; - }, - }), + withChildDepth( + flattenExpandedTree({ + nodes, + depth, + parentId, + isExpanded: (nodeId) => expansion.isExpanded(nodeId), + getChildren: (node) => { + // Show an unpublished draft below its parent while it is open. + if ( + collection && + activeDraft && + activeDraft.parentDocumentId === node.id + ) { + return sortNavigationNodes( + [activeDraft.asNavigationNode, ...node.children], + collection.sort, + false + ); + } + return node.children; + }, + }), + depth + ), [nodes, depth, parentId, collection, expansion, activeDraft] ); @@ -273,3 +279,28 @@ export const DocumentTree = observer(function DocumentTree({ ); }); + +/** + * Moves the descendants of root rows at depth 0 one level deeper, so that the + * rows match childDepthFor. + * + * @param rows The flattened rows of the tree. + * @param depth The depth of the root rows. + * @returns the rows with adjusted depths. + */ +function withChildDepth( + rows: FlattenedTreeNode[], + depth: number +): FlattenedTreeNode[] { + if (depth !== 0) { + return rows; + } + + const adjust = (row: FlattenedTreeNode): FlattenedTreeNode => + row.depth === 0 ? row : { ...row, depth: row.depth + 1 }; + + return rows.map((row) => ({ + ...adjust(row), + trailingAncestors: row.trailingAncestors.map(adjust), + })); +} diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index e46c9cad1c..dc3fc6b285 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -83,7 +83,7 @@ function DraggableCollectionLink({ collection, belowCollection }: Props) { type: "collection", item: () => ({ id: collection.id, - title: collection.name, + title: collection.displayName, icon: , }), collect: (monitor) => ({ diff --git a/app/components/Sidebar/components/DraggableSection.tsx b/app/components/Sidebar/components/DraggableSection.tsx index 29577e158b..8ce612f44e 100644 --- a/app/components/Sidebar/components/DraggableSection.tsx +++ b/app/components/Sidebar/components/DraggableSection.tsx @@ -112,6 +112,7 @@ function DraggableSection({ section, children }: Props) { [SidebarSection.Starred]: t("Starred"), [SidebarSection.SharedWithMe]: t("Shared with me"), [SidebarSection.Collections]: t("Collections"), + [SidebarSection.Personal]: t("Personal"), }; const order = normalizeSidebarSectionOrder( diff --git a/app/components/Sidebar/components/PersonalDocs.tsx b/app/components/Sidebar/components/PersonalDocs.tsx new file mode 100644 index 0000000000..f16dc84c8b --- /dev/null +++ b/app/components/Sidebar/components/PersonalDocs.tsx @@ -0,0 +1,172 @@ +import { observer } from "mobx-react"; +import { DocumentIcon, PlusIcon } from "outline-icons"; +import { useCallback, useMemo, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { useHistory } from "react-router-dom"; +import { PersonalCollectionId } from "@shared/constants"; +import { UserPreference } from "@shared/types"; +import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; +import { DocumentValidation } from "@shared/validations"; +import { createAction } from "~/actions"; +import { DocumentSection } from "~/actions/sections"; +import EditableTitle, { type RefHandle } from "~/components/EditableTitle"; +import Flex from "~/components/Flex"; +import useBoolean from "~/hooks/useBoolean"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; +import usePolicy from "~/hooks/usePolicy"; +import useStores from "~/hooks/useStores"; +import { useSyncSidebarContext } from "~/hooks/useSyncSidebarContext"; +import { documentEditPath } from "~/utils/routeHelpers"; +import CollectionLinkChildren from "./CollectionLinkChildren"; +import Header from "./Header"; +import Relative from "./Relative"; +import SidebarAction from "./SidebarAction"; +import SidebarContext, { type SidebarContextType } from "./SidebarContext"; +import SidebarLink from "./SidebarLink"; + +/** + * The sidebar section that shows the documents in the personal collection of + * the current user. + */ +export const PersonalDocs = observer(function PersonalDocs() { + const { collections, documents } = useStores(); + const { t } = useTranslation(); + const history = useHistory(); + const user = useCurrentUser(); + const team = useCurrentTeam(); + const can = usePolicy(team); + const collection = collections.personal; + const canCollection = usePolicy(collection); + const canCreate = collection + ? !!canCollection.createDocument + : !!can.createPersonalCollection; + const [isAddingNew, setIsAddingNew, closeAddingNew] = useBoolean(); + const newTitleRef = useRef(null); + + // Opens a temporary row with an editable title, the document is only + // created once a title is submitted. + const newDocAction = useMemo( + () => + createAction({ + name: ({ t, isMenu }) => (isMenu ? t("New document") : t("New doc")), + analyticsName: "New personal document", + section: DocumentSection, + icon: , + keywords: "create personal private", + visible: canCreate, + perform: setIsAddingNew, + }), + [canCreate, setIsAddingNew] + ); + const headerActions = useMemo(() => [newDocAction], [newDocAction]); + + const handleNewDoc = useCallback( + async (title: string) => { + // The personal collection is created with the first document. + const newDocument = await documents.create( + { + collectionId: collection?.id ?? PersonalCollectionId, + title, + fullWidth: user.getPreference(UserPreference.FullWidthDocuments), + data: ProsemirrorDataHelper.getEmpty(), + }, + { publish: true } + ); + if (newDocument.collectionId) { + const personal = + collection ?? (await collections.fetch(newDocument.collectionId)); + personal.addDocument(newDocument); + } + history.push({ + pathname: documentEditPath(newDocument), + state: { sidebarContext: "personal" }, + }); + }, + [collection, collections, documents, user, history] + ); + + const handleNewDocSubmit = useCallback( + async (value: string) => { + try { + newTitleRef.current?.setIsEditing(false); + await handleNewDoc(value); + closeAddingNew(); + } catch (_err) { + newTitleRef.current?.setIsEditing(true); + } + }, + [handleNewDoc, closeAddingNew] + ); + + const collectionId = collection?.id; + useSyncSidebarContext( + useCallback( + (context: NonNullable) => context === "personal", + [] + ), + useCallback( + (activeDocumentId: string) => + collectionId && + documents.get(activeDocumentId)?.collectionId === collectionId + ? "personal" + : undefined, + [documents, collectionId] + ) + ); + + if (!collection && !canCreate) { + return null; + } + + const newDocRow = + isAddingNew && canCreate ? ( + true} + depth={0} + icon={} + ellipsis={false} + label={ + + } + /> + ) : null; + + return ( + + +
+ + {collection ? ( + + {newDocRow} + + ) : ( + newDocRow + )} + + +
+
+
+ ); +}); diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 901faab02a..43b345eb86 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -227,6 +227,14 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { parentRef={parentRef} dropToReparentRef={dropToReparent} isActiveDropTarget={isOverReparent} + cursorAfter={ + reorderProps.isDragging ? ( + + ) : undefined + } menu={menu} menuOpen={menuOpen} isActiveOverride={isActive} @@ -240,16 +248,13 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { parentId={document.id} collection={collection} membership={membership} + // Loads the document and its policies on hover, without which + // rows that were never opened cannot be dragged or dropped on. + prefetchDocument={documents.prefetchDocument} /> - {reorderProps.isDragging && ( - - )}
); } diff --git a/app/components/Sidebar/components/SidebarContext.ts b/app/components/Sidebar/components/SidebarContext.ts index 71a3833182..1c08ae9ff4 100644 --- a/app/components/Sidebar/components/SidebarContext.ts +++ b/app/components/Sidebar/components/SidebarContext.ts @@ -5,6 +5,7 @@ import type User from "~/models/User"; export type SidebarContextType = | "collections" | "shared" + | "personal" | "archive" | `group-${string}` | `starred-${string}` @@ -57,7 +58,10 @@ export const determineSidebarContext = ({ } if (document.collection) { - return document.collection.isArchived ? "archive" : "collections"; + if (document.collection.isArchived) { + return "archive"; + } + return document.collection.isPersonal ? "personal" : "collections"; } else if ( user.documentMemberships.find((m) => m.documentId === document.id) ) { diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 0689edb134..5793305a90 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -30,6 +30,17 @@ export function indentForDepth(depth: number): number { return depth * 16 + 12; } +/** + * Returns the nesting depth of the children of a sidebar row. A row at depth 0 + * shows an icon, so its children skip a level to start beyond the icon. + * + * @param depth The nesting depth of the row, 0-based. + * @returns the nesting depth of the children. + */ +export function childDepthFor(depth: number): number { + return depth === 0 ? 2 : depth + 1; +} + /** * Props for the SidebarLink component. * Extends NavLink props with additional sidebar-specific functionality. diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index ee8774bdb1..2de85b68fd 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -353,7 +353,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ onExpand={handleExpand} onClickIntent={handlePrefetch} canEdit={can.update} - labelText={collection.name} + labelText={collection.displayName} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} contextAction={contextMenuAction} diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 0f3ca5fb71..d49291efa8 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -394,7 +394,7 @@ export function useDropToChangeCollection( "You do not have permission to move {{ documentName }} to the {{ collectionName }} collection", { documentName: item.title, - collectionName: collection.name, + collectionName: collection.displayName, } ) ); diff --git a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx index 79c5071001..eff563fb43 100644 --- a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx +++ b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx @@ -33,7 +33,7 @@ export function useSidebarLabelAndIcon({ const initial = document?.initial; const color = document?.color; const isDraft = document?.isDraft; - const collectionName = collection?.name; + const collectionName = collection?.displayName; return React.useMemo(() => { if (document) { diff --git a/app/components/TemplatizeDialog/SelectLocation.tsx b/app/components/TemplatizeDialog/SelectLocation.tsx index 1a293d3131..e3d5a17793 100644 --- a/app/components/TemplatizeDialog/SelectLocation.tsx +++ b/app/components/TemplatizeDialog/SelectLocation.tsx @@ -52,7 +52,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => { if (canCollection.createTemplate) { memo.push({ type: "item", - label: collection.name, + label: collection.displayName, value: collection.id, icon: , }); diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx index a1311c9356..92a268fc25 100644 --- a/app/editor/components/MentionMenu.tsx +++ b/app/editor/components/MentionMenu.tsx @@ -185,6 +185,8 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { .concat( collections .findByQuery(search, { maxResults: maxResultsInSection, weight }) + // A personal collection has no page for a mention to link to. + .filter((collection) => !collection.isPersonal) .map((collection) => collectionMentionItem(collection, actorId)) ) .concat( diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index 557a76b1fa..14ac459653 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -197,7 +197,7 @@ export default class PasteHandler extends Extension { state.schema.nodes.mention.create({ type: MentionType.Collection, modelId: collection.id, - label: collection.name, + label: collection.displayName, id: uuidv4(), }) ) @@ -209,7 +209,7 @@ export default class PasteHandler extends Extension { IconType.Emoji; const title = `${hasEmoji ? collection.icon + " " : ""}${ - collection.name + collection.displayName }`; this.insertLink(`${collection.path}${hash}`, title); diff --git a/app/editor/menus/mention.tsx b/app/editor/menus/mention.tsx index 22669bf984..1027c08384 100644 --- a/app/editor/menus/mention.tsx +++ b/app/editor/menus/mention.tsx @@ -128,7 +128,7 @@ export function collectionMentionItem( ) : ( ), - title: collection.name, + title: collection.displayName, section: CollectionsSection, appendSpace: true, attrs: { @@ -136,7 +136,7 @@ export function collectionMentionItem( type: MentionType.Collection, modelId: collection.id, actorId, - label: collection.name, + label: collection.displayName, }, }; } diff --git a/app/hooks/useCollectionTrees.ts b/app/hooks/useCollectionTrees.ts index 829e50b6b7..a106ce8fa9 100644 --- a/app/hooks/useCollectionTrees.ts +++ b/app/hooks/useCollectionTrees.ts @@ -30,7 +30,7 @@ export default function useCollectionTrees(): NavigationNode[] { function getCollectionTree(collection: Collection): NavigationNode { const root: NavigationNode = { id: collection.id, - title: collection.name, + title: collection.displayName, url: collection.path, type: NavigationNodeType.Collection, collectionId: collection.id, diff --git a/app/hooks/useSyncSidebarContext.ts b/app/hooks/useSyncSidebarContext.ts new file mode 100644 index 0000000000..5889700332 --- /dev/null +++ b/app/hooks/useSyncSidebarContext.ts @@ -0,0 +1,53 @@ +import { useEffect } from "react"; +import { useHistory } from "react-router-dom"; +import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext"; +import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; +import useStores from "~/hooks/useStores"; +import { patchLocation } from "~/utils/history"; + +/** + * Writes the sidebar context of the active document into the location state, so + * that the section which contains the document is the one revealed in the + * sidebar. Sections the user is already looking at, and the starred section, + * are left alone. + * + * @param belongsToSection whether the given context is one of this section's own. + * @param resolve returns the context for the active document, or undefined when + * the document does not belong to this section. + */ +export function useSyncSidebarContext( + belongsToSection: (context: NonNullable) => boolean, + resolve: (activeDocumentId: string) => SidebarContextType | undefined +) { + const { ui } = useStores(); + const history = useHistory(); + const locationSidebarContext = useLocationSidebarContext(); + + useEffect(() => { + if ( + !ui.activeDocumentId || + (locationSidebarContext && + (belongsToSection(locationSidebarContext) || + locationSidebarContext.startsWith("starred"))) + ) { + return; + } + + const sidebarContext = resolve(ui.activeDocumentId); + if (!sidebarContext) { + return; + } + + history.push( + patchLocation(history.location, { + state: { + ...(history.location.state as Record), + sidebarContext, + }, + }) + ); + // `history` is read imperatively, the sidebar context should only be + // recalculated when the active document or memberships change. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ui.activeDocumentId, locationSidebarContext, belongsToSection, resolve]); +} diff --git a/app/menus/NewChildDocumentMenu.tsx b/app/menus/NewChildDocumentMenu.tsx index b3264c26d5..81f351d827 100644 --- a/app/menus/NewChildDocumentMenu.tsx +++ b/app/menus/NewChildDocumentMenu.tsx @@ -25,7 +25,7 @@ function NewChildDocumentMenu({ document }: Props) { const collection = document.collectionId ? collections.get(document.collectionId) : undefined; - const collectionName = collection ? collection.name : t("collection"); + const collectionName = collection ? collection.displayName : t("collection"); const actions = React.useMemo( () => [ diff --git a/app/menus/NewTemplateMenu.tsx b/app/menus/NewTemplateMenu.tsx index dd7e7f3a6b..23a4e264c5 100644 --- a/app/menus/NewTemplateMenu.tsx +++ b/app/menus/NewTemplateMenu.tsx @@ -30,7 +30,7 @@ function NewTemplateMenu() { collections.orderedData.map((collection) => { const canCollection = policies.abilities(collection.id); return createInternalLinkAction({ - name: collection.name, + name: collection.displayName, section: DocumentSection, icon: , visible: !!canCollection.createTemplate, diff --git a/app/models/Collection.test.ts b/app/models/Collection.test.ts index 6397b90444..c1edf365be 100644 --- a/app/models/Collection.test.ts +++ b/app/models/Collection.test.ts @@ -9,4 +9,16 @@ describe("Collection model", () => { }); expect(collection.name).toBe("Engineering"); }); + + it("should show the translated name for a personal collection", () => { + const collection = stores.collections.add({ + id: "456", + name: "Renamed", + ownerId: "user-id", + }); + expect(collection.displayName).toBe("Personal"); + + const shared = stores.collections.add({ id: "789", name: "Design" }); + expect(shared.displayName).toBe("Design"); + }); }); diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 228cac21ff..44e936ac66 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -1,3 +1,4 @@ +import i18n from "i18next"; import invariant from "invariant"; import { action, @@ -60,6 +61,10 @@ export default class Collection extends ParanoidModel { @Field @observable permission?: CollectionPermission = undefined; + + /** The user that owns this collection, if it is a personal collection. */ + @observable + ownerId: string | null; /** * Whether public sharing is enabled for the collection. Note this can also be disabled at the * workspace level. @@ -116,7 +121,18 @@ export default class Collection extends ParanoidModel { archivedBy?: User = undefined; @computed get searchContent(): string { - return this.name; + return this.displayName; + } + + /** + * The name to show for the collection. A personal collection is always shown + * with a translated name, whatever name is stored. + * + * @returns the name to display. + */ + @computed + get displayName(): string { + return this.isPersonal ? i18n.t("Personal") : this.name; } /** Returns whether the collection is empty, or undefined if not loaded. */ @@ -143,6 +159,15 @@ export default class Collection extends ParanoidModel { return this.permission === null; } + /** + * Whether this collection is the personal collection of a user. + * + * @returns boolean + */ + get isPersonal(): boolean { + return !!this.ownerId; + } + @computed get isStarred(): boolean { return !!this.store.rootStore.stars.orderedData.find( @@ -199,7 +224,7 @@ export default class Collection extends ParanoidModel { /** The initial letter of the collection name as a string. */ @computed get initial() { - return (this.name?.charAt(0) ?? "?").toUpperCase(); + return (this.displayName?.charAt(0) ?? "?").toUpperCase(); } @computed diff --git a/app/models/Document.ts b/app/models/Document.ts index 8256c06742..2051baf53e 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -135,6 +135,12 @@ export default class Document extends ArchivableModel implements Searchable { @Relation(() => Collection, { onDelete: "cascade" }) collection?: Collection; + /** + * The owner of the personal collection that this document is in, if any. + */ + @observable + ownerId?: string | null; + /** * The title of the document. */ diff --git a/app/models/Notification.ts b/app/models/Notification.ts index 6fd4c29f49..e925f3193d 100644 --- a/app/models/Notification.ts +++ b/app/models/Notification.ts @@ -256,7 +256,7 @@ class Notification extends Model { return this.document?.title ?? t("a document"); } if (this.collectionId) { - return this.collection?.name ?? t("a collection"); + return this.collection?.displayName ?? t("a collection"); } if (this.groupId) { return this.group?.name ?? t("a group"); diff --git a/app/scenes/Collection/components/Actions.tsx b/app/scenes/Collection/components/Actions.tsx index 8b638d9b59..5b6bc458f3 100644 --- a/app/scenes/Collection/components/Actions.tsx +++ b/app/scenes/Collection/components/Actions.tsx @@ -53,7 +53,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) { return ( <> - {(!isEditing || !user?.separateEditMode) && ( + {(!isEditing || !user?.separateEditMode) && !collection.isPersonal && ( diff --git a/app/scenes/Collection/components/Empty.tsx b/app/scenes/Collection/components/Empty.tsx index 3226725a0e..19cb5dbda7 100644 --- a/app/scenes/Collection/components/Empty.tsx +++ b/app/scenes/Collection/components/Empty.tsx @@ -12,7 +12,7 @@ type Props = { }; function EmptyCollection({ collection }: Props) { - const collectionName = collection ? collection.name : ""; + const collectionName = collection ? collection.displayName : ""; return ( diff --git a/app/scenes/Collection/components/Header.tsx b/app/scenes/Collection/components/Header.tsx index c9252fb53e..5236130477 100644 --- a/app/scenes/Collection/components/Header.tsx +++ b/app/scenes/Collection/components/Header.tsx @@ -49,7 +49,7 @@ export const Header = observer(function Header_({ ) : null; - const dir = isRTL(collection.name) ? "rtl" : "ltr"; + const dir = isRTL(collection.displayName) ? "rtl" : "ltr"; return ( @@ -80,7 +80,7 @@ export const Header = observer(function Header_({ dir="auto" /> ) : ( - collection.name + collection.displayName )} ); diff --git a/app/scenes/Collection/index.tsx b/app/scenes/Collection/index.tsx index 9c067deacc..01ea0fcd1c 100644 --- a/app/scenes/Collection/index.tsx +++ b/app/scenes/Collection/index.tsx @@ -98,7 +98,7 @@ const CollectionScene = observer(function CollectionScene_() { }, [collection, collection?.name, history, id, match.url]); useEffect(() => { - if (collection) { + if (collection && !collection.isPersonal) { ui.setActiveCollection(collection.id); } @@ -140,12 +140,17 @@ const CollectionScene = observer(function CollectionScene_() { return ; } + // A personal collection is only shown in the sidebar, it has no page. + if (collection.isPersonal) { + return ; + } + const showOverview = can.update || hasDescription; return ( @@ -161,12 +166,14 @@ const CollectionScene = observer(function CollectionScene_() { title={ <> -  {collection.name} +  {collection.displayName} } actions={ <> - + {!collection.isPersonal && ( + + )} {collections.nonPrivate.map((collection) => ( -
  • {collection.name}
  • +
  • {collection.displayName}
  • ))} } diff --git a/app/scenes/Search/components/CollectionFilter.tsx b/app/scenes/Search/components/CollectionFilter.tsx index 18768b7bfc..f61c65ef6a 100644 --- a/app/scenes/Search/components/CollectionFilter.tsx +++ b/app/scenes/Search/components/CollectionFilter.tsx @@ -20,7 +20,7 @@ function CollectionFilter(props: Props) { const options = useMemo(() => { const collectionOptions = collections.orderedData.map((collection) => ({ key: collection.id, - label: collection.name, + label: collection.displayName, icon: , })); return [ diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index 35ac63e6d0..e8ab25a5d7 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -164,6 +164,17 @@ function Security() { [saveData, team.preferences] ); + const handlePersonalDocsChange = React.useCallback( + async (checked: boolean) => { + const preferences = { + ...team.preferences, + [TeamPreference.PersonalDocs]: checked, + }; + await saveData({ preferences }); + }, + [saveData, team.preferences] + ); + const handleViewersCanExportChange = React.useCallback( async (checked: boolean) => { const preferences = { @@ -389,6 +400,19 @@ function Security() { short /> + + + , to: collectionPath(collection), diff --git a/app/scenes/Settings/components/TemplatesTable.tsx b/app/scenes/Settings/components/TemplatesTable.tsx index 6c29e9167f..b46a3e7224 100644 --- a/app/scenes/Settings/components/TemplatesTable.tsx +++ b/app/scenes/Settings/components/TemplatesTable.tsx @@ -97,7 +97,7 @@ export function TemplatesTable(props: Props) { type: "data", id: "collectionId", header: t("Visibility"), - accessor: (template) => template.collection?.name, + accessor: (template) => template.collection?.displayName, component: (template) => , width: "2fr", }, @@ -198,7 +198,9 @@ const Permission = observer(({ template }: { template: Template }) => { {template.collection ? ( ) : null} - {template.collectionId ? template.collection?.name : t("Workspace")} + {template.collectionId + ? template.collection?.displayName + : t("Workspace")} ); }); diff --git a/app/scenes/Shared/Collection.tsx b/app/scenes/Shared/Collection.tsx index 94b527aeec..7230c066aa 100644 --- a/app/scenes/Shared/Collection.tsx +++ b/app/scenes/Shared/Collection.tsx @@ -54,12 +54,12 @@ function SharedCollection({ collection }: Props) { return ( } title={ <> -  {collection.name} +  {collection.displayName} } actions={ @@ -75,7 +75,7 @@ function SharedCollection({ collection }: Props) { - {collection.name} + {collection.displayName} {!!shareId && showLastUpdated && !!collection.updatedAt ? ( diff --git a/app/scenes/Shared/index.tsx b/app/scenes/Shared/index.tsx index 7c7471a85b..b52d216929 100644 --- a/app/scenes/Shared/index.tsx +++ b/app/scenes/Shared/index.tsx @@ -138,7 +138,7 @@ function SharedScene() { const pageTitle = model instanceof Collection - ? model.name + ? model.displayName : model instanceof Document ? model.title : undefined; diff --git a/app/stores/CollectionsStore.ts b/app/stores/CollectionsStore.ts index c431ca9671..674101bf46 100644 --- a/app/stores/CollectionsStore.ts +++ b/app/stores/CollectionsStore.ts @@ -31,9 +31,23 @@ export default class CollectionsStore extends IndexedStore { : undefined; } + /** Active collections, other than the personal collection. */ @computed get allActive() { - return this.orderedData.filter((c) => c.isActive); + return this.orderedData.filter((c) => c.isActive && !c.isPersonal); + } + + /** + * Returns the personal collection of the current user, if it was loaded. + * + * @returns The personal Collection or undefined + */ + @computed + get personal(): Collection | undefined { + const userId = this.rootStore.auth.user?.id; + return userId + ? this.orderedData.find((c) => c.ownerId === userId) + : undefined; } @override @@ -73,7 +87,7 @@ export default class CollectionsStore extends IndexedStore { get all(): Collection[] { return sortBy( Array.from(this.data.values()), - (collection) => collection.name + (collection) => collection.displayName ); } diff --git a/plugins/webhooks/server/helpers/WebhookEventHelper.ts b/plugins/webhooks/server/helpers/WebhookEventHelper.ts new file mode 100644 index 0000000000..3374b3d851 --- /dev/null +++ b/plugins/webhooks/server/helpers/WebhookEventHelper.ts @@ -0,0 +1,78 @@ +import { Op } from "sequelize"; +import { + Attachment, + Collection, + Document, + FileOperation, +} from "@server/models"; +import type { Event } from "@server/types"; + +export class WebhookEventHelper { + /** + * Whether an event relates to a personal collection, or to a document, + * attachment or file operation in one. Such events are never sent to workspace webhooks, + * as any admin can change where a webhook delivers to. + * + * @param event The event to check. + * @returns true if the event is in a personal collection. + */ + public static async isInPersonalCollection(event: Event): Promise { + const modelId = "modelId" in event ? event.modelId : null; + const collectionIds: string[] = []; + let documentId = "documentId" in event ? event.documentId : null; + + if ("collectionId" in event && event.collectionId) { + collectionIds.push(event.collectionId); + } + if (event.name.startsWith("collections.") && modelId) { + collectionIds.push(modelId); + } + + if (event.name.startsWith("fileOperations.") && modelId) { + const fileOperation = await FileOperation.unscoped().findOne({ + attributes: ["collectionId", "documentId"], + where: { id: modelId }, + paranoid: false, + }); + if (fileOperation?.collectionId) { + collectionIds.push(fileOperation.collectionId); + } + documentId = documentId ?? fileOperation?.documentId ?? null; + } + + if (event.name.startsWith("attachments.") && modelId) { + const attachment = await Attachment.unscoped().findOne({ + attributes: ["documentId"], + where: { id: modelId }, + paranoid: false, + }); + documentId = documentId ?? attachment?.documentId ?? null; + } + + // The document may have moved since the event, so its current collection + // is checked as well. + if (documentId) { + const document = await Document.unscoped().findOne({ + attributes: ["collectionId"], + where: { id: documentId }, + paranoid: false, + }); + if (document?.collectionId) { + collectionIds.push(document.collectionId); + } + } + + if (!collectionIds.length) { + return false; + } + + const count = await Collection.unscoped().count({ + where: { + id: collectionIds, + ownerId: { [Op.ne]: null }, + }, + paranoid: false, + }); + return count > 0; + } +} diff --git a/plugins/webhooks/server/processors/WebhookProcessor.test.ts b/plugins/webhooks/server/processors/WebhookProcessor.test.ts index dae000d664..75f9758260 100644 --- a/plugins/webhooks/server/processors/WebhookProcessor.test.ts +++ b/plugins/webhooks/server/processors/WebhookProcessor.test.ts @@ -1,6 +1,13 @@ -import { buildUser, buildWebhookSubscription } from "@server/test/factories"; +import { + buildAdmin, + buildAttachment, + buildDocument, + buildPersonalCollection, + buildUser, + buildWebhookSubscription, +} from "@server/test/factories"; import { mockTaskSchedule } from "@server/test/support"; -import type { UserEvent } from "@server/types"; +import type { AttachmentEvent, DocumentEvent, UserEvent } from "@server/types"; import WebhookProcessor from "./WebhookProcessor"; const ip = "127.0.0.1"; @@ -133,4 +140,72 @@ describe("WebhookProcessor", () => { expect(await WebhookProcessor.shouldQueue(event)).toBe(false); }); }); + + it("does not schedule events in a personal collection", async () => { + const owner = await buildUser(); + const admin = await buildAdmin({ teamId: owner.teamId }); + const personal = await buildPersonalCollection(owner); + const document = await buildDocument({ + teamId: owner.teamId, + userId: owner.id, + collectionId: personal.id, + }); + for (const createdById of [admin.id, owner.id]) { + await buildWebhookSubscription({ + teamId: owner.teamId, + createdById, + url: "http://example.com", + events: ["*"], + }); + } + const processor = new WebhookProcessor(); + + const event: DocumentEvent = { + name: "documents.update", + documentId: document.id, + collectionId: personal.id, + teamId: owner.teamId, + actorId: owner.id, + ip, + createdAt: new Date().toISOString(), + data: { done: true }, + }; + schedule.mockClear(); + await processor.perform(event); + + expect(schedule).not.toHaveBeenCalled(); + }); + + it("does not schedule attachment events in a personal collection", async () => { + const owner = await buildUser(); + const personal = await buildPersonalCollection(owner); + const document = await buildDocument({ + teamId: owner.teamId, + userId: owner.id, + collectionId: personal.id, + }); + const attachment = await buildAttachment({ + teamId: owner.teamId, + userId: owner.id, + documentId: document.id, + }); + await buildWebhookSubscription({ + teamId: owner.teamId, + url: "http://example.com", + events: ["*"], + }); + + const event: AttachmentEvent = { + name: "attachments.create", + modelId: attachment.id, + teamId: owner.teamId, + actorId: owner.id, + ip, + data: { name: attachment.name }, + }; + schedule.mockClear(); + await new WebhookProcessor().perform(event); + + expect(schedule).not.toHaveBeenCalled(); + }); }); diff --git a/plugins/webhooks/server/processors/WebhookProcessor.ts b/plugins/webhooks/server/processors/WebhookProcessor.ts index 1a4b14097f..df2ad856d1 100644 --- a/plugins/webhooks/server/processors/WebhookProcessor.ts +++ b/plugins/webhooks/server/processors/WebhookProcessor.ts @@ -1,6 +1,7 @@ import { WebhookSubscription } from "@server/models"; import BaseProcessor from "@server/queues/processors/BaseProcessor"; import type { Event } from "@server/types"; +import { WebhookEventHelper } from "../helpers/WebhookEventHelper"; import DeliverWebhookTask from "../tasks/DeliverWebhookTask"; export default class WebhookProcessor extends BaseProcessor { @@ -40,6 +41,12 @@ export default class WebhookProcessor extends BaseProcessor { const applicableSubscriptions = subscriptions.filter((subscription) => WebhookSubscription.matchEvent(subscription.events, event.name) ); + if ( + !applicableSubscriptions.length || + (await WebhookEventHelper.isInPersonalCollection(event)) + ) { + return; + } await Promise.all( applicableSubscriptions.map((subscription) => diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts index 0b007ea601..ba21f0b824 100644 --- a/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts +++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.test.ts @@ -8,11 +8,14 @@ import { import { server } from "@server/test/msw"; import { WebhookDelivery } from "@server/models"; import { + buildCollection, + buildDocument, + buildPersonalCollection, buildUser, buildWebhookDelivery, buildWebhookSubscription, } from "@server/test/factories"; -import type { UserEvent } from "@server/types"; +import type { DocumentEvent, UserEvent } from "@server/types"; import DeliverWebhookTask, { isExpectedNetworkError, } from "./DeliverWebhookTask"; @@ -40,6 +43,50 @@ const captureWebhook = ( }; describe("DeliverWebhookTask", () => { + test("should not deliver events in a personal collection", async () => { + const owner = await buildUser(); + const subscription = await buildWebhookSubscription({ + teamId: owner.teamId, + createdById: owner.id, + url: "http://example.com", + events: ["*"], + }); + const previous = await buildCollection({ + teamId: owner.teamId, + userId: owner.id, + }); + const personal = await buildPersonalCollection(owner); + const document = await buildDocument({ + teamId: owner.teamId, + userId: owner.id, + collectionId: personal.id, + }); + const captured = captureWebhook("http://example.com"); + + // The event was queued before the document moved to the personal collection. + const event: DocumentEvent = { + name: "documents.update", + documentId: document.id, + collectionId: previous.id, + teamId: owner.teamId, + actorId: owner.id, + ip, + createdAt: new Date().toISOString(), + data: { done: true }, + }; + await new DeliverWebhookTask().perform({ + subscriptionId: subscription.id, + event, + }); + + expect(captured.length).toBe(0); + expect( + await WebhookDelivery.count({ + where: { webhookSubscriptionId: subscription.id }, + }) + ).toBe(0); + }); + test("should hit the subscription url and record a delivery", async () => { const subscription = await buildWebhookSubscription({ url: "http://example.com", diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts index c9db826617..362b306ce7 100644 --- a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts +++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts @@ -71,6 +71,7 @@ import type { WebhookSubscriptionEvent, } from "@server/types"; import fetch from "@server/utils/fetch"; +import { WebhookEventHelper } from "../helpers/WebhookEventHelper"; import type { WebhookPayload } from "../presenters/webhook"; import presentWebhook from "../presenters/webhook"; import presentWebhookSubscription from "../presenters/webhookSubscription"; @@ -151,6 +152,16 @@ export default class DeliverWebhookTask extends BaseTask { return; } + // Checked again, as a document can move into a personal collection after + // the delivery was queued. + if (await WebhookEventHelper.isInPersonalCollection(event)) { + Logger.info("task", `Skipped webhook for personal collection event`, { + event: event.name, + subscriptionId: subscription.id, + }); + return; + } + Logger.info("task", `DeliverWebhookTask: ${event.name}`, { event: event.name, subscriptionId: subscription.id, diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index aa69671cd2..8b9103c48e 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -217,6 +217,7 @@ async function accountProvisioner( const count = await Collection.count({ where: { teamId: team.id, + ownerId: null, }, }); provision = count === 0; diff --git a/server/commands/documentCreator.ts b/server/commands/documentCreator.ts index dd0e09b388..8d4afaf09f 100644 --- a/server/commands/documentCreator.ts +++ b/server/commands/documentCreator.ts @@ -1,4 +1,5 @@ import type { Optional } from "utility-types"; +import { PersonalCollectionId } from "@shared/constants"; import { TextHelper } from "@shared/utils/TextHelper"; import { Collection, Document, type Template } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; @@ -6,6 +7,7 @@ import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { authorize } from "@server/policies"; import type { APIContext } from "@server/types"; import { assertPresent } from "@server/validation"; +import personalCollectionLoader from "./personalCollectionLoader"; type Props = Optional< Pick< @@ -50,7 +52,9 @@ type CreateLocation = { * the collection and parent document it will belong to. Shared by the * documents.create API route and the MCP create_document tool so that both * enforce identical permissions, including the team-level check that prevents - * viewers and guests from creating drafts with no collection. + * viewers and guests from creating drafts with no collection. The collectionId + * "personal" refers to the personal collection of the user, which is created + * when it does not exist yet. * * @param ctx the API context containing the acting user. * @param location the requested collection and/or parent document. @@ -83,10 +87,13 @@ export async function authorizeDocumentCreate( } if (collectionId) { - const collection = await Collection.findByPk(collectionId, { - userId: user.id, - transaction, - }); + const collection = + collectionId === PersonalCollectionId + ? await personalCollectionLoader(ctx) + : await Collection.findByPk(collectionId, { + userId: user.id, + transaction, + }); authorize(user, "createDocument", collection); return { collection }; } diff --git a/server/commands/documentMover.test.ts b/server/commands/documentMover.test.ts index 6530fbba68..0c51e48368 100644 --- a/server/commands/documentMover.test.ts +++ b/server/commands/documentMover.test.ts @@ -2,6 +2,7 @@ import Pin from "@server/models/Pin"; import { buildDocument, buildCollection, + buildPersonalCollection, buildTeam, buildUser, } from "@server/test/factories"; @@ -205,6 +206,46 @@ describe("documentMover", () => { expect(response.documents[0].updatedBy.id).toEqual(user.id); }); + it("should remove all pins if moved to a personal collection", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + userId: user.id, + teamId: team.id, + }); + const document = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: team.id, + }); + const child = await buildDocument({ + userId: user.id, + collectionId: collection.id, + parentDocumentId: document.id, + teamId: team.id, + }); + const personal = await buildPersonalCollection(user); + for (const documentId of [document.id, child.id]) { + await Pin.create({ + createdById: user.id, + collectionId: null, + documentId, + teamId: team.id, + }); + } + + await withAPIContext(user, (ctx) => + documentMover(ctx, { + document, + collectionId: personal.id, + parentDocumentId: undefined, + index: 0, + }) + ); + + expect(await Pin.count({ where: { teamId: team.id } })).toBe(0); + }); + it("should detach document from collection and move it to drafts", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index 28c8284661..4bf1c8107b 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -190,6 +190,21 @@ async function documentMover( }); await pin?.destroyWithCtx(ctx); + + // Pins are not shown for documents in a personal collection, so any pin of + // the moved documents, including pins to home, is removed. + if (newCollection?.isPersonal) { + const pins = await Pin.findAll({ + where: { + documentId: [document.id, ...childDocumentIds], + }, + transaction, + lock: Transaction.LOCK.UPDATE, + }); + for (const personalPin of pins) { + await personalPin.destroyWithCtx(ctx); + } + } } result.documents.push(document); diff --git a/server/commands/personalCollectionLoader.ts b/server/commands/personalCollectionLoader.ts new file mode 100644 index 0000000000..692d7b9f40 --- /dev/null +++ b/server/commands/personalCollectionLoader.ts @@ -0,0 +1,64 @@ +import { PersonalCollectionId } from "@shared/constants"; +import { createContext } from "@server/context"; +import { Collection } from "@server/models"; +import { authorize } from "@server/policies"; +import { sequelize } from "@server/storage/database"; +import type { APIContext } from "@server/types"; + +/** + * Loads the personal collection of the acting user, and creates it when the + * user does not have one yet. + * + * @param ctx the API context containing the acting user. + * @returns the personal collection, with the memberships of the user loaded. + * @throws AuthorizationError when the collection does not exist and the user + * may not create it. + */ +export default async function personalCollectionLoader( + ctx: APIContext +): Promise { + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const existing = await Collection.findPersonal(user, { transaction }); + if (existing) { + return existing; + } + + authorize(user, "createPersonalCollection", user.team); + + if (transaction) { + return Collection.findOrCreatePersonal(ctx); + } + + // The creation lock is only held inside a transaction. + return sequelize.transaction((innerTransaction) => + Collection.findOrCreatePersonal( + createContext({ + user, + authType: ctx.state.auth.type, + ip: ctx.context.ip, + transaction: innerTransaction, + }) + ) + ); +} + +/** + * Resolves the collectionId "personal" to the id of the personal collection of + * the acting user, which is created when it does not exist yet. Other values + * are returned unchanged. + * + * @param ctx the API context containing the acting user. + * @param collectionId the requested collectionId. + * @returns the resolved collectionId. + * @throws AuthorizationError when the collection does not exist and the user + * may not create it. + */ +export async function resolvePersonalCollectionId< + T extends string | null | undefined, +>(ctx: APIContext, collectionId: T): Promise { + return collectionId === PersonalCollectionId + ? (await personalCollectionLoader(ctx)).id + : collectionId; +} diff --git a/server/commands/teamUpdater.ts b/server/commands/teamUpdater.ts index 8aa08af663..4b320471ae 100644 --- a/server/commands/teamUpdater.ts +++ b/server/commands/teamUpdater.ts @@ -3,7 +3,7 @@ import { TeamPreference } from "@shared/types"; import env from "@server/env"; import { ValidationError } from "@server/errors"; import type { User } from "@server/models"; -import { Team, TeamDomain } from "@server/models"; +import { Collection, Team, TeamDomain } from "@server/models"; import type { APIContext } from "@server/types"; type Props = { @@ -16,6 +16,22 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { const { allowedDomains, preferences, subdomain, ...attributes } = params; team.setAttributes(attributes); + if (attributes.defaultCollectionId) { + const collection = await Collection.findOne({ + attributes: ["id"], + where: { + id: attributes.defaultCollectionId, + teamId: team.id, + ownerId: null, + }, + transaction: ctx.state.transaction, + }); + + if (!collection) { + throw ValidationError("Default collection not found"); + } + } + if (subdomain !== undefined && env.isCloudHosted) { const newSubdomain = subdomain === "" ? null : subdomain; diff --git a/server/mcp/index.ts b/server/mcp/index.ts index 682a9219a6..de890cc309 100644 --- a/server/mcp/index.ts +++ b/server/mcp/index.ts @@ -103,4 +103,6 @@ Read images and attachments with the "fetch" tool by setting resource to "attach Base64-encoded images are supported in document content for all formats. When creating a document from HTML that includes images or videos, pass the markup with format "html" — remote URLs and base64 media are imported as attachments automatically. Do not convert such HTML to markdown, and do not upload the HTML file itself as an attachment. +Each user can have a personal collection, marked with isPersonal. It is private to that user, cannot be shared as a collection, and cannot be renamed or archived. Use the collectionId "personal" in create_document, move_document or update_document to place a document in it; the collection is created if it does not exist yet. + When asked to create a document that follows a template, use the "list_templates" tool to find a matching template; each result already includes the template body as markdown. To use it unchanged, pass its ID as templateId to "create_document" and the new document is pre-filled from it. To adapt it first, modify the returned body and pass the result as the text parameter to "create_document". Either way no separate fetch is needed.`; diff --git a/server/mcp/tools/collections.test.ts b/server/mcp/tools/collections.test.ts index 813c795522..9d2cfbd37a 100644 --- a/server/mcp/tools/collections.test.ts +++ b/server/mcp/tools/collections.test.ts @@ -1,6 +1,10 @@ import { DeprecationValidation } from "@shared/validations"; import { Collection } from "@server/models"; -import { buildCollection, buildUser } from "@server/test/factories"; +import { + buildCollection, + buildPersonalCollection, + buildUser, +} from "@server/test/factories"; import { getTestServer } from "@server/test/support"; import { buildOAuthUser, @@ -32,6 +36,23 @@ describe("collection tools", () => { expect(match!.url).toMatch(/^https?:\/\//); }); + it("list_collections marks the personal collection", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const personal = await buildPersonalCollection(user); + + const res = await callMcpTool(server, accessToken, "list_collections"); + const data = parseMcpListContent<{ id: string; isPersonal: boolean }>( + res?.result?.content + ); + + expect(data.find((c) => c.id === personal.id)?.isPersonal).toBe(true); + expect(data.find((c) => c.id === collection.id)?.isPersonal).toBe(false); + }); + it("list_collections filters by name ignoring case", async () => { const { user, accessToken } = await buildOAuthUser(); const collection = await buildCollection({ @@ -117,6 +138,20 @@ describe("collection tools", () => { expect(collection.description).toEqual("Updated description"); }); + it("update_collection does not rename a personal collection", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildPersonalCollection(user); + + const res = await callMcpTool(server, accessToken, "update_collection", { + id: collection.id, + name: "Notes", + }); + + expect(res?.result?.isError).toBe(true); + await collection.reload(); + expect(collection.name).toEqual("Personal"); + }); + it("update_collection errors when no fields are provided to update", async () => { const { user, accessToken } = await buildOAuthUser(); const collection = await buildCollection({ diff --git a/server/mcp/tools/collections.ts b/server/mcp/tools/collections.ts index 85e886595b..c6a8fd1e1c 100644 --- a/server/mcp/tools/collections.ts +++ b/server/mcp/tools/collections.ts @@ -28,11 +28,14 @@ import { * @param collection - the collection to present. * @returns the presented collection object. */ -export function presentCollection(collection: Collection) { - return presentCollectionBase(undefined, collection, { - includeData: false, - includeText: true, - }); +export async function presentCollection(collection: Collection) { + return { + ...(await presentCollectionBase(undefined, collection, { + includeData: false, + includeText: true, + })), + isPersonal: collection.isPersonal, + }; } /** diff --git a/server/mcp/tools/documents.test.ts b/server/mcp/tools/documents.test.ts index 2c3063f180..e105f0c24e 100644 --- a/server/mcp/tools/documents.test.ts +++ b/server/mcp/tools/documents.test.ts @@ -1,16 +1,23 @@ import { DeprecationValidation } from "@shared/validations"; -import { CollectionPermission, DocumentPermission, Scope } from "@shared/types"; +import { + CollectionPermission, + DocumentPermission, + Scope, + TeamPreference, +} from "@shared/types"; import { buildUser, buildViewer, buildCollection, buildDocument, + buildDraftDocument, buildTemplate, buildOAuthAuthentication, buildGroup, } from "@server/test/factories"; import { Attachment, + Collection, Document, GroupMembership, SearchQuery, @@ -384,6 +391,26 @@ describe("list_documents", () => { }); describe("create_document", () => { + it("creates in the personal collection", async () => { + const { user, accessToken } = await buildOAuthUser(); + user.team.setPreference(TeamPreference.PersonalDocs, true); + await user.team.save(); + + const res = await callMcpTool(server, accessToken, "create_document", { + title: "Personal Document", + collectionId: "personal", + }); + const data = JSON.parse(res?.result?.content?.[0]?.text ?? "{}"); + expect(data.success).toBe(true); + + const document = await Document.findByPk(data.id, { rejectOnEmpty: true }); + const collection = await Collection.findOne({ + where: { ownerId: user.id }, + rejectOnEmpty: true, + }); + expect(document.collectionId).toEqual(collection.id); + }); + it("creates in a collection", async () => { const { user, accessToken } = await buildOAuthUser(); const collection = await buildCollection({ @@ -604,6 +631,54 @@ describe("create_document", () => { }); describe("update_document", () => { + it("does not create the personal collection when it is not used", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + title: "Renamed", + collectionId: "personal", + }); + expect(res?.result?.isError).toBeFalsy(); + expect(await Collection.count({ where: { ownerId: user.id } })).toEqual(0); + + await document.reload(); + expect(document.collectionId).toEqual(collection.id); + }); + + it("publishes a draft to the personal collection", async () => { + const { user, accessToken } = await buildOAuthUser(); + const document = await buildDraftDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: null, + }); + + const res = await callMcpTool(server, accessToken, "update_document", { + id: document.id, + publish: true, + collectionId: "personal", + }); + expect(res?.result?.isError).toBeFalsy(); + + const personal = await Collection.findOne({ + where: { ownerId: user.id }, + rejectOnEmpty: true, + }); + await document.reload(); + expect(document.collectionId).toEqual(personal.id); + expect(document.publishedAt).not.toBeNull(); + }); + it("updates title and text", async () => { const { user, accessToken } = await buildOAuthUser(); const collection = await buildCollection({ @@ -791,6 +866,32 @@ describe("update_document", () => { }); describe("move_document", () => { + it("moves a document to the personal collection", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + }); + + const res = await callMcpTool(server, accessToken, "move_document", { + id: document.id, + collectionId: "personal", + }); + expect(res?.result?.isError).toBeFalsy(); + + const personal = await Collection.findOne({ + where: { ownerId: user.id }, + rejectOnEmpty: true, + }); + await document.reload(); + expect(document.collectionId).toEqual(personal.id); + }); + it("moves to a different collection", async () => { const { user, accessToken } = await buildOAuthUser(); const collection1 = await buildCollection({ diff --git a/server/mcp/tools/documents.ts b/server/mcp/tools/documents.ts index 30c4d53b43..4d90a010dd 100644 --- a/server/mcp/tools/documents.ts +++ b/server/mcp/tools/documents.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { PersonalCollectionId } from "@shared/constants"; import { type McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import documentCreator, { @@ -6,6 +7,7 @@ import documentCreator, { authorizeDocumentPublish, } from "@server/commands/documentCreator"; import documentMover from "@server/commands/documentMover"; +import { resolvePersonalCollectionId } from "@server/commands/personalCollectionLoader"; import documentRestorer from "@server/commands/documentRestorer"; import documentUpdater from "@server/commands/documentUpdater"; import { Collection, Document, SearchQuery, Template } from "@server/models"; @@ -368,8 +370,7 @@ export function documentTools(server: McpServer, scopes: string[]) { "create_document", { title: "Create document", - description: - "Creates a new document from markdown or HTML content. Requires a collectionId to place the document in a collection, or parentDocumentId to nest it under an existing document. Pass a templateId (from list_templates) to pre-fill the document from a template; the template's content is used unless text is also provided.", + description: `Creates a new document from markdown or HTML content. Requires a collectionId to place the document in a collection, or parentDocumentId to nest it under an existing document. Use the collectionId "${PersonalCollectionId}" to place the document in the user's personal collection, which only they can see and which is created if it does not exist yet. Pass a templateId (from list_templates) to pre-fill the document from a template; the template's content is used unless text is also provided.`, annotations: { idempotentHint: false, readOnlyHint: false, @@ -394,7 +395,7 @@ export function documentTools(server: McpServer, scopes: string[]) { 'The name of the file the content was read from, e.g. "notes.md". Recorded on the document and shown to users as the file it was imported from, so only set it when the content genuinely came from a file. Also used as the title when the content has no heading and no title is given.' ), collectionId: optionalString().describe( - "The collection to place the document in." + `The collection to place the document in, or "${PersonalCollectionId}" for the user's personal collection.` ), parentDocumentId: optionalString().describe( "The parent document ID to nest this document under." @@ -520,7 +521,7 @@ export function documentTools(server: McpServer, scopes: string[]) { .string() .describe("The unique identifier of the document to move."), collectionId: optionalString().describe( - "The destination collection ID. Required if parentDocumentId is not provided." + `The destination collection ID, or "${PersonalCollectionId}" for the user's personal collection. Required if parentDocumentId is not provided.` ), parentDocumentId: optionalString().describe( "The ID of the document to nest this document under. The document will be moved to the parent's collection." @@ -552,7 +553,11 @@ export function documentTools(server: McpServer, scopes: string[]) { authorize(user, "move", document); - let collectionId = input.collectionId; + // A parent decides the collection, so the personal collection is + // only resolved, and created, when there is no parent. + let collectionId = input.parentDocumentId + ? input.collectionId + : await resolvePersonalCollectionId(ctx, input.collectionId); if (input.parentDocumentId) { if (input.parentDocumentId === input.id) { @@ -644,7 +649,7 @@ export function documentTools(server: McpServer, scopes: string[]) { 'Required when editMode is "patch". The exact markdown substring to find in the document. This should be copied verbatim from the document\'s existing markdown content. The first occurrence will be replaced with the text parameter. Can span multiple blocks (paragraphs, headings, etc).' ), collectionId: optionalString().describe( - "The collection ID to publish a draft to, required when publishing a draft that has no collection." + `The collection ID to publish a draft to, or "${PersonalCollectionId}" for the user's personal collection. Required when publishing a draft that has no collection.` ), icon: z .string() @@ -696,8 +701,17 @@ export function documentTools(server: McpServer, scopes: string[]) { } else { authorize(user, "update", document); + // The collection is only used when publishing a draft that has + // none, so the personal collection is only created in that case. + const collectionId = + input.collectionId === PersonalCollectionId + ? input.publish && !document.collectionId + ? await resolvePersonalCollectionId(ctx, input.collectionId) + : undefined + : input.collectionId; + if (input.publish) { - await authorizeDocumentPublish(ctx, document, input.collectionId); + await authorizeDocumentPublish(ctx, document, collectionId); } const { revisionCount } = document; @@ -705,6 +719,7 @@ export function documentTools(server: McpServer, scopes: string[]) { updated = await documentUpdater(ctx, { document, ...input, + collectionId, }); // Every save increments revisionCount, so an unchanged count means diff --git a/server/migrations/20261012120000-add-owner-id-to-collections.js b/server/migrations/20261012120000-add-owner-id-to-collections.js new file mode 100644 index 0000000000..8feaea3f33 --- /dev/null +++ b/server/migrations/20261012120000-add-owner-id-to-collections.js @@ -0,0 +1,51 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.addColumn( + "collections", + "ownerId", + { + type: Sequelize.UUID, + allowNull: true, + references: { + model: "users", + }, + onDelete: "SET NULL", + }, + { transaction } + ); + + // A personal collection must always be private. + await queryInterface.sequelize.query( + `ALTER TABLE "collections" ADD CONSTRAINT "collections_owner_id_private" + CHECK ("ownerId" IS NULL OR "permission" IS NULL);`, + { transaction } + ); + }); + + // One personal collection per user and team. The leading ownerId column + // also covers the foreign key checks when a user is deleted. + await queryInterface.sequelize.query( + `CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "collections_owner_id_team_id" + ON "collections" ("ownerId", "teamId") WHERE "ownerId" IS NOT NULL;` + ); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query( + 'DROP INDEX CONCURRENTLY IF EXISTS "collections_owner_id_team_id";' + ); + await queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.sequelize.query( + 'ALTER TABLE "collections" DROP CONSTRAINT IF EXISTS "collections_owner_id_private";', + { transaction } + ); + await queryInterface.removeColumn("collections", "ownerId", { + transaction, + }); + }); + }, +}; diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 86582f5e88..3c2f7348d8 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -429,7 +429,9 @@ class Collection extends ParanoidModel< const total = await this.count({ where: { teamId: model.teamId, + ownerId: null, }, + transaction: options.transaction, }); if (total === 1) { throw ValidationError("Cannot delete last collection"); @@ -514,6 +516,19 @@ class Collection extends ParanoidModel< return existing; } + @BeforeUpdate + static checkPersonal(model: Collection) { + if (!model.ownerId) { + return; + } + if (model.changed("name")) { + throw ValidationError("A personal collection cannot be renamed"); + } + if (model.changed("permission") && model.permission) { + throw ValidationError("A personal collection must stay private"); + } + } + @BeforeUpdate static async checkIndex( model: Collection, @@ -569,6 +584,15 @@ class Collection extends ParanoidModel< @Column(DataType.UUID) archivedById?: string | null; + /** The user that owns this collection, if it is a personal collection. */ + @BelongsTo(() => User, "ownerId") + owner?: User | null; + + @AllowNull + @ForeignKey(() => User) + @Column(DataType.UUID) + ownerId: string | null; + @HasMany(() => Document, "collectionId") documents: Document[]; @@ -751,6 +775,7 @@ class Collection extends ParanoidModel< return this.findOne({ where: { teamId: user.teamId, + ownerId: null, id, }, order: [ @@ -762,6 +787,81 @@ class Collection extends ParanoidModel< }); } + /** + * Find the personal collection of a user, with the memberships of the user + * loaded. + * + * @param user The user that owns the collection. + * @param options Additional options for the query. + * @returns the personal collection, or null if the user has none. + */ + static async findPersonal( + user: User, + options: Omit, "where"> = {} + ) { + return this.scope([ + "defaultScope", + { method: ["withMembership", user.id] }, + ]).findOne({ + ...options, + where: { + teamId: user.teamId, + ownerId: user.id, + }, + }); + } + + /** + * Find the personal collection of the user in the context, and create it if + * the user does not have one yet. The caller must authorize the creation. + * + * @param ctx The request context with the acting user and a transaction. + * @returns the personal collection of the user. + */ + static async findOrCreatePersonal(ctx: APIContext): Promise { + const { user } = ctx.state.auth; + const { transaction } = ctx.state; + + const existing = await this.findPersonal(user, { transaction }); + if (existing) { + return existing; + } + + await LockHelper.acquire( + this.sequelize!, + `collections:personal:${user.teamId}:${user.id}`, + transaction + ); + + const locked = await this.findPersonal(user, { transaction }); + if (locked) { + return locked; + } + + const collection = await this.createWithCtx(ctx, { + name: "Personal", + teamId: user.teamId, + createdById: user.id, + ownerId: user.id, + permission: null, + }); + + // The owner membership is created without hooks, so clear the cache here. + const invalidate = () => + CacheHelper.clearData(RedisPrefixHelper.getUserCollectionIdsKey(user.id)); + if (transaction) { + transaction.afterCommit(invalidate); + } else { + await invalidate(); + } + + return this.findByPk(collection.id, { + userId: user.id, + transaction, + rejectOnEmpty: true, + }); + } + /** * Convenience method to return if a collection is considered private. * This means that a membership is required to view it rather than just being @@ -773,6 +873,16 @@ class Collection extends ParanoidModel< return !this.permission; } + /** + * Whether this collection is the personal collection of a user. A personal + * collection is private and only its owner can see or manage it. + * + * @returns boolean + */ + get isPersonal() { + return !!this.ownerId; + } + /** * Returns the collection's documentStructure via cache, populating it on * miss. The cache is kept fresh by this model's save hooks, so callers diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index b58df8f6f2..2282a59ec9 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -38,6 +38,8 @@ export type FileOperationOptions = { includeAttachments?: boolean; includePrivate?: boolean; permission?: CollectionPermission | null; + /** The owner of the personal collection that was exported, if any. */ + personalOwnerId?: string; }; type AdditionalFindOptions = { @@ -78,9 +80,18 @@ type CreateExportOptions = { model: Document.unscoped(), as: "document", - attributes: ["id", "title"], + attributes: ["id", "title", "collectionId"], required: false, paranoid: false, + include: [ + { + model: Collection.unscoped(), + as: "collection", + attributes: ["id", "ownerId"], + required: false, + paranoid: false, + }, + ], }, ], })) @@ -148,12 +159,29 @@ class FileOperation extends ParanoidModel< ): Promise { const { user } = ctx.state.auth; const format = options.format ?? FileOperationFormat.MarkdownZip; + + // The owner is stored on the export, as a document can move out of the + // personal collection after it was exported. + const sourceCollectionId = + "document" in options + ? options.document.collectionId + : options.collection?.id; + const sourceCollection = sourceCollectionId + ? await Collection.unscoped().findOne({ + attributes: ["ownerId"], + where: { id: sourceCollectionId }, + transaction: ctx.state.transaction, + }) + : null; + const personalOwnerId = sourceCollection?.ownerId ?? undefined; + const source = "document" in options ? { name: options.document.titleWithDefault, documentId: options.document.id, teamId: options.document.teamId, + options: personalOwnerId ? { personalOwnerId } : null, } : { name: options.collection?.name || options.team.name, @@ -162,6 +190,7 @@ class FileOperation extends ParanoidModel< options: { includeAttachments: options.includeAttachments ?? true, includePrivate: options.includePrivate ?? true, + ...(personalOwnerId ? { personalOwnerId } : {}), }, }; const { name, ...attributes } = source; diff --git a/server/models/Share.ts b/server/models/Share.ts index 6526154603..3d2e46b630 100644 --- a/server/models/Share.ts +++ b/server/models/Share.ts @@ -56,6 +56,7 @@ import Length from "./validators/Length"; "id", "name", "permission", + "ownerId", "sharing", "urlId", "teamId", @@ -81,6 +82,7 @@ import Length from "./validators/Length"; "id", "name", "permission", + "ownerId", "urlId", "sharing", "teamId", diff --git a/server/models/User.ts b/server/models/User.ts index cc1b60fea3..3f1f47a81d 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -500,6 +500,10 @@ class User extends ParanoidModel< attributes: ["id"], where: { teamId: this.teamId, + // Only the owner can access a personal collection. + ownerId: { + [Op.or]: [{ [Op.is]: null }, { [Op.eq]: this.id }], + }, [Op.or]: [ ...(this.isGuest ? [] diff --git a/server/policies/collection.test.ts b/server/policies/collection.test.ts index c43bc2a17c..fecc988328 100644 --- a/server/policies/collection.test.ts +++ b/server/policies/collection.test.ts @@ -1,10 +1,11 @@ -import { CollectionPermission, UserRole } from "@shared/types"; +import { CollectionPermission, TeamPreference, UserRole } from "@shared/types"; import { UserMembership, Collection } from "@server/models"; import { buildUser, buildTeam, buildCollection, buildAdmin, + buildPersonalCollection, } from "@server/test/factories"; import { serialize } from "./index"; @@ -607,3 +608,126 @@ describe("manage templates", () => { }); }); }); + +describe("personal collection", () => { + const buildPersonal = async () => { + const team = await buildTeam(); + team.setPreference(TeamPreference.PersonalDocs, true); + await team.save(); + const owner = await buildUser({ teamId: team.id }); + const collection = await buildPersonalCollection(owner); + return { team, owner, collection }; + }; + + it("should allow the owner to use but not share or remove it", async () => { + const { owner, collection } = await buildPersonal(); + const reloaded = await Collection.findByPk(collection.id, { + userId: owner.id, + }); + const abilities = serialize(owner, reloaded); + expect(abilities.read).toBeTruthy(); + expect(abilities.readDocument).toBeTruthy(); + expect(abilities.createDocument).toBeTruthy(); + expect(abilities.updateDocument).toBeTruthy(); + expect(abilities.update).toBeTruthy(); + expect(abilities.export).toBeTruthy(); + expect(abilities.shareDocument).toBeTruthy(); + expect(abilities.share).toEqual(false); + expect(abilities.star).toEqual(false); + expect(abilities.unstar).toEqual(false); + expect(abilities.createTemplate).toEqual(false); + expect(abilities.manageTemplate).toEqual(false); + expect(abilities.manageUsers).toEqual(false); + expect(abilities.duplicate).toEqual(false); + expect(abilities.archive).toEqual(false); + expect(abilities.delete).toEqual(false); + expect(abilities.move).toEqual(false); + }); + + it("should allow nothing for a workspace admin", async () => { + const { team, collection } = await buildPersonal(); + const admin = await buildAdmin({ teamId: team.id }); + const reloaded = await Collection.findByPk(collection.id, { + userId: admin.id, + }); + const abilities = serialize(admin, reloaded); + for (const [ability, value] of Object.entries(abilities)) { + expect({ ability, value }).toEqual({ ability, value: false }); + } + }); + + it("should allow nothing for a workspace admin with a membership", async () => { + const { team, owner, collection } = await buildPersonal(); + const admin = await buildAdmin({ teamId: team.id }); + await UserMembership.create({ + collectionId: collection.id, + userId: admin.id, + permission: CollectionPermission.Admin, + createdById: owner.id, + }); + const reloaded = await Collection.findByPk(collection.id, { + userId: admin.id, + }); + const abilities = serialize(admin, reloaded); + for (const [ability, value] of Object.entries(abilities)) { + expect({ ability, value }).toEqual({ ability, value: false }); + } + }); + + it("should allow nothing for another member", async () => { + const { team, collection } = await buildPersonal(); + const member = await buildUser({ teamId: team.id }); + const reloaded = await Collection.findByPk(collection.id, { + userId: member.id, + }); + const abilities = serialize(member, reloaded); + for (const [ability, value] of Object.entries(abilities)) { + expect({ ability, value }).toEqual({ ability, value: false }); + } + }); + + it("should be read-only when personal documents are turned off", async () => { + const { team, owner, collection } = await buildPersonal(); + team.setPreference(TeamPreference.PersonalDocs, false); + await team.save(); + owner.team = team; + const reloaded = await Collection.findByPk(collection.id, { + userId: owner.id, + }); + const abilities = serialize(owner, reloaded); + expect(abilities.read).toBeTruthy(); + expect(abilities.readDocument).toBeTruthy(); + expect(abilities.createDocument).toEqual(false); + expect(abilities.updateDocument).toEqual(false); + expect(abilities.createTemplate).toEqual(false); + }); + + it("should become an ordinary private collection without an owner", async () => { + const { team, collection } = await buildPersonal(); + const admin = await buildAdmin({ teamId: team.id }); + collection.ownerId = null; + await collection.save(); + const reloaded = await Collection.findByPk(collection.id, { + userId: admin.id, + }); + const abilities = serialize(admin, reloaded); + expect(abilities.read).toBeTruthy(); + expect(abilities.update).toBeTruthy(); + expect(abilities.manageUsers).toBeTruthy(); + expect(abilities.readDocument).toEqual(false); + }); + + it("should allow only members to create a personal collection", async () => { + const team = await buildTeam(); + const member = await buildUser({ teamId: team.id }); + const viewer = await buildUser({ teamId: team.id, role: UserRole.Viewer }); + const guest = await buildUser({ teamId: team.id, role: UserRole.Guest }); + expect(serialize(member, team).createPersonalCollection).toBeTruthy(); + expect(serialize(viewer, team).createPersonalCollection).toEqual(false); + expect(serialize(guest, team).createPersonalCollection).toEqual(false); + + team.setPreference(TeamPreference.PersonalDocs, false); + await team.save(); + expect(serialize(member, team).createPersonalCollection).toEqual(false); + }); +}); diff --git a/server/policies/collection.ts b/server/policies/collection.ts index a7aeef58ec..d02e1281fa 100644 --- a/server/policies/collection.ts +++ b/server/policies/collection.ts @@ -2,7 +2,15 @@ import invariant from "invariant"; import { CollectionPermission, TeamPreference } from "@shared/types"; import { Collection, User, Team } from "@server/models"; import { allow, can } from "./cancan"; -import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils"; +import { + and, + isCollectionOwner, + isCollectionWritable, + isTeamAdmin, + isTeamModel, + isTeamMutable, + or, +} from "./utils"; allow(User, "createCollection", Team, (actor, team) => and( @@ -22,10 +30,20 @@ allow(User, "importCollection", Team, (actor, team) => ) ); +allow(User, "createPersonalCollection", Team, (actor, team) => + and( + !actor.isGuest, + !actor.isViewer, + isTeamModel(actor, team), + isTeamMutable(actor), + !!team?.getPreference(TeamPreference.PersonalDocs) + ) +); + allow(User, "move", Collection, (actor, collection) => and( - // !!collection?.isActive, + !collection?.isPersonal, isTeamAdmin(actor, collection), isTeamMutable(actor) ) @@ -35,6 +53,9 @@ allow(User, "read", Collection, (user, collection) => { if (!collection || user.teamId !== collection.teamId) { return false; } + if (collection.isPersonal) { + return isCollectionOwner(user, collection); + } if (user.isAdmin) { return true; } @@ -49,6 +70,7 @@ allow(User, "read", Collection, (user, collection) => { allow(User, "duplicate", Collection, (actor, collection) => and( !!collection?.isActive, + !collection?.isPersonal, can(actor, "read", collection), can(actor, "createCollection", actor.team) ) @@ -64,15 +86,28 @@ allow(User, "download", Collection, (actor, collection) => ) ); +// A personal collection cannot be starred, as it has no page to link to. +allow(User, ["star", "unstar"], Collection, (user, collection) => + and( + // + !collection?.isPersonal, + can(user, "readDocument", collection) + ) +); + allow( User, - ["readDocument", "star", "unstar", "subscribe", "unsubscribe"], + ["readDocument", "subscribe", "unsubscribe"], Collection, (user, collection) => { if (!collection || user.teamId !== collection.teamId) { return false; } + if (collection.isPersonal) { + return isCollectionOwner(user, collection); + } + if (collection.isPrivate || user.isGuest) { return includesMembership( collection, @@ -84,7 +119,15 @@ allow( } ); -allow(User, "share", Collection, (user, collection) => { +allow(User, "share", Collection, (user, collection) => + and( + // + !collection?.isPersonal, + can(user, "shareDocument", collection) + ) +); + +allow(User, "shareDocument", Collection, (user, collection) => { if ( !collection || user.isGuest || @@ -96,6 +139,9 @@ allow(User, "share", Collection, (user, collection) => { if (!collection.sharing) { return false; } + if (collection.isPersonal) { + return isCollectionOwner(user, collection); + } if (!collection.isPrivate && user.isAdmin) { return true; } @@ -114,9 +160,17 @@ allow(User, "share", Collection, (user, collection) => { }); allow(User, "updateDocument", Collection, (user, collection) => { - if (!collection || !isTeamModel(user, collection) || !isTeamMutable(user)) { + if ( + !collection || + !isTeamModel(user, collection) || + !isTeamMutable(user) || + !isCollectionWritable(user, collection) + ) { return false; } + if (collection.isPersonal) { + return isCollectionOwner(user, collection); + } if ( collection.permission !== CollectionPermission.ReadWrite || @@ -141,10 +195,14 @@ allow( !collection || !collection.isActive || !isTeamModel(user, collection) || - !isTeamMutable(user) + !isTeamMutable(user) || + !isCollectionWritable(user, collection) ) { return false; } + if (collection.isPersonal) { + return isCollectionOwner(user, collection); + } if ( collection.permission !== CollectionPermission.ReadWrite || @@ -171,6 +229,8 @@ allow( !!collection?.isActive, isTeamModel(user, collection), isTeamMutable(user), + // Templates in a personal collection would only be visible to its owner. + !collection?.isPersonal, or( isTeamAdmin(user, collection), includesMembership(collection, [CollectionPermission.Admin]), @@ -192,23 +252,57 @@ allow( ) ); -allow(User, ["update", "archive"], Collection, (user, collection) => +allow(User, "update", Collection, (user, collection) => and( !!collection, !!collection?.isActive, + isOwnerIfPersonal(user, collection), or( + isCollectionOwner(user, collection), isTeamAdmin(user, collection), includesMembership(collection, [CollectionPermission.Admin]) ) ) ); +// A personal collection cannot be archived or deleted, so that its owner always +// has exactly one. +allow(User, "archive", Collection, (user, collection) => + and( + // + !collection?.isPersonal, + can(user, "update", collection) + ) +); + +// Pins are shown on the collection page, which a personal collection does not +// have. +allow(User, "pin", Collection, (user, collection) => + and( + // + !collection?.isPersonal, + can(user, "update", collection) + ) +); + +// Only the owner is a member of a personal collection, documents in it are +// shared through document memberships instead. +allow(User, "manageUsers", Collection, (user, collection) => + and( + // + !collection?.isPersonal, + can(user, "update", collection) + ) +); + allow(User, "export", Collection, (user, collection) => and( !!collection, !!collection?.isActive, can(user, "download", collection), + isOwnerIfPersonal(user, collection), or( + isCollectionOwner(user, collection), isTeamAdmin(user, collection), includesMembership(collection, [CollectionPermission.Admin]) ) @@ -219,6 +313,7 @@ allow(User, "delete", Collection, (user, collection) => and( !!collection, !collection?.deletedAt, + !collection?.isPersonal, or( isTeamAdmin(user, collection), includesMembership(collection, [CollectionPermission.Admin]) @@ -230,7 +325,9 @@ allow(User, "restore", Collection, (user, collection) => and( !!collection, !collection?.isActive, + isOwnerIfPersonal(user, collection), or( + isCollectionOwner(user, collection), isTeamAdmin(user, collection), includesMembership(collection, [CollectionPermission.Admin]) ) @@ -247,6 +344,18 @@ allow(User, "updateDeprecatedReason", Collection, (actor, collection) => ) ); +/** + * Check that the actor owns the collection when it is a personal collection. + * Admins have no access to the personal collections of other users. + * + * @param user The actor to check. + * @param collection The collection to check. + * @returns True if the collection is not personal or the actor owns it. + */ +function isOwnerIfPersonal(user: User, collection: Collection | null) { + return !collection?.isPersonal || isCollectionOwner(user, collection); +} + function includesMembership( collection: Collection | null, permissions: CollectionPermission[] diff --git a/server/policies/document.test.ts b/server/policies/document.test.ts index 5c9e5d6172..5ea2841c2e 100644 --- a/server/policies/document.test.ts +++ b/server/policies/document.test.ts @@ -13,6 +13,7 @@ import { buildDraftDocument, buildCollection, buildAdmin, + buildPersonalCollection, } from "@server/test/factories"; import { serialize } from "./index"; @@ -782,3 +783,115 @@ describe("manage document", () => { }); } }); + +describe("personal collection", () => { + const buildPersonal = async () => { + const team = await buildTeam(); + team.setPreference(TeamPreference.PersonalDocs, true); + await team.save(); + const owner = await buildUser({ teamId: team.id }); + owner.team = team; + const collection = await buildPersonalCollection(owner); + const doc = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: collection.id, + }); + return { team, owner, collection, doc }; + }; + + it("should allow the owner full access", async () => { + const { owner, doc } = await buildPersonal(); + const document = await Document.findByPk(doc.id, { userId: owner.id }); + const abilities = serialize(owner, document); + expect(abilities.read).toBeTruthy(); + expect(abilities.update).toBeTruthy(); + expect(abilities.move).toBeTruthy(); + expect(abilities.archive).toBeTruthy(); + expect(abilities.delete).toBeTruthy(); + expect(abilities.share).toBeTruthy(); + expect(abilities.manageUsers).toBeTruthy(); + expect(abilities.unpublish).toEqual(false); + expect(abilities.updateInsights).toEqual(false); + expect(abilities.pin).toEqual(false); + expect(abilities.unpin).toEqual(false); + expect(abilities.pinToHome).toEqual(false); + }); + + it("should allow nothing for a workspace admin", async () => { + const { team, doc } = await buildPersonal(); + const admin = await buildAdmin({ teamId: team.id }); + const document = await Document.findByPk(doc.id, { userId: admin.id }); + const abilities = serialize(admin, document); + for (const [ability, value] of Object.entries(abilities)) { + expect({ ability, value }).toEqual({ ability, value: false }); + } + }); + + it("should not allow a workspace admin to permanently delete", async () => { + const { team, owner, doc } = await buildPersonal(); + const admin = await buildAdmin({ teamId: team.id }); + await doc.destroy({ hooks: false }); + const ownerDocument = await Document.findByPk(doc.id, { + userId: owner.id, + paranoid: false, + }); + const adminDocument = await Document.findByPk(doc.id, { + userId: admin.id, + paranoid: false, + }); + expect(serialize(admin, adminDocument).permanentDelete).toEqual(false); + expect(serialize(owner, ownerDocument).restore).toBeTruthy(); + }); + + it("should allow a collaborator through a document membership", async () => { + const { team, owner, doc } = await buildPersonal(); + const collaborator = await buildUser({ teamId: team.id }); + collaborator.team = team; + await UserMembership.create({ + documentId: doc.id, + userId: collaborator.id, + permission: DocumentPermission.ReadWrite, + createdById: owner.id, + }); + const document = await Document.findByPk(doc.id, { + userId: collaborator.id, + }); + const abilities = serialize(collaborator, document); + expect(abilities.read).toBeTruthy(); + expect(abilities.update).toBeTruthy(); + expect(abilities.manageUsers).toEqual(false); + }); + + it("should be read-only when personal documents are turned off", async () => { + const { team, owner, doc } = await buildPersonal(); + const collaborator = await buildUser({ teamId: team.id }); + await UserMembership.create({ + documentId: doc.id, + userId: collaborator.id, + permission: DocumentPermission.ReadWrite, + createdById: owner.id, + }); + team.setPreference(TeamPreference.PersonalDocs, false); + await team.save(); + owner.team = team; + collaborator.team = team; + + const document = await Document.findByPk(doc.id, { userId: owner.id }); + const abilities = serialize(owner, document); + expect(abilities.read).toBeTruthy(); + expect(abilities.update).toEqual(false); + expect(abilities.createChildDocument).toEqual(false); + expect(abilities.move).toBeTruthy(); + expect(abilities.archive).toBeTruthy(); + expect(abilities.delete).toBeTruthy(); + + const collaboratorDocument = await Document.findByPk(doc.id, { + userId: collaborator.id, + }); + const collaboratorAbilities = serialize(collaborator, collaboratorDocument); + expect(collaboratorAbilities.read).toBeTruthy(); + expect(collaboratorAbilities.update).toEqual(false); + expect(collaboratorAbilities.move).toEqual(false); + }); +}); diff --git a/server/policies/document.ts b/server/policies/document.ts index 2063f0a477..260402e280 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -6,7 +6,15 @@ import { } from "@shared/types"; import { Document, Revision, User, Team } from "@server/models"; import { allow, cannot, can } from "./cancan"; -import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils"; +import { + and, + isCollectionOwner, + isCollectionWritable, + isTeamAdmin, + isTeamModel, + isTeamMutable, + or, +} from "./utils"; allow(User, "createDocument", Team, (actor, document) => and( @@ -79,7 +87,7 @@ allow(User, "share", Document, (actor, document) => !!document?.isActive, isTeamMutable(actor), can(actor, "read", document), - or(!document?.collection, can(actor, "share", document?.collection)) + or(!document?.collection, can(actor, "shareDocument", document?.collection)) ) ); @@ -88,6 +96,7 @@ allow(User, "update", Document, (actor, document) => !!document?.isActive, isTeamMutable(actor), can(actor, "read", document), + isCollectionWritable(actor, document?.collection), or( includesMembership(document, [ DocumentPermission.ReadWrite, @@ -140,17 +149,20 @@ allow(User, "duplicate", Document, (actor, document) => ); allow(User, "move", Document, (actor, document) => - and( - can(actor, "update", document), - or( - includesMembership(document, [ - DocumentPermission.ReadWrite, - DocumentPermission.Admin, - ]), - can(actor, "updateDocument", document?.collection), - and(!!document?.isDraft && actor.id === document?.createdById), - and(!!document?.isDraft && !document?.collection) - ) + or( + and( + can(actor, "update", document), + or( + includesMembership(document, [ + DocumentPermission.ReadWrite, + DocumentPermission.Admin, + ]), + can(actor, "updateDocument", document?.collection), + and(!!document?.isDraft && actor.id === document?.createdById), + and(!!document?.isDraft && !document?.collection) + ) + ), + and(!!document?.isActive, isPersonalOwner(actor, document)) ) ); @@ -162,10 +174,12 @@ allow(User, "createChildDocument", Document, (actor, document) => ) ); +// Pins and insights are not shown for documents in a personal collection. allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) => and( !document?.isDraft, !actor.isGuest, + !document?.collection?.isPersonal, can(actor, "update", document), can(actor, "update", document?.collection) ) @@ -173,9 +187,9 @@ allow(User, ["updateInsights", "pin", "unpin"], Document, (actor, document) => allow(User, "pinToHome", Document, (actor, document) => and( - // !document?.isDraft, !!document?.isActive, + !document?.collection?.isPersonal, isTeamAdmin(actor, document), isTeamMutable(actor) ) @@ -189,6 +203,7 @@ allow(User, "delete", Document, (actor, document) => or( can(actor, "unarchive", document), can(actor, "update", document), + isPersonalOwner(actor, document), and(!document?.collection, actor.id === document?.createdById) ) ) @@ -215,7 +230,11 @@ allow(User, "permanentDelete", Document, (actor, document) => !actor.isGuest, !!document?.isDeleted, isTeamModel(actor, document), - isTeamAdmin(actor, document) + isTeamAdmin(actor, document), + or( + !document?.collection?.isPersonal, + isCollectionOwner(actor, document?.collection) + ) ) ); @@ -223,11 +242,16 @@ allow(User, "archive", Document, (actor, document) => and( !document?.isDraft, !!document?.isActive, - can(actor, "update", document), or( - includesMembership(document, [DocumentPermission.Admin]), - and(isTeamAdmin(actor, document), can(actor, "read", document)), - can(actor, "updateDocument", document?.collection) + and( + can(actor, "update", document), + or( + includesMembership(document, [DocumentPermission.Admin]), + and(isTeamAdmin(actor, document), can(actor, "read", document)), + can(actor, "updateDocument", document?.collection) + ) + ), + isPersonalOwner(actor, document) ) ) ); @@ -278,12 +302,33 @@ allow(User, "unpublish", Document, (user, document) => { document.collection, "collection is missing, did you forget to include in the query scope?" ); + + // Documents in a personal collection are already private to the owner. + if (document.collection.isPersonal) { + return false; + } if (cannot(user, "updateDocument", document.collection)) { return false; } return user.teamId === document.teamId; }); +/** + * Check if the actor owns the personal collection that the document is in. The + * owner can always move, archive and delete these documents, also when the + * collection is read-only. + * + * @param actor The actor to check. + * @param document The document to check. + * @returns True if the actor owns the personal collection of the document. + */ +function isPersonalOwner(actor: User, document: Document | null) { + return !!and( + isTeamMutable(actor), + isCollectionOwner(actor, document?.collection) + ); +} + function includesMembership( document: Document | null, permissions: DocumentPermission[] diff --git a/server/policies/fileOperation.ts b/server/policies/fileOperation.ts index 77cd67b8b5..246310ee85 100644 --- a/server/policies/fileOperation.ts +++ b/server/policies/fileOperation.ts @@ -1,7 +1,14 @@ import { FileOperationState, FileOperationType } from "@shared/types"; import { User, Team, FileOperation } from "@server/models"; import { allow, can } from "./cancan"; -import { and, isTeamAdmin, isTeamModel, isTeamMutable, or } from "./utils"; +import { + and, + isCollectionOwner, + isTeamAdmin, + isTeamModel, + isTeamMutable, + or, +} from "./utils"; const TerminalStates = [ FileOperationState.Complete, @@ -28,6 +35,22 @@ function canAccessSource(actor: User, fileOperation: FileOperation) { return can(actor, "createExport", actor.team); } +/** + * Admins have no access to exports of the personal collections of other users, + * or of the documents in them. + */ +function isOwnerIfPersonalSource(actor: User, fileOperation: FileOperation) { + // The owner at the time of the export applies, also after the source moved. + const personalOwnerId = fileOperation.options?.personalOwnerId; + if (personalOwnerId && personalOwnerId !== actor.id) { + return false; + } + + const collection = + fileOperation.collection ?? fileOperation.document?.collection; + return !collection?.isPersonal || isCollectionOwner(actor, collection); +} + allow( User, ["createFileOperation", "createExport"], @@ -40,7 +63,10 @@ allow(User, "read", FileOperation, (actor, fileOperation) => and( isTeamModel(actor, fileOperation), or( - isTeamAdmin(actor, fileOperation), + and( + isTeamAdmin(actor, fileOperation), + !!fileOperation && isOwnerIfPersonalSource(actor, fileOperation) + ), and( fileOperation?.userId === actor.id, !!fileOperation && canAccessSource(actor, fileOperation) diff --git a/server/policies/utils.ts b/server/policies/utils.ts index cc958192ed..a7602cfd72 100644 --- a/server/policies/utils.ts +++ b/server/policies/utils.ts @@ -1,8 +1,12 @@ import env from "@server/env"; -import type { User } from "@server/models"; +import type { Collection, User } from "@server/models"; import { Team, type Group } from "@server/models"; import type Model from "@server/models/base/Model"; -import { GroupPermission, type PlanFeature } from "@shared/types"; +import { + GroupPermission, + TeamPreference, + type PlanFeature, +} from "@shared/types"; import invariant from "invariant"; type Args = boolean | string | Args[]; @@ -80,6 +84,42 @@ export function isTeamAdmin( return !!and(isTeamModel(actor, model), actor.isAdmin); } +/** + * Check if the actor owns the personal collection. + * + * @param actor The actor to check + * @param collection The collection to check + * @returns True if the collection is personal and owned by the actor + */ +export function isCollectionOwner( + actor: User, + collection: Collection | null | undefined +): boolean { + return ( + !!collection?.ownerId && + isTeamModel(actor, collection) && + collection.ownerId === actor.id + ); +} + +/** + * Check if documents in the collection can be changed. A personal collection + * is read-only when the team turns personal documents off. + * + * @param actor The actor to check + * @param collection The collection to check + * @returns True if documents in the collection can be changed + */ +export function isCollectionWritable( + actor: User, + collection: Collection | null | undefined +): boolean { + return ( + !collection?.ownerId || + !!actor.team?.getPreference(TeamPreference.PersonalDocs) + ); +} + /** * Check if the actor is a member of the team. * diff --git a/server/presenters/collection.ts b/server/presenters/collection.ts index 04db5e46aa..9b1b08bb48 100644 --- a/server/presenters/collection.ts +++ b/server/presenters/collection.ts @@ -64,6 +64,7 @@ export default async function presentCollection( res.commenting = collection.commenting; res.templateManagement = collection.templateManagement; res.permission = collection.permission; + res.ownerId = collection.ownerId; res.deletedAt = collection.deletedAt; res.archivedAt = collection.archivedAt; res.deprecatedReason = collection.deprecatedReason; diff --git a/server/presenters/document.ts b/server/presenters/document.ts index b4e6f1b90a..beb55dabe3 100644 --- a/server/presenters/document.ts +++ b/server/presenters/document.ts @@ -110,6 +110,13 @@ async function presentDocument( res.tasks = document.tasks; res.isCollectionDeleted = await document.isCollectionDeleted(); res.collectionId = document.collectionId; + // The owner of the personal collection that the document is in. Left out + // when the collection is not loaded, so that the value is not cleared. + if (!document.collectionId) { + res.ownerId = null; + } else if (document.collection !== undefined) { + res.ownerId = document.collection?.ownerId ?? null; + } res.parentDocumentId = document.parentDocumentId; res.createdBy = presentUser(document.createdBy); res.updatedBy = presentUser(document.updatedBy); diff --git a/server/queues/processors/UserDeletedProcessor.test.ts b/server/queues/processors/UserDeletedProcessor.test.ts index 8a6cf74d61..741b09f6fe 100644 --- a/server/queues/processors/UserDeletedProcessor.test.ts +++ b/server/queues/processors/UserDeletedProcessor.test.ts @@ -1,5 +1,12 @@ import UserAuthentication from "@server/models/UserAuthentication"; -import { buildUser, buildWebhookSubscription } from "@server/test/factories"; +import { Collection } from "@server/models"; +import { + buildAdmin, + buildPersonalCollection, + buildUser, + buildWebhookSubscription, +} from "@server/test/factories"; +import { serialize } from "@server/policies"; import UserDeletedProcessor from "./UserDeletedProcessor"; const ip = "127.0.0.1"; @@ -52,4 +59,31 @@ describe("UserDeletedProcessor", () => { await webhook.reload(); expect(webhook.enabled).toEqual(false); }); + + it("should turn the personal collection into a private collection", async () => { + const user = await buildUser(); + const admin = await buildAdmin({ teamId: user.teamId }); + const personal = await buildPersonalCollection(user); + + const processor = new UserDeletedProcessor(); + await processor.perform({ + name: "users.delete", + userId: user.id, + actorId: admin.id, + teamId: user.teamId, + ip, + }); + + const collection = await Collection.findByPk(personal.id, { + userId: admin.id, + rejectOnEmpty: true, + }); + expect(collection.ownerId).toBeNull(); + expect(collection.permission).toBeNull(); + expect(collection.memberships).toHaveLength(0); + + const abilities = serialize(admin, collection); + expect(abilities.read).toBeTruthy(); + expect(abilities.manageUsers).toBeTruthy(); + }); }); diff --git a/server/queues/processors/UserDeletedProcessor.ts b/server/queues/processors/UserDeletedProcessor.ts index 31ea63a61c..7b256d0a2e 100644 --- a/server/queues/processors/UserDeletedProcessor.ts +++ b/server/queues/processors/UserDeletedProcessor.ts @@ -1,5 +1,6 @@ import { ApiKey, + Collection, GroupUser, OAuthAuthentication, Star, @@ -60,6 +61,17 @@ export default class UserDeletedProcessor extends BaseProcessor { }, transaction, }); + // The personal collection becomes an ordinary private collection, so + // that admins can recover the documents in it. + await Collection.update( + { ownerId: null }, + { + where: { + ownerId: event.userId, + }, + transaction, + } + ); await WebhookSubscription.update( { enabled: false }, { diff --git a/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts index c984a2a185..74a310b62d 100644 --- a/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts +++ b/server/queues/tasks/DocumentAccessRequestNotificationsTask.ts @@ -105,6 +105,16 @@ export default class DocumentAccessRequestNotificationsTask extends BaseTask { await fs.remove(filePath); } }); + + it("should only export a personal collection to its owner", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + const shared = await buildCollection({ teamId: team.id, userId: admin.id }); + const ownPersonal = await buildPersonalCollection(admin); + const otherPersonal = await buildPersonalCollection( + await buildUser({ teamId: team.id }) + ); + const exportCollections = vi + .spyOn(ExportJSONTask.prototype, "exportCollections") + .mockResolvedValue(""); + const exported = async (collectionId?: string) => { + const fileOperation = await buildFileOperation({ + teamId: team.id, + userId: admin.id, + collectionId, + options: { includeAttachments: false, includePrivate: true }, + }); + exportCollections.mockClear(); + await new ExportJSONTask().loadDataAndExport(fileOperation, admin); + const collections: Collection[] = exportCollections.mock.calls[0][0]; + return collections.map((collection) => collection.id); + }; + + const workspace = await exported(); + expect(workspace).toContain(shared.id); + expect(workspace).not.toContain(ownPersonal.id); + expect(workspace).not.toContain(otherPersonal.id); + + expect(await exported(ownPersonal.id)).toEqual([ownPersonal.id]); + expect(await exported(otherPersonal.id)).toEqual([]); + }); }); diff --git a/server/queues/tasks/ExportTask.ts b/server/queues/tasks/ExportTask.ts index fd50ad9a8e..ec1231622b 100644 --- a/server/queues/tasks/ExportTask.ts +++ b/server/queues/tasks/ExportTask.ts @@ -190,10 +190,14 @@ export default abstract class ExportTask extends BaseTask { if (fileOperation.collectionId) { where.id = fileOperation.collectionId; + // Only the owner can export a personal collection. + where.ownerId = { [Op.or]: [{ [Op.is]: null }, { [Op.eq]: user.id }] }; } else { where.archivedAt = { [Op.eq]: null, }; + // A workspace export never includes personal collections. + where.ownerId = { [Op.is]: null }; } const collections = await sequelizeReadOnly.transaction((transaction) => diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index 219231dd2f..3a0ecd92b5 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -1,6 +1,18 @@ -import { CollectionPermission, CollectionStatusFilter } from "@shared/types"; +import { + CollectionPermission, + CollectionStatusFilter, + DocumentPermission, + Scope, +} from "@shared/types"; import { DeprecationValidation } from "@shared/validations"; -import { Document, UserMembership, GroupMembership } from "@server/models"; +import { + Document, + UserMembership, + GroupMembership, + View, +} from "@server/models"; +import type { User } from "@server/models"; +import { callMcpTool } from "@server/test/McpHelper"; import { buildUser, buildViewer, @@ -9,6 +21,9 @@ import { buildCollection, buildDocument, buildTeam, + buildPersonalCollection, + buildOAuthAuthentication, + buildRelationship, } from "@server/test/factories"; import { getTestServer, mockTaskSchedule } from "@server/test/support"; @@ -2690,3 +2705,292 @@ describe("#collections.restore", () => { expect(body.data.index).not.toBe("P"); }); }); + +describe("personal collections", () => { + it("should not list the personal collection of another user", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const personal = await buildPersonalCollection(owner); + const own = await buildPersonalCollection(admin); + + for (const body of [{}, { includeListOnly: true }]) { + const res = await server.post("/api/collections.list", admin, { body }); + const json = await res.json(); + expect(res.status).toEqual(200); + const ids = json.data.map((c: { id: string }) => c.id); + expect(ids).not.toContain(personal.id); + expect(ids).toContain(own.id); + } + + const res = await server.post("/api/collections.list", owner); + const json = await res.json(); + expect(json.data.map((c: { id: string }) => c.id)).toEqual([personal.id]); + }); + + it("should not return the personal collection of another user", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const admin = await buildAdmin({ teamId: team.id }); + const personal = await buildPersonalCollection(owner); + + for (const route of [ + "collections.info", + "collections.memberships", + "collections.group_memberships", + "collections.export", + "collections.update", + "collections.archive", + "collections.delete", + ]) { + const res = await server.post(`/api/${route}`, admin, { + body: { id: personal.id }, + }); + expect({ route, status: res.status }).toEqual({ route, status: 403 }); + } + }); + + it("should not allow membership changes", async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + const member = await buildUser({ teamId: team.id }); + const group = await buildGroup({ teamId: team.id }); + const personal = await buildPersonalCollection(owner); + + const res = await server.post("/api/collections.add_user", owner, { + body: { id: personal.id, userId: member.id }, + }); + expect(res.status).toEqual(403); + + const res2 = await server.post("/api/collections.add_group", owner, { + body: { id: personal.id, groupId: group.id }, + }); + expect(res2.status).toEqual(403); + + const res3 = await server.post("/api/collections.remove_user", owner, { + body: { id: personal.id, userId: owner.id }, + }); + expect(res3.status).toEqual(403); + }); + + it("should not allow the owner to make it public or rename it", async () => { + const owner = await buildUser(); + const personal = await buildPersonalCollection(owner); + + const res = await server.post("/api/collections.update", owner, { + body: { id: personal.id, permission: CollectionPermission.ReadWrite }, + }); + expect(res.status).toEqual(400); + + const res2 = await server.post("/api/collections.update", owner, { + body: { id: personal.id, name: "Notes" }, + }); + expect(res2.status).toEqual(400); + + const res3 = await server.post("/api/collections.update", owner, { + body: { id: personal.id, sort: { field: "index", direction: "asc" } }, + }); + expect(res3.status).toEqual(200); + }); + + it("should not allow the owner to archive, delete or duplicate it", async () => { + const owner = await buildUser(); + const personal = await buildPersonalCollection(owner); + + for (const route of [ + "collections.archive", + "collections.delete", + "collections.duplicate", + ]) { + const res = await server.post(`/api/${route}`, owner, { + body: { id: personal.id }, + }); + expect({ route, status: res.status }).toEqual({ route, status: 403 }); + } + }); +}); + +describe("personal collection lists", () => { + const keyword = "personalcollectionlists"; + + type UserKey = "owner" | "collaborator" | "member" | "admin"; + + const userKeys: UserKey[] = ["owner", "collaborator", "member", "admin"]; + + let users: Record; + let tokens: Record; + let collectionId: string; + let rootId: string; + let nestedId: string; + let publicDocumentId: string; + + /** + * The personal ids that a user is expected to see. The collaborator has a + * membership on the root document, which the nested document inherits. + * + * @param key The user. + * @returns the ids of the collection and documents. + */ + const readableIds = (key: UserKey) => { + switch (key) { + case "owner": + return [collectionId, rootId, nestedId]; + case "collaborator": + return [rootId, nestedId]; + default: + return []; + } + }; + + const personalIds = () => [collectionId, rootId, nestedId]; + + beforeAll(async () => { + const team = await buildTeam(); + const owner = await buildUser({ teamId: team.id }); + users = { + owner, + collaborator: await buildUser({ teamId: team.id }), + member: await buildUser({ teamId: team.id }), + admin: await buildAdmin({ teamId: team.id }), + }; + + const collection = await buildPersonalCollection(owner); + const root = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: collection.id, + title: `Root ${keyword}`, + text: `Root ${keyword}`, + }); + const nested = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: collection.id, + parentDocumentId: root.id, + title: `Nested ${keyword}`, + text: `Nested ${keyword}`, + }); + await collection.addDocumentToStructure(root, 0); + await collection.addDocumentToStructure(nested, 0); + + await UserMembership.create({ + documentId: root.id, + userId: users.collaborator.id, + permission: DocumentPermission.Read, + createdById: owner.id, + }); + + // A public document that links to the personal document. + const publicCollection = await buildCollection({ + teamId: team.id, + userId: owner.id, + }); + const publicDocument = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: publicCollection.id, + }); + await buildRelationship({ + userId: owner.id, + documentId: publicDocument.id, + reverseDocumentId: root.id, + }); + + // Everybody has viewed the document at some point. + for (const user of Object.values(users)) { + await View.create({ documentId: root.id, userId: user.id }); + } + + tokens = {} as Record; + for (const key of userKeys) { + const auth = await buildOAuthAuthentication({ + user: users[key], + scope: [Scope.Read], + }); + tokens[key] = auth.accessToken!; + } + + collectionId = collection.id; + rootId = root.id; + nestedId = nested.id; + publicDocumentId = publicDocument.id; + }); + + // Lists filter in queries rather than through the read policy, so they are + // checked here for each user. + it.each(userKeys)("only list what %s can read", async (key) => { + const ids = (values: { id: string }[]) => values.map((value) => value.id); + const post = async (route: string, body: Record) => { + const res = await server.post(`/api/${route}`, users[key], { body }); + expect({ route, status: res.status }).toEqual({ route, status: 200 }); + return res.json(); + }; + const mcpText = async (tool: string, args: Record) => { + const res = await callMcpTool(server, tokens[key], tool, args); + return res?.result?.content?.map((c) => c.text).join("\n") ?? ""; + }; + + const results: Record = { + "collections.list": ids((await post("collections.list", {})).data), + "collections.list includeListOnly": ids( + (await post("collections.list", { includeListOnly: true })).data + ), + "documents.list": ids((await post("documents.list", {})).data), + "documents.viewed": ids((await post("documents.viewed", {})).data), + "documents.search": ( + await post("documents.search", { query: keyword }) + ).data.map((result: { document: { id: string } }) => result.document.id), + "documents.search_titles": ids( + (await post("documents.search_titles", { query: keyword })).data + ), + "relationships.list": ids( + (await post("relationships.list", { documentId: publicDocumentId })) + .data.documents + ), + }; + + // Documents include their collectionId, so only document ids are matched. + const collectionsText = await mcpText("list_collections", {}); + const documentsText = await mcpText("list_documents", { query: keyword }); + results.list_collections = personalIds().filter((id) => + collectionsText.includes(id) + ); + results.list_documents = [rootId, nestedId].filter((id) => + documentsText.includes(id) + ); + + const readable = readableIds(key); + for (const [label, listed] of Object.entries(results)) { + const leaked = listed.filter( + (id) => personalIds().includes(id) && !readable.includes(id) + ); + expect({ key, label, leaked }).toEqual({ key, label, leaked: [] }); + } + + if (key === "owner") { + expect(results["collections.list"]).toContain(collectionId); + expect(results["documents.search"]).toEqual( + expect.arrayContaining([rootId, nestedId]) + ); + } + }); + + it("should include the owner for the owner and collaborators", async () => { + for (const key of ["owner", "collaborator"] as const) { + const res = await server.post("/api/documents.info", users[key], { + body: { id: nestedId }, + }); + const body = await res.json(); + expect({ key, ownerId: body.data.ownerId }).toEqual({ + key, + ownerId: users.owner.id, + }); + } + + const res = await server.post("/api/documents.info", users.owner, { + body: { id: publicDocumentId }, + }); + const body = await res.json(); + expect(body.data.ownerId).toBeNull(); + }); +}); diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 372c5ee3a9..7e77ccedbc 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -246,7 +246,7 @@ router.post( Collection.findByPk(id, { userId: user.id, transaction }), Group.findByPk(groupId, { transaction }), ]); - authorize(user, "update", collection); + authorize(user, "manageUsers", collection); authorize(user, "read", group); let membership = await GroupMembership.findOne({ @@ -302,7 +302,7 @@ router.post( transaction, }), ]); - authorize(user, "update", collection); + authorize(user, "manageUsers", collection); authorize(user, "read", group); const [membership] = await collection.$get("groupMemberships", { @@ -404,7 +404,7 @@ router.post( Collection.findByPk(id, { userId: actor.id, transaction }), User.findByPk(userId, { transaction }), ]); - authorize(actor, "update", collection); + authorize(actor, "manageUsers", collection); authorize(actor, "read", user); let membership = await UserMembership.findOne({ @@ -454,7 +454,7 @@ router.post( Collection.findByPk(id, { userId: actor.id, transaction }), User.findByPk(userId, { transaction }), ]); - authorize(actor, "update", collection); + authorize(actor, "manageUsers", collection); authorize(actor, "read", user); const [membership] = await collection.$get("memberships", { @@ -807,6 +807,10 @@ router.post( // are not a member of, so they must be able to see them listed. if (!user.isAdmin || !(includeListOnly || includeArchived)) { where[Op.and].push({ id: collectionIds }); + } else { + where[Op.and].push({ + ownerId: { [Op.or]: [{ [Op.is]: null }, { [Op.eq]: user.id }] }, + }); } if (filter) { diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 3a87a73159..89e06f43fe 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -10,6 +10,7 @@ import { FileOperationFormat, HeadingPrefixStyle, StatusFilter, + TeamPreference, UserRole, } from "@shared/types"; import { TextHelper } from "@shared/utils/TextHelper"; @@ -18,6 +19,7 @@ import { createContext } from "@server/context"; import { parser } from "@server/editor"; import type { Group, User } from "@server/models"; import { + Collection, Document, View, Revision, @@ -6242,6 +6244,45 @@ describe("#documents.import", () => { }); describe("#documents.create", () => { + it("should create the personal collection for the personal collectionId", async () => { + const team = await buildTeam(); + team.setPreference(TeamPreference.PersonalDocs, true); + await team.save(); + const user = await buildUser({ teamId: team.id }); + + const res = await server.post("/api/documents.create", user, { + body: { collectionId: "personal", title: "First", publish: true }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + + const collection = await Collection.findOne({ + where: { teamId: team.id, ownerId: user.id }, + rejectOnEmpty: true, + }); + expect(body.data.collectionId).toEqual(collection.id); + expect(body.data.ownerId).toEqual(user.id); + + const res2 = await server.post("/api/documents.create", user, { + body: { collectionId: "personal", title: "Second", publish: true }, + }); + const body2 = await res2.json(); + expect(res2.status).toEqual(200); + expect(body2.data.collectionId).toEqual(collection.id); + }); + + it("should not create the personal collection when turned off", async () => { + const team = await buildTeam(); + team.setPreference(TeamPreference.PersonalDocs, false); + await team.save(); + const user = await buildUser({ teamId: team.id }); + const res = await server.post("/api/documents.create", user, { + body: { collectionId: "personal", title: "First", publish: true }, + }); + expect(res.status).toEqual(403); + expect(await Collection.count({ where: { ownerId: user.id } })).toEqual(0); + }); + it("should replace template variables when a doc is created from a template", async () => { const user = await buildUser(); const text = `This document was created by {author} on {date}`; diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index fdf05d62c5..f533cbbb3e 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -1,6 +1,7 @@ import type formidable from "formidable"; import { isEmpty } from "es-toolkit/compat"; import { z } from "zod"; +import { PersonalCollectionId } from "@shared/constants"; import { createFilterSchema } from "@shared/helpers/FilterHelper"; import { DirectionFilter, @@ -560,8 +561,10 @@ export const DocumentsImportSchema = BaseSchema.extend({ ]) .optional(), - /** Import docs to this collection */ - collectionId: z.uuid().nullish(), + /** Import docs to this collection, or "personal" for the personal collection */ + collectionId: z + .union([z.uuid(), z.literal(PersonalCollectionId)]) + .nullish(), /** Import under this parent doc */ parentDocumentId: z.uuid().nullish(), @@ -603,8 +606,10 @@ export const DocumentsCreateSchema = BaseSchema.extend({ /** Boolean to denote if the doc should be published */ publish: z.boolean().optional(), - /** Collection to create document within */ - collectionId: z.uuid().nullish(), + /** Collection to create document within, or "personal" for the personal collection */ + collectionId: z + .union([z.uuid(), z.literal(PersonalCollectionId)]) + .nullish(), /** Index to create the document at within the collection */ index: z.number().optional(), diff --git a/server/routes/api/fileOperations/fileOperations.test.ts b/server/routes/api/fileOperations/fileOperations.test.ts index d67cb70af8..5788d73f12 100644 --- a/server/routes/api/fileOperations/fileOperations.test.ts +++ b/server/routes/api/fileOperations/fileOperations.test.ts @@ -1,9 +1,11 @@ // @vitest-isolate true import { CollectionPermission, + FileOperationFormat, FileOperationState, FileOperationType, } from "@shared/types"; +import { createContext } from "@server/context"; import { Collection, User, @@ -16,6 +18,7 @@ import { buildCollection, buildDocument, buildFileOperation, + buildPersonalCollection, buildTeam, buildUser, } from "@server/test/factories"; @@ -593,3 +596,112 @@ describe("#fileOperations.delete", () => { expect(res.status).toEqual(403); }); }); + +describe("personal collection exports", () => { + it("should not show or allow admins to download them", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + const owner = await buildUser({ teamId: team.id }); + const personal = await buildPersonalCollection(owner); + const document = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: personal.id, + }); + const collectionExport = await buildFileOperation({ + state: FileOperationState.Complete, + type: FileOperationType.Export, + teamId: team.id, + userId: owner.id, + collectionId: personal.id, + }); + const documentExport = await buildFileOperation({ + state: FileOperationState.Complete, + type: FileOperationType.Export, + teamId: team.id, + userId: owner.id, + documentId: document.id, + }); + const workspaceExport = await buildFileOperation({ + state: FileOperationState.Complete, + type: FileOperationType.Export, + teamId: team.id, + userId: admin.id, + }); + + const res = await server.post("/api/fileOperations.list", admin, { + body: { type: FileOperationType.Export }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.map((f: { id: string }) => f.id)).toEqual([ + workspaceExport.id, + ]); + + for (const fileOperation of [collectionExport, documentExport]) { + const info = await server.post("/api/fileOperations.info", admin, { + body: { id: fileOperation.id }, + }); + expect(info.status).toEqual(403); + + const redirect = await server.post( + "/api/fileOperations.redirect", + admin, + { + body: { id: fileOperation.id }, + redirect: "manual", + } + ); + expect(redirect.status).toEqual(403); + + const own = await server.post("/api/fileOperations.redirect", owner, { + body: { id: fileOperation.id }, + redirect: "manual", + }); + expect(own.status).toEqual(302); + } + }); + + it("should keep a document export private after the document moves", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + const owner = await buildUser({ teamId: team.id }); + const personal = await buildPersonalCollection(owner); + const shared = await buildCollection({ teamId: team.id, userId: owner.id }); + const document = await buildDocument({ + teamId: team.id, + userId: owner.id, + collectionId: personal.id, + }); + const fileOperation = await FileOperation.createExport( + createContext({ user: owner }), + { document, format: FileOperationFormat.MarkdownZip } + ); + fileOperation.state = FileOperationState.Complete; + await fileOperation.save(); + expect(fileOperation.options?.personalOwnerId).toEqual(owner.id); + + document.collectionId = shared.id; + await document.save(); + + const list = await server.post("/api/fileOperations.list", admin, { + body: { type: FileOperationType.Export }, + }); + const body = await list.json(); + expect(body.data.map((f: { id: string }) => f.id)).not.toContain( + fileOperation.id + ); + + const redirect = await server.post("/api/fileOperations.redirect", admin, { + body: { id: fileOperation.id }, + redirect: "manual", + }); + expect(redirect.status).toEqual(403); + + const own = await server.post("/api/fileOperations.redirect", owner, { + body: { id: fileOperation.id }, + redirect: "manual", + }); + expect(own.status).toEqual(302); + }); +}); diff --git a/server/routes/api/fileOperations/fileOperations.ts b/server/routes/api/fileOperations/fileOperations.ts index fb75c063df..60901391fb 100644 --- a/server/routes/api/fileOperations/fileOperations.ts +++ b/server/routes/api/fileOperations/fileOperations.ts @@ -1,5 +1,5 @@ import Router from "@koa/router"; -import type { WhereOptions } from "sequelize"; +import { Op, type WhereOptions } from "sequelize"; import { UserRole } from "@shared/types"; import { ValidationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; @@ -48,6 +48,27 @@ router.post( const where: WhereOptions = { teamId: user.teamId, type, + // Exclude operations on the personal collections of other users. + [Op.and]: [ + { + [Op.or]: [ + { "$collection.ownerId$": null }, + { "$collection.ownerId$": user.id }, + ], + }, + { + [Op.or]: [ + { "$document.collection.ownerId$": null }, + { "$document.collection.ownerId$": user.id }, + ], + }, + { + [Op.or]: [ + { "options.personalOwnerId": null }, + { "options.personalOwnerId": user.id }, + ], + }, + ], }; const team = await Team.findByPk(user.teamId); authorize(user, "update", team); diff --git a/server/routes/api/pins/pins.test.ts b/server/routes/api/pins/pins.test.ts index 1d72a256e5..0030b8a6e8 100644 --- a/server/routes/api/pins/pins.test.ts +++ b/server/routes/api/pins/pins.test.ts @@ -4,6 +4,7 @@ import { buildCollection, buildDocument, buildDraftDocument, + buildPersonalCollection, buildPin, buildUser, } from "@server/test/factories"; @@ -35,6 +36,17 @@ describe("#pins.create", () => { }); }); + it("should not pin to a personal collection", async () => { + const personal = await buildPersonalCollection(admin); + const res = await server.post("/api/pins.create", admin, { + body: { + documentId: document.id, + collectionId: personal.id, + }, + }); + expect(res.status).toEqual(403); + }); + it("should fail with status 401 unauthorized when user token is missing", async () => { const res = await server.post("/api/pins.create", { body: { diff --git a/server/routes/api/pins/pins.ts b/server/routes/api/pins/pins.ts index 79d572d9dd..283397539c 100644 --- a/server/routes/api/pins/pins.ts +++ b/server/routes/api/pins/pins.ts @@ -40,7 +40,7 @@ router.post( userId: user.id, transaction, }); - authorize(user, "update", collection); + authorize(user, "pin", collection); authorize(user, "pin", document); } else { authorize(user, "pinToHome", document); diff --git a/server/routes/api/teams/schema.ts b/server/routes/api/teams/schema.ts index 1f3439f26f..41b1541a32 100644 --- a/server/routes/api/teams/schema.ts +++ b/server/routes/api/teams/schema.ts @@ -78,6 +78,8 @@ export const TeamsUpdateSchema = BaseSchema.extend({ [TeamPreference.MCP]: z.boolean(), /** List of disabled embed provider titles. */ [TeamPreference.DisabledEmbeds]: z.array(z.string()), + /** Whether users can create documents in a personal collection. */ + [TeamPreference.PersonalDocs]: z.boolean(), }) .partial() .optional(), diff --git a/server/routes/auth/index.ts b/server/routes/auth/index.ts index d4eafbcc44..8b37ca9059 100644 --- a/server/routes/auth/index.ts +++ b/server/routes/auth/index.ts @@ -72,6 +72,7 @@ router.get( where: { id: defaultCollectionId, teamId: team.id, + ownerId: null, }, }); diff --git a/server/test/factories.ts b/server/test/factories.ts index 3cf59e39e2..fd2322f928 100644 --- a/server/test/factories.ts +++ b/server/test/factories.ts @@ -338,6 +338,27 @@ export async function buildCollection( }); } +/** + * Build the personal collection of a user. + * + * @param owner The user that owns the collection. + * @param overrides Attributes to set on the collection. + * @returns the personal collection. + */ +export async function buildPersonalCollection( + owner: User, + overrides: Partial = {} +) { + return buildCollection({ + name: "Personal", + ...overrides, + teamId: owner.teamId, + userId: owner.id, + ownerId: owner.id, + permission: null, + }); +} + export async function buildGroup( overrides: Partial & { userId?: string } = {} ) { diff --git a/server/utils/authentication.ts b/server/utils/authentication.ts index 83a7401c77..5e0b99e608 100644 --- a/server/utils/authentication.ts +++ b/server/utils/authentication.ts @@ -196,6 +196,7 @@ export async function signIn( where: { id: defaultCollectionId, teamId: team.id, + ownerId: null, }, transaction, }); diff --git a/shared/constants.ts b/shared/constants.ts index f5ff0994bc..2264b3594d 100644 --- a/shared/constants.ts +++ b/shared/constants.ts @@ -52,6 +52,12 @@ export const CSRF = { fieldName: "_csrf", }; +/** + * A collectionId that refers to the personal collection of the current user, + * which is created when it does not exist yet. + */ +export const PersonalCollectionId = "personal"; + /** The maximum number of sub-requests permitted in a single `/batch` request. */ export const BatchMaxRequests = 25; @@ -97,6 +103,7 @@ export const TeamPreferenceDefaults: TeamPreferences = { [TeamPreference.EmailDisplay]: EmailDisplay.Members, [TeamPreference.MCP]: true, [TeamPreference.DisabledEmbeds]: [], + [TeamPreference.PersonalDocs]: true, }; export const DocumentPreferenceDefaults: DocumentPreferences = { diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 7bf4ea4a57..c8713f9ed8 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -657,6 +657,8 @@ "Can view": "Can view", "Everyone in the collection": "Everyone in the collection", "You have full access": "You have full access", + "Owner": "Owner", + "This document is in their personal space": "This document is in their personal space", "Other people": "Other people", "Other workspace members may have access": "Other workspace members may have access", "This document may be shared with more workspace members through a parent document or collection you do not have access to": "This document may be shared with more workspace members through a parent document or collection you do not have access to", @@ -687,6 +689,7 @@ "Hide": "Hide", "Starred": "Starred", "Shared with me": "Shared with me", + "Personal": "Personal", "Move up": "Move up", "Move down": "Move down", "Import files": "Import files", @@ -1534,6 +1537,8 @@ "Email address visibility": "Email address visibility", "Controls who can see user email addresses in the workspace": "Controls who can see user email addresses in the workspace", "Controls who can add comments to documents": "Controls who can add comments to documents", + "Personal documents": "Personal documents", + "Allow editors to create personal documents that are only visible to themselves and the people they share them with": "Allow editors to create personal documents that are only visible to themselves and the people they share them with", "Collection creation": "Collection creation", "Allow editors to create new collections within the workspace": "Allow editors to create new collections within the workspace", "Workspace creation": "Workspace creation", diff --git a/shared/types/team.ts b/shared/types/team.ts index 111421c534..1c6ac361d3 100644 --- a/shared/types/team.ts +++ b/shared/types/team.ts @@ -65,6 +65,8 @@ export enum TeamPreference { MCP = "mcp", /** List of disabled embed provider titles. */ DisabledEmbeds = "disabledEmbeds", + /** Whether users can create documents in a personal collection. */ + PersonalDocs = "personalDocs", } /** Workspace preference values, keyed by preference. */ @@ -83,4 +85,5 @@ export type TeamPreferences = { [TeamPreference.EmailDisplay]?: EmailDisplay; [TeamPreference.MCP]?: boolean; [TeamPreference.DisabledEmbeds]?: string[]; + [TeamPreference.PersonalDocs]?: boolean; }; diff --git a/shared/types/user.ts b/shared/types/user.ts index 027831435d..8510cdb4a7 100644 --- a/shared/types/user.ts +++ b/shared/types/user.ts @@ -6,6 +6,8 @@ export enum SidebarSection { SharedWithMe = "shared", /** The collections section. */ Collections = "collections", + /** The user's own personal documents section. */ + Personal = "personal", } /** User-level preferences. */ From c46fbc637567d2dc5a2f703b8e948ba9ef00814b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 13 Oct 2026 07:56:51 -0400 Subject: [PATCH 276/368] fix: Search terms inside dot-separated identifiers (#14072) * fix: Search terms inside dot-separated identifiers * fix: Strip leading join operator from search tsquery --- .../server/PostgresSearchProvider.test.ts | 77 +++++++++++ .../server/PostgresSearchProvider.ts | 125 ++++++++++++------ 2 files changed, 160 insertions(+), 42 deletions(-) diff --git a/plugins/search-postgres/server/PostgresSearchProvider.test.ts b/plugins/search-postgres/server/PostgresSearchProvider.test.ts index 494a8b2cc4..884194afe3 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.test.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.test.ts @@ -773,6 +773,78 @@ describe("PostgresSearchProvider", () => { expect(total).toBe(1); }); + it("should find identifiers inside dot separated identifiers", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Registers", + text: "When dsws_config.2.ws_fp4tofp8_cvt == 1", + }); + + for (const query of [ + "ws_fp4tofp8_cvt", + "WS_FP4TOFP8_CVT", + "config.2.ws_fp4tofp8_cvt", + "registers ws_fp4tofp8_cvt", + "the ws_fp4tofp8_cvt", + ]) { + const { results } = await provider.searchForUser(user, { query }); + expect(results.map((result) => result.document?.id)).toEqual([ + document.id, + ]); + } + + for (const query of ["missing ws_fp4tofp8_cvt", "ws_fp4tofp8_cvt_x"]) { + const { total } = await provider.searchForUser(user, { query }); + expect(total).toBe(0); + } + }); + + it("should match underscores in identifiers literally", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + text: "When dsws_config.2.wsXcvt == 1", + }); + const { total } = await provider.searchForUser(user, { + query: "ws_cvt", + }); + expect(total).toBe(0); + }); + + it("should handle a query that starts with a quote after an identifier", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + text: "When dsws_config.2.ws_fp4tofp8_cvt == 1", + }); + const { total } = await provider.searchForUser(user, { + query: "ws_fp4tofp8_cvt ' foo", + }); + expect(total).toBe(0); + }); + it("should return context that is not shifted by earlier highlights", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); @@ -1664,6 +1736,11 @@ describe("PostgresSearchProvider", () => { `"plugins"` ); }); + + it("should strip a leading join operator", () => { + expect(PostgresSearchProvider.webSearchQuery("' foo")).toBe("foo:*"); + }); + 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. diff --git a/plugins/search-postgres/server/PostgresSearchProvider.ts b/plugins/search-postgres/server/PostgresSearchProvider.ts index bbdedbebd9..de1844e820 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.ts @@ -63,6 +63,12 @@ export default class PostgresSearchProvider extends BaseSearchProvider { */ private static readonly QUOTED_QUERY_REGEX = /"([^"]*)"/g; + /** + * Cached regex pattern for identifier-like terms, words joined by "." or "_". + */ + private static readonly IDENTIFIER_REGEX = + /^[\p{L}\p{N}]+(?:[._][\p{L}\p{N}]+)+$/u; + /** * Cached regex pattern for break characters. */ @@ -710,20 +716,13 @@ export default class PostgresSearchProvider extends BaseSearchProvider { if (options.query) { // find words that look like urls, these should be treated separately as the postgres full-text // index will generally not match them. - let likelyUrls = getUrls(options.query); + const likelyUrls = getUrls(options.query); - // remove likely urls, and escape the rest of the query. - let limitedQuery = PostgresSearchProvider.escapeQuery( - likelyUrls - .reduce((q, url) => q.replace(url, ""), options.query) - .slice(0, PostgresSearchProvider.maxQueryLength) - .trim() - ); - - // Escape the URLs - likelyUrls = likelyUrls.map((url) => - PostgresSearchProvider.escapeQuery(url) - ); + // remove likely urls from the query. + let limitedQuery = likelyUrls + .reduce((q, url) => q.replace(url, ""), options.query) + .slice(0, PostgresSearchProvider.maxQueryLength) + .trim(); // Extract quoted queries and add them to the where clause, up to a maximum of 3 total. const quotedQueries = Array.from(limitedQuery.matchAll(/"([^"]*)"/g)).map( @@ -736,38 +735,84 @@ export default class PostgresSearchProvider extends BaseSearchProvider { const iLikeQueries = [...quotedQueries, ...likelyUrls].slice(0, 3); for (const match of iLikeQueries) { - // only escape % and _ as backslashes were already escaped above. - const pattern = `%${match.replace(/[%_]/g, "\\$&")}%`; - where[Op.and].push({ - [Op.or]: [ - { - title: { - [Op.iLike]: pattern, - }, - }, - { - text: { - [Op.iLike]: pattern, - }, - }, - ], - }); + where[Op.and].push(PostgresSearchProvider.buildContainsMatch(match)); } if (limitedQuery || iLikeQueries.length === 0) { - where[Op.and].push( - Sequelize.fn( - `"searchVector" @@ to_tsquery`, - "english", - Sequelize.literal(":query") - ) - ); + where[Op.and].push(PostgresSearchProvider.buildTextMatch(limitedQuery)); } } return where; } + /** + * Builds the full-text condition for the unquoted part of a query. Terms + * that look like identifiers, such as "config.ws_value", also match as + * literal text, as the postgres parser does not always split them into the + * same lexemes in a document as in a query. + * + * @param query the unquoted part of the user search query. + * @returns the where condition. + */ + private static buildTextMatch(query: string): WhereOptions { + const fullTextMatch = Sequelize.fn( + `"searchVector" @@ to_tsquery`, + "english", + Sequelize.literal(":query") + ); + const terms = query.split(/\s+/).filter(Boolean); + const identifiers = terms + .filter((term) => PostgresSearchProvider.IDENTIFIER_REGEX.test(term)) + .slice(0, 3); + + if (!identifiers.length) { + return fullTextMatch; + } + + const conditions: WhereOptions[] = identifiers.map((term) => + PostgresSearchProvider.buildContainsMatch(term) + ); + const remainder = terms + .filter((term) => !identifiers.includes(term)) + .join(" "); + + if (remainder) { + const remainderQuery = Sequelize.fn( + "to_tsquery", + "english", + PostgresSearchProvider.webSearchQuery(remainder) + ); + + // a remainder of only stop words gives an empty tsquery, which matches nothing. + conditions.push({ + [Op.or]: [ + Sequelize.fn(`"searchVector" @@`, remainderQuery), + Sequelize.where(Sequelize.fn("numnode", remainderQuery), 0), + ], + }); + } + + return { [Op.or]: [fullTextMatch, { [Op.and]: conditions }] }; + } + + /** + * Builds a condition that matches documents whose title or text contains + * the term as literal, case-insensitive text. + * + * @param term the term to match. + * @returns the where condition. + */ + private static buildContainsMatch(term: string): WhereOptions { + const pattern = QueryHelper.likeContains(term); + return { + [Op.or]: [ + { title: { [Op.iLike]: pattern } }, + { text: { [Op.iLike]: pattern } }, + ], + }; + } + private static buildResponse({ query, results, @@ -852,15 +897,11 @@ export default class PostgresSearchProvider extends BaseSearchProvider { // combination, so we never hand to_tsquery an operator with no // operand (e.g. a tail of "&\" would leave a dangling "&"). .replace(/[&\\]+$/, "") + // A leading single quote can also leave a join with no operand. + .replace(/^&+/, "") ); } - private static escapeQuery(query: string): string { - // 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. From dccd9fcfe95c41fafffb798dbe40edce5a471e5d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 13 Oct 2026 07:59:44 -0400 Subject: [PATCH 277/368] chore: Rename titleWithDefault to displayTitle (#14063) --- app/actions/definitions/templates.tsx | 2 +- app/actions/definitions/webmcp.ts | 4 ++-- app/actions/sections.ts | 4 ++-- app/components/CommandBar/useRecentDocumentActions.tsx | 2 +- app/components/CommandBar/useSearchIndex.ts | 2 +- app/components/CommandBar/useTemplatesAction.tsx | 2 +- app/components/DialogTitle.tsx | 2 +- app/components/DocumentCard.tsx | 6 +++--- app/components/DocumentChip.tsx | 2 +- app/components/DocumentListItem.tsx | 4 ++-- app/components/Sidebar/components/SharedWithMeLink.tsx | 2 +- app/components/Sidebar/components/StarredLink.tsx | 2 +- .../Sidebar/hooks/useSidebarLabelAndIcon.tsx | 2 +- app/editor/components/BlockMenu.tsx | 7 ++----- app/editor/extensions/PasteHandler.tsx | 4 ++-- app/hooks/useTemplateMenuActions.tsx | 5 +---- app/menus/NewChildDocumentMenu.tsx | 4 ++-- app/models/Document.ts | 2 +- app/models/Template.ts | 4 ++-- app/scenes/Document/components/Document.tsx | 4 ++-- app/scenes/Document/components/Editor.tsx | 4 +--- app/scenes/Document/components/ReferenceListItem.tsx | 2 +- app/scenes/DocumentDelete.tsx | 4 ++-- app/scenes/DocumentPermanentDelete.tsx | 2 +- app/scenes/Search/components/DocumentFilter.tsx | 2 +- app/scenes/Settings/components/TemplatesTable.tsx | 6 +++--- app/stores/UiStore.ts | 2 +- plugins/slack/server/presenters/messageAttachment.ts | 2 +- plugins/slack/server/processors/SlackProcessor.ts | 4 ++-- server/emails/templates/CommentCreatedEmail.tsx | 10 +++++----- server/emails/templates/CommentMentionedEmail.tsx | 8 ++++---- server/emails/templates/CommentResolvedEmail.tsx | 8 ++++---- server/emails/templates/DocumentAccessRequestEmail.tsx | 8 ++++---- server/emails/templates/DocumentMentionedEmail.tsx | 6 +++--- .../templates/DocumentPublishedOrUpdatedEmail.tsx | 10 +++++----- server/emails/templates/DocumentSharedEmail.tsx | 8 ++++---- server/emails/templates/GroupCommentMentionedEmail.tsx | 8 ++++---- .../emails/templates/GroupDocumentMentionedEmail.tsx | 6 +++--- server/models/Document.ts | 2 +- server/models/FileOperation.ts | 2 +- server/models/helpers/OKFHelper.ts | 2 +- server/presenters/fileOperation.ts | 2 +- server/presenters/unfurl.ts | 2 +- server/queues/tasks/ExportDocumentTreeTask.ts | 4 ++-- .../queues/tasks/ShareSubscriptionNotificationsTask.ts | 2 +- server/routes/api/documents/documents.ts | 2 +- server/routes/api/shares/shares.ts | 2 +- server/routes/api/urls/urls.test.ts | 8 ++++---- 48 files changed, 93 insertions(+), 101 deletions(-) diff --git a/app/actions/definitions/templates.tsx b/app/actions/definitions/templates.tsx index 187cec8cac..e88e859a7a 100644 --- a/app/actions/definitions/templates.tsx +++ b/app/actions/definitions/templates.tsx @@ -84,7 +84,7 @@ export const deleteTemplate = dialogActionFactory({ , diff --git a/app/actions/definitions/webmcp.ts b/app/actions/definitions/webmcp.ts index 17ed0d6718..4aa246d825 100644 --- a/app/actions/definitions/webmcp.ts +++ b/app/actions/definitions/webmcp.ts @@ -25,7 +25,7 @@ export const getCurrentContext = createAction({ document: document ? { id: document.id, - title: document.titleWithDefault, + title: document.displayTitle, path: document.url, } : undefined, @@ -69,7 +69,7 @@ export const searchWorkspace = createAction({ return JSON.stringify( results.map((result) => ({ id: result.document.id, - title: result.document.titleWithDefault, + title: result.document.displayTitle, path: result.document.url, context: result.context, })) diff --git a/app/actions/sections.ts b/app/actions/sections.ts index 6531dde2d4..699771bbf2 100644 --- a/app/actions/sections.ts +++ b/app/actions/sections.ts @@ -30,7 +30,7 @@ DocumentsSection.priority = 0.8; export const ActiveDocumentSection = ({ t, stores }: ActionContext) => { const activeDocument = stores.documents.active; - return `${t("Document")} · ${activeDocument?.titleWithDefault}`; + return `${t("Document")} · ${activeDocument?.displayTitle}`; }; ActiveDocumentSection.priority = 0.9; @@ -39,7 +39,7 @@ export const TemplateSection = ({ t }: ActionContext) => t("Template"); export const ActiveTemplateSection = ({ t, stores }: ActionContext) => { const activeTemplate = stores.templates.active; - return `${t("Template")} · ${activeTemplate?.titleWithDefault}`; + return `${t("Template")} · ${activeTemplate?.displayTitle}`; }; ActiveTemplateSection.priority = 0.9; diff --git a/app/components/CommandBar/useRecentDocumentActions.tsx b/app/components/CommandBar/useRecentDocumentActions.tsx index 2d5545286c..0da9ea7f1d 100644 --- a/app/components/CommandBar/useRecentDocumentActions.tsx +++ b/app/components/CommandBar/useRecentDocumentActions.tsx @@ -43,7 +43,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => { count ).map((item) => createInternalLinkAction({ - name: item.titleWithDefault, + name: item.displayTitle, analyticsName: "Recently viewed document", section: RecentSection, visible: ({ isMCP }) => !isMCP, diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index d81900984c..1ec692195d 100644 --- a/app/components/CommandBar/useSearchIndex.ts +++ b/app/components/CommandBar/useSearchIndex.ts @@ -49,7 +49,7 @@ export function toSearchRecord( ): SearchIndexDocument { return { id: doc.id, - title: doc.titleWithDefault, + title: doc.displayTitle, url: doc.url, text: doc.data ? getPlainText(doc) : stripHighlightTags(context), icon: doc.icon, diff --git a/app/components/CommandBar/useTemplatesAction.tsx b/app/components/CommandBar/useTemplatesAction.tsx index 8ce09d2d81..8aa6f09716 100644 --- a/app/components/CommandBar/useTemplatesAction.tsx +++ b/app/components/CommandBar/useTemplatesAction.tsx @@ -28,7 +28,7 @@ const useTemplatesAction = () => { () => templates.alphabetical.map((template) => createInternalLinkAction({ - name: template.titleWithDefault, + name: template.displayTitle, analyticsName: "New document", section: template.isWorkspaceTemplate ? TeamSection diff --git a/app/components/DialogTitle.tsx b/app/components/DialogTitle.tsx index 0085d43bd3..1e1a561db8 100644 --- a/app/components/DialogTitle.tsx +++ b/app/components/DialogTitle.tsx @@ -60,7 +60,7 @@ export const DialogTitle = observer(function DialogTitle_({ {icon} - {isDocument ? model.titleWithDefault : model.displayName} + {isDocument ? model.displayTitle : model.displayName} diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index 245dffb1c5..b471db8121 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -127,7 +127,7 @@ function DocumentCard(props: Props) { to={{ pathname: document.path, state: { - title: document.titleWithDefault, + title: document.displayTitle, }, }} > @@ -169,8 +169,8 @@ function DocumentCard(props: Props) {
    {hasEmojiInTitle - ? document.titleWithDefault.replace(document.icon!, "") - : document.titleWithDefault} + ? document.displayTitle.replace(document.icon!, "") + : document.displayTitle} {isRecentlyUpdated ? ( diff --git a/app/components/DocumentChip.tsx b/app/components/DocumentChip.tsx index 5c45fb46ae..c39eab42fe 100644 --- a/app/components/DocumentChip.tsx +++ b/app/components/DocumentChip.tsx @@ -34,7 +34,7 @@ export const DocumentChip = observer(function DocumentChip_({ const { icon, color } = document; const canPin = usePolicy(pin); const canDocument = usePolicy(document); - const title = document.titleWithDefault; + const title = document.displayTitle; const isEmoji = determineIconType(icon) === IconType.Emoji; // Pins in a collection are governed by the document policy, pins on home by diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index 76bd7fcd18..278c76ec01 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -170,7 +170,7 @@ function DocumentListItem(props: Props) { pathname: documentPath(document), search: highlight ? `?q=${encodeURIComponent(highlight)}` : undefined, state: { - title: document.titleWithDefault, + title: document.displayTitle, sidebarContext, }, }} @@ -213,7 +213,7 @@ function DocumentListItem(props: Props) { diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 43b345eb86..0aca26920e 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -184,7 +184,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const label = determineIconType(docIcon) === IconType.Emoji ? document.title.replace(docIcon!, "") - : document.titleWithDefault; + : document.displayTitle; const collection = document.collectionId ? collections.get(document.collectionId) : undefined; diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index 2de85b68fd..6a48f7df56 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -222,7 +222,7 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ depth={0} icon={icon} canEdit={can.update} - labelText={document.titleWithDefault} + labelText={document.displayTitle} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} expanded={expanded} diff --git a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx index eff563fb43..3b8cf5c4e5 100644 --- a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx +++ b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx @@ -28,7 +28,7 @@ export function useSidebarLabelAndIcon({ const collection = !document && collectionId ? collections.get(collectionId) : undefined; - const title = document?.titleWithDefault; + const title = document?.displayTitle; const documentIcon = document?.icon; const initial = document?.initial; const color = document?.color; diff --git a/app/editor/components/BlockMenu.tsx b/app/editor/components/BlockMenu.tsx index 5737fdf700..95ada775a6 100644 --- a/app/editor/components/BlockMenu.tsx +++ b/app/editor/components/BlockMenu.tsx @@ -55,10 +55,7 @@ function useTemplateMenuItem(isActive: boolean): MenuItem | undefined { const toMenuItem = (template: (typeof allTemplates)[0]): MenuItem => ({ name: "noop", - title: TextHelper.replaceTemplateVariables( - template.titleWithDefault, - user - ), + title: TextHelper.replaceTemplateVariables(template.displayTitle, user), icon: template.icon ? ( <Icon value={template.icon} @@ -68,7 +65,7 @@ function useTemplateMenuItem(isActive: boolean): MenuItem | undefined { ) : ( <DocumentIcon /> ), - keywords: template.titleWithDefault, + keywords: template.displayTitle, onClick: () => { const data = cloneDeep(template.data); ProsemirrorHelper.replaceTemplateVariables(data, user); diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index 14ac459653..312a5ec6d2 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -149,7 +149,7 @@ export default class PasteHandler extends Extension { state.schema.nodes.mention.create({ type: MentionType.Document, modelId: document.id, - label: document.titleWithDefault, + label: document.displayTitle, id: uuidv4(), anchorId: trimmedHash.length ? trimmedHash @@ -164,7 +164,7 @@ export default class PasteHandler extends Extension { IconType.Emoji; const title = `${hasEmoji ? document.icon + " " : ""}${ - document.titleWithDefault + document.displayTitle }`; this.insertLink(`${document.path}${hash}`, title); diff --git a/app/hooks/useTemplateMenuActions.tsx b/app/hooks/useTemplateMenuActions.tsx index f1d4a30765..ad1545b387 100644 --- a/app/hooks/useTemplateMenuActions.tsx +++ b/app/hooks/useTemplateMenuActions.tsx @@ -47,10 +47,7 @@ export function useTemplateMenuActions({ const templateToAction = useCallback( (template: Template): Action => createAction({ - name: TextHelper.replaceTemplateVariables( - template.titleWithDefault, - user - ), + name: TextHelper.replaceTemplateVariables(template.displayTitle, user), section: DocumentsSection, icon: template.icon ? ( <Icon diff --git a/app/menus/NewChildDocumentMenu.tsx b/app/menus/NewChildDocumentMenu.tsx index 81f351d827..7c5a084d4d 100644 --- a/app/menus/NewChildDocumentMenu.tsx +++ b/app/menus/NewChildDocumentMenu.tsx @@ -50,7 +50,7 @@ function NewChildDocumentMenu({ document }: Props) { <Trans defaults="New document in <em>{{ collectionName }}</em>" values={{ - collectionName: document.titleWithDefault, + collectionName: document.displayTitle, }} components={{ em: <strong />, @@ -66,7 +66,7 @@ function NewChildDocumentMenu({ document }: Props) { collectionName, canCollection.createDocument, document.id, - document.titleWithDefault, + document.displayTitle, document.collectionId, ] ); diff --git a/app/models/Document.ts b/app/models/Document.ts index 2051baf53e..2126347441 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -490,7 +490,7 @@ export default class Document extends ArchivableModel implements Searchable { return path.map((item) => item.asNavigationNode); } - get titleWithDefault(): string { + get displayTitle(): string { return this.title || i18n.t("Untitled"); } diff --git a/app/models/Template.ts b/app/models/Template.ts index 1705e716a6..517dc04875 100644 --- a/app/models/Template.ts +++ b/app/models/Template.ts @@ -185,13 +185,13 @@ export default class Template extends ParanoidModel implements Searchable { return addDays(new Date(this.deletedAt), 30).toString(); } - get titleWithDefault(): string { + get displayTitle(): string { return this.title || i18n.t("Untitled"); } @computed get initial(): string { - return (this.titleWithDefault?.charAt(0) ?? "?").toUpperCase(); + return (this.displayTitle?.charAt(0) ?? "?").toUpperCase(); } @computed diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index aaa1c7c6be..5b7df6c65b 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -371,8 +371,8 @@ function DocumentScene({ const hasEmojiInTitle = determineIconType(document.icon) === IconType.Emoji; const pageTitle = hasEmojiInTitle - ? document.titleWithDefault.replace(document.icon!, "") - : document.titleWithDefault; + ? document.displayTitle.replace(document.icon!, "") + : document.displayTitle; const favicon = hasEmojiInTitle ? emojiToUrl(document.icon!) : undefined; const fullWidthTransformOffsetStyle = { diff --git a/app/scenes/Document/components/Editor.tsx b/app/scenes/Document/components/Editor.tsx index 0c90e23f5c..a557f23b80 100644 --- a/app/scenes/Document/components/Editor.tsx +++ b/app/scenes/Document/components/Editor.tsx @@ -227,9 +227,7 @@ function DocumentEditor(props: Props) { readOnly={readOnly} documentId={document.id} title={ - !document.title && readOnly - ? document.titleWithDefault - : document.title + !document.title && readOnly ? document.displayTitle : document.title } icon={document.icon} color={iconColor} diff --git a/app/scenes/Document/components/ReferenceListItem.tsx b/app/scenes/Document/components/ReferenceListItem.tsx index 17259c84cc..dee72da7ae 100644 --- a/app/scenes/Document/components/ReferenceListItem.tsx +++ b/app/scenes/Document/components/ReferenceListItem.tsx @@ -238,7 +238,7 @@ function ReferenceListItem({ const { icon, color } = document; const isEmoji = determineIconType(icon) === IconType.Emoji; const title = - document instanceof Document ? document.titleWithDefault : document.title; + document instanceof Document ? document.displayTitle : document.title; const initial = title.charAt(0).toUpperCase(); const showContextMenu = document instanceof Document && !!user; diff --git a/app/scenes/DocumentDelete.tsx b/app/scenes/DocumentDelete.tsx index 2e4031fc87..a8d05716b9 100644 --- a/app/scenes/DocumentDelete.tsx +++ b/app/scenes/DocumentDelete.tsx @@ -109,7 +109,7 @@ function DocumentDelete({ document, onSubmit }: Props) { <Trans defaults="Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }} components={{ em: <strong />, @@ -120,7 +120,7 @@ function DocumentDelete({ document, onSubmit }: Props) { count={nestedDocumentsCount} defaults="Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested document</em>." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, any: nestedDocumentsCount, }} components={{ diff --git a/app/scenes/DocumentPermanentDelete.tsx b/app/scenes/DocumentPermanentDelete.tsx index a7cf03da53..9c7465a6e2 100644 --- a/app/scenes/DocumentPermanentDelete.tsx +++ b/app/scenes/DocumentPermanentDelete.tsx @@ -37,7 +37,7 @@ function DocumentPermanentDelete({ document, onSubmit }: Props) { <Trans defaults="Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }} components={{ em: <strong />, diff --git a/app/scenes/Search/components/DocumentFilter.tsx b/app/scenes/Search/components/DocumentFilter.tsx index f634cc7027..5416d5a370 100644 --- a/app/scenes/Search/components/DocumentFilter.tsx +++ b/app/scenes/Search/components/DocumentFilter.tsx @@ -19,7 +19,7 @@ export function DocumentFilter(props: Props) { <div> <Tooltip content={t("Remove document filter")}> <StyledButton onClick={props.onClick} icon={<CloseIcon />} neutral> - {props.document.titleWithDefault} + {props.document.displayTitle} </StyledButton> </Tooltip> </div> diff --git a/app/scenes/Settings/components/TemplatesTable.tsx b/app/scenes/Settings/components/TemplatesTable.tsx index b46a3e7224..c59dc96ab3 100644 --- a/app/scenes/Settings/components/TemplatesTable.tsx +++ b/app/scenes/Settings/components/TemplatesTable.tsx @@ -89,7 +89,7 @@ export function TemplatesTable(props: Props) { type: "data", id: "title", header: t("Title"), - accessor: (template) => template.titleWithDefault, + accessor: (template) => template.displayTitle, component: (template) => <TemplateLink template={template} />, width: "4fr", }, @@ -167,9 +167,9 @@ const TemplateLink = observer(({ template }: { template: Template }) => { <ShapesIcon size={24} color={theme.textSecondary} /> )} {can.update ? ( - <Title>{template.titleWithDefault} + {template.displayTitle} ) : ( - {template.titleWithDefault} + {template.displayTitle} )} {template.isDraft && ( diff --git a/app/stores/UiStore.ts b/app/stores/UiStore.ts index 410ff39eba..a97425518d 100644 --- a/app/stores/UiStore.ts +++ b/app/stores/UiStore.ts @@ -130,7 +130,7 @@ class UiStore { setPresentingDocument = (document: Document | null): void => { this.presentationData = document ? { - title: document.titleWithDefault, + title: document.displayTitle, icon: document.icon, color: document.color, data: document.data, diff --git a/plugins/slack/server/presenters/messageAttachment.ts b/plugins/slack/server/presenters/messageAttachment.ts index b7e6193637..8caf03f67e 100644 --- a/plugins/slack/server/presenters/messageAttachment.ts +++ b/plugins/slack/server/presenters/messageAttachment.ts @@ -22,7 +22,7 @@ export function presentMessageAttachment( return { color: collection?.color, - title: document.titleWithDefault, + title: document.displayTitle, title_link: `${team.url}${document.url}`, footer: collection?.name, callback_id: document.id, diff --git a/plugins/slack/server/processors/SlackProcessor.ts b/plugins/slack/server/processors/SlackProcessor.ts index 50a81b47a5..4c6aee432f 100644 --- a/plugins/slack/server/processors/SlackProcessor.ts +++ b/plugins/slack/server/processors/SlackProcessor.ts @@ -124,10 +124,10 @@ export default class SlackProcessor extends BaseProcessor { if (!integration) { return; } - let text = `${document.updatedBy.name} updated "${document.titleWithDefault}"`; + let text = `${document.updatedBy.name} updated "${document.displayTitle}"`; if (event.name === "documents.publish") { - text = `${document.createdBy.name} published "${document.titleWithDefault}"`; + text = `${document.createdBy.name} published "${document.displayTitle}"`; } await fetch(integration.settings.url, { diff --git a/server/emails/templates/CommentCreatedEmail.tsx b/server/emails/templates/CommentCreatedEmail.tsx index 910e33a157..2192a589c8 100644 --- a/server/emails/templates/CommentCreatedEmail.tsx +++ b/server/emails/templates/CommentCreatedEmail.tsx @@ -106,7 +106,7 @@ export default class CommentCreatedEmail extends BaseEmail< return `${parentComment ? this.t("Re") + ": " : ""}${this.t( "New comment on “{{ documentTitle }}” - {{ trimmedText }}", - { documentTitle: document.titleWithDefault, trimmedText } + { documentTitle: document.displayTitle, trimmedText } )}`; } @@ -140,11 +140,11 @@ export default class CommentCreatedEmail extends BaseEmail< const action = isReply ? this.t("{{ actorName }} replied to a thread in “{{ documentTitle }}”", { actorName, - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }) : this.t("{{ actorName }} commented on “{{ documentTitle }}”", { actorName, - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }); const inCollection = collection?.name ? ` ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}` @@ -178,12 +178,12 @@ ${this.t("Open Thread")}: ${teamUrl}${document.url}?commentId=${commentId}
    - {document.titleWithDefault} + {document.displayTitle}

    {isReply ? this.t("{{ actorName }} replied to a thread in", { actorName }) : this.t("{{ actorName }} commented on", { actorName })}{" "} - {document.titleWithDefault}{" "} + {document.displayTitle}{" "} {collection?.name ? this.t("in the {{ collectionName }} collection", { collectionName: collection.name, diff --git a/server/emails/templates/CommentMentionedEmail.tsx b/server/emails/templates/CommentMentionedEmail.tsx index 69691abaf2..260de7b305 100644 --- a/server/emails/templates/CommentMentionedEmail.tsx +++ b/server/emails/templates/CommentMentionedEmail.tsx @@ -95,7 +95,7 @@ export default class CommentMentionedEmail extends BaseEmail< protected subject({ document }: Props) { return this.t("Mentioned you in “{{ documentTitle }}”", { - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }); } @@ -116,7 +116,7 @@ export default class CommentMentionedEmail extends BaseEmail< }: Props): string { const action = this.t( "{{ actorName }} mentioned you in a comment on “{{ documentTitle }}”", - { actorName, documentTitle: document.titleWithDefault } + { actorName, documentTitle: document.displayTitle } ); const inCollection = collection.name ? ` ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}` @@ -149,12 +149,12 @@ ${this.t("Open Thread")}: ${teamUrl}${document.url}?commentId=${commentId}

    - {document.titleWithDefault} + {document.displayTitle}

    {this.t("{{ actorName }} mentioned you in a comment on", { actorName, })}{" "} - {document.titleWithDefault}{" "} + {document.displayTitle}{" "} {collection.name ? this.t("in the {{ collectionName }} collection", { collectionName: collection.name, diff --git a/server/emails/templates/CommentResolvedEmail.tsx b/server/emails/templates/CommentResolvedEmail.tsx index 91d0ded895..4f4b312782 100644 --- a/server/emails/templates/CommentResolvedEmail.tsx +++ b/server/emails/templates/CommentResolvedEmail.tsx @@ -95,7 +95,7 @@ export default class CommentResolvedEmail extends BaseEmail< protected subject({ document }: Props) { return this.t("Resolved a comment thread in “{{ documentTitle }}”", { - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }); } @@ -116,7 +116,7 @@ export default class CommentResolvedEmail extends BaseEmail< }: Props): string { const action = this.t( "{{ actorName }} resolved a comment thread on “{{ documentTitle }}”", - { actorName, documentTitle: document.titleWithDefault } + { actorName, documentTitle: document.displayTitle } ); const inCollection = collection.name ? ` ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}` @@ -145,10 +145,10 @@ export default class CommentResolvedEmail extends BaseEmail<

    - {document.titleWithDefault} + {document.displayTitle}

    {this.t("{{ actorName }} resolved a comment on", { actorName })}{" "} - {document.titleWithDefault}{" "} + {document.displayTitle}{" "} {collection.name ? this.t("in the {{ collectionName }} collection", { collectionName: collection.name, diff --git a/server/emails/templates/DocumentAccessRequestEmail.tsx b/server/emails/templates/DocumentAccessRequestEmail.tsx index 94c9fe198b..db7fba073a 100644 --- a/server/emails/templates/DocumentAccessRequestEmail.tsx +++ b/server/emails/templates/DocumentAccessRequestEmail.tsx @@ -47,7 +47,7 @@ export default class DocumentAccessRequestEmail extends BaseEmail< } protected subject({ actor, document }: Props) { - return `${actor.name} is requesting access to "${document.titleWithDefault}"`; + return `${actor.name} is requesting access to "${document.displayTitle}"`; } protected preview({ actor }: Props): string { @@ -60,7 +60,7 @@ export default class DocumentAccessRequestEmail extends BaseEmail< protected renderAsText({ actor, teamUrl, document }: Props): string { return ` -${actor.name} is requesting access to "${document.titleWithDefault}". +${actor.name} is requesting access to "${document.displayTitle}". Open the document to share it with them: ${teamUrl}${document.path} `; @@ -78,10 +78,10 @@ Open the document to share it with them: ${teamUrl}${document.path}

    - {document.titleWithDefault} + {document.displayTitle}

    {actor.name} is requesting access to the{" "} - {document.titleWithDefault} document. + {document.displayTitle} document.

    Open the document to share it with them.

    diff --git a/server/emails/templates/DocumentMentionedEmail.tsx b/server/emails/templates/DocumentMentionedEmail.tsx index 0f0a7a910a..2e92501a3c 100644 --- a/server/emails/templates/DocumentMentionedEmail.tsx +++ b/server/emails/templates/DocumentMentionedEmail.tsx @@ -94,7 +94,7 @@ export default class DocumentMentionedEmail extends BaseEmail< protected subject({ document }: Props) { return this.t(`Mentioned you in “{{ documentTitle }}”`, { - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }); } @@ -119,7 +119,7 @@ export default class DocumentMentionedEmail extends BaseEmail< return ` ${this.t("You were mentioned")} -${this.t(`{{ actorName }} mentioned you in the document “{{ documentTitle }}”.`, { actorName, documentTitle: document.titleWithDefault })} +${this.t(`{{ actorName }} mentioned you in the document “{{ documentTitle }}”.`, { actorName, documentTitle: document.displayTitle })} ${this.t("Open Document")}: ${teamUrl}${document.url} `; @@ -142,7 +142,7 @@ ${this.t("Open Document")}: ${teamUrl}${document.url} {this.t("{{ actorName }} mentioned you in the document", { actorName, })}{" "} - {document.titleWithDefault}. + {document.displayTitle}.

    {body && ( <> diff --git a/server/emails/templates/DocumentPublishedOrUpdatedEmail.tsx b/server/emails/templates/DocumentPublishedOrUpdatedEmail.tsx index 770c548663..3d1ac5068d 100644 --- a/server/emails/templates/DocumentPublishedOrUpdatedEmail.tsx +++ b/server/emails/templates/DocumentPublishedOrUpdatedEmail.tsx @@ -118,7 +118,7 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail< protected subject({ document, eventType }: Props) { return this.t(`“{{ documentTitle }}” {{ eventName }}`, { - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, eventName: this.eventName(eventType), }); } @@ -153,9 +153,9 @@ export default class DocumentPublishedOrUpdatedEmail extends BaseEmail< const eventName = this.eventName(eventType); return ` -${this.t("“{{ documentTitle }}” {{ eventName }}", { documentTitle: document.titleWithDefault, eventName })} +${this.t("“{{ documentTitle }}” {{ eventName }}", { documentTitle: document.displayTitle, eventName })} -${this.t("{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”", { actorName, eventName, documentTitle: document.titleWithDefault })}${ +${this.t("{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”", { actorName, eventName, documentTitle: document.displayTitle })}${ collection?.name ? `, ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}` : "" @@ -188,7 +188,7 @@ ${this.t("Open Document")}: ${teamUrl}${document.url} {this.t(`“{{ documentTitle }}” {{ eventName }}`, { - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, eventName, })} @@ -197,7 +197,7 @@ ${this.t("Open Document")}: ${teamUrl}${document.url} actorName, eventName, })}{" "} - {document.titleWithDefault} + {document.displayTitle} {collection?.name ? ( <> ,{" "} diff --git a/server/emails/templates/DocumentSharedEmail.tsx b/server/emails/templates/DocumentSharedEmail.tsx index b1cb1b7c5e..207ccda214 100644 --- a/server/emails/templates/DocumentSharedEmail.tsx +++ b/server/emails/templates/DocumentSharedEmail.tsx @@ -59,7 +59,7 @@ export default class DocumentSharedEmail extends BaseEmail< protected subject({ actorName, document }: Props) { return this.t(`{{ actorName }} shared “{{ documentTitle }}” with you`, { actorName, - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }); } @@ -73,7 +73,7 @@ export default class DocumentSharedEmail extends BaseEmail< protected renderAsText({ actorName, teamUrl, document }: Props): string { return ` -${this.t(`{{ actorName }} shared “{{ documentTitle }}” with you.`, { actorName, documentTitle: document.titleWithDefault })} +${this.t(`{{ actorName }} shared “{{ documentTitle }}” with you.`, { actorName, documentTitle: document.displayTitle })} ${this.t("View Document")}: ${teamUrl}${document.path} `; @@ -96,13 +96,13 @@ ${this.t("View Document")}: ${teamUrl}${document.path}
    - {document.titleWithDefault} + {document.displayTitle}

    {this.t("{{ actorName }} invited you to {{ permission }} the", { actorName, permission, })}{" "} - {document.titleWithDefault}{" "} + {document.displayTitle}{" "} {this.t("document")}.

    diff --git a/server/emails/templates/GroupCommentMentionedEmail.tsx b/server/emails/templates/GroupCommentMentionedEmail.tsx index 56957114e8..1a31c0c7c1 100644 --- a/server/emails/templates/GroupCommentMentionedEmail.tsx +++ b/server/emails/templates/GroupCommentMentionedEmail.tsx @@ -104,7 +104,7 @@ export default class GroupCommentMentionedEmail extends BaseEmail< protected subject({ document, groupName }: Props) { return this.t( "The {{ groupName }} group was mentioned in “{{ documentTitle }}”", - { groupName, documentTitle: document.titleWithDefault } + { groupName, documentTitle: document.displayTitle } ); } @@ -129,7 +129,7 @@ export default class GroupCommentMentionedEmail extends BaseEmail< }: Props): string { const action = this.t( "{{ actorName }} mentioned the “{{ groupName }}” group in a comment on “{{ documentTitle }}”", - { actorName, groupName, documentTitle: document.titleWithDefault } + { actorName, groupName, documentTitle: document.displayTitle } ); const inCollection = collection.name ? ` ${this.t("in the {{ collectionName }} collection", { collectionName: collection.name })}` @@ -163,13 +163,13 @@ ${this.t("Open Thread")}: ${teamUrl}${document.url}?commentId=${commentId}

    - {document.titleWithDefault} + {document.displayTitle}

    {this.t( "{{ actorName }} mentioned the “{{ groupName }}” group in a comment on", { actorName, groupName } )}{" "} - {document.titleWithDefault}{" "} + {document.displayTitle}{" "} {collection.name ? this.t("in the {{ collectionName }} collection", { collectionName: collection.name, diff --git a/server/emails/templates/GroupDocumentMentionedEmail.tsx b/server/emails/templates/GroupDocumentMentionedEmail.tsx index 31c29eca62..3db3b76aaa 100644 --- a/server/emails/templates/GroupDocumentMentionedEmail.tsx +++ b/server/emails/templates/GroupDocumentMentionedEmail.tsx @@ -103,7 +103,7 @@ export default class GroupDocumentMentionedEmail extends BaseEmail< `The {{ groupName }} group was mentioned in “{{ documentTitle }}”`, { groupName, - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, } ); } @@ -135,7 +135,7 @@ export default class GroupDocumentMentionedEmail extends BaseEmail< groupName, }: Props): string { return ` -${this.t(`{{ actorName }} mentioned the “{{ groupName }}” group in the document “{{ documentTitle }}”.`, { actorName, groupName, documentTitle: document.titleWithDefault })} +${this.t(`{{ actorName }} mentioned the “{{ groupName }}” group in the document “{{ documentTitle }}”.`, { actorName, groupName, documentTitle: document.displayTitle })} ${this.t("Open Document")}: ${teamUrl}${document.url} `; @@ -159,7 +159,7 @@ ${this.t("Open Document")}: ${teamUrl}${document.url} "{{ actorName }} mentioned the “{{ groupName }}” group in the document", { actorName, groupName } )}{" "} - {document.titleWithDefault}. + {document.displayTitle}.

    {body && ( <> diff --git a/server/models/Document.ts b/server/models/Document.ts index fb4005d540..43cebb06e6 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -1107,7 +1107,7 @@ class Document extends ArchivableModel< * * @returns boolean */ - get titleWithDefault(): string { + get displayTitle(): string { return this.title || "Untitled"; } diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index 2282a59ec9..db7e78ec28 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -178,7 +178,7 @@ class FileOperation extends ParanoidModel< const source = "document" in options ? { - name: options.document.titleWithDefault, + name: options.document.displayTitle, documentId: options.document.id, teamId: options.document.teamId, options: personalOwnerId ? { personalOwnerId } : null, diff --git a/server/models/helpers/OKFHelper.ts b/server/models/helpers/OKFHelper.ts index 42c961ed83..e1b4bb365f 100644 --- a/server/models/helpers/OKFHelper.ts +++ b/server/models/helpers/OKFHelper.ts @@ -63,7 +63,7 @@ export default class OKFHelper { const data: Frontmatter = { type: this.conceptType, - title: document.titleWithDefault, + title: document.displayTitle, ...(description ? { description } : {}), resource: `${origin}${document.path}`, status: this.status(document), diff --git a/server/presenters/fileOperation.ts b/server/presenters/fileOperation.ts index 0c624e0e2a..4df2331f83 100644 --- a/server/presenters/fileOperation.ts +++ b/server/presenters/fileOperation.ts @@ -9,7 +9,7 @@ export default function presentFileOperation(data: FileOperation) { format: data.format, name: data.collection?.name || - data.document?.titleWithDefault || + data.document?.displayTitle || path.basename(data.key || ""), state: data.state, error: data.error, diff --git a/server/presenters/unfurl.ts b/server/presenters/unfurl.ts index 3633fb4cca..18d14dc1c2 100644 --- a/server/presenters/unfurl.ts +++ b/server/presenters/unfurl.ts @@ -114,7 +114,7 @@ const presentDocument = ( url: url ?? `${document.url}${anchor ?? ""}`, type: UnfurlResourceType.Document, id: document.id, - title: document.titleWithDefault, + title: document.displayTitle, summary: sectionSummary || document.getSummary(), lastActivityByViewer: viewer ? presentLastActivityInfoFor(document, viewer) diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts index 3a39fa9559..04c584e13e 100644 --- a/server/queues/tasks/ExportDocumentTreeTask.ts +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -289,7 +289,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { }) { const pathMap = new Map(); - const rootFolderName = serializeFilename(document.titleWithDefault); + const rootFolderName = serializeFilename(document.displayTitle); const rootPath = `${rootFolderName}.${ExportDocumentTreeTask.extensionForFormat(format)}`; // entry for root document @@ -317,7 +317,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { Buffer.from( OKFHelper.rootIndex("Documents", [ { - title: document.titleWithDefault, + title: document.displayTitle, path: rootPath, description: document.getSummary(), }, diff --git a/server/queues/tasks/ShareSubscriptionNotificationsTask.ts b/server/queues/tasks/ShareSubscriptionNotificationsTask.ts index 674bb652b6..7a5b0ecdb7 100644 --- a/server/queues/tasks/ShareSubscriptionNotificationsTask.ts +++ b/server/queues/tasks/ShareSubscriptionNotificationsTask.ts @@ -72,7 +72,7 @@ export default class ShareSubscriptionNotificationsTask extends BaseTask { const body = await res.json(); expect(res.status).toEqual(200); expect(body.type).toEqual(UnfurlResourceType.Document); - expect(body.title).toEqual(document.titleWithDefault); + expect(body.title).toEqual(document.displayTitle); expect(body.id).toEqual(document.id); }); @@ -348,7 +348,7 @@ Install instructions here.` const body = await res.json(); expect(res.status).toEqual(200); expect(body.type).toEqual(UnfurlResourceType.Document); - expect(body.title).toEqual(document.titleWithDefault); + expect(body.title).toEqual(document.displayTitle); expect(body.id).toEqual(document.id); }); @@ -372,7 +372,7 @@ Install instructions here.` const body = await res.json(); expect(res.status).toEqual(200); expect(body.type).toEqual(UnfurlResourceType.Document); - expect(body.title).toEqual(document.titleWithDefault); + expect(body.title).toEqual(document.displayTitle); expect(body.id).toEqual(document.id); }); @@ -395,7 +395,7 @@ Install instructions here.` const body = await res.json(); expect(res.status).toEqual(200); expect(body.type).toEqual(UnfurlResourceType.Document); - expect(body.title).toEqual(document.titleWithDefault); + expect(body.title).toEqual(document.displayTitle); expect(body.id).toEqual(document.id); }); From d3e991f977b68abdebd361341b15215fdb06c7e3 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 13 Oct 2026 08:07:00 -0400 Subject: [PATCH 278/368] fix: Restore selection outline on non-text block nodes (#14058) --- shared/editor/components/Styles.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index cd607aec8c..f9d6b4e31d 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -1000,6 +1000,15 @@ th .image .image-wrapper img { caret-color: transparent; } +/* Text blocks selected with the drag handle do not get an outline. */ +.ProseMirror-selectednode:not(p, h1, h2, h3, h4, h5, h6, ul, ol, li, blockquote, hr) { + outline: 2px solid ${props.readOnly ? "transparent" : props.theme.selected}; + + @media print { + outline: none; + } +} + .ProseMirror.dragging .ProseMirror-selectednode, .ProseMirror .${EditorStyleHelper.draggingSource} { opacity: 0.25; From 95216810f823b78dd563311d85f330d2aa4a9abb Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 13 Oct 2026 08:07:12 -0400 Subject: [PATCH 279/368] fix: Link Input label to its field so prefix buttons cannot take it (#14075) --- app/components/Input.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 8c07f1ac67..579ab54dfe 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -197,6 +197,7 @@ function Input( const internalRef = React.useRef< HTMLInputElement | HTMLTextAreaElement | null >(null); + const generatedId = React.useId(); const [focused, setFocused] = React.useState(false); const [charCount, setCharCount] = React.useState(() => { if (typeof props.value === "string") { @@ -284,6 +285,7 @@ function Input( onRequestSubmit, children, ref, + id = generatedId, ...rest } = props; @@ -310,7 +312,7 @@ function Input( return ( -