From 021a286d9993d8ec95e7680179a78853e06c7d5b Mon Sep 17 00:00:00 2001 From: Hemachandar <132386067+hmacr@users.noreply.github.com> Date: Tue, 18 Mar 2025 09:07:40 +0530 Subject: [PATCH 001/268] Migrate language, theme and user-role input-select to Radix (#8711) * Migrate language, theme and user-role input-select to Radix * use theme --- app/scenes/Settings/Preferences.tsx | 68 +++++++++++++++++++++-------- app/scenes/Settings/Security.tsx | 35 +++++++++------ 2 files changed, 71 insertions(+), 32 deletions(-) diff --git a/app/scenes/Settings/Preferences.tsx b/app/scenes/Settings/Preferences.tsx index 4acfb52c66..b6240c357c 100644 --- a/app/scenes/Settings/Preferences.tsx +++ b/app/scenes/Settings/Preferences.tsx @@ -3,12 +3,12 @@ import { SettingsIcon } from "outline-icons"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; -import { languageOptions } from "@shared/i18n"; +import { languageOptions as availableLanguages } from "@shared/i18n"; import { TeamPreference, UserPreference } from "@shared/types"; import { Theme } from "~/stores/UiStore"; import Button from "~/components/Button"; import Heading from "~/components/Heading"; -import InputSelect from "~/components/InputSelect"; +import { InputSelectNew, Option } from "~/components/InputSelectNew"; import Scene from "~/components/Scene"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; @@ -26,6 +26,29 @@ function Preferences() { const team = useCurrentTeam(); const can = usePolicy(user.id); + const languageOptions: Option[] = React.useMemo( + () => + availableLanguages.map( + (lang) => + ({ + type: "item", + label: lang.label, + value: lang.value, + } satisfies Option) + ), + [] + ); + + const themeOptions: Option[] = React.useMemo( + () => + [ + { type: "item", label: t("Light"), value: Theme.Light }, + { type: "item", label: t("Dark"), value: Theme.Dark }, + { type: "item", label: t("System"), value: Theme.System }, + ] satisfies Option[], + [t] + ); + const handlePreferenceChange = (inverted = false) => async (ev: React.ChangeEvent) => { @@ -37,10 +60,21 @@ function Preferences() { toast.success(t("Preferences saved")); }; - const handleLanguageChange = async (language: string) => { - await user.save({ language }); - toast.success(t("Preferences saved")); - }; + const handleLanguageChange = React.useCallback( + async (language: string) => { + await user.save({ language }); + toast.success(t("Preferences saved")); + }, + [t, user] + ); + + const handleThemeChange = React.useCallback( + (theme) => { + ui.setTheme(theme as Theme); + toast.success(t("Preferences saved")); + }, + [t, ui] + ); const showDeleteAccount = () => { dialogs.openModal({ @@ -77,12 +111,13 @@ function Preferences() { } > - - { - ui.setTheme(theme as Theme); - toast.success(t("Preferences saved")); - }} + label={t("Appearance")} + hideLabel /> + [ + { + type: "item", + label: t("Editor"), + value: "member", + }, + { + type: "item", + label: t("Viewer"), + value: "viewer", + }, + ] satisfies Option[], + [t] + ); + React.useEffect(() => { if (!providers && !loading) { void request(); @@ -229,21 +246,13 @@ function Security() { )} border={false} > - From 307f4a1351ed519f459a215009d7b66c8b9ecdb4 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 18 Mar 2025 18:27:19 -0400 Subject: [PATCH 002/268] fix: Write lastValidatedAt when accessToken changes (#8716) --- server/models/UserAuthentication.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/server/models/UserAuthentication.ts b/server/models/UserAuthentication.ts index 6a0e706c41..8e630ad327 100644 --- a/server/models/UserAuthentication.ts +++ b/server/models/UserAuthentication.ts @@ -7,6 +7,7 @@ import { } from "sequelize"; import { BeforeCreate, + BeforeUpdate, BelongsTo, Column, DataType, @@ -69,6 +70,13 @@ class UserAuthentication extends IdModel< model.lastValidatedAt = new Date(); } + @BeforeUpdate + static updateValidated(model: UserAuthentication) { + if (model.changed("accessToken")) { + model.lastValidatedAt = new Date(); + } + } + // instance methods /** From 912b9159f0bd265cbfa79a99796833434d6dcdcd Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 18 Mar 2025 18:27:27 -0400 Subject: [PATCH 003/268] fix: Add missing users.delete event handling (#8715) --- app/components/WebsocketProvider.tsx | 4 ++++ server/queues/processors/WebsocketsProcessor.ts | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 70543b40b2..4370f3339f 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -661,6 +661,10 @@ class WebsocketProvider extends React.Component { } }); + this.socket.on("users.delete", (event: WebsocketEntityDeletedEvent) => { + users.remove(event.modelId); + }); + this.socket.on( "userMemberships.update", async (event: PartialExcept) => { diff --git a/server/queues/processors/WebsocketsProcessor.ts b/server/queues/processors/WebsocketsProcessor.ts index 75c49f37e9..4a586b3f21 100644 --- a/server/queues/processors/WebsocketsProcessor.ts +++ b/server/queues/processors/WebsocketsProcessor.ts @@ -828,6 +828,12 @@ export default class WebsocketsProcessor { .emit(event.name, { id: event.userId }); } + case "users.delete": { + return socketio + .to(`team-${event.teamId}`) + .emit(event.name, { modelId: event.userId }); + } + case "userMemberships.update": { return socketio .to(`user-${event.userId}`) From 0a9e76f600524f0df771811683edd88ccd53274e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 18 Mar 2025 21:08:49 -0400 Subject: [PATCH 004/268] fix: Mentions of current user not highlighted (#8718) --- app/components/CollectionDescription.tsx | 3 +++ app/editor/index.tsx | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/app/components/CollectionDescription.tsx b/app/components/CollectionDescription.tsx index 2b76f4dd84..be2ba2fb4f 100644 --- a/app/components/CollectionDescription.tsx +++ b/app/components/CollectionDescription.tsx @@ -11,6 +11,7 @@ import Collection from "~/models/Collection"; import Editor from "~/components/Editor"; import LoadingIndicator from "~/components/LoadingIndicator"; import { withUIExtensions } from "~/editor/extensions"; +import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import Text from "./Text"; @@ -24,6 +25,7 @@ type Props = { function CollectionDescription({ collection }: Props) { const { collections } = useStores(); const { t } = useTranslation(); + const user = useCurrentUser({ rejectOnEmpty: true }); const can = usePolicy(collection); const handleSave = React.useMemo( @@ -65,6 +67,7 @@ function CollectionDescription({ collection }: Props) { maxLength={CollectionValidation.maxDescriptionLength} canUpdate={can.update} readOnly={!can.update} + userId={user.id} editorStyle={editorStyle} embedsDisabled /> diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 0e8fe99a4c..328730bea1 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -843,7 +843,7 @@ const EditorContainer = styled(Styles)<{ ${(props) => props.userId && css` - .mention[data-id=${props.userId}] { + .mention[data-id="${props.userId}"] { color: ${props.theme.textHighlightForeground}; background: ${props.theme.textHighlight}; From ae249f720df17bedc9167932f3252dea71bd76be Mon Sep 17 00:00:00 2001 From: "Josiah \"Rebase\" Roberts" <37082009+josiah-roberts@users.noreply.github.com> Date: Wed, 19 Mar 2025 16:27:47 -0700 Subject: [PATCH 005/268] Allow middle click (#8725) --- shared/editor/marks/Link.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/shared/editor/marks/Link.tsx b/shared/editor/marks/Link.tsx index 4d3b05325f..06c6a3e016 100644 --- a/shared/editor/marks/Link.tsx +++ b/shared/editor/marks/Link.tsx @@ -179,7 +179,10 @@ export default class Link extends Mark { }, mousedown: (view: EditorView, event: MouseEvent) => { const target = (event.target as HTMLElement)?.closest("a"); - if (!(target instanceof HTMLAnchorElement) || event.button !== 0) { + if ( + !(target instanceof HTMLAnchorElement) || + (event.button !== 0 && event.button !== 1) + ) { return false; } From 0fe50c179c4617b1928eba93ff821e3e309f2b3f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 20 Mar 2025 00:00:04 -0400 Subject: [PATCH 006/268] fix: "unknown" users visible in users table (#8726) * fix: 'Unknown' users appearing in members table * snapshots * refactor --- app/components/Collaborators.tsx | 4 ++-- .../Sharing/components/Suggestions.tsx | 4 ++-- app/models/base/ParanoidModel.ts | 7 ++++++- app/scenes/Settings/Members.tsx | 2 +- app/stores/UsersStore.ts | 18 ++++++++---------- app/stores/base/Store.ts | 6 +++++- .../presenters/__snapshots__/user.test.ts.snap | 2 ++ server/presenters/user.ts | 2 ++ 8 files changed, 28 insertions(+), 17 deletions(-) diff --git a/app/components/Collaborators.tsx b/app/components/Collaborators.tsx index c420d37349..a02d480477 100644 --- a/app/components/Collaborators.tsx +++ b/app/components/Collaborators.tsx @@ -49,7 +49,7 @@ function Collaborators(props: Props) { () => orderBy( filter( - users.orderedData, + users.all, (u) => (presentIds.includes(u.id) || document.collaboratorIds.includes(u.id)) && @@ -58,7 +58,7 @@ function Collaborators(props: Props) { [(u) => presentIds.includes(u.id), "id"], ["asc", "asc"] ), - [document.collaboratorIds, users.orderedData, presentIds] + [document.collaboratorIds, users.all, presentIds] ); // load any users we don't yet have in memory diff --git a/app/components/Sharing/components/Suggestions.tsx b/app/components/Sharing/components/Suggestions.tsx index ac2cf6d0b6..88ac6c6053 100644 --- a/app/components/Sharing/components/Suggestions.tsx +++ b/app/components/Sharing/components/Suggestions.tsx @@ -96,7 +96,7 @@ export const Suggestions = observer( ? users.notInDocument(document.id, query) : collection ? users.notInCollection(collection.id, query) - : users.orderedData + : users.activeOrInvited ).filter((u) => !u.isSuspended && u.id !== user.id); if (isEmail(query)) { @@ -114,7 +114,7 @@ export const Suggestions = observer( }, [ getSuggestionForEmail, users, - users.orderedData, + users.activeOrInvited, groups, groups.orderedData, document?.id, diff --git a/app/models/base/ParanoidModel.ts b/app/models/base/ParanoidModel.ts index ffca1a250c..6930e28aa3 100644 --- a/app/models/base/ParanoidModel.ts +++ b/app/models/base/ParanoidModel.ts @@ -1,7 +1,12 @@ -import { observable } from "mobx"; +import { computed, observable } from "mobx"; import Model from "./Model"; export default abstract class ParanoidModel extends Model { @observable deletedAt: string | undefined; + + @computed + get isDeleted(): boolean { + return !!this.deletedAt; + } } diff --git a/app/scenes/Settings/Members.tsx b/app/scenes/Settings/Members.tsx index aebe49cb46..cb3deeb0d6 100644 --- a/app/scenes/Settings/Members.tsx +++ b/app/scenes/Settings/Members.tsx @@ -194,7 +194,7 @@ function getFilteredUsers({ switch (filter) { case "all": - filteredUsers = users.orderedData; + filteredUsers = users.all; break; case "suspended": filteredUsers = users.suspended; diff --git a/app/stores/UsersStore.ts b/app/stores/UsersStore.ts index f517f16678..6433e75d2e 100644 --- a/app/stores/UsersStore.ts +++ b/app/stores/UsersStore.ts @@ -27,46 +27,44 @@ export default class UsersStore extends Store { @computed get active(): User[] { - return this.orderedData.filter( - (user) => !user.isSuspended && user.lastActiveAt - ); + return this.all.filter((user) => !user.isSuspended && !user.isInvited); } @computed get suspended(): User[] { - return this.orderedData.filter((user) => user.isSuspended); + return this.all.filter((user) => user.isSuspended); } @computed get activeOrInvited(): User[] { - return this.orderedData.filter((user) => !user.isSuspended); + return this.all.filter((user) => !user.isSuspended); } @computed get invited(): User[] { - return this.orderedData.filter((user) => user.isInvited); + return this.all.filter((user) => user.isInvited); } @computed get admins(): User[] { - return this.orderedData.filter((user) => user.isAdmin); + return this.all.filter((user) => user.isAdmin && !user.isInvited); } @computed get members(): User[] { - return this.orderedData.filter( + return this.all.filter( (user) => !user.isViewer && !user.isAdmin && !user.isInvited ); } @computed get viewers(): User[] { - return this.orderedData.filter((user) => user.isViewer); + return this.all.filter((user) => user.isViewer && !user.isInvited); } @computed get all(): User[] { - return this.orderedData.filter((user) => user.lastActiveAt); + return this.orderedData.filter((user) => !user.isDeleted); } @computed diff --git a/app/stores/base/Store.ts b/app/stores/base/Store.ts index 20944c614e..498e783c41 100644 --- a/app/stores/base/Store.ts +++ b/app/stores/base/Store.ts @@ -1,6 +1,7 @@ import commandScore from "command-score"; import invariant from "invariant"; -import { deburr, type ObjectIterateeCustom } from "lodash"; +import type { ObjectIterateeCustom } from "lodash"; +import deburr from "lodash/deburr"; import filter from "lodash/filter"; import find from "lodash/find"; import flatten from "lodash/flatten"; @@ -102,6 +103,9 @@ export default abstract class Store { return this.orderedData .filter((item: T & Searchable) => { + if ("deletedAt" in item && item.deletedAt) { + return false; + } if ("searchContent" in item) { const seachables = typeof item.searchContent === "string" diff --git a/server/presenters/__snapshots__/user.test.ts.snap b/server/presenters/__snapshots__/user.test.ts.snap index c1766ed444..3a165f8ea7 100644 --- a/server/presenters/__snapshots__/user.test.ts.snap +++ b/server/presenters/__snapshots__/user.test.ts.snap @@ -5,6 +5,7 @@ exports[`presents a user 1`] = ` "avatarUrl": null, "color": "#FF5C80", "createdAt": undefined, + "deletedAt": undefined, "id": "123", "isSuspended": false, "lastActiveAt": undefined, @@ -20,6 +21,7 @@ exports[`presents a user without slack data 1`] = ` "avatarUrl": null, "color": "#FF5C80", "createdAt": undefined, + "deletedAt": undefined, "id": "123", "isSuspended": false, "lastActiveAt": undefined, diff --git a/server/presenters/user.ts b/server/presenters/user.ts index f9b73d55b3..2bdca9fc47 100644 --- a/server/presenters/user.ts +++ b/server/presenters/user.ts @@ -13,6 +13,7 @@ type UserPresentation = { avatarUrl: string | null | undefined; createdAt: Date; updatedAt: Date; + deletedAt: Date | null; lastActiveAt: Date | null; color: string; role: UserRole; @@ -37,6 +38,7 @@ export default function presentUser( isSuspended: user.isSuspended, createdAt: user.createdAt, updatedAt: user.updatedAt, + deletedAt: user.deletedAt, lastActiveAt: user.lastActiveAt, timezone: user.timezone, }; From 08f91aa60c7e3630d3cfec9ebf06e3cc85ad8c4b Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 20 Mar 2025 09:46:53 -0400 Subject: [PATCH 007/268] fix: Error rendering read only editor with paragraph without text content (#8730) --- app/components/Editor.tsx | 2 +- app/models/Document.ts | 2 +- shared/types.ts | 2 +- shared/utils/ProsemirrorHelper.test.ts | 18 ++++++++++++++++++ shared/utils/ProsemirrorHelper.ts | 19 ++++++++++++------- 5 files changed, 33 insertions(+), 10 deletions(-) diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index 19f6a7c4f0..e41ef39a51 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -205,7 +205,7 @@ function Editor(props: Props, ref: React.RefObject | null) {
{paragraphs.map((paragraph, index) => (

- {paragraph.content.map((content) => content.text)} + {paragraph.content?.map((content) => content.text)}

))}
diff --git a/app/models/Document.ts b/app/models/Document.ts index 57a530a93a..78be2fe01a 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -600,7 +600,7 @@ export default class Document extends ArchivableModel implements Searchable { */ getSummary = (blocks = 4) => ({ ...this.data, - content: this.data.content.slice(0, blocks), + content: this.data.content?.slice(0, blocks), }); @computed diff --git a/shared/types.ts b/shared/types.ts index dc45116750..3a6891db03 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -430,7 +430,7 @@ export type JSONObject = { [x: string]: JSONValue }; export type ProsemirrorData = { type: string; - content: ProsemirrorData[]; + content?: ProsemirrorData[]; text?: string; attrs?: JSONObject; marks?: { diff --git a/shared/utils/ProsemirrorHelper.test.ts b/shared/utils/ProsemirrorHelper.test.ts index 3974785c01..d557ad2b69 100644 --- a/shared/utils/ProsemirrorHelper.test.ts +++ b/shared/utils/ProsemirrorHelper.test.ts @@ -214,5 +214,23 @@ describe("ProsemirrorHelper", () => { const paragraphs = ProsemirrorHelper.getPlainParagraphs(data); expect(paragraphs).toBeUndefined(); }); + + it("should handle paragraph without content", async () => { + const data = { + type: "doc", + content: [ + { + type: "paragraph", + }, + ], + } as ProsemirrorData; + + const paragraphs = ProsemirrorHelper.getPlainParagraphs(data); + expect(paragraphs).toEqual([ + { + type: "paragraph", + }, + ]); + }); }); }); diff --git a/shared/utils/ProsemirrorHelper.ts b/shared/utils/ProsemirrorHelper.ts index 9b77644135..c20eacfeae 100644 --- a/shared/utils/ProsemirrorHelper.ts +++ b/shared/utils/ProsemirrorHelper.ts @@ -70,7 +70,7 @@ export class ProsemirrorHelper { return false; } - if (data.content.length === 1) { + if (data.content?.length === 1) { const node = data.content[0]; return ( node.type === "paragraph" && @@ -80,7 +80,7 @@ export class ProsemirrorHelper { ); } - return data.content.length === 0; + return !data.content || data.content.length === 0; } /** @@ -355,14 +355,19 @@ export class ProsemirrorHelper { * @returns An array of paragraph nodes or undefined */ static getPlainParagraphs(data: ProsemirrorData) { - const paragraphs = []; + const paragraphs: ProsemirrorData[] = []; + if (!data.content) { + return paragraphs; + } + for (const node of data.content) { if ( node.type === "paragraph" && - !node.content.some( - (item) => - item.type !== "text" || (item.marks && item.marks.length > 0) - ) + (!node.content || + !node.content.some( + (item) => + item.type !== "text" || (item.marks && item.marks.length > 0) + )) ) { paragraphs.push(node); } else { From f369c2f8bfe8e1c592837c49f7c17cc2ca16c2ca Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 20 Mar 2025 23:49:47 -0400 Subject: [PATCH 008/268] Refactor logic for validating authentication tokens (#8727) * Remove use of Promise.any * Restore retry on all invalid --- server/queues/tasks/ValidateSSOAccessTask.ts | 38 ++++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/server/queues/tasks/ValidateSSOAccessTask.ts b/server/queues/tasks/ValidateSSOAccessTask.ts index 4a38523ab8..002ddd600e 100644 --- a/server/queues/tasks/ValidateSSOAccessTask.ts +++ b/server/queues/tasks/ValidateSSOAccessTask.ts @@ -19,26 +19,26 @@ export default class ValidateSSOAccessTask extends BaseTask { return; } - try { - // Check the validity of all the user's associated authentications. - // @ts-expect-error TODO: Need to setup nested tsconfig with ES2021 - const valid = await Promise.any( - userAuthentications.map(async (authentication) => - authentication.validateAccess({ transaction }) - ) - ); + // Check the validity of the user's authentications. + let error; + const validity = await Promise.all( + userAuthentications.map(async (authentication) => { + try { + return await authentication.validateAccess({ transaction }); + } catch (err) { + error = err; + return false; + } + }) + ); - // If any are valid then we're done here. - if (valid) { - return; - } - } catch (err) { - // Promise.any will throw an AggregateError if all validateAccess calls throw, this would - // only be the case if all receive an unexpected error. We want to throw the first error - // as a descriptive error message. - if ("errors" in err && err.errors.length > 0) { - throw err.errors[0]; - } + if (validity.some((isValid) => isValid)) { + return; + } + + // If an unexpected error occurred, throw it to trigger a retry. + if (error) { + throw error; } // If all are invalid then we need to revoke the users Outline sessions. From 42cfac97aa25083884d676587ec1eb5eee24ded2 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Mar 2025 07:57:26 -0400 Subject: [PATCH 009/268] fix: Add prevention of auto-following unsubscribe links in emails (#8735) --- server/routes/api/notifications/notifications.ts | 13 ++++++++++++- server/routes/api/notifications/schema.ts | 1 + server/routes/api/subscriptions/schema.ts | 1 + server/routes/api/subscriptions/subscriptions.ts | 8 +++++++- 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/server/routes/api/notifications/notifications.ts b/server/routes/api/notifications/notifications.ts index 587fe446cd..9a1d5c5785 100644 --- a/server/routes/api/notifications/notifications.ts +++ b/server/routes/api/notifications/notifications.ts @@ -57,8 +57,19 @@ router.get( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), transaction(), - handleUnsubscribe + async (ctx: APIContext) => { + const { follow } = ctx.input.query; + + // The link in the email does not include the follow query param, this + // is to help prevent anti-virus, and email clients from pre-fetching the link + if (!follow) { + return ctx.redirectOnClient(ctx.request.href + "&follow=true"); + } + + return handleUnsubscribe(ctx); + } ); + router.post( "notifications.unsubscribe", validate(T.NotificationsUnsubscribeSchema), diff --git a/server/routes/api/notifications/schema.ts b/server/routes/api/notifications/schema.ts index 2e4c66f48c..ecc8dfd352 100644 --- a/server/routes/api/notifications/schema.ts +++ b/server/routes/api/notifications/schema.ts @@ -30,6 +30,7 @@ export const NotificationsUnsubscribeSchema = BaseSchema.extend({ eventType: z.nativeEnum(NotificationEventType).optional(), }), query: z.object({ + follow: z.string().default(""), userId: z.string().uuid().optional(), token: z.string().optional(), eventType: z.nativeEnum(NotificationEventType).optional(), diff --git a/server/routes/api/subscriptions/schema.ts b/server/routes/api/subscriptions/schema.ts index f76cb3d941..e4624ad1eb 100644 --- a/server/routes/api/subscriptions/schema.ts +++ b/server/routes/api/subscriptions/schema.ts @@ -47,6 +47,7 @@ export type SubscriptionsDeleteReq = z.infer; export const SubscriptionsDeleteTokenSchema = BaseSchema.extend({ query: z.object({ + follow: z.string().default(""), userId: z.string().uuid(), documentId: z.string().uuid(), token: z.string(), diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index caa96b5703..350098a993 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -150,7 +150,13 @@ router.get( transaction(), async (ctx: APIContext) => { const { transaction } = ctx.state; - const { userId, documentId, token } = ctx.input.query; + const { follow, userId, documentId, token } = ctx.input.query; + + // The link in the email does not include the follow query param, this + // is to help prevent anti-virus, and email clients from pre-fetching the link + if (!follow) { + return ctx.redirectOnClient(ctx.request.href + "&follow=true"); + } const unsubscribeToken = SubscriptionHelper.unsubscribeToken( userId, From 556503448641383e64f5b7064ee97cc762b0efc0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Mar 2025 08:38:28 -0400 Subject: [PATCH 010/268] Revert "Double test timeout (#8696)" (#8738) This reverts commit 7c41c1360b2c17fdd6308d98f5d4aed44aa6b0a5. --- .jestconfig.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.jestconfig.json b/.jestconfig.json index c63342864f..c45e43e75e 100644 --- a/.jestconfig.json +++ b/.jestconfig.json @@ -14,8 +14,7 @@ "setupFilesAfterEnv": ["/server/test/setup.ts"], "globalSetup": "/server/test/globalSetup.js", "globalTeardown": "/server/test/globalTeardown.js", - "testEnvironment": "node", - "testTimeout": 10000 + "testEnvironment": "node" }, { "displayName": "app", From dd053c4152deafb0245f08f22e023901b8097c4a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 11:22:01 -0400 Subject: [PATCH 011/268] fix: Allow dash,emdash,underscore in mention search (#8747) * fix: Allow dash,emdash,underscore in mention search * fix: Highlight color on secondary accent menu items --- app/editor/components/SuggestionsMenuItem.tsx | 9 +++++++-- app/editor/extensions/Suggestion.ts | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/editor/components/SuggestionsMenuItem.tsx b/app/editor/components/SuggestionsMenuItem.tsx index 0660485f54..199548ca3a 100644 --- a/app/editor/components/SuggestionsMenuItem.tsx +++ b/app/editor/components/SuggestionsMenuItem.tsx @@ -1,3 +1,4 @@ +import { transparentize } from "polished"; import * as React from "react"; import scrollIntoView from "scroll-into-view-if-needed"; import styled from "styled-components"; @@ -68,12 +69,16 @@ function SuggestionsMenuItem({ const Subtitle = styled.span<{ $active?: boolean }>` color: ${(props) => - props.$active ? props.theme.white50 : props.theme.textTertiary}; + props.$active + ? transparentize(0.35, props.theme.accentText) + : props.theme.textTertiary}; `; const Shortcut = styled.span<{ $active?: boolean }>` color: ${(props) => - props.$active ? props.theme.white50 : props.theme.textTertiary}; + props.$active + ? transparentize(0.35, props.theme.accentText) + : props.theme.textTertiary}; flex-grow: 1; text-align: right; `; diff --git a/app/editor/extensions/Suggestion.ts b/app/editor/extensions/Suggestion.ts index 33dee58d3c..b77f31ab18 100644 --- a/app/editor/extensions/Suggestion.ts +++ b/app/editor/extensions/Suggestion.ts @@ -23,7 +23,7 @@ export default class Suggestion extends Extension { this.options.trigger )}(${`[\\p{L}\/\\p{M}\\d${ this.options.allowSpaces ? "\\s{1}" : "" - }\\.]+`})${this.options.requireSearchTerm ? "" : "?"}$`, + }\\.\\-–_]+`})${this.options.requireSearchTerm ? "" : "?"}$`, "u" ); } From ec9f45f310fede221ca0171789f681fc07ab0322 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 11:22:09 -0400 Subject: [PATCH 012/268] fix: Allow team admin to manage permissions on any document they have access to (#8746) --- server/policies/document.test.ts | 41 +++++++++++++++++++++++++++++++- server/policies/document.ts | 3 +++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/server/policies/document.test.ts b/server/policies/document.test.ts index 3ac5c9a1ce..d79f531fe4 100644 --- a/server/policies/document.test.ts +++ b/server/policies/document.test.ts @@ -10,6 +10,7 @@ import { buildDocument, buildDraftDocument, buildCollection, + buildAdmin, } from "@server/test/factories"; import { serialize } from "./index"; @@ -355,7 +356,10 @@ describe("read document", () => { }); describe("read_write document", () => { - for (const role of Object.values(UserRole)) { + const nonAdminRoles = Object.values(UserRole).filter( + (role) => role !== UserRole.Admin + ); + for (const role of nonAdminRoles) { it(`should allow write permissions for ${role}`, async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id, role }); @@ -391,6 +395,41 @@ describe("read_write document", () => { expect(abilities.move).toEqual(false); }); } + + it(`should allow write permissions for admin`, async () => { + const team = await buildTeam(); + const user = await buildAdmin({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + permission: null, + }); + const doc = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + }); + await UserMembership.create({ + userId: user.id, + documentId: doc.id, + permission: DocumentPermission.ReadWrite, + createdById: user.id, + }); + + // reload to get membership + const document = await Document.findByPk(doc.id, { userId: user.id }); + const abilities = serialize(user, document); + expect(abilities.read).toBeTruthy(); + expect(abilities.download).toBeTruthy(); + expect(abilities.update).toBeTruthy(); + expect(abilities.delete).toBeTruthy(); + expect(abilities.subscribe).toBeTruthy(); + expect(abilities.unsubscribe).toBeTruthy(); + expect(abilities.comment).toBeTruthy(); + expect(abilities.createChildDocument).toBeTruthy(); + expect(abilities.manageUsers).toBeTruthy(); + expect(abilities.archive).toBeTruthy(); + expect(abilities.share).toEqual(false); + expect(abilities.move).toEqual(false); + }); }); describe("manage document", () => { diff --git a/server/policies/document.ts b/server/policies/document.ts index 96972e72d7..f76e62d5ab 100644 --- a/server/policies/document.ts +++ b/server/policies/document.ts @@ -125,6 +125,7 @@ allow(User, "manageUsers", Document, (actor, document) => can(actor, "update", document), or( includesMembership(document, [DocumentPermission.Admin]), + and(isTeamAdmin(actor, document), can(actor, "read", document)), can(actor, "updateDocument", document?.collection), !!document?.isDraft && actor.id === document?.createdById ) @@ -136,6 +137,7 @@ allow(User, "duplicate", Document, (actor, document) => can(actor, "update", document), or( includesMembership(document, [DocumentPermission.Admin]), + and(isTeamAdmin(actor, document), can(actor, "read", document)), can(actor, "updateDocument", document?.collection), !!document?.isDraft && actor.id === document?.createdById, and( @@ -233,6 +235,7 @@ allow(User, "archive", Document, (actor, document) => can(actor, "update", document), or( includesMembership(document, [DocumentPermission.Admin]), + and(isTeamAdmin(actor, document), can(actor, "read", document)), can(actor, "updateDocument", document?.collection) ) ) From a48f6c7a8557b550c9f7ecd3077307c2c2d25c27 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 11:22:20 -0400 Subject: [PATCH 013/268] fix: Unsubscribe link for collection subscriptions (#8734) * fix: Cannot unsubscribe from collection subscriptions via email token * tests * Separate redirect for pass through * Delete both subscriptions * Test draft documents --- app/hooks/useQueryNotices.ts | 8 + .../models/helpers/SubscriptionHelper.test.ts | 20 ++ server/models/helpers/SubscriptionHelper.ts | 17 +- .../api/subscriptions/subscriptions.test.ts | 313 ++++++++++++------ .../routes/api/subscriptions/subscriptions.ts | 52 ++- shared/i18n/locales/en_US/translation.json | 1 + shared/types.ts | 1 + 7 files changed, 290 insertions(+), 122 deletions(-) create mode 100644 server/models/helpers/SubscriptionHelper.test.ts diff --git a/app/hooks/useQueryNotices.ts b/app/hooks/useQueryNotices.ts index 145fc00ffe..a9227880a4 100644 --- a/app/hooks/useQueryNotices.ts +++ b/app/hooks/useQueryNotices.ts @@ -24,6 +24,14 @@ export default function useQueryNotices() { ); break; } + case QueryNotices.UnsubscribeCollection: { + toast.success( + t("Unsubscribed from collection", { + type: "success", + }) + ); + break; + } default: } }, [t, notice]); diff --git a/server/models/helpers/SubscriptionHelper.test.ts b/server/models/helpers/SubscriptionHelper.test.ts new file mode 100644 index 0000000000..a91f18f4d4 --- /dev/null +++ b/server/models/helpers/SubscriptionHelper.test.ts @@ -0,0 +1,20 @@ +import { v4 as uuidv4 } from "uuid"; +import env from "@server/env"; +import SubscriptionHelper from "./SubscriptionHelper"; + +describe("SubscriptionHelper", () => { + describe("unsubscribeUrl", () => { + it("should return a valid unsubscribe URL", () => { + const userId = uuidv4(); + const documentId = uuidv4(); + + const unsubscribeUrl = SubscriptionHelper.unsubscribeUrl( + userId, + documentId + ); + expect(unsubscribeUrl).toContain(`${env.URL}/api/subscriptions.delete`); + expect(unsubscribeUrl).toContain(`userId=${userId}`); + expect(unsubscribeUrl).toContain(`documentId=${documentId}`); + }); + }); +}); diff --git a/server/models/helpers/SubscriptionHelper.ts b/server/models/helpers/SubscriptionHelper.ts index 4bcd5ae63b..e099eded31 100644 --- a/server/models/helpers/SubscriptionHelper.ts +++ b/server/models/helpers/SubscriptionHelper.ts @@ -1,4 +1,5 @@ import crypto from "crypto"; +import queryString from "query-string"; import env from "@server/env"; /** @@ -15,12 +16,22 @@ export default class SubscriptionHelper { * @returns The unsubscribe URL */ public static unsubscribeUrl(userId: string, documentId: string) { - return `${env.URL}/api/subscriptions.delete?token=${this.unsubscribeToken( + const token = this.unsubscribeToken(userId, documentId); + + return `${env.URL}/api/subscriptions.delete?${queryString.stringify({ + token, userId, - documentId - )}&userId=${userId}&documentId=${documentId}`; + documentId, + })}`; } + /** + * Generate a token for unsubscribing a user from a document or collection. + * + * @param userId The user ID to unsubscribe + * @param documentId The document ID to unsubscribe from + * @returns The unsubscribe token + */ public static unsubscribeToken(userId: string, documentId: string) { const hash = crypto.createHash("sha256"); hash.update(`${userId}-${env.SECRET_KEY}-${documentId}`); diff --git a/server/routes/api/subscriptions/subscriptions.test.ts b/server/routes/api/subscriptions/subscriptions.test.ts index 1cdae3d154..96d2034323 100644 --- a/server/routes/api/subscriptions/subscriptions.test.ts +++ b/server/routes/api/subscriptions/subscriptions.test.ts @@ -1,10 +1,13 @@ -import { SubscriptionType } from "@shared/types"; -import { Event } from "@server/models"; +import queryString from "query-string"; +import { QueryNotices, SubscriptionType } from "@shared/types"; +import { Event, Subscription } from "@server/models"; +import SubscriptionHelper from "@server/models/helpers/SubscriptionHelper"; import { buildUser, buildSubscription, buildDocument, buildCollection, + buildDraftDocument, } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; @@ -704,126 +707,220 @@ describe("#subscriptions.list", () => { }); describe("#subscriptions.delete", () => { - it("should delete user's subscription", async () => { - const user = await buildUser(); - - const document = await buildDocument({ - userId: user.id, - teamId: user.teamId, - }); - - const subscription = await buildSubscription({ - userId: user.id, - documentId: document.id, - }); - - const res = await server.post("/api/subscriptions.delete", { - body: { + describe("GET", () => { + it("should delete user's document subscription", async () => { + const user = await buildUser(); + const document = await buildDraftDocument({ userId: user.id, - id: subscription.id, - token: user.getJwtToken(), - }, + teamId: user.teamId, + }); + const subscription = await buildSubscription({ + userId: user.id, + documentId: document.id, + }); + + const res = await server.get( + `/api/subscriptions.delete?${queryString.stringify({ + userId: user.id, + documentId: document.id, + follow: true, + token: SubscriptionHelper.unsubscribeToken(user.id, document.id), + })}`, + { + redirect: "manual", + } + ); + + expect(res.status).toEqual(302); + expect(res.headers.get("location")).toContain( + `/home?notice=${QueryNotices.UnsubscribeDocument}` + ); + expect(await Subscription.findByPk(subscription.id)).toBeNull(); }); - const body = await res.json(); + it("should delete user's collection subscription", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const subscription = await buildSubscription({ + userId: user.id, + collectionId: document.collectionId, + }); - expect(res.status).toEqual(200); - expect(body.ok).toEqual(true); - expect(body.success).toEqual(true); + const res = await server.get( + `/api/subscriptions.delete?${queryString.stringify({ + userId: user.id, + documentId: document.id, + follow: true, + token: SubscriptionHelper.unsubscribeToken(user.id, document.id), + })}`, + { + redirect: "manual", + } + ); + + expect(res.status).toEqual(302); + expect(res.headers.get("location")).toContain( + `/home?notice=${QueryNotices.UnsubscribeCollection}` + ); + expect(await Subscription.findByPk(subscription.id)).toBeNull(); + }); + + it("should not fail if subscription is already deleted", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const subscription = await buildSubscription({ + userId: user.id, + documentId: document.id, + }); + + await subscription.destroy(); + + const res = await server.get( + `/api/subscriptions.delete?${queryString.stringify({ + userId: user.id, + documentId: document.id, + follow: true, + token: SubscriptionHelper.unsubscribeToken(user.id, document.id), + })}`, + { + redirect: "manual", + } + ); + + expect(res.status).toEqual(302); + expect(res.headers.get("location")).toContain(`/home`); + expect(await Subscription.findByPk(subscription.id)).toBeNull(); + }); }); - it("should emit event", async () => { - const user = await buildUser(); - - const document = await buildDocument({ - userId: user.id, - teamId: user.teamId, - }); - - const subscription = await buildSubscription({ - userId: user.id, - documentId: document.id, - }); - - const res = await server.post("/api/subscriptions.delete", { - body: { + describe("POST", () => { + it("should delete user's document subscription", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const subscription = await buildSubscription({ userId: user.id, - id: subscription.id, - token: user.getJwtToken(), - }, - }); - - const events = await Event.findAll({ - where: { - teamId: document.teamId, - }, - }); - - expect(events.length).toEqual(1); - expect(events[0].name).toEqual("subscriptions.delete"); - expect(events[0].modelId).toEqual(subscription.id); - expect(events[0].actorId).toEqual(user.id); - expect(events[0].documentId).toEqual(document.id); - - const body = await res.json(); - - expect(res.status).toEqual(200); - expect(body.ok).toEqual(true); - expect(body.success).toEqual(true); - }); - - it("users should not be able to delete other's subscriptions on document", async () => { - const subscriber0 = await buildUser(); - // `subscriber1` belongs to `subscriber0`'s team. - const subscriber1 = await buildUser({ teamId: subscriber0.teamId }); - - // `subscriber0` created a document. - const document = await buildDocument({ - userId: subscriber0.id, - teamId: subscriber0.teamId, - }); - - // `subscriber0` wants to be notified about - // changes on this document. - await server.post("/api/subscriptions.create", { - body: { - token: subscriber0.getJwtToken(), documentId: document.id, - event: "documents.update", - }, + }); + + const res = await server.post("/api/subscriptions.delete", { + body: { + id: subscription.id, + token: user.getJwtToken(), + }, + }); + + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.ok).toEqual(true); + expect(body.success).toEqual(true); + + const events = await Event.findAll({ + where: { + teamId: document.teamId, + }, + }); + + expect(events.length).toEqual(1); + expect(events[0].name).toEqual("subscriptions.delete"); + expect(events[0].modelId).toEqual(subscription.id); + expect(events[0].actorId).toEqual(user.id); + expect(events[0].documentId).toEqual(document.id); }); - // `subscriber1` wants to be notified about - // changes on this document. - const resp = await server.post("/api/subscriptions.create", { - body: { - token: subscriber1.getJwtToken(), - documentId: document.id, - event: "documents.update", - }, + it("should delete user's collection subscription", async () => { + const user = await buildUser(); + const collection = await buildCollection({ userId: user.id }); + const subscription = await buildSubscription({ + userId: user.id, + collectionId: collection.id, + }); + + const res = await server.post("/api/subscriptions.delete", { + body: { + id: subscription.id, + token: user.getJwtToken(), + }, + }); + + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.ok).toEqual(true); + expect(body.success).toEqual(true); + + const events = await Event.findAll({ + where: { + teamId: user.teamId, + }, + }); + + expect(events.length).toEqual(1); + expect(events[0].name).toEqual("subscriptions.delete"); + expect(events[0].modelId).toEqual(subscription.id); + expect(events[0].actorId).toEqual(user.id); + expect(events[0].collectionId).toEqual(collection.id); }); - const subscription1 = await resp.json(); - const subscription1Id = subscription1.data.id; + it("users should not be able to delete other's subscriptions on document", async () => { + const subscriber0 = await buildUser(); + // `subscriber1` belongs to `subscriber0`'s team. + const subscriber1 = await buildUser({ teamId: subscriber0.teamId }); - // `subscriber0` wants to change `subscriber1`'s - // subscription for this document. - const res = await server.post("/api/subscriptions.delete", { - body: { - // `subscriber0` + // `subscriber0` created a document. + const document = await buildDocument({ userId: subscriber0.id, - // subscription id of `subscriber1` - id: subscription1Id, - token: subscriber0.getJwtToken(), - }, + teamId: subscriber0.teamId, + }); + + // `subscriber0` wants to be notified about + // changes on this document. + await server.post("/api/subscriptions.create", { + body: { + token: subscriber0.getJwtToken(), + documentId: document.id, + event: "documents.update", + }, + }); + + // `subscriber1` wants to be notified about + // changes on this document. + const resp = await server.post("/api/subscriptions.create", { + body: { + token: subscriber1.getJwtToken(), + documentId: document.id, + event: "documents.update", + }, + }); + + const subscription1 = await resp.json(); + const subscription1Id = subscription1.data.id; + + // `subscriber0` wants to change `subscriber1`'s + // subscription for this document. + const res = await server.post("/api/subscriptions.delete", { + body: { + id: subscription1Id, + token: subscriber0.getJwtToken(), + }, + }); + + const body = await res.json(); + + // `subscriber0` should be unauthorized. + expect(res.status).toEqual(403); + expect(body.ok).toEqual(false); + expect(body.error).toEqual("authorization_error"); + expect(body.message).toEqual("Authorization error"); }); - - const body = await res.json(); - - // `subscriber0` should be unauthorized. - expect(res.status).toEqual(403); - expect(body.ok).toEqual(false); - expect(body.error).toEqual("authorization_error"); - expect(body.message).toEqual("Authorization error"); }); }); diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index 350098a993..78d1017fc8 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -168,14 +168,21 @@ router.get( return; } - const [subscription, user] = await Promise.all([ + const [documentSubscription, document, user] = await Promise.all([ Subscription.findOne({ where: { userId, documentId, }, lock: Transaction.LOCK.UPDATE, - rejectOnEmpty: true, + transaction, + }), + Document.unscoped().findOne({ + attributes: ["collectionId"], + where: { + id: documentId, + }, + paranoid: false, transaction, }), User.scope("withTeam").findByPk(userId, { @@ -184,18 +191,41 @@ router.get( }), ]); - authorize(user, "delete", subscription); + const context = createContext({ + user, + ip: ctx.request.ip, + transaction, + }); - await subscription.destroyWithCtx( - createContext({ - user, - ip: ctx.request.ip, - transaction, - }) - ); + const collectionSubscription = document?.collectionId + ? await Subscription.findOne({ + where: { + userId, + collectionId: document.collectionId, + }, + lock: Transaction.LOCK.UPDATE, + transaction, + }) + : undefined; + + if (collectionSubscription) { + authorize(user, "delete", collectionSubscription); + await collectionSubscription.destroyWithCtx(context); + } + + if (documentSubscription) { + authorize(user, "delete", documentSubscription); + await documentSubscription.destroyWithCtx(context); + } ctx.redirect( - `${user.team.url}/home?notice=${QueryNotices.UnsubscribeDocument}` + `${user.team.url}/home?notice=${ + collectionSubscription + ? QueryNotices.UnsubscribeCollection + : documentSubscription + ? QueryNotices.UnsubscribeDocument + : "" + }` ); } ); diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index c2b9bf20ba..2c234835fa 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -507,6 +507,7 @@ "None": "None", "Could not import file": "Could not import file", "Unsubscribed from document": "Unsubscribed from document", + "Unsubscribed from collection": "Unsubscribed from collection", "Account": "Account", "API Keys": "API Keys", "Details": "Details", diff --git a/shared/types.ts b/shared/types.ts index 3a6891db03..6fb60fadb2 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -415,6 +415,7 @@ export type UnfurlResponse = { export enum QueryNotices { UnsubscribeDocument = "unsubscribe-document", + UnsubscribeCollection = "unsubscribe-collection", } export type JSONValue = From 18bbe6ecf6eec62b1a13a05777992bb67ce2d3bf Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 13:02:09 -0400 Subject: [PATCH 014/268] fix: Direct link to heading lost when pasting (#8749) --- app/editor/extensions/PasteHandler.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index 6982f74c93..9a7d7bcafa 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -122,6 +122,8 @@ export default class PasteHandler extends Extension { } // Is the link a link to a document? If so, we can grab the title and insert it. + const containsHash = text.includes("#"); + if (isDocumentUrl(text)) { const slug = parseDocumentSlug(text); @@ -133,7 +135,7 @@ export default class PasteHandler extends Extension { return; } if (document) { - if (state.schema.nodes.mention) { + if (state.schema.nodes.mention && !containsHash) { view.dispatch( view.state.tr.replaceWith( state.selection.from, @@ -178,7 +180,7 @@ export default class PasteHandler extends Extension { return; } if (collection) { - if (state.schema.nodes.mention) { + if (state.schema.nodes.mention && !containsHash) { view.dispatch( view.state.tr.replaceWith( state.selection.from, From 6fde025ce47121bca4304022e35808b03514cfd0 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 16:06:54 -0400 Subject: [PATCH 015/268] Revert "Send editor version down websocket and force reload (#8582)" (#8750) This reverts commit 13f45e1a1c95a43883acec0c994bf0ec4cc8c32d. --- app/components/WebsocketProvider.tsx | 18 +----------------- server/services/websockets.ts | 3 +-- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 4370f3339f..03d007e6bb 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -1,14 +1,11 @@ import invariant from "invariant"; import find from "lodash/find"; -import isObject from "lodash/isObject"; import { action, observable } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { withTranslation, WithTranslation } from "react-i18next"; -import semver from "semver"; import { io, Socket } from "socket.io-client"; import { toast } from "sonner"; -import EDITOR_VERSION from "@shared/editor/version"; import { FileOperationState, FileOperationType } from "@shared/types"; import RootStore from "~/stores/RootStore"; import Collection from "~/models/Collection"; @@ -117,23 +114,10 @@ class WebsocketProvider extends React.Component { } }); - this.socket.on("authenticated", (data) => { + this.socket.on("authenticated", () => { if (this.socket) { this.socket.authenticated = true; } - if (isObject(data) && "editorVersion" in data) { - const parsedClientVersion = semver.parse(EDITOR_VERSION); - const parsedCurrentVersion = semver.parse(String(data.editorVersion)); - - if ( - parsedClientVersion && - parsedCurrentVersion && - (parsedClientVersion.major < parsedCurrentVersion.major || - parsedClientVersion.minor < parsedCurrentVersion.minor) - ) { - window.location.reload(); - } - } }); this.socket.on("unauthorized", (err: Error) => { diff --git a/server/services/websockets.ts b/server/services/websockets.ts index c88195c630..f17c132fb3 100644 --- a/server/services/websockets.ts +++ b/server/services/websockets.ts @@ -4,7 +4,6 @@ import cookie from "cookie"; import Koa from "koa"; import IO from "socket.io"; import { createAdapter } from "socket.io-redis"; -import EDITOR_VERSION from "@shared/editor/version"; import { AuthenticationError } from "@server/errors"; import Logger from "@server/logging/Logger"; import Metrics from "@server/logging/Metrics"; @@ -117,7 +116,7 @@ export default function init( await authenticate(socket); Logger.debug("websockets", `Authenticated socket ${socket.id}`); - socket.emit("authenticated", { editorVersion: EDITOR_VERSION }); + socket.emit("authenticated", true); void authenticated(io, socket); } catch (err) { Logger.debug("websockets", `Authentication error socket ${socket.id}`, { From 0ec64405067d7a8f02f75f2a300f04de0c890705 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 17:35:45 -0400 Subject: [PATCH 016/268] Prevent outdated clients from connecting to collaboration server (#8751) * Move editor version check to collaboration server connection * connected -> onConnect * docs * Remove hardcoded event codes --- app/components/ConnectionStatus.tsx | 14 +++++-- .../Document/components/MultiplayerEditor.tsx | 17 +++++++- server/collaboration/CloseEvents.ts | 4 -- .../collaboration/ConnectionLimitExtension.ts | 16 +++++--- .../collaboration/EditorVersionExtension.ts | 40 +++++++++++++++++++ server/routes/api/middlewares/editor.ts | 11 ++--- server/services/collaboration.ts | 2 + shared/collaboration/CloseEvents.ts | 24 +++++++++++ 8 files changed, 108 insertions(+), 20 deletions(-) delete mode 100644 server/collaboration/CloseEvents.ts create mode 100644 server/collaboration/EditorVersionExtension.ts create mode 100644 shared/collaboration/CloseEvents.ts diff --git a/app/components/ConnectionStatus.tsx b/app/components/ConnectionStatus.tsx index 6d79959633..1ec4e5eb44 100644 --- a/app/components/ConnectionStatus.tsx +++ b/app/components/ConnectionStatus.tsx @@ -4,6 +4,12 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import { + AuthenticationFailed, + AuthorizationFailed, + DocumentTooLarge, + TooManyConnections, +} from "@shared/collaboration/CloseEvents"; import Fade from "~/components/Fade"; import NudeButton from "~/components/NudeButton"; import Tooltip from "~/components/Tooltip"; @@ -14,21 +20,21 @@ function ConnectionStatus() { const { t } = useTranslation(); const codeToMessage = { - 1009: { + [DocumentTooLarge.code]: { title: t("Document is too large"), body: t( "This document has reached the maximum size and can no longer be edited" ), }, - 4401: { + [AuthenticationFailed.code]: { title: t("Authentication failed"), body: t("Please try logging out and back in again"), }, - 4403: { + [AuthorizationFailed.code]: { title: t("Authorization failed"), body: t("You may have lost access to this document, try reloading"), }, - 4503: { + [TooManyConnections.code]: { title: t("Too many users connected to document"), body: t("Your edits will sync once other users leave the document"), }, diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index 805ad055a2..bf405cf418 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -6,6 +6,12 @@ import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import { IndexeddbPersistence } from "y-indexeddb"; import * as Y from "yjs"; +import { + AuthenticationFailed, + DocumentTooLarge, + EditorUpdateError, +} from "@shared/collaboration/CloseEvents"; +import EDITOR_VERSION from "@shared/editor/version"; import { supportsPassiveListener } from "@shared/utils/browser"; import Editor, { Props as EditorProps } from "~/components/Editor"; import MultiplayerExtension from "~/editor/extensions/Multiplayer"; @@ -65,6 +71,9 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) { const name = `document.${documentId}`; const localProvider = new IndexeddbPersistence(name, ydoc); const provider = new HocuspocusProvider({ + parameters: { + editorVersion: EDITOR_VERSION, + }, url: `${env.COLLABORATION_URL}/collaboration`, name, document: ydoc, @@ -140,8 +149,14 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) { provider.on("close", (ev: MessageEvent) => { if ("code" in ev.event) { provider.shouldConnect = - ev.event.code !== 1009 && ev.event.code !== 4401; + ev.event.code !== DocumentTooLarge.code && + ev.event.code !== AuthenticationFailed.code && + ev.event.code !== EditorUpdateError.code; ui.setMultiplayerStatus("disconnected", ev.event.code); + + if (ev.event.code === EditorUpdateError.code) { + window.location.reload(); + } } }); diff --git a/server/collaboration/CloseEvents.ts b/server/collaboration/CloseEvents.ts deleted file mode 100644 index 3e61b6aa50..0000000000 --- a/server/collaboration/CloseEvents.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const TooManyConnections = { - code: 4503, - reason: "Too Many Connections", -}; diff --git a/server/collaboration/ConnectionLimitExtension.ts b/server/collaboration/ConnectionLimitExtension.ts index 3077009d97..b4628e42bf 100644 --- a/server/collaboration/ConnectionLimitExtension.ts +++ b/server/collaboration/ConnectionLimitExtension.ts @@ -1,12 +1,12 @@ import { Extension, - connectedPayload, + onConnectPayload, onDisconnectPayload, } from "@hocuspocus/server"; +import { TooManyConnections } from "@shared/collaboration/CloseEvents"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import { trace } from "@server/logging/tracing"; -import { TooManyConnections } from "./CloseEvents"; import { withContext } from "./types"; @trace() @@ -17,8 +17,10 @@ export class ConnectionLimitExtension implements Extension { connectionsByDocument: Map> = new Map(); /** - * onDisconnect hook + * On disconnect hook + * * @param data The disconnect payload + * @returns Promise */ onDisconnect({ documentName, socketId }: withContext) { const connections = this.connectionsByDocument.get(documentName); @@ -41,10 +43,12 @@ export class ConnectionLimitExtension implements Extension { } /** - * connected hook - * @param data The connected payload + * On connect hook + * + * @param data The connect payload + * @returns Promise, resolving will allow the connection, rejecting will drop it */ - connected({ documentName, socketId }: withContext) { + onConnect({ documentName, socketId }: withContext) { const connections = this.connectionsByDocument.get(documentName) || new Set(); if (connections?.size >= env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT) { diff --git a/server/collaboration/EditorVersionExtension.ts b/server/collaboration/EditorVersionExtension.ts new file mode 100644 index 0000000000..45cfe77917 --- /dev/null +++ b/server/collaboration/EditorVersionExtension.ts @@ -0,0 +1,40 @@ +import { Extension, onConnectPayload } from "@hocuspocus/server"; +import semver from "semver"; +import { EditorUpdateError } from "@shared/collaboration/CloseEvents"; +import EDITOR_VERSION from "@shared/editor/version"; +import Logger from "@server/logging/Logger"; +import { trace } from "@server/logging/tracing"; +import { withContext } from "./types"; + +@trace() +export class EditorVersionExtension implements Extension { + /** + * On connect hook – prevents connections from clients with an outdated editor + * version. See the equivalent logic for API in /server/routes/api/middlewares/editor.ts + * + * @param data The connect payload + * @returns Promise, resolving will allow the connection, rejecting will drop. + */ + onConnect({ requestParameters }: withContext) { + const clientVersion = requestParameters.get("editorVersion"); + + if (clientVersion) { + const parsedClientVersion = semver.parse(clientVersion); + const parsedServerVersion = semver.parse(EDITOR_VERSION); + + if ( + parsedClientVersion && + parsedServerVersion && + parsedClientVersion.major < parsedServerVersion.major + ) { + Logger.debug( + "multiplayer", + `Dropping connection due to outdated editor version: ${clientVersion} < ${EDITOR_VERSION}` + ); + return Promise.reject(EditorUpdateError); + } + } + + return Promise.resolve(); + } +} diff --git a/server/routes/api/middlewares/editor.ts b/server/routes/api/middlewares/editor.ts index 91be5035e9..cf9debfefb 100644 --- a/server/routes/api/middlewares/editor.ts +++ b/server/routes/api/middlewares/editor.ts @@ -4,12 +4,14 @@ import EDITOR_VERSION from "@shared/editor/version"; import { EditorUpdateError } from "@server/errors"; export default function editor() { + /** + * Middleware to prevent connections from clients with an outdated editor + * version. See the equivalent logic for collab server in: + * /server/collaboration/EditorVersionExtension.ts + */ return async function editorMiddleware(ctx: Context, next: Next) { const clientVersion = ctx.headers["x-editor-version"]; - // If the editor version on the client is behind the current version being - // served in production by either a minor (new features), or major (breaking - // changes) then force a client reload. if (clientVersion) { const parsedClientVersion = semver.parse(clientVersion as string); const parsedCurrentVersion = semver.parse(EDITOR_VERSION); @@ -17,8 +19,7 @@ export default function editor() { if ( parsedClientVersion && parsedCurrentVersion && - (parsedClientVersion.major < parsedCurrentVersion.major || - parsedClientVersion.minor < parsedCurrentVersion.minor) + parsedClientVersion.major < parsedCurrentVersion.major ) { throw EditorUpdateError(); } diff --git a/server/services/collaboration.ts b/server/services/collaboration.ts index 4e2c22064e..7471ca6a35 100644 --- a/server/services/collaboration.ts +++ b/server/services/collaboration.ts @@ -12,6 +12,7 @@ import env from "@server/env"; import Logger from "@server/logging/Logger"; import ShutdownHelper, { ShutdownOrder } from "@server/utils/ShutdownHelper"; import AuthenticationExtension from "../collaboration/AuthenticationExtension"; +import { EditorVersionExtension } from "../collaboration/EditorVersionExtension"; import LoggerExtension from "../collaboration/LoggerExtension"; import MetricsExtension from "../collaboration/MetricsExtension"; import PersistenceExtension from "../collaboration/PersistenceExtension"; @@ -39,6 +40,7 @@ export default function init( banTime: 5, }), new ConnectionLimitExtension(), + new EditorVersionExtension(), new AuthenticationExtension(), new PersistenceExtension(), new ViewsExtension(), diff --git a/shared/collaboration/CloseEvents.ts b/shared/collaboration/CloseEvents.ts new file mode 100644 index 0000000000..924f8b9db6 --- /dev/null +++ b/shared/collaboration/CloseEvents.ts @@ -0,0 +1,24 @@ +export const DocumentTooLarge = { + code: 1009, + reason: "Document Too Large", +}; + +export const AuthenticationFailed = { + code: 4401, + reason: "Authentication Failed", +}; + +export const AuthorizationFailed = { + code: 4403, + reason: "Authorization Failed", +}; + +export const TooManyConnections = { + code: 4503, + reason: "Too Many Connections", +}; + +export const EditorUpdateError = { + code: 5000, + reason: "Editor Update Required", +}; From 533a14369c53287417ef29266d389468f9700e46 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 22 Mar 2025 23:46:36 -0400 Subject: [PATCH 017/268] fix: Do not wait for connections at end of test suites (#8752) --- plugins/storage/server/api/files.test.ts | 3 +++ server/test/TestServer.ts | 4 +--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/plugins/storage/server/api/files.test.ts b/plugins/storage/server/api/files.test.ts index 10e454d2c1..f6ed0ab034 100644 --- a/plugins/storage/server/api/files.test.ts +++ b/plugins/storage/server/api/files.test.ts @@ -17,6 +17,9 @@ import { getTestServer } from "@server/test/support"; const server = getTestServer(); +// Increase timeout for all tests in this file +jest.setTimeout(10000); + describe("#files.create", () => { it("should fail with status 400 bad request if key is invalid", async () => { const user = await buildUser(); diff --git a/server/test/TestServer.ts b/server/test/TestServer.ts index 1a2df84b21..0f8f5326a1 100644 --- a/server/test/TestServer.ts +++ b/server/test/TestServer.ts @@ -47,9 +47,7 @@ class TestServer { close() { this.listener = null; - return new Promise((resolve, reject) => { - this.server.close((err) => (err ? reject(err) : resolve())); - }); + this.server.closeAllConnections(); } delete(path: string, options?: any) { From 8b65ad3cfafc110dba48d49576c2c0ac4f8dfbf5 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 23 Mar 2025 14:59:19 -0400 Subject: [PATCH 018/268] chore: Move notification event writing to model layer (#8754) * Move notification event writing to model layer fix: Bulk notification action does not reflect on other clients * Add missing locks * fixes --- server/commands/notificationUpdater.test.ts | 182 ------------------ server/commands/notificationUpdater.ts | 53 ----- server/models/base/Model.ts | 7 +- .../routes/api/notifications/notifications.ts | 59 ++++-- 4 files changed, 50 insertions(+), 251 deletions(-) delete mode 100644 server/commands/notificationUpdater.test.ts delete mode 100644 server/commands/notificationUpdater.ts diff --git a/server/commands/notificationUpdater.test.ts b/server/commands/notificationUpdater.test.ts deleted file mode 100644 index bb889758c0..0000000000 --- a/server/commands/notificationUpdater.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { NotificationEventType } from "@shared/types"; -import { Event } from "@server/models"; -import { - buildUser, - buildNotification, - buildDocument, - buildCollection, -} from "@server/test/factories"; -import { withAPIContext } from "@server/test/support"; -import notificationUpdater from "./notificationUpdater"; - -describe("notificationUpdater", () => { - it("should mark the notification as viewed", async () => { - const user = await buildUser(); - const actor = await buildUser({ - teamId: user.teamId, - }); - const collection = await buildCollection({ - teamId: user.teamId, - createdById: actor.id, - }); - const document = await buildDocument({ - teamId: user.teamId, - collectionId: collection.id, - createdById: actor.id, - }); - const notification = await buildNotification({ - actorId: actor.id, - event: NotificationEventType.UpdateDocument, - userId: user.id, - teamId: user.teamId, - documentId: document.id, - collectionId: collection.id, - }); - - expect(notification.archivedAt).toBe(null); - expect(notification.viewedAt).toBe(null); - - await withAPIContext(user, (ctx) => - notificationUpdater(ctx, { - notification, - viewedAt: new Date(), - }) - ); - const event = await Event.findLatest({ - teamId: user.teamId, - }); - - expect(notification.viewedAt).not.toBe(null); - expect(notification.archivedAt).toBe(null); - expect(event!.name).toEqual("notifications.update"); - expect(event!.modelId).toEqual(notification.id); - }); - - it("should mark the notification as unseen", async () => { - const user = await buildUser(); - const actor = await buildUser({ - teamId: user.teamId, - }); - const collection = await buildCollection({ - teamId: user.teamId, - createdById: actor.id, - }); - const document = await buildDocument({ - teamId: user.teamId, - collectionId: collection.id, - createdById: actor.id, - }); - const notification = await buildNotification({ - actorId: actor.id, - event: NotificationEventType.UpdateDocument, - userId: user.id, - teamId: user.teamId, - documentId: document.id, - collectionId: collection.id, - viewedAt: new Date(), - }); - - expect(notification.archivedAt).toBe(null); - expect(notification.viewedAt).not.toBe(null); - - await withAPIContext(user, (ctx) => - notificationUpdater(ctx, { - notification, - viewedAt: null, - }) - ); - const event = await Event.findLatest({ - teamId: user.teamId, - }); - - expect(notification.viewedAt).toBe(null); - expect(notification.archivedAt).toBe(null); - expect(event!.name).toEqual("notifications.update"); - expect(event!.modelId).toEqual(notification.id); - }); - - it("should archive the notification", async () => { - const user = await buildUser(); - const actor = await buildUser({ - teamId: user.teamId, - }); - const collection = await buildCollection({ - teamId: user.teamId, - createdById: actor.id, - }); - const document = await buildDocument({ - teamId: user.teamId, - collectionId: collection.id, - createdById: actor.id, - }); - const notification = await buildNotification({ - actorId: actor.id, - event: NotificationEventType.UpdateDocument, - userId: user.id, - teamId: user.teamId, - documentId: document.id, - collectionId: collection.id, - }); - - expect(notification.archivedAt).toBe(null); - expect(notification.viewedAt).toBe(null); - - await withAPIContext(user, (ctx) => - notificationUpdater(ctx, { - notification, - archivedAt: new Date(), - }) - ); - const event = await Event.findLatest({ - teamId: user.teamId, - }); - - expect(notification.viewedAt).toBe(null); - expect(notification.archivedAt).not.toBe(null); - expect(event!.name).toEqual("notifications.update"); - expect(event!.modelId).toEqual(notification.id); - }); - - it("should unarchive the notification", async () => { - const user = await buildUser(); - const actor = await buildUser({ - teamId: user.teamId, - }); - const collection = await buildCollection({ - teamId: user.teamId, - createdById: actor.id, - }); - const document = await buildDocument({ - teamId: user.teamId, - collectionId: collection.id, - createdById: actor.id, - }); - const notification = await buildNotification({ - actorId: actor.id, - event: NotificationEventType.UpdateDocument, - userId: user.id, - teamId: user.teamId, - documentId: document.id, - collectionId: collection.id, - archivedAt: new Date(), - }); - - expect(notification.archivedAt).not.toBe(null); - expect(notification.viewedAt).toBe(null); - - await withAPIContext(user, (ctx) => - notificationUpdater(ctx, { - notification, - archivedAt: null, - }) - ); - const event = await Event.findLatest({ - teamId: user.teamId, - }); - - expect(notification.viewedAt).toBe(null); - expect(notification.archivedAt).toBeNull(); - expect(event!.name).toEqual("notifications.update"); - expect(event!.modelId).toEqual(notification.id); - }); -}); diff --git a/server/commands/notificationUpdater.ts b/server/commands/notificationUpdater.ts deleted file mode 100644 index 6f85f8de3b..0000000000 --- a/server/commands/notificationUpdater.ts +++ /dev/null @@ -1,53 +0,0 @@ -import isUndefined from "lodash/isUndefined"; -import { Event, Notification } from "@server/models"; -import { APIContext } from "@server/types"; - -type Props = { - /** Notification to be updated */ - notification: Notification; - /** Time at which notification was viewed */ - viewedAt?: Date | null; - /** Time at which notification was archived */ - archivedAt?: Date | null; -}; - -/** - * This command updates notification properties. - * - * @param ctx The originating request context - * @param Props The properties of the notification to update - * @returns Notification The updated notification - */ -export default async function notificationUpdater( - ctx: APIContext, - { notification, viewedAt, archivedAt }: Props -): Promise { - const { transaction } = ctx.state; - - if (!isUndefined(viewedAt)) { - notification.viewedAt = viewedAt; - } - if (!isUndefined(archivedAt)) { - notification.archivedAt = archivedAt; - } - const changed = notification.changed(); - if (changed) { - await notification.save({ transaction }); - - await Event.createFromContext( - ctx, - { - name: "notifications.update", - userId: notification.userId, - modelId: notification.id, - documentId: notification.documentId, - }, - { - actorId: notification.userId, - teamId: notification.teamId, - } - ); - } - - return notification; -} diff --git a/server/models/base/Model.ts b/server/models/base/Model.ts index e27c416f85..ac0cb7078b 100644 --- a/server/models/base/Model.ts +++ b/server/models/base/Model.ts @@ -280,6 +280,7 @@ class Model< * * @param query The query options. * @param callback The function to call for each batch of results + * @return The total number of results processed. */ static async findAllInBatches( query: Replace, "limit", "batchLimit"> & { @@ -287,7 +288,8 @@ class Model< totalLimit?: number; }, callback: (results: Array, query: FindOptions) => Promise - ) { + ): Promise { + let total = 0; const mappedQuery = { ...query, offset: query.offset ?? 0, @@ -299,12 +301,15 @@ class Model< do { // @ts-expect-error this T results = await this.findAll(mappedQuery); + total += results.length; await callback(results, mappedQuery); mappedQuery.offset += mappedQuery.limit; } while ( results.length >= mappedQuery.limit && (mappedQuery.totalLimit ?? Infinity) > mappedQuery.offset ); + + return total; } /** diff --git a/server/routes/api/notifications/notifications.ts b/server/routes/api/notifications/notifications.ts index 9a1d5c5785..9a3766d090 100644 --- a/server/routes/api/notifications/notifications.ts +++ b/server/routes/api/notifications/notifications.ts @@ -1,10 +1,10 @@ import Router from "koa-router"; -import { isNil } from "lodash"; +import isEmpty from "lodash/isEmpty"; +import isNil from "lodash/isNil"; import isNull from "lodash/isNull"; import isUndefined from "lodash/isUndefined"; import { WhereOptions, Op } from "sequelize"; import { NotificationEventType } from "@shared/types"; -import notificationUpdater from "@server/commands/notificationUpdater"; import env from "@server/env"; import { AuthenticationError } from "@server/errors"; import auth from "@server/middlewares/authentication"; @@ -29,6 +29,7 @@ const pixel = Buffer.from( const handleUnsubscribe = async ( ctx: APIContext ) => { + const { transaction } = ctx.state; const eventType = (ctx.input.body.eventType ?? ctx.input.query.eventType) as NotificationEventType; const userId = (ctx.input.body.userId ?? ctx.input.query.userId) as string; @@ -46,6 +47,8 @@ const handleUnsubscribe = async ( const user = await User.scope("withTeam").findByPk(userId, { rejectOnEmpty: true, + lock: transaction.LOCK.UPDATE, + transaction, }); user.setNotificationEventType(eventType, false); @@ -145,17 +148,21 @@ router.get( transaction(), async (ctx: APIContext) => { const { id, token } = ctx.input.query; - const notification = await Notification.unscoped().findByPk(id); + const { transaction } = ctx.state; + + const notification = await Notification.unscoped().findByPk(id, { + lock: transaction.LOCK.UPDATE, + rejectOnEmpty: true, + transaction, + }); if (!notification || !safeEqual(token, notification.pixelToken)) { throw AuthenticationError(); } if (!notification.viewedAt) { - await notificationUpdater(ctx, { - notification, - viewedAt: new Date(), - }); + notification.viewedAt = new Date(); + await notification.saveWithCtx(ctx); } ctx.response.set("Content-Type", "image/gif"); @@ -171,15 +178,25 @@ router.post( async (ctx: APIContext) => { const { id, viewedAt, archivedAt } = ctx.input.body; const { user } = ctx.state.auth; + const { transaction } = ctx.state; - const notification = await Notification.findByPk(id); + const notification = await Notification.findByPk(id, { + lock: { + level: transaction.LOCK.UPDATE, + of: Notification, + }, + rejectOnEmpty: true, + transaction, + }); authorize(user, "update", notification); - await notificationUpdater(ctx, { - notification, - viewedAt, - archivedAt, - }); + if (!isUndefined(viewedAt)) { + notification.viewedAt = viewedAt; + } + if (!isUndefined(archivedAt)) { + notification.archivedAt = archivedAt; + } + await notification.saveWithCtx(ctx); ctx.body = { data: await presentNotification(ctx, notification), @@ -196,7 +213,7 @@ router.post( const { viewedAt, archivedAt } = ctx.input.body; const { user } = ctx.state.auth; - const values: { [x: string]: any } = {}; + const values: Partial = {}; let where: WhereOptions = { teamId: user.teamId, userId: user.id, @@ -216,7 +233,19 @@ router.post( }; } - const [total] = await Notification.update(values, { where }); + let total = 0; + if (!isEmpty(values)) { + total = await Notification.findAllInBatches( + { where }, + async (results) => { + await Promise.all( + results.map((notification) => + notification.updateWithCtx(ctx, values) + ) + ); + } + ); + } ctx.body = { success: true, From 6e98568e5b7a5ad70641c8139d7bc6990fabdf34 Mon Sep 17 00:00:00 2001 From: Hemachandar <132386067+hmacr@users.noreply.github.com> Date: Mon, 24 Mar 2025 00:49:13 +0530 Subject: [PATCH 019/268] API importer for Notion (#8710) --- .env.sample | 4 + app/components/Dialogs.tsx | 5 +- app/components/WebsocketProvider.tsx | 25 +- app/hooks/usePolicy.ts | 5 +- app/menus/ImportMenu.tsx | 62 + app/models/Import.ts | 54 + app/models/base/Model.ts | 28 +- app/scenes/Settings/Import.tsx | 242 +- .../Settings/components/ImportListItem.tsx | 148 + app/stores/DialogsStore.ts | 4 + app/stores/ImportsStore.ts | 25 + app/stores/RootStore.ts | 3 + app/utils/ApiClient.ts | 5 + app/utils/PluginManager.ts | 11 + app/utils/errors.ts | 2 + package.json | 2 + plugins/notion/client/Imports.tsx | 88 + .../notion/client/components/ImportDialog.tsx | 78 + plugins/notion/client/index.tsx | 19 + plugins/notion/plugin.json | 5 + plugins/notion/server/api/notion.ts | 105 + plugins/notion/server/api/schema.ts | 25 + plugins/notion/server/env.ts | 19 + plugins/notion/server/index.ts | 26 + plugins/notion/server/notion.ts | 284 + .../processors/NotionImportsProcessor.ts | 71 + .../server/tasks/NotionAPIImportTask.ts | 144 + .../server/utils/NotionConverter.test.ts | 15 + .../notion/server/utils/NotionConverter.ts | 584 ++ .../NotionConverter.test.ts.snap | 1985 +++++ plugins/notion/shared/NotionUtils.ts | 58 + plugins/notion/shared/types.ts | 18 + .../server/tasks/DeliverWebhookTask.ts | 6 + server/commands/documentCreator.ts | 5 +- server/errors.ts | 6 + .../20250306181804-create-imports.js | 93 + .../20250310043011-create-import-tasks.js | 67 + ...piImportId-to-collections-and-documents.js | 59 + server/models/Collection.ts | 9 + server/models/Document.ts | 8 + server/models/Import.ts | 87 + server/models/ImportTask.ts | 58 + server/models/index.ts | 4 + server/policies/fileOperation.ts | 2 +- server/policies/import.ts | 31 + server/policies/index.ts | 1 + server/presenters/import.ts | 19 + server/presenters/index.ts | 2 + server/queues/processors/BaseProcessor.ts | 11 + server/queues/processors/ImportsProcessor.ts | 529 ++ .../queues/processors/WebsocketsProcessor.ts | 19 +- server/queues/processors/index.ts | 4 +- server/queues/tasks/APIImportTask.ts | 391 + server/queues/tasks/BaseTask.ts | 11 + server/queues/tasks/CleanupOldImportsTask.ts | 84 + .../queues/tasks/ErrorTimedOutImportsTask.ts | 89 + .../tasks/UploadAttachmentsForImportTask.ts | 69 + .../api/fileOperations/fileOperations.ts | 7 +- server/routes/api/imports/imports.test.ts | 308 + server/routes/api/imports/imports.ts | 185 + server/routes/api/imports/index.ts | 1 + server/routes/api/imports/schema.ts | 69 + server/routes/api/index.ts | 2 + server/services/worker.ts | 10 + server/test/factories.ts | 39 + server/test/fixtures/notion-page.json | 6753 +++++++++++++++++ server/types.ts | 14 +- server/utils/indexing.ts | 2 +- shared/i18n/locales/en_US/translation.json | 15 +- shared/schema.ts | 59 + shared/types.ts | 33 + shared/utils/ProsemirrorHelper.ts | 40 + shared/validations.ts | 5 + yarn.lock | 54 +- 74 files changed, 13259 insertions(+), 150 deletions(-) create mode 100644 app/menus/ImportMenu.tsx create mode 100644 app/models/Import.ts create mode 100644 app/scenes/Settings/components/ImportListItem.tsx create mode 100644 app/stores/ImportsStore.ts create mode 100644 plugins/notion/client/Imports.tsx create mode 100644 plugins/notion/client/components/ImportDialog.tsx create mode 100644 plugins/notion/client/index.tsx create mode 100644 plugins/notion/plugin.json create mode 100644 plugins/notion/server/api/notion.ts create mode 100644 plugins/notion/server/api/schema.ts create mode 100644 plugins/notion/server/env.ts create mode 100644 plugins/notion/server/index.ts create mode 100644 plugins/notion/server/notion.ts create mode 100644 plugins/notion/server/processors/NotionImportsProcessor.ts create mode 100644 plugins/notion/server/tasks/NotionAPIImportTask.ts create mode 100644 plugins/notion/server/utils/NotionConverter.test.ts create mode 100644 plugins/notion/server/utils/NotionConverter.ts create mode 100644 plugins/notion/server/utils/__snapshots__/NotionConverter.test.ts.snap create mode 100644 plugins/notion/shared/NotionUtils.ts create mode 100644 plugins/notion/shared/types.ts create mode 100644 server/migrations/20250306181804-create-imports.js create mode 100644 server/migrations/20250310043011-create-import-tasks.js create mode 100644 server/migrations/20250314105847-add-apiImportId-to-collections-and-documents.js create mode 100644 server/models/Import.ts create mode 100644 server/models/ImportTask.ts create mode 100644 server/policies/import.ts create mode 100644 server/presenters/import.ts create mode 100644 server/queues/processors/ImportsProcessor.ts create mode 100644 server/queues/tasks/APIImportTask.ts create mode 100644 server/queues/tasks/CleanupOldImportsTask.ts create mode 100644 server/queues/tasks/ErrorTimedOutImportsTask.ts create mode 100644 server/queues/tasks/UploadAttachmentsForImportTask.ts create mode 100644 server/routes/api/imports/imports.test.ts create mode 100644 server/routes/api/imports/imports.ts create mode 100644 server/routes/api/imports/index.ts create mode 100644 server/routes/api/imports/schema.ts create mode 100644 server/test/fixtures/notion-page.json create mode 100644 shared/schema.ts diff --git a/.env.sample b/.env.sample index 51046501da..8f2e4910e8 100644 --- a/.env.sample +++ b/.env.sample @@ -147,6 +147,10 @@ DISCORD_SERVER_ID= # DISCORD_SERVER_ID and DISCORD_SERVER_ROLES must be set together. DISCORD_SERVER_ROLES= +# –––––––––––––– IMPORTS –––––––––––––– +NOTION_CLIENT_ID= +NOTION_CLIENT_SECRET= + # –––––––––––––––– OPTIONAL –––––––––––––––– # Base64 encoded private key and certificate for HTTPS termination. This is only diff --git a/app/components/Dialogs.tsx b/app/components/Dialogs.tsx index e7f4d05589..d1af42168c 100644 --- a/app/components/Dialogs.tsx +++ b/app/components/Dialogs.tsx @@ -23,7 +23,10 @@ function Dialogs() { key={id} isOpen={modal.isOpen} fullscreen={modal.fullscreen ?? false} - onRequestClose={() => dialogs.closeModal(id)} + onRequestClose={() => { + modal.onClose?.(); + dialogs.closeModal(id); + }} title={modal.title} style={modal.style} > diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 03d007e6bb..4a4b0405da 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -6,7 +6,11 @@ import * as React from "react"; import { withTranslation, WithTranslation } from "react-i18next"; import { io, Socket } from "socket.io-client"; import { toast } from "sonner"; -import { FileOperationState, FileOperationType } from "@shared/types"; +import { + FileOperationState, + FileOperationType, + ImportState, +} from "@shared/types"; import RootStore from "~/stores/RootStore"; import Collection from "~/models/Collection"; import Comment from "~/models/Comment"; @@ -15,6 +19,7 @@ import FileOperation from "~/models/FileOperation"; import Group from "~/models/Group"; import GroupMembership from "~/models/GroupMembership"; import GroupUser from "~/models/GroupUser"; +import Import from "~/models/Import"; import Membership from "~/models/Membership"; import Notification from "~/models/Notification"; import Pin from "~/models/Pin"; @@ -100,6 +105,7 @@ class WebsocketProvider extends React.Component { subscriptions, fileOperations, notifications, + imports, } = this.props; const currentUserId = auth?.user?.id; @@ -620,6 +626,23 @@ class WebsocketProvider extends React.Component { } ); + this.socket.on("imports.create", (event: PartialExcept) => { + imports.add(event); + }); + + this.socket.on("imports.update", (event: PartialExcept) => { + imports.add(event); + + if ( + event.state === ImportState.Completed && + event.createdBy?.id === auth.user?.id + ) { + toast.success(event.name, { + description: this.props.t("Your import completed"), + }); + } + }); + this.socket.on( "subscriptions.create", (event: PartialExcept) => { diff --git a/app/hooks/usePolicy.ts b/app/hooks/usePolicy.ts index 86052f7c3d..4bb9e8b86b 100644 --- a/app/hooks/usePolicy.ts +++ b/app/hooks/usePolicy.ts @@ -18,6 +18,7 @@ export default function usePolicy(entity?: string | Model | null) { ? entity : entity.id : ""; + const policy = policies.get(entityId); React.useEffect(() => { if ( @@ -28,11 +29,11 @@ export default function usePolicy(entity?: string | Model | null) { ) { // The policy for this model is missing and we have an authenticated session, attempt to // reload relationships for this model. - if (!policies.get(entity.id) && user) { + if (!policy && user) { void entity.loadRelations(); } } - }, [policies, user, entity]); + }, [policies, policy, user, entity]); return policies.abilities(entityId); } diff --git a/app/menus/ImportMenu.tsx b/app/menus/ImportMenu.tsx new file mode 100644 index 0000000000..3b55e6fe40 --- /dev/null +++ b/app/menus/ImportMenu.tsx @@ -0,0 +1,62 @@ +import { observer } from "mobx-react"; +import { CrossIcon, TrashIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { useMenuState } from "reakit/Menu"; +import Import from "~/models/Import"; +import ContextMenu from "~/components/ContextMenu"; +import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton"; +import Template from "~/components/ContextMenu/Template"; +import usePolicy from "~/hooks/usePolicy"; +import { MenuItem } from "~/types"; + +type Props = { + /** Import to which actions will be applied. */ + importModel: Import; + /** Callback to handle import cancellation. */ + onCancel: () => Promise; + /** Callback to handle import deletion. */ + onDelete: () => Promise; +}; + +export const ImportMenu = observer( + ({ importModel, onCancel, onDelete }: Props) => { + const { t } = useTranslation(); + const can = usePolicy(importModel); + const menu = useMenuState({ + modal: true, + }); + + const items = React.useMemo( + () => + [ + { + type: "button", + title: t("Cancel"), + visible: can.cancel, + icon: , + dangerous: true, + onClick: onCancel, + }, + { + type: "button", + title: t("Delete"), + visible: can.delete, + icon: , + dangerous: true, + onClick: onDelete, + }, + ] satisfies MenuItem[], + [t, can.delete, can.cancel, onCancel, onDelete] + ); + + return ( + <> + + +