Merge remote-tracking branch 'origin/main' into claude/document-owners

# Conflicts:
#	shared/i18n/locales/en_US/translation.json
This commit is contained in:
Tom Moor committed 2026-11-01 10:11:48 -05:00
commit e4cfabf99b
35 files changed
+960 -146

No files matched your search

+12
View File
@@ -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": {
+8 -14
View File
@@ -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: <MarkdownIcon />,
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: <CodeIcon />,
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: <ArchiveIcon />,
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: <PDFIcon />,
iconInContextMenu: false,
@@ -1818,12 +1815,9 @@ const headingPrefixNames: Record<HeadingPrefixStyle, (t: TFunction) => 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",
+2 -4
View File
@@ -25,10 +25,8 @@ export const switchTeamsList = ({ stores }: { stores: RootStore }) =>
stores.auth.availableTeams?.map<ExternalLinkAction>((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",
+4
View File
@@ -152,6 +152,7 @@ export function actionToMenuItem(
const visible = resolve<boolean>(action.visible, context) ?? true;
const disabled = resolve<boolean>(action.disabled, context);
const shortcut = resolve<string[] | undefined>(action.shortcut, context);
const badge = resolve<React.ReactNode>(action.badge, context);
const icon =
!!action.icon && action.iconInContextMenu !== false
? resolve<React.ReactNode>(action.icon, context)
@@ -169,6 +170,7 @@ export function actionToMenuItem(
selected: resolve<boolean>(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,
+12
View File
@@ -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}
<Components.MenuLabel>{item.title}</Components.MenuLabel>
{item.badge && (
<Components.MenuBadge>{item.badge}</Components.MenuBadge>
)}
{item.selected !== undefined && (
<Components.SelectedIconWrapper aria-hidden>
{item.selected ? <CheckmarkIcon size={18} /> : null}
@@ -199,6 +205,9 @@ export function toMobileMenuItems(
>
{icon}
<Components.MenuLabel>{item.title}</Components.MenuLabel>
{item.badge && (
<Components.MenuBadge>{item.badge}</Components.MenuBadge>
)}
</Components.MenuInternalLink>
);
@@ -215,6 +224,9 @@ export function toMobileMenuItems(
>
{icon}
<Components.MenuLabel>{item.title}</Components.MenuLabel>
{item.badge && (
<Components.MenuBadge>{item.badge}</Components.MenuBadge>
)}
</Components.MenuExternalLink>
);
+9 -2
View File
@@ -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}
<Components.MenuLabel>{label}</Components.MenuLabel>
{badge && <Components.MenuBadge>{badge}</Components.MenuBadge>}
{selected !== undefined && (
<Components.SelectedIconWrapper aria-hidden>
{selected ? <CheckmarkIcon size={18} /> : 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) {
<Components.MenuInternalLink to={to} disabled={disabled}>
{icon}
<Components.MenuLabel>{label}</Components.MenuLabel>
{badge && <Components.MenuBadge>{badge}</Components.MenuBadge>}
<MenuItemShortcut shortcut={shortcut} />
</Components.MenuInternalLink>
</Item>
@@ -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}
<Components.MenuLabel>{label}</Components.MenuLabel>
{badge && <Components.MenuBadge>{badge}</Components.MenuBadge>}
<MenuItemShortcut shortcut={shortcut} />
</Components.MenuExternalLink>
</Item>
@@ -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;
+3
View File
@@ -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 = {
+1
View File
@@ -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",
+81
View File
@@ -0,0 +1,81 @@
import { APIErrorCode, APIResponseError } from "@notionhq/client";
import { Headers } from "node-fetch";
import { NotionClient } from "./notion";
const rateLimitError = (headers: Record<string, string> = {}) =>
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);
});
});
+56 -15
View File
@@ -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<typeof RateLimit>;
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<T>(apiCall: () => Promise<T>): Promise<T> {
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<string, string>;
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",
+7
View File
@@ -34,6 +34,13 @@
}
]
}
],
"no-restricted-properties": [
"error",
{
"property": "isBot",
"message": "Use `isbot` from the `isbot` package instead"
}
]
},
"plugins": ["import"]
@@ -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}
<Footer
unsubscribeUrl={unsubscribeUrl}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
>
<Link
href={SubscriptionHelper.unsubscribeUrl(
props.userId,
props.documentId
)}
>
{this.t("Unsubscribe from this doc")}
</Link>
</Footer>
</EmailTemplate>
);
}
@@ -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<
<Footer
unsubscribeUrl={unsubscribeUrl}
unsubscribeText={this.t("Unsubscribe from these emails")}
/>
>
<Link
href={SubscriptionHelper.unsubscribeUrl(
props.userId,
props.documentId
)}
>
{this.t("Unsubscribe from this doc")}
</Link>
</Footer>
</EmailTemplate>
);
}
@@ -62,6 +62,11 @@ export default ({ unsubscribeUrl, unsubscribeText, children }: Props) => {
</a>
</TD>
</TR>
{children && (
<TR>
<TD style={footerLinkStyle}>{children}</TD>
</TR>
)}
{unsubscribeUrl && (
<TR>
<TD style={footerLinkStyle}>
@@ -71,11 +76,6 @@ export default ({ unsubscribeUrl, unsubscribeText, children }: Props) => {
</TD>
</TR>
)}
{children && (
<TR>
<TD style={footerLinkStyle}>{children}</TD>
</TR>
)}
</TBody>
</Table>
);
+5
View File
@@ -118,6 +118,11 @@ class Integration<T = unknown> extends ParanoidModel<
case IntegrationType.Embed: {
const settings = this
.settings as IntegrationSettings<IntegrationType.Embed>;
// 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,
+17
View File
@@ -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
*
@@ -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({
+114 -24
View File
@@ -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<Set<string>> => {
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
);
}
@@ -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: "<b>Title</b>",
});
expect(html).toContain('<h1 dir="ltr">&lt;b&gt;Title&lt;/b&gt;</h1>');
expect(html).toContain('<div id="content" class="ProseMirror exported">');
expect(html).toContain("<strong>world</strong>");
});
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<string, Record<string, string>> = {
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();
+58 -1
View File
@@ -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<HTMLOptions, "title" | "headingPrefix">
): Promise<string> {
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<void> = Promise.resolve();
/** Detached document that static HTML is built in, created on first use. */
private static staticDocument?: Promise<Document>;
/**
* 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<Document> {
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
+8 -1
View File
@@ -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(
@@ -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<CommentEve
// Don't notify resolver
userIdsNotified.push(event.actorId);
// Don't notify users that unsubscribed from the document
const unsubscribedUserIds =
await NotificationHelper.getUsersUnsubscribedFromThread(
document.id,
commentsAndReplies
);
userIdsNotified.push(...unsubscribedUserIds);
for (const item of commentsAndReplies) {
// Mentions:
const proseCommentData = ProsemirrorHelper.toProsemirror(item.data);
@@ -6,6 +6,7 @@ import {
buildAdmin,
buildTeam,
buildUser,
buildGuestUser,
buildIntegration,
} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
@@ -274,6 +275,47 @@ describe("#integrations.list", () => {
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<IntegrationType.Post>,
});
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<IntegrationType.Post>,
});
const res = await server.post("/api/integrations.info", guest, {
body: { id: integration.id },
});
expect(res.status).toEqual(403);
});
});
@@ -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 },
},
],
};
@@ -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()
);
});
});
@@ -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}`
);
}
);
+17
View File
@@ -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({
+6 -1
View File
@@ -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(
+32 -10
View File
@@ -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<string | undefined> {
const html = await CacheHelper.getDataOrSet<string>(
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<IntegrationType.Analytics>[] = [];
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}${
+61
View File
@@ -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(`<title>${document.title}</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("<img");
expect(body).not.toContain(attachment.redirectUrl);
});
it("should not render document content for browsers", async () => {
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(`<title>${document.title}</title>`);
expect(body).not.toContain('<div id="content"');
});
it("should render updated content after the document changes", async () => {
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({
+12
View File
@@ -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.
+2 -1
View File
@@ -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 += `
+2 -3
View File
@@ -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.",
+8
View File
@@ -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"