diff --git a/.oxlintrc.json b/.oxlintrc.json index f124795a6a..75b70179c3 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -105,6 +105,18 @@ "bundle/no-constructor-name": "error" } }, + { + "files": ["plugins/*/server/**/*.{js,ts}"], + "rules": { + "no-restricted-properties": [ + "error", + { + "property": "isBot", + "message": "Use `isbot` from the `isbot` package instead" + } + ] + } + }, { "files": ["**/*.{ts,tsx}"], "rules": { diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 4bfa4ec979..0eee33a7a3 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -722,20 +722,17 @@ 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. - */ +/** Shows a file extension at the end of menu items only. */ const fileExtensionHint = (extension: string) => ({ isMenu }: ActionContext) => - isMenu ? [extension] : undefined; + 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"), + badge: fileExtensionHint(".md"), keywords: "md markdown export download", icon: , iconInContextMenu: false, @@ -757,7 +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"), + badge: fileExtensionHint(".html"), keywords: "xml html export download", icon: , iconInContextMenu: false, @@ -780,7 +777,7 @@ export const downloadDocumentAsTextBundle = createAction({ isMenu ? t("TextBundle") : t("Download as TextBundle"), analyticsName: "Download document as TextBundle", section: ActiveDocumentSection, - shortcut: fileExtensionHint(".textpack"), + badge: fileExtensionHint(".textpack"), keywords: "textbundle textpack bear ulysses export download", icon: , iconInContextMenu: false, @@ -802,7 +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"), + badge: fileExtensionHint(".pdf"), keywords: "pdf export download", icon: , iconInContextMenu: false, @@ -1818,12 +1815,9 @@ const headingPrefixNames: Record string> = const changeHeadingPrefixFactory = (style: HeadingPrefixStyle) => createAction({ name: ({ t }) => headingPrefixNames[style](t), - // The example is displayed in the shortcut slot of menu items, but must - // not be set on the command bar action where shortcuts are registered as - // key sequences. - shortcut: ({ isMenu }) => + badge: ({ isMenu }) => isMenu && headingPrefixExamples[style] - ? [headingPrefixExamples[style]] + ? headingPrefixExamples[style] : undefined, keywords: headingPrefixExamples[style], analyticsName: "Change heading numbering", diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx index ea22fbcfeb..25b02851ee 100644 --- a/app/actions/definitions/teams.tsx +++ b/app/actions/definitions/teams.tsx @@ -25,10 +25,8 @@ export const switchTeamsList = ({ stores }: { stores: RootStore }) => stores.auth.availableTeams?.map((session) => createExternalLinkAction({ id: `switch-${session.id}`, - name: ({ t }) => - session.isSignedIn - ? session.name - : t("{{ name }} (Logged out)", { name: session.name }), + name: session.name, + badge: ({ t }) => (session.isSignedIn ? undefined : t("Logged out")), analyticsName: "Switch workspace", section: TeamSection, keywords: "change switch workspace organization team", diff --git a/app/actions/index.ts b/app/actions/index.ts index 37cbcca3e7..63052e3255 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -152,6 +152,7 @@ export function actionToMenuItem( const visible = resolve(action.visible, context) ?? true; const disabled = resolve(action.disabled, context); const shortcut = resolve(action.shortcut, context); + const badge = resolve(action.badge, context); const icon = !!action.icon && action.iconInContextMenu !== false ? resolve(action.icon, context) @@ -169,6 +170,7 @@ export function actionToMenuItem( selected: resolve(action.selected, context), dangerous: action.dangerous, shortcut, + badge, onClick: () => performAction(action, context), }; @@ -181,6 +183,7 @@ export function actionToMenuItem( visible, disabled, shortcut, + badge, to, }; } @@ -193,6 +196,7 @@ export function actionToMenuItem( visible, disabled, shortcut, + badge, href: action.target ? { url: action.url, target: action.target } : action.url, diff --git a/app/components/Menu/transformer.tsx b/app/components/Menu/transformer.tsx index 0ede28d900..2ac0c4bf97 100644 --- a/app/components/Menu/transformer.tsx +++ b/app/components/Menu/transformer.tsx @@ -50,6 +50,7 @@ export function toMenuItems(items: MenuItem[]) { selected={item.selected} dangerous={item.dangerous} shortcut={item.shortcut} + badge={item.badge} onClick={item.onClick} /> ); @@ -62,6 +63,7 @@ export function toMenuItems(items: MenuItem[]) { icon={icon} disabled={item.disabled} shortcut={item.shortcut} + badge={item.badge} to={item.to} /> ); @@ -74,6 +76,7 @@ export function toMenuItems(items: MenuItem[]) { icon={icon} disabled={item.disabled} shortcut={item.shortcut} + badge={item.badge} href={typeof item.href === "string" ? item.href : item.href.url} target={ typeof item.href === "string" ? undefined : item.href.target @@ -181,6 +184,9 @@ export function toMobileMenuItems( > {icon} {item.title} + {item.badge && ( + {item.badge} + )} {item.selected !== undefined && ( {item.selected ? : null} @@ -199,6 +205,9 @@ export function toMobileMenuItems( > {icon} {item.title} + {item.badge && ( + {item.badge} + )} ); @@ -215,6 +224,9 @@ export function toMobileMenuItems( > {icon} {item.title} + {item.badge && ( + {item.badge} + )} ); diff --git a/app/components/primitives/Menu/index.tsx b/app/components/primitives/Menu/index.tsx index 17b4f6ed1e..ffaf031601 100644 --- a/app/components/primitives/Menu/index.tsx +++ b/app/components/primitives/Menu/index.tsx @@ -232,6 +232,8 @@ type BaseItemProps = { icon?: React.ReactElement; disabled?: boolean; shortcut?: string[]; + /** Additional content displayed at the end of the item. */ + badge?: React.ReactNode; }; /** @@ -290,6 +292,7 @@ function MenuButton(props: MenuButtonProps) { selected, dangerous, shortcut, + badge, onClick, ...rest } = props; @@ -308,6 +311,7 @@ function MenuButton(props: MenuButtonProps) { > {icon} {label} + {badge && {badge}} {selected !== undefined && ( {selected ? : null} @@ -343,7 +347,7 @@ type MenuInternalLinkProps = BaseItemProps & { function MenuInternalLink(props: MenuInternalLinkProps) { const { variant } = useMenuContext(); - const { ref, label, icon, disabled, shortcut, to, ...rest } = props; + const { ref, label, icon, disabled, shortcut, badge, to, ...rest } = props; const Item = variant === "dropdown" @@ -355,6 +359,7 @@ function MenuInternalLink(props: MenuInternalLinkProps) { {icon} {label} + {badge && {badge}} @@ -378,7 +383,8 @@ type MenuExternalLinkProps = BaseItemProps & { function MenuExternalLink(props: MenuExternalLinkProps) { const { variant } = useMenuContext(); - const { ref, label, icon, disabled, shortcut, href, target, ...rest } = props; + const { ref, label, icon, disabled, shortcut, badge, href, target, ...rest } = + props; const Item = variant === "dropdown" @@ -394,6 +400,7 @@ function MenuExternalLink(props: MenuExternalLinkProps) { > {icon} {label} + {badge && {badge}} diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx index 045912f46f..eb41ac9314 100644 --- a/app/components/primitives/components/Menu.tsx +++ b/app/components/primitives/components/Menu.tsx @@ -169,6 +169,14 @@ export const SelectedIconWrapper = styled.span` justify-content: center; `; +export const MenuBadge = styled.span` + font-size: 13px; + color: currentColor; + opacity: 0.5; + margin-inline-start: 16px; + flex-shrink: 0; +`; + export const MenuShortcut = styled.span` display: flex; align-items: center; diff --git a/app/types.ts b/app/types.ts index 0999f5d56e..b89088aaa7 100644 --- a/app/types.ts +++ b/app/types.ts @@ -27,6 +27,7 @@ export type MenuItemButton = { icon?: React.ReactNode; tooltip?: React.ReactNode; shortcut?: string[]; + badge?: React.ReactNode; }; export type MenuItemWithChildren = { @@ -62,6 +63,7 @@ export type MenuInternalLink = { disabled?: boolean; icon?: React.ReactNode; shortcut?: string[]; + badge?: React.ReactNode; }; export type MenuExternalLink = { @@ -74,6 +76,7 @@ export type MenuExternalLink = { level?: number; icon?: React.ReactNode; shortcut?: string[]; + badge?: React.ReactNode; }; export type MenuGroup = { diff --git a/package.json b/package.json index 20c871c557..45928f8c30 100644 --- a/package.json +++ b/package.json @@ -156,6 +156,7 @@ "invariant": "^2.2.4", "ioredis": "^5.11.1", "ipaddr.js": "^2.5.0", + "isbot": "^5.2.2", "iso-639-3": "^3.0.1", "js-yaml": "^4.3.2", "js.foresight": "^4.2.1", diff --git a/plugins/notion/server/notion.test.ts b/plugins/notion/server/notion.test.ts new file mode 100644 index 0000000000..7a39459756 --- /dev/null +++ b/plugins/notion/server/notion.test.ts @@ -0,0 +1,81 @@ +import { APIErrorCode, APIResponseError } from "@notionhq/client"; +import { Headers } from "node-fetch"; +import { NotionClient } from "./notion"; + +const rateLimitError = (headers: Record = {}) => + new APIResponseError({ + code: APIErrorCode.RateLimited, + status: 429, + message: "You have been rate limited. Please try again later.", + headers: new Headers(headers), + rawBodyText: "", + }); + +const emptySearch = { + object: "list" as const, + type: "page_or_database" as const, + page_or_database: {}, + results: [], + has_more: false, + next_cursor: null, +}; + +describe("NotionClient", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("should wait for the Retry-After header before retrying", async () => { + const notion = new NotionClient("token"); + const search = vi + .spyOn(notion["client"], "search") + .mockRejectedValueOnce(rateLimitError({ "Retry-After": "120" })) + .mockResolvedValue(emptySearch); + + const promise = notion.fetchRootPages(); + + await vi.advanceTimersByTimeAsync(119900); + expect(search).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(500); + expect(search).toHaveBeenCalledTimes(2); + await expect(promise).resolves.toEqual([]); + }); + + it("should pause other requests from the same client", async () => { + const notion = new NotionClient("token"); + const search = vi + .spyOn(notion["client"], "search") + .mockRejectedValueOnce(rateLimitError({ "Retry-After": "5" })) + .mockResolvedValue(emptySearch); + + const first = notion.fetchRootPages(); + await vi.advanceTimersByTimeAsync(100); + const second = notion.fetchRootPages(); + + await vi.advanceTimersByTimeAsync(4800); + expect(search).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(1000); + expect(search).toHaveBeenCalledTimes(3); + await expect(Promise.all([first, second])).resolves.toEqual([[], []]); + }); + + it("should throw after the maximum number of rate limit retries", async () => { + const notion = new NotionClient("token"); + const search = vi + .spyOn(notion["client"], "search") + .mockRejectedValue(rateLimitError()); + + const promise = notion.fetchRootPages(); + const assertion = expect(promise).rejects.toBeInstanceOf(APIResponseError); + + await vi.runAllTimersAsync(); + await assertion; + expect(search).toHaveBeenCalledTimes(9); + }); +}); diff --git a/plugins/notion/server/notion.ts b/plugins/notion/server/notion.ts index 3f2aa2d7f2..cf8aea30f1 100644 --- a/plugins/notion/server/notion.ts +++ b/plugins/notion/server/notion.ts @@ -17,8 +17,10 @@ import type { import { RateLimit } from "async-sema"; import emojiRegex from "emoji-regex"; import { compact, truncate } from "es-toolkit/compat"; +import { Headers } from "node-fetch"; import { z } from "zod"; -import { Second } from "@shared/utils/time"; +import { Minute, Second } from "@shared/utils/time"; +import { sleep } from "@shared/utils/timers"; import { isUrl } from "@shared/utils/urls"; import { CollectionValidation, DocumentValidation } from "@shared/validations"; import Logger from "@server/logging/Logger"; @@ -61,8 +63,11 @@ export class NotionClient { private limiter: ReturnType; private pageSize = 100; private maxRetries = 3; + private maxRateLimitRetries = 8; private maxServerErrorRetries = 8; private retryDelay = 1000; + private maxRateLimitDelay = Minute.ms; + private pausedUntil = 0; private skipChildrenForBlock = [ "unsupported", "child_page", @@ -96,11 +101,12 @@ export class NotionClient { */ private async fetchWithRetry(apiCall: () => Promise): Promise { let retries = 0; + let rateLimitRetries = 0; let serverErrorRetries = 0; while (true) { try { - await this.limiter(); + await this.acquire(); return await apiCall(); } catch (error) { // Check if this is a timeout and try again @@ -128,25 +134,27 @@ export class NotionClient { error instanceof APIResponseError && error.code === APIErrorCode.RateLimited ) { - if (retries < this.maxRetries) { - retries++; - const headers = error.headers as Record; - const retryAfter = headers["Retry-After"] - ? parseInt(headers["Retry-After"], 10) * 1000 // Convert seconds to milliseconds - : undefined; - const delay = retryAfter ?? this.retryDelay * retries; - Logger.info( - "task", - `Notion API rate limit hit, retrying in ${delay}ms (retry ${retries}/${this.maxRetries})` + const delay = + this.getRetryAfter(error) ?? + Math.min( + this.retryDelay * 2 ** rateLimitRetries, + this.maxRateLimitDelay ); - // Wait before retrying - await new Promise((resolve) => setTimeout(resolve, delay)); + // Pause all requests from this client, not only this one. + this.pausedUntil = Math.max(this.pausedUntil, Date.now() + delay); + + if (rateLimitRetries < this.maxRateLimitRetries) { + rateLimitRetries++; + Logger.info( + "task", + `Notion API rate limit hit, retrying in ${delay}ms (retry ${rateLimitRetries}/${this.maxRateLimitRetries})` + ); continue; } Logger.warn( - `Notion API rate limit exceeded after ${this.maxRetries} retries`, + `Notion API rate limit exceeded after ${this.maxRateLimitRetries} retries`, { error: error.message } ); } @@ -183,6 +191,39 @@ export class NotionClient { } } + /** + * Waits for a slot from the rate limiter and for any rate limit pause to end. + * + * @returns a promise that resolves when a request can be sent. + */ + private async acquire() { + while (true) { + if (Date.now() < this.pausedUntil) { + await sleep(this.pausedUntil - Date.now()); + } + await this.limiter(); + + // A pause can start while this request waits in the limiter queue. + if (Date.now() >= this.pausedUntil) { + return; + } + } + } + + /** + * Reads the Retry-After header from a rate limit error. + * + * @param error the error returned by the Notion API. + * @returns the delay in milliseconds, or undefined if the header is missing. + */ + private getRetryAfter(error: APIResponseError) { + if (!(error.headers instanceof Headers)) { + return undefined; + } + const seconds = parseInt(error.headers.get("retry-after") ?? "", 10); + return Number.isFinite(seconds) ? seconds * Second.ms : undefined; + } + static async oauthAccess(code: string) { const headers = { "Content-Type": "application/json", diff --git a/server/.oxlintrc.json b/server/.oxlintrc.json index f9cd1a350f..8a0ecf9887 100644 --- a/server/.oxlintrc.json +++ b/server/.oxlintrc.json @@ -34,6 +34,13 @@ } ] } + ], + "no-restricted-properties": [ + "error", + { + "property": "isBot", + "message": "Use `isbot` from the `isbot` package instead" + } ] }, "plugins": ["import"] diff --git a/server/emails/templates/CommentCreatedEmail.tsx b/server/emails/templates/CommentCreatedEmail.tsx index 0557c08671..92e6115ce4 100644 --- a/server/emails/templates/CommentCreatedEmail.tsx +++ b/server/emails/templates/CommentCreatedEmail.tsx @@ -4,6 +4,7 @@ import type { Collection } from "@server/models"; import { Comment, Document } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper"; +import SubscriptionHelper from "@server/models/helpers/SubscriptionHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { can } from "@server/policies"; import type { EmailProps } from "./BaseEmail"; @@ -13,7 +14,7 @@ import Button from "./components/Button"; import Diff from "./components/Diff"; import EmailTemplate from "./components/EmailLayout"; import EmptySpace from "./components/EmptySpace"; -import Footer from "./components/Footer"; +import Footer, { Link } from "./components/Footer"; import Header from "./components/Header"; import Heading from "./components/Heading"; @@ -208,7 +209,16 @@ ${this.t("Open Thread")}: ${teamUrl}${document.url}?commentId=${commentId}
+ > + + {this.t("Unsubscribe from this doc")} + +
); } diff --git a/server/emails/templates/CommentResolvedEmail.tsx b/server/emails/templates/CommentResolvedEmail.tsx index 4f4b312782..c99444e296 100644 --- a/server/emails/templates/CommentResolvedEmail.tsx +++ b/server/emails/templates/CommentResolvedEmail.tsx @@ -3,6 +3,7 @@ import { NotificationEventType } from "@shared/types"; import type { Collection } from "@server/models"; import { Comment, Document } from "@server/models"; import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper"; +import SubscriptionHelper from "@server/models/helpers/SubscriptionHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { can } from "@server/policies"; import type { EmailProps } from "./BaseEmail"; @@ -12,7 +13,7 @@ import Button from "./components/Button"; import Diff from "./components/Diff"; import EmailTemplate from "./components/EmailLayout"; import EmptySpace from "./components/EmptySpace"; -import Footer from "./components/Footer"; +import Footer, { Link } from "./components/Footer"; import Header from "./components/Header"; import Heading from "./components/Heading"; @@ -173,7 +174,16 @@ export default class CommentResolvedEmail extends BaseEmail<
+ > + + {this.t("Unsubscribe from this doc")} + +
); } diff --git a/server/emails/templates/components/Footer.tsx b/server/emails/templates/components/Footer.tsx index 2755c0a8db..76aba46f1b 100644 --- a/server/emails/templates/components/Footer.tsx +++ b/server/emails/templates/components/Footer.tsx @@ -62,6 +62,11 @@ export default ({ unsubscribeUrl, unsubscribeText, children }: Props) => { + {children && ( + + {children} + + )} {unsubscribeUrl && ( @@ -71,11 +76,6 @@ export default ({ unsubscribeUrl, unsubscribeText, children }: Props) => { )} - {children && ( - - {children} - - )} ); diff --git a/server/models/Integration.ts b/server/models/Integration.ts index 6f40a6f947..97139b42a9 100644 --- a/server/models/Integration.ts +++ b/server/models/Integration.ts @@ -118,6 +118,11 @@ class Integration extends ParanoidModel< case IntegrationType.Embed: { const settings = this .settings as IntegrationSettings; + + // Guests only need the URLs used to render and edit embeds. + if (viewer?.isGuest) { + return { url: settings?.url, diagrams: settings?.diagrams }; + } return { url: settings?.url, github: settings?.github, diff --git a/server/models/helpers/DocumentHelper.tsx b/server/models/helpers/DocumentHelper.tsx index 5a50ccd383..a116c6aecc 100644 --- a/server/models/helpers/DocumentHelper.tsx +++ b/server/models/helpers/DocumentHelper.tsx @@ -436,6 +436,23 @@ export class DocumentHelper { return output; } + /** + * Returns the document or collection as static HTML with its title. The + * output is rendered from the schema without node components or styles. + * + * @param model The document or collection to convert. + * @returns The title and content as a HTML string. + */ + static async toStaticHTML(model: Document | Collection) { + return ProsemirrorHelper.toStaticHTML(DocumentHelper.toProsemirror(model), { + title: model instanceof Collection ? model.name : model.title, + headingPrefix: + model instanceof Document + ? model.getPreference(DocumentPreference.HeadingPrefix) + : undefined, + }); + } + /** * Parse a list of mentions contained in a document or revision * diff --git a/server/models/helpers/NotificationHelper.test.ts b/server/models/helpers/NotificationHelper.test.ts index e9522773ca..c50cd350d8 100644 --- a/server/models/helpers/NotificationHelper.test.ts +++ b/server/models/helpers/NotificationHelper.test.ts @@ -6,6 +6,7 @@ import { buildComment, buildDocument, buildDraftDocument, + buildNotification, buildSubscription, buildUser, } from "@server/test/factories"; @@ -341,9 +342,180 @@ describe("NotificationHelper", () => { viewedBefore.id, ]); }); + + it("should not return users in the thread who unsubscribed from the document after they were involved", async () => { + const documentAuthor = await buildUser(); + const document = await buildDocument({ + userId: documentAuthor.id, + teamId: documentAuthor.teamId, + }); + const userInThread = await buildUser({ teamId: document.teamId }); + const parentComment = await buildComment({ + documentId: document.id, + userId: userInThread.id, + }); + await buildSubscription({ + userId: userInThread.id, + documentId: document.id, + deletedAt: addMinutes(new Date(), 1), + }); + const childComment = await buildComment({ + documentId: document.id, + userId: documentAuthor.id, + parentCommentId: parentComment.id, + }); + + const recipients = + await NotificationHelper.getCommentNotificationRecipients( + document, + childComment, + childComment.createdById + ); + + expect(recipients.length).toEqual(0); + }); + + it("should return users in the thread who were involved again after they unsubscribed from the document", async () => { + const documentAuthor = await buildUser(); + const document = await buildDocument({ + userId: documentAuthor.id, + teamId: documentAuthor.teamId, + }); + const userInThread = await buildUser({ teamId: document.teamId }); + await buildSubscription({ + userId: userInThread.id, + documentId: document.id, + deletedAt: subMinutes(new Date(), 1), + }); + const parentComment = await buildComment({ + documentId: document.id, + userId: userInThread.id, + }); + const childComment = await buildComment({ + documentId: document.id, + userId: documentAuthor.id, + parentCommentId: parentComment.id, + }); + + const recipients = + await NotificationHelper.getCommentNotificationRecipients( + document, + childComment, + childComment.createdById + ); + + expect(recipients.length).toEqual(1); + expect(recipients[0].id).toEqual(userInThread.id); + }); + + it("should return users in the thread who were mentioned after they unsubscribed from the document", async () => { + const documentAuthor = await buildUser(); + const document = await buildDocument({ + userId: documentAuthor.id, + teamId: documentAuthor.teamId, + }); + const userInThread = await buildUser({ teamId: document.teamId }); + const parentComment = await buildComment({ + documentId: document.id, + userId: userInThread.id, + }); + await buildSubscription({ + userId: userInThread.id, + documentId: document.id, + deletedAt: addMinutes(new Date(), 1), + }); + const mention = await buildNotification({ + event: NotificationEventType.MentionedInComment, + userId: userInThread.id, + teamId: document.teamId, + documentId: document.id, + commentId: parentComment.id, + }); + await sequelize.query( + 'UPDATE notifications SET "createdAt" = :createdAt WHERE id = :id', + { + replacements: { + createdAt: addMinutes(new Date(), 2), + id: mention.id, + }, + } + ); + const childComment = await buildComment({ + documentId: document.id, + userId: documentAuthor.id, + parentCommentId: parentComment.id, + }); + + const recipients = + await NotificationHelper.getCommentNotificationRecipients( + document, + childComment, + childComment.createdById + ); + + expect(recipients.map((recipient) => recipient.id)).toEqual([ + userInThread.id, + ]); + }); }); describe("getDocumentNotificationRecipients", () => { + it("should not return collection subscribers who opted out of the document later", async () => { + const documentAuthor = await buildUser(); + const document = await buildDocument({ + userId: documentAuthor.id, + teamId: documentAuthor.teamId, + }); + const subscribedUser = await buildUser({ teamId: document.teamId }); + await buildSubscription({ + userId: subscribedUser.id, + collectionId: document.collectionId!, + }); + await buildSubscription({ + userId: subscribedUser.id, + documentId: document.id, + deletedAt: addMinutes(new Date(), 1), + }); + + const recipients = + await NotificationHelper.getDocumentNotificationRecipients({ + document, + notificationType: NotificationEventType.UpdateDocument, + actorId: documentAuthor.id, + }); + + expect(recipients.length).toEqual(0); + }); + + it("should return collection subscribers who subscribed after they opted out of the document", async () => { + const documentAuthor = await buildUser(); + const document = await buildDocument({ + userId: documentAuthor.id, + teamId: documentAuthor.teamId, + }); + const subscribedUser = await buildUser({ teamId: document.teamId }); + await buildSubscription({ + userId: subscribedUser.id, + documentId: document.id, + deletedAt: subMinutes(new Date(), 1), + }); + await buildSubscription({ + userId: subscribedUser.id, + collectionId: document.collectionId!, + }); + + const recipients = + await NotificationHelper.getDocumentNotificationRecipients({ + document, + notificationType: NotificationEventType.UpdateDocument, + actorId: documentAuthor.id, + }); + + expect(recipients.map((recipient) => recipient.id)).toEqual([ + subscribedUser.id, + ]); + }); + it("should return users who have subscribed to the document", async () => { const documentAuthor = await buildUser(); const document = await buildDocument({ diff --git a/server/models/helpers/NotificationHelper.ts b/server/models/helpers/NotificationHelper.ts index f9bfc23a5c..381588ac71 100644 --- a/server/models/helpers/NotificationHelper.ts +++ b/server/models/helpers/NotificationHelper.ts @@ -7,7 +7,13 @@ import { } from "@shared/types"; import Logger from "@server/logging/Logger"; import type { Document, Collection } from "@server/models"; -import { User, Subscription, Comment, View } from "@server/models"; +import { + User, + Subscription, + Comment, + Notification, + View, +} from "@server/models"; import { canUserAccessDocument } from "@server/utils/permissions"; import { ProsemirrorHelper } from "./ProsemirrorHelper"; @@ -61,7 +67,7 @@ export default class NotificationHelper { // comment and all replies to it). if (comment.parentCommentId) { const contextComments = await Comment.findAll({ - attributes: ["createdById", "data"], + attributes: ["id", "createdById", "createdAt", "data"], where: { [Op.or]: [ { id: comment.parentCommentId }, @@ -80,10 +86,16 @@ export default class NotificationHelper { ) .map((mention) => mention.modelId); + const unsubscribedUserIds = await this.getUsersUnsubscribedFromThread( + document.id, + contextComments + ); const userIdsInThread = uniq([ ...createdUserIdsInThread, ...mentionedUserIdsInThread, - ]).filter((userId) => userId !== actorId); + ]).filter( + (userId) => userId !== actorId && !unsubscribedUserIds.has(userId) + ); recipients = await User.findAll({ where: { @@ -147,6 +159,60 @@ export default class NotificationHelper { return filtered; }; + /** + * Get the users who unsubscribed from the document and were not involved in + * the thread after they unsubscribed. A user is involved when they comment in + * the thread, or are mentioned in a comment in the thread. + * + * @param documentId The id of the document the thread belongs to. + * @param comments The comments in the thread. + * @returns The ids of the users that unsubscribed. + */ + public static getUsersUnsubscribedFromThread = async ( + documentId: string, + comments: Comment[] + ): Promise> => { + const deletedSubscriptions = await Subscription.findAll({ + attributes: ["userId", "deletedAt"], + where: { + documentId, + event: SubscriptionType.Document, + deletedAt: { [Op.ne]: null }, + }, + paranoid: false, + }); + if (!deletedSubscriptions.length) { + return new Set(); + } + + // Mention notifications record when a user was mentioned, including in edits. + const mentions = await Notification.unscoped().findAll({ + attributes: ["userId", "createdAt"], + where: { + event: NotificationEventType.MentionedInComment, + userId: deletedSubscriptions.map((subscription) => subscription.userId), + commentId: comments.map((comment) => comment.id), + }, + }); + + return new Set( + deletedSubscriptions + .filter( + ({ userId, deletedAt }) => + !!deletedAt && + !comments.some( + (comment) => + comment.createdById === userId && comment.createdAt > deletedAt + ) && + !mentions.some( + (mention) => + mention.userId === userId && mention.createdAt > deletedAt + ) + ) + .map((subscription) => subscription.userId) + ); + }; + /** * Get the recipients of a notification for a document event. * @@ -185,29 +251,53 @@ export default class NotificationHelper { const userFilter = { userId: { [Op.ne]: actorId } }; const userInclude = [{ association: "user" as const, required: true }]; - const [collectionSubs, documentSubs] = await Promise.all([ - document.collectionId - ? Subscription.findAll({ - where: { - ...userFilter, - event: SubscriptionType.Document, - collectionId: document.collectionId, - }, - include: userInclude, - }) - : [], - Subscription.findAll({ - where: { - ...userFilter, - event: SubscriptionType.Document, - documentId: document.id, - }, - include: userInclude, - }), - ]); + const [collectionSubs, documentSubs]: Subscription[][] = + await Promise.all([ + document.collectionId + ? Subscription.findAll({ + where: { + ...userFilter, + event: SubscriptionType.Document, + collectionId: document.collectionId, + }, + include: userInclude, + }) + : [], + Subscription.findAll({ + where: { + ...userFilter, + event: SubscriptionType.Document, + documentId: document.id, + }, + include: userInclude, + }), + ]); + + // A document opt-out takes precedence over an older collection subscription. + const optedOut = collectionSubs.length + ? await Subscription.findAll({ + attributes: ["userId", "deletedAt"], + where: { + event: SubscriptionType.Document, + documentId: document.id, + userId: collectionSubs.map((s) => s.userId), + deletedAt: { [Op.ne]: null }, + }, + paranoid: false, + }) + : []; + const activeCollectionSubs = collectionSubs.filter( + (collectionSub) => + !optedOut.some( + (optOut) => + optOut.userId === collectionSub.userId && + !!optOut.deletedAt && + optOut.deletedAt > collectionSub.updatedAt + ) + ); recipients = uniqBy( - [...collectionSubs, ...documentSubs].map((s) => s.user), + [...activeCollectionSubs, ...documentSubs].map((s) => s.user), (user) => user.id ); } diff --git a/server/models/helpers/ProseMirrorHelper.test.ts b/server/models/helpers/ProseMirrorHelper.test.ts index 679c8e22dc..b409a8093c 100644 --- a/server/models/helpers/ProseMirrorHelper.test.ts +++ b/server/models/helpers/ProseMirrorHelper.test.ts @@ -5,7 +5,7 @@ import type { DeepPartial } from "utility-types"; import { prosemirrorToYDoc, yDocToProsemirrorJSON } from "y-prosemirror"; import * as Y from "yjs"; import type { ProsemirrorData } from "@shared/types"; -import { MentionType } from "@shared/types"; +import { HeadingPrefixStyle, MentionType } from "@shared/types"; import { ProsemirrorHelper as SharedProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { createContext } from "@server/context"; import { parser, schema, serializer } from "@server/editor"; @@ -99,6 +99,57 @@ describe("ProsemirrorHelper", () => { }); }); + describe("toStaticHTML", () => { + it("should render the title and content", async () => { + const doc = parser.parse("Hello **world**")!; + const html = await ProsemirrorHelper.toStaticHTML(doc, { + title: "Title", + }); + expect(html).toContain('

<b>Title</b>

'); + expect(html).toContain('
'); + expect(html).toContain("world"); + }); + + it("should apply the heading prefix", async () => { + const doc = parser.parse("# One\n\n## Two")!; + const html = await ProsemirrorHelper.toStaticHTML(doc, { + headingPrefix: HeadingPrefixStyle.Numeric, + }); + expect(html).toContain('data-heading-prefix="1."'); + expect(html).toContain('data-heading-prefix="1.1"'); + }); + + it("should render every node and mark without a global document", async () => { + expect(globalThis.document).toBeUndefined(); + + const requiredAttrs: Record> = { + attachment: { title: "file.pdf" }, + comment: { id: "comment-id", userId: "user-id" }, + embed: { href: "https://example.com" }, + mention: { label: "Label", modelId: "model-id" }, + }; + const nodes = Object.values(schema.nodes) + .filter((type) => type !== schema.topNodeType) + .map((type) => + type.isText + ? schema.text("text") + : type.createAndFill(requiredAttrs[type.name]) + ) + .filter((node) => node !== null); + const marked = Object.values(schema.marks).map((type) => + schema.text("marked", [type.create(requiredAttrs[type.name])]) + ); + const doc = schema.topNodeType.create(null, [ + ...nodes, + schema.nodes.paragraph.create(null, marked), + ]); + + await expect(ProsemirrorHelper.toStaticHTML(doc)).resolves.toContain( + "marked" + ); + }); + }); + describe("processMentions", () => { it("should handle deleted users", async () => { const user = await buildUser(); diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index df5178fae0..91fb953c6a 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -10,7 +10,7 @@ import { EditorView, type DecorationSource, } from "prosemirror-view"; -import { Node, Fragment } from "prosemirror-model"; +import { DOMSerializer, Node, Fragment } from "prosemirror-model"; import { Transform } from "prosemirror-transform"; import { renderToString } from "react-dom/server"; import styled, { ServerStyleSheet, ThemeProvider } from "styled-components"; @@ -886,9 +886,66 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { }); } + /** + * Converts a ProseMirror node to static HTML from the `toDOM` specs of the + * schema. Unlike toHTML it does not mount an editor or node components, so + * it is cheaper and can run concurrently, but the output has no styles. + * + * @param node The node to convert to HTML. + * @param options Options for the HTML output. + * @returns The content as a HTML string. + */ + public static async toStaticHTML( + node: Node, + options?: Pick + ): Promise { + const doc = await ProsemirrorHelper.getStaticDocument(); + const rtl = isRTL(node.textBetween(0, Math.min(node.content.size, 100))); + const article = doc.createElement("article"); + + if (options?.title) { + const title = doc.createElement("h1"); + title.setAttribute("dir", rtl ? "rtl" : "ltr"); + title.textContent = options.title; + article.appendChild(title); + } + + const content = doc.createElement("div"); + content.id = "content"; + content.className = "ProseMirror exported"; + content.appendChild( + DOMSerializer.fromSchema(schema).serializeFragment(node.content, { + document: doc, + }) + ); + article.appendChild(content); + + if (options?.headingPrefix) { + HeadingPrefixHelper.applyToDOM(content, node, options.headingPrefix); + } + + return article.outerHTML; + } + /** Promise chain serializing HTML exports within the process. */ private static htmlRenderQueue: Promise = Promise.resolve(); + /** Detached document that static HTML is built in, created on first use. */ + private static staticDocument?: Promise; + + /** + * Returns the shared detached document for static HTML. Loads jsdom lazily + * to keep it off the startup path. + * + * @returns A promise that resolves to the document. + */ + private static getStaticDocument(): Promise { + ProsemirrorHelper.staticDocument ??= import("jsdom").then( + ({ JSDOM }) => new JSDOM().window.document + ); + return ProsemirrorHelper.staticDocument; + } + /** * Flushes React passive effects and the follow-on renders they trigger by * yielding a couple of macrotask turns. Turn 1 flushes passive effects, and diff --git a/server/policies/integration.ts b/server/policies/integration.ts index b4850c2f3d..b5d5ab7cb1 100644 --- a/server/policies/integration.ts +++ b/server/policies/integration.ts @@ -14,7 +14,14 @@ allow(User, "createIntegration", Team, (actor, team) => and(isTeamAdmin(actor, team), isTeamMutable(actor)) ); -allow(User, "read", Integration, isTeamModel); +allow(User, "read", Integration, (actor, integration) => + and( + isTeamModel(actor, integration), + integration?.type === IntegrationType.LinkedAccount + ? isOwner(actor, integration) + : !actor.isGuest || integration?.type === IntegrationType.Embed + ) +); allow(User, ["update", "delete"], Integration, (actor, integration) => and( diff --git a/server/queues/tasks/CommentUpdatedNotificationsTask.ts b/server/queues/tasks/CommentUpdatedNotificationsTask.ts index c056ddc9e9..40cfe1695f 100644 --- a/server/queues/tasks/CommentUpdatedNotificationsTask.ts +++ b/server/queues/tasks/CommentUpdatedNotificationsTask.ts @@ -2,6 +2,7 @@ import invariant from "invariant"; import { Op } from "sequelize"; import { MentionType, NotificationEventType } from "@shared/types"; import { Comment, Document, Group, Notification, User } from "@server/models"; +import NotificationHelper from "@server/models/helpers/NotificationHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import type { CommentEvent, CommentUpdateEvent } from "@server/types"; import { canUserAccessDocument } from "@server/utils/permissions"; @@ -127,6 +128,14 @@ export default class CommentUpdatedNotificationsTask extends BaseTask { expect(body.data.length).toEqual(1); expect(body.data[0].settings.url).toEqual("https://example.com"); }); + + it("should only expose embed urls to guests", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + const guest = await buildGuestUser({ teamId: team.id }); + await buildIntegration({ + userId: admin.id, + teamId: team.id, + service: IntegrationService.GitHub, + type: IntegrationType.Embed, + settings: { + url: "https://example.com", + github: { + installation: { + id: 123, + account: { id: 456, name: "acme", avatarUrl: "" }, + }, + }, + }, + }); + await buildIntegration({ + userId: admin.id, + teamId: team.id, + service: IntegrationService.Slack, + type: IntegrationType.Post, + settings: { + url: "https://hooks.slack.com/services/secret", + channel: "#general", + channelId: "C123", + } as IntegrationSettings, + }); + + const res = await server.post("/api/integrations.list", guest); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].type).toEqual(IntegrationType.Embed); + expect(body.data[0].settings.url).toEqual("https://example.com"); + expect(body.data[0].settings.github).toBeUndefined(); + }); }); describe("#integrations.info", () => { @@ -308,7 +350,7 @@ describe("#integrations.info", () => { expect(body.data.settings.figma.account.email).toEqual("owner@example.com"); }); - it("should not expose linked account settings to other users", async () => { + it("should not allow other users to read a linked account", async () => { const owner = await buildUser(); const admin = await buildAdmin({ teamId: owner.teamId }); const integration = await buildFigmaAccount(owner); @@ -316,9 +358,29 @@ describe("#integrations.info", () => { const res = await server.post("/api/integrations.info", admin, { body: { id: integration.id }, }); - const body = await res.json(); - expect(res.status).toEqual(200); - expect(body.data.settings).toBeUndefined(); + expect(res.status).toEqual(403); + }); + + it("should not allow guests to read workspace integrations", async () => { + const admin = await buildAdmin(); + const guest = await buildGuestUser({ teamId: admin.teamId }); + const integration = await buildIntegration({ + userId: admin.id, + teamId: admin.teamId, + service: IntegrationService.Slack, + type: IntegrationType.Post, + settings: { + url: "https://hooks.slack.com/services/secret", + channel: "#general", + channelId: "C123", + } as IntegrationSettings, + }); + + const res = await server.post("/api/integrations.info", guest, { + body: { id: integration.id }, + }); + + expect(res.status).toEqual(403); }); }); diff --git a/server/routes/api/integrations/integrations.ts b/server/routes/api/integrations/integrations.ts index 244a79eea3..c528327807 100644 --- a/server/routes/api/integrations/integrations.ts +++ b/server/routes/api/integrations/integrations.ts @@ -35,15 +35,16 @@ router.post( where = { ...where, service }; } - // Linked account is special as these are user-specific, other integrations are workspace-wide. + // Linked account is special as these are user-specific, other integrations + // are workspace-wide. Guests only receive embeds, which the editor needs. where = { ...where, [Op.or]: [ { userId: user.id, type: IntegrationType.LinkedAccount }, { - type: { - [Op.not]: IntegrationType.LinkedAccount, - }, + type: user.isGuest + ? IntegrationType.Embed + : { [Op.not]: IntegrationType.LinkedAccount }, }, ], }; diff --git a/server/routes/api/subscriptions/subscriptions.test.ts b/server/routes/api/subscriptions/subscriptions.test.ts index 0b7a0a98a0..3df9089488 100644 --- a/server/routes/api/subscriptions/subscriptions.test.ts +++ b/server/routes/api/subscriptions/subscriptions.test.ts @@ -1,3 +1,4 @@ +import { subDays } from "date-fns"; import queryString from "query-string"; import { QueryNotices, SubscriptionType } from "@shared/types"; import { Event, Subscription } from "@server/models"; @@ -762,7 +763,7 @@ describe("#subscriptions.delete", () => { expect(await Subscription.findByPk(subscription.id)).toBeNull(); }); - it("should delete user's collection subscription", async () => { + it("should keep the collection subscription and record a document opt-out", async () => { const user = await buildUser(); const document = await buildDocument({ userId: user.id, @@ -787,24 +788,57 @@ describe("#subscriptions.delete", () => { expect(res.status).toEqual(302); expect(res.headers.get("location")).toContain( - `/home?notice=${QueryNotices.UnsubscribeCollection}` + `/home?notice=${QueryNotices.UnsubscribeDocument}` ); - expect(await Subscription.findByPk(subscription.id)).toBeNull(); + expect(await Subscription.findByPk(subscription.id)).not.toBeNull(); + + const optOut = await Subscription.findOne({ + where: { userId: user.id, documentId: document.id }, + paranoid: false, + }); + expect(optOut?.deletedAt).toBeTruthy(); }); - it("should not fail if subscription is already deleted", async () => { + it("should record a document opt-out when no subscription exists", async () => { const user = await buildUser(); const document = await buildDocument({ userId: user.id, teamId: user.teamId, }); + + 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); + const optOut = await Subscription.findOne({ + where: { userId: user.id, documentId: document.id }, + paranoid: false, + }); + expect(optOut?.deletedAt).toBeTruthy(); + }); + + it("should refresh the opt-out if subscription is already deleted", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const deletedAt = subDays(new Date(), 1); const subscription = await buildSubscription({ userId: user.id, documentId: document.id, + deletedAt, }); - await subscription.destroy(); - const res = await server.get( `/api/subscriptions.delete?${queryString.stringify({ userId: user.id, @@ -820,6 +854,11 @@ describe("#subscriptions.delete", () => { expect(res.status).toEqual(302); expect(res.headers.get("location")).toContain(`/home`); expect(await Subscription.findByPk(subscription.id)).toBeNull(); + + await subscription.reload({ paranoid: false }); + expect(subscription.deletedAt!.getTime()).toBeGreaterThan( + deletedAt.getTime() + ); }); }); diff --git a/server/routes/api/subscriptions/subscriptions.ts b/server/routes/api/subscriptions/subscriptions.ts index 0c07b5d1fb..012191adee 100644 --- a/server/routes/api/subscriptions/subscriptions.ts +++ b/server/routes/api/subscriptions/subscriptions.ts @@ -1,7 +1,7 @@ import Router from "@koa/router"; import type { WhereOptions } from "sequelize"; import { Transaction } from "sequelize"; -import { QueryNotices } from "@shared/types"; +import { QueryNotices, SubscriptionType } from "@shared/types"; import subscriptionCreator from "@server/commands/subscriptionCreator"; import { createContext } from "@server/context"; import env from "@server/env"; @@ -179,64 +179,55 @@ router.get( return; } - // Queries within a transaction share a single connection, so they are run - // sequentially rather than with Promise.all. - const documentSubscription = await Subscription.findOne({ - where: { - userId, - documentId, - }, - lock: Transaction.LOCK.UPDATE, - transaction, - }); - const document = await Document.unscoped().findOne({ - attributes: ["collectionId"], - where: { - id: documentId, - }, - paranoid: false, - transaction, - }); const user = await User.scope("withTeam").findByPk(userId, { rejectOnEmpty: true, transaction, }); - const context = createContext({ - user, - ip: ctx.request.ip, + // Always record a fresh opt-out, also when no active subscription exists. + const documentSubscription = await Subscription.findOne({ + where: { + userId, + documentId, + event: SubscriptionType.Document, + }, + paranoid: false, + lock: Transaction.LOCK.UPDATE, transaction, }); - const collectionSubscription = document?.collectionId - ? await Subscription.findOne({ - where: { - userId, - collectionId: document.collectionId, - }, - lock: Transaction.LOCK.UPDATE, + if (!documentSubscription) { + await Subscription.create( + { + userId, + documentId, + event: SubscriptionType.Document, + deletedAt: new Date(), + }, + { transaction } + ); + } else if (documentSubscription.deletedAt) { + await Subscription.update( + { deletedAt: new Date() }, + { + where: { id: documentSubscription.id }, + paranoid: false, + transaction, + } + ); + } else { + authorize(user, "delete", documentSubscription); + await documentSubscription.destroyWithCtx( + createContext({ + user, + ip: ctx.request.ip, 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=${ - collectionSubscription - ? QueryNotices.UnsubscribeCollection - : documentSubscription - ? QueryNotices.UnsubscribeDocument - : "" - }` + `${user.team.url}/home?notice=${QueryNotices.UnsubscribeDocument}` ); } ); diff --git a/server/routes/api/urls/urls.test.ts b/server/routes/api/urls/urls.test.ts index e2c58aac49..4874844aa1 100644 --- a/server/routes/api/urls/urls.test.ts +++ b/server/routes/api/urls/urls.test.ts @@ -12,6 +12,7 @@ import { buildDocument, buildShare, buildTeam, + buildGuestUser, buildUser, } from "@server/test/factories"; import Redis from "@server/storage/redis"; @@ -559,6 +560,22 @@ Install instructions here.` ); }); + it("should not unfurl external urls for guests", async () => { + const guest = await buildGuestUser({ teamId: user.teamId }); + const callCount = (Iframely.requestResource as Mock).mock.calls.length; + + const res = await server.post("/api/urls.unfurl", guest, { + body: { + url: "https://github.com/acme/private/issues/1", + }, + }); + + expect(res.status).toEqual(204); + expect((Iframely.requestResource as Mock).mock.calls.length).toEqual( + callCount + ); + }); + it("should succeed with status 204 no content for a non-existing external url", async () => { (Iframely.requestResource as Mock).mockResolvedValue( Promise.resolve({ diff --git a/server/routes/api/urls/urls.ts b/server/routes/api/urls/urls.ts index 51d30c0a43..c7185390ec 100644 --- a/server/routes/api/urls/urls.ts +++ b/server/routes/api/urls/urls.ts @@ -190,7 +190,12 @@ router.post( return; } - // External resources + // External resources are unfurled with workspace credentials + if (actor.isGuest) { + ctx.response.status = 204; + return; + } + // Use getDataOrSet which handles distributed locking to prevent thundering herd // when multiple clients request the same URL simultaneously const cacheKey = RedisPrefixHelper.getUnfurlKey( diff --git a/server/routes/app.ts b/server/routes/app.ts index cb40e70cff..0e88395179 100644 --- a/server/routes/app.ts +++ b/server/routes/app.ts @@ -3,6 +3,7 @@ import path from "node:path"; import util from "node:util"; import type { Context, Next } from "koa"; import { escape } from "es-toolkit/compat"; +import { isbot } from "isbot"; import { Sequelize } from "sequelize"; import isUUID from "validator/lib/isUUID"; import { @@ -15,12 +16,16 @@ import { Hour } from "@shared/utils/time"; import env from "@server/env"; import { allowFraming, allowScriptSrc } from "@server/middlewares/csp"; import { Integration } from "@server/models"; +import type { Collection, Document } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import IntegrationHelper from "@server/models/helpers/IntegrationHelper"; +import { TextHelper } from "@server/models/helpers/TextHelper"; import presentEnv from "@server/presenters/env"; +import { CacheHelper } from "@server/utils/CacheHelper"; import { getTeamFromContext } from "@server/utils/passport"; import prefetchTags from "@server/utils/prefetchTags"; import readManifestFile from "@server/utils/readManifestFile"; +import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper"; import { loadPublicShare } from "@server/commands/shareLoader"; const readFile = util.promisify(fs.readFile); @@ -52,6 +57,28 @@ function formatChildDocumentsAsMarkdown( return `\n\n---\n\n**Documents**\n\n${lines.join("\n")}`; } +/** + * Renders the server-side HTML of a shared document or collection. The HTML is + * cached for each version of the model, and attachment urls are signed on each + * request. + * + * @param model The shared document or collection. + * @returns The HTML string, or undefined if it could not be rendered. + */ +async function renderShareContent( + model: Document | Collection +): Promise { + const html = await CacheHelper.getDataOrSet( + RedisPrefixHelper.getShareContentKey(model.id, model.updatedAt), + () => DocumentHelper.toStaticHTML(model), + Hour.seconds + ); + if (!html) { + return undefined; + } + return TextHelper.attachmentsToSignedUrls(html, model.teamId, Hour.seconds); +} + /** * Builds Open Graph and Twitter card meta tags for link unfurls. * @@ -270,6 +297,7 @@ export const renderShare = async (ctx: Context, next: Next) => { // Find the share record if published so that the document title can be returned // in the server-rendered HTML. This allows it to appear in unfurls more reliably. let share, collection, document, team; + const isBot = isbot(ctx.get("user-agent")); let analytics: Integration[] = []; let sharedTree; @@ -298,7 +326,7 @@ export const renderShare = async (ctx: Context, next: Next) => { share.teamId ); - if (share && !ctx.userAgent.isBot) { + if (share && !isBot) { await share.update( { lastAccessedAt: new Date(), @@ -385,15 +413,9 @@ export const renderShare = async (ctx: Context, next: Next) => { ? ((await team.publicAvatarUrl()) ?? undefined) : undefined; - const content = - document || collection - ? await DocumentHelper.toHTML(document || collection!, { - includeStyles: false, - includeHead: false, - includeTitle: true, - signedUrls: Hour.seconds, - }) - : undefined; + // Only bots read the server-rendered content, so skip the render for others. + const model = document || collection; + const content = model && isBot ? await renderShareContent(model) : undefined; const canonicalUrl = share ? `${share.canonicalUrl}${ diff --git a/server/routes/index.test.ts b/server/routes/index.test.ts index 29ac53ff2a..a08a7ddcf3 100644 --- a/server/routes/index.test.ts +++ b/server/routes/index.test.ts @@ -6,8 +6,10 @@ import { TeamPreference, } from "@shared/types"; import { parseSessionsCookie } from "@shared/utils/sessions"; +import { parser } from "@server/editor"; import env from "@server/env"; import { + buildAttachment, buildShare, buildDocument, buildIntegration, @@ -17,6 +19,11 @@ import { getTestServer } from "@server/test/support"; const server = getTestServer(); +const botHeaders = { + "User-Agent": + "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", +}; + describe("/s/:id", () => { it("should return standard title in html when loading unpublished share", async () => { const share = await buildShare({ @@ -109,6 +116,60 @@ describe("/s/:id", () => { expect(body).toContain(`${document.title}`); }); + it("should render document content with signed attachment urls", async () => { + const team = await buildTeam(); + const attachment = await buildAttachment({ teamId: team.id }); + const document = await buildDocument({ + teamId: team.id, + text: `Shared content\n\n![image](${attachment.redirectUrl})`, + }); + const share = await buildShare({ + documentId: document.id, + teamId: document.teamId, + }); + const res = await server.get(`/s/${share.id}`, { headers: botHeaders }); + const body = await res.text(); + expect(res.status).toEqual(200); + expect(body).toContain("Shared content"); + expect(body).toContain(" { + const document = await buildDocument({ text: "Shared content" }); + const share = await buildShare({ + documentId: document.id, + teamId: document.teamId, + }); + const res = await server.get(`/s/${share.id}`, { + headers: { + "User-Agent": + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", + }, + }); + const body = await res.text(); + expect(res.status).toEqual(200); + expect(body).toContain(`${document.title}`); + expect(body).not.toContain('
{ + const document = await buildDocument({ text: "First version" }); + const share = await buildShare({ + documentId: document.id, + teamId: document.teamId, + }); + const first = await server.get(`/s/${share.id}`, { headers: botHeaders }); + expect(await first.text()).toContain("First version"); + + document.content = parser.parse("Second version")?.toJSON(); + await document.save(); + const second = await server.get(`/s/${share.id}`, { + headers: botHeaders, + }); + expect(await second.text()).toContain("Second version"); + }); + it("should return markdown when Accept header prefers text/markdown", async () => { const document = await buildDocument(); const share = await buildShare({ diff --git a/server/utils/RedisPrefixHelper.ts b/server/utils/RedisPrefixHelper.ts index 695d194ea2..8dca8edbe9 100644 --- a/server/utils/RedisPrefixHelper.ts +++ b/server/utils/RedisPrefixHelper.ts @@ -36,6 +36,18 @@ export class RedisPrefixHelper { return `cd:${collectionId}`; } + /** + * Gets key for caching the rendered HTML of a shared document or collection. + * The key changes when the model is updated. + * + * @param id The document or collection ID. + * @param updatedAt The time the model was last updated. + * @returns the cache key string. + */ + public static getShareContentKey(id: string, updatedAt: Date) { + return `share:html:${id}:${updatedAt.getTime()}`; + } + /** * Gets key for caching embed check results. This is a global cache key * (not team-specific) since embed headers are the same for all users. diff --git a/server/utils/redirectOnClient.ts b/server/utils/redirectOnClient.ts index 6b4cd050a4..3977f1e491 100644 --- a/server/utils/redirectOnClient.ts +++ b/server/utils/redirectOnClient.ts @@ -1,4 +1,5 @@ import { escape } from "es-toolkit/compat"; +import { isbot } from "isbot"; import type { Context } from "koa"; import { addMissingUrlPort } from "@shared/utils/urls"; @@ -33,7 +34,7 @@ export function redirectOnClient( // Bots are shown a manual submit button instead of auto-submitting, so that // link scanners in email clients don't follow the redirect. - const isBot = this.userAgent.isBot; + const isBot = isbot(this.get("user-agent")); if (isBot) { formFields += ` diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 930dddfb3a..c05ef1a4e8 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -221,7 +221,7 @@ "{{ count }} share link revoked_plural": "{{ count }} share links revoked", "Could not revoke {{ count }} share link": "Could not revoke {{ count }} share link", "Could not revoke {{ count }} share link_plural": "Could not revoke {{ count }} share links", - "{{ name }} (Logged out)": "{{ name }} (Logged out)", + "Logged out": "Logged out", "Switch workspace": "Switch workspace", "Select a workspace": "Select a workspace", "New workspace": "New workspace", @@ -1159,7 +1159,6 @@ "This doesn’t appear to be a valid installation": "This doesn’t appear to be a valid installation", "Choose a workspace": "Choose a workspace", "Choose an {{ appName }} workspace or log in to continue connecting this app": "Choose an {{ appName }} workspace or log in to continue connecting this app", - "Logged out": "Logged out", "Create workspace": "Create workspace", "Set up your workspace by providing a name and details for admin login. You can change these later.": "Set up your workspace by providing a name and details for admin login. You can change these later.", "Workspace name": "Workspace name", @@ -1846,6 +1845,7 @@ "View Thread": "View Thread", "{{ actorName }} replied to a thread in": "{{ actorName }} replied to a thread in", "{{ actorName }} commented on": "{{ actorName }} commented on", + "Unsubscribe from this doc": "Unsubscribe from this doc", "Mentioned you in “{{ documentTitle }}”": "Mentioned you in “{{ documentTitle }}”", "{{ actorName }} mentioned you in a thread": "{{ actorName }} mentioned you in a thread", "{{ actorName }} mentioned you in a comment on “{{ documentTitle }}”": "{{ actorName }} mentioned you in a comment on “{{ documentTitle }}”", @@ -1892,7 +1892,6 @@ "{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”_plural": "{{ actorName }} {{ eventName }} the document “{{ documentTitle }}”", "{{ actorName }} {{ eventName }} the document": "{{ actorName }} {{ eventName }} the document", "{{ actorName }} {{ eventName }} the document_plural": "{{ actorName }} {{ eventName }} the document", - "Unsubscribe from this doc": "Unsubscribe from this doc", "{{ actorName }} shared “{{ documentTitle }}” with you": "{{ actorName }} shared “{{ documentTitle }}” with you", "{{ actorName }} shared a document": "{{ actorName }} shared a document", "{{ actorName }} shared “{{ documentTitle }}” with you.": "{{ actorName }} shared “{{ documentTitle }}” with you.", diff --git a/yarn.lock b/yarn.lock index de6226332d..7b197e64f0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11839,6 +11839,13 @@ __metadata: languageName: node linkType: hard +"isbot@npm:^5.2.2": + version: 5.2.2 + resolution: "isbot@npm:5.2.2" + checksum: 10c0/df8356dd8745d7fe1922fc8df894bf5560fe959ad7826ac97311c430dc9c6dd628c8aab68d3e45769b50b61411bd4530d874aae07947f6cd04e25206566a7bb3 + languageName: node + linkType: hard + "isexe@npm:^2.0.0": version: 2.0.0 resolution: "isexe@npm:2.0.0" @@ -14078,6 +14085,7 @@ __metadata: ioredis: "npm:^5.11.1" ioredis-mock: "npm:^8.13.1" ipaddr.js: "npm:^2.5.0" + isbot: "npm:^5.2.2" iso-639-3: "npm:^3.0.1" js-yaml: "npm:^4.3.2" js.foresight: "npm:^4.2.1"