diff --git a/.dockerignore b/.dockerignore index 33df1a6a11..173b38cfdf 100644 --- a/.dockerignore +++ b/.dockerignore @@ -23,3 +23,5 @@ node_modules **/*.test.jsx **/__tests__ **/__mocks__ +**/__snapshots__ +**/test/fixtures diff --git a/app/components/CenteredContent.tsx b/app/components/CenteredContent.tsx index 27ddd99289..7281629634 100644 --- a/app/components/CenteredContent.tsx +++ b/app/components/CenteredContent.tsx @@ -10,6 +10,7 @@ type Props = { }; const Container = styled.div` + position: relative; width: 100%; max-width: 100vw; padding: ${(props) => (props.withStickyHeader ? "4px 16px" : "60px 16px")}; diff --git a/app/editor/components/CommentGutter.tsx b/app/editor/components/CommentGutter.tsx index d8295d9dad..c405b7f8ca 100644 --- a/app/editor/components/CommentGutter.tsx +++ b/app/editor/components/CommentGutter.tsx @@ -3,6 +3,7 @@ import { observer } from "mobx-react"; import { CommentIcon } from "outline-icons"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import stores from "~/stores"; type IconProps = { @@ -60,7 +61,11 @@ export function CommentGutter({ onHoverCommentMark, }: Props) { return ( - + {commentIds.map((commentId) => ( { + const prev = prevSizeRef.current; + prevSizeRef.current = { width, height }; + if (isDraggingRef.current) { return; } - if ( - width !== Number(localDimension.width) || - height !== Number(localDimension.height) - ) { + if (prev.width !== width || prev.height !== height) { reset(); } - }, [width, height, reset, localDimension.width, localDimension.height]); + }, [width, height, reset]); // Listen to drag resize updates in real-time. useEffect(() => { diff --git a/app/editor/components/NodeViewRenderer.tsx b/app/editor/components/NodeViewRenderer.tsx index 88c71a01da..0b62a423cb 100644 --- a/app/editor/components/NodeViewRenderer.tsx +++ b/app/editor/components/NodeViewRenderer.tsx @@ -11,9 +11,16 @@ export interface PortalRenderer { readonly content: ReactNode; } +let nextRendererId = 0; + export class NodeViewRenderer implements PortalRenderer { @observable public props: T; + /** + * Stable identity used as the React key when renderers are rendered + */ + public readonly key = `renderer-${nextRendererId++}`; + public constructor( public element: HTMLElement, private Component: FunctionComponent, @@ -24,7 +31,11 @@ export class NodeViewRenderer implements PortalRenderer { @computed public get content() { - return createPortal(, this.element); + return createPortal( + , + this.element, + this.key + ); } @action diff --git a/app/editor/extensions/CommentGutter.tsx b/app/editor/extensions/CommentGutter.tsx index 61be878ade..bda11fa582 100644 --- a/app/editor/extensions/CommentGutter.tsx +++ b/app/editor/extensions/CommentGutter.tsx @@ -4,8 +4,7 @@ import { Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import Extension from "@shared/editor/lib/Extension"; import { changedDescendants } from "@shared/editor/lib/changedDescendants"; -import { isRemoteTransaction } from "@shared/editor/lib/multiplayer"; -import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; +import { mapDecorations } from "@shared/editor/lib/multiplayer"; import { UserPreferenceDefaults } from "@shared/constants"; import { UserPreference } from "@shared/types"; import { CommentGutter as CommentGutterComponent } from "../components/CommentGutter"; @@ -32,14 +31,8 @@ export default class CommentGutter extends Extension { const handleClickCommentMark = (commentId: string) => this.editor.props.onClickCommentMark?.(commentId); - // Mirror the comment mark's hover state when its gutter indicator is - // hovered, by toggling a class on the matching mark(s) in the document. const handleHoverCommentMark = (commentId: string, hovered: boolean) => { - this.editor.view?.dom - .querySelectorAll(`[id="comment-${commentId}"]`) - .forEach((element) => - element.classList.toggle(EditorStyleHelper.commentHovered, hovered) - ); + this.editor.setHoveredCommentId(hovered ? commentId : null); }; const handlers = { @@ -63,14 +56,20 @@ export default class CommentGutter extends Extension { return pluginState; } - if (isRemoteTransaction(tr) || this.hasCommentChange(tr)) { + // Only rebuild when the comments themselves change. Otherwise map + // the existing decorations, preserving each widget's identity so + // the React-rendered indicators are not torn down and recreated on + // every remote edit — churn that leaves their event handlers dead. + // mapDecorations handles remote (Yjs) transactions, whose mapping + // cannot be applied naively. + if (this.hasCommentChange(tr)) { return { decorations: this.createDecorations(newState, handlers), }; } return { - decorations: pluginState.decorations.map(tr.mapping, tr.doc), + decorations: mapDecorations(pluginState.decorations, tr), }; }, }, @@ -194,6 +193,8 @@ export default class CommentGutter extends Extension { key: `comment-gutter-${anchor}-${[...commentIds].sort().join("-")}`, side: -1, ignoreSelection: true, + // Keep interactions on the indicator from reaching ProseMirror + stopEvent: () => true, destroy: (node: HTMLElement) => { // Clear any forced hover state, otherwise it can remain stuck commentIds.forEach((commentId) => diff --git a/app/editor/index.tsx b/app/editor/index.tsx index 7445c42f0a..eda88f6100 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -182,6 +182,8 @@ type State = { isEditorFocused: boolean; /** Image that's being currently viewed in Lightbox */ activeLightboxImage: LightboxImage | null; + /** The comment thread currently highlighted from its gutter indicator */ + hoveredCommentId: string | null; }; /** @@ -212,6 +214,7 @@ export class Editor extends React.PureComponent< isRTL: false, isEditorFocused: false, activeLightboxImage: null, + hoveredCommentId: null, }; isInitialized = false; @@ -933,6 +936,19 @@ export class Editor extends React.PureComponent< this.portalDestroyers.delete(element); } + /** + * Highlight (or clear) the comment thread whose gutter indicator is hovered. + * Applied as container CSS rather than by mutating the mark's DOM directly, + * which would trip ProseMirror's mutation observer and force a redraw. + * + * @param commentId - The comment thread id to highlight, or null to clear. + */ + public setHoveredCommentId = (commentId: string | null) => { + if (this.state.hoveredCommentId !== commentId) { + this.setState({ hoveredCommentId: commentId }); + } + }; + public render() { const { readOnly, canUpdate, grow, style, className, onKeyDown } = this.props; @@ -956,6 +972,7 @@ export class Editor extends React.PureComponent< readOnly={readOnly} readOnlyWriteCheckboxes={canUpdate} focusedCommentId={this.props.focusedCommentId} + hoveredCommentId={this.state.hoveredCommentId ?? undefined} userId={this.props.userId} editorStyle={this.props.editorStyle} commenting={!!this.props.onClickCommentMark} @@ -1001,6 +1018,7 @@ export class Editor extends React.PureComponent< const EditorContainer = styled(Styles)<{ userId?: string; focusedCommentId?: string; + hoveredCommentId?: string; }>` ${(props) => props.focusedCommentId && @@ -1020,6 +1038,24 @@ const EditorContainer = styled(Styles)<{ } `} + ${(props) => + props.hoveredCommentId && + props.hoveredCommentId !== props.focusedCommentId && + css` + span#comment-${props.hoveredCommentId} { + background: ${props.theme.commentMarkBackground}; + + * { + background: transparent !important; + } + } + a#comment-${props.hoveredCommentId} + ~ span.component-image + div.image-wrapper { + outline: ${props.theme.commentedImageOutlineDark} solid 2px; + } + `} + ${(props) => props.userId && css` diff --git a/app/editor/menus/code.tsx b/app/editor/menus/code.tsx index c1106720f3..0a88805b5c 100644 --- a/app/editor/menus/code.tsx +++ b/app/editor/menus/code.tsx @@ -37,7 +37,8 @@ export default function codeMenuItems(ctx: SelectionContext): MenuItem[] { const remainingLangMenuItems = Object.entries(codeLanguages) .filter( - ([value]) => + ([value, item]) => + !item.alias && !frequentLanguages.includes(value as keyof typeof codeLanguages) ) .map(([value, item]) => langToMenuItem({ node, value, label: item.label })); diff --git a/app/scenes/Document/components/Comments/CommentThread.tsx b/app/scenes/Document/components/Comments/CommentThread.tsx index 40218dd994..e2a264579b 100644 --- a/app/scenes/Document/components/Comments/CommentThread.tsx +++ b/app/scenes/Document/components/Comments/CommentThread.tsx @@ -25,6 +25,7 @@ import useCurrentUser from "~/hooks/useCurrentUser"; import { sidebarAppearDuration } from "~/styles/animations"; import CommentForm from "./CommentForm"; import CommentThreadItem from "./CommentThreadItem"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; type Props = { /** The document that this comment thread belongs to */ @@ -56,7 +57,6 @@ function CommentThread({ const { editor, setFocusedCommentId } = useDocumentContext(); const { comments } = useStores(); const topRef = React.useRef(null); - const replyRef = React.useRef(null); const { t } = useTranslation(); const [autoFocus, setAutoFocusOn, setAutoFocusOff] = useBoolean(thread.isNew); const user = useCurrentUser(); @@ -104,6 +104,7 @@ function CommentThread({ // click handler, so skip deselecting here to avoid a flash of the // deselected state (and the new comment form) in between. !target.closest("[data-comment-thread]") && + !target.closest("." + EditorStyleHelper.commentGutter) && event.defaultPrevented === false ) { setFocusedCommentId(null); @@ -193,13 +194,14 @@ function CommentThread({ }, sidebarAppearDuration); } else { setTimeout(() => { - if (!replyRef.current) { + if (!topRef.current) { return; } - scrollIntoView(replyRef.current, { + // Scroll the whole into view when its mark is clicked + scrollIntoView(topRef.current, { scrollMode: "if-needed", behavior: "smooth", - block: "center", + block: "nearest", boundary: (parent) => // Prevents body and other parent elements from being scrolled parent.id !== "comments", @@ -278,7 +280,7 @@ function CommentThread({ ); })} - + {(focused || draft || commentsInThread.length === 0) && canReply && ( (null); @@ -267,14 +266,14 @@ function Details() { > void - ) { - const context = req.ctx; - try { - const team = await getTeamFromContext(context); - const client = getClientFromOAuthState(context); - /** Fetch the user's profile */ - const profile: RESTGetAPICurrentUserResult = await request( - "GET", - "https://discord.com/api/users/@me", - accessToken - ); - - const email = profile.email; - if (!email) { - /** We have the email scope, so this should never happen */ - throw InvalidRequestError("Discord profile email is missing"); - } - const { domain } = parseEmail(email); - - if (!domain) { - throw TeamDomainRequiredError(); - } - - /** Determine the user's language from the locale */ - const { locale } = profile; - const language = locale - ? languages.find((l) => l.startsWith(locale)) - : undefined; - - /** Default user and team names metadata */ - let userName = profile.username; - let teamName; - let userAvatarUrl: string = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.png`; - let teamAvatarUrl: string | undefined = undefined; - let subdomain = slugifyDomain(domain); - - /** - * If a Discord server is configured, we will check if the user is a member of the server - * Additionally, we can get the user's nickname in the server if it exists - */ - if (env.DISCORD_SERVER_ID) { - /** Fetch the guilds a user is in */ - const guilds: RESTGetAPICurrentUserGuildsResult = await request( + withProxyAgent( + new Strategy( + { + clientID: env.DISCORD_CLIENT_ID, + clientSecret: env.DISCORD_CLIENT_SECRET, + passReqToCallback: true, + scope, + // @ts-expect-error custom state store + store: new StateStore(), + state: true, + callbackURL: `${env.URL}/auth/${config.id}.callback`, + authorizationURL: + "https://discord.com/api/oauth2/authorize?prompt=none", + tokenURL: "https://discord.com/api/oauth2/token", + pkce: false, + }, + async function ( + req: Request, + accessToken: string, + refreshToken: string, + params: { expires_in: number }, + _profile: unknown, + done: ( + err: Error | null, + user: User | null, + result?: AuthenticationResult + ) => void + ) { + const context = req.ctx; + try { + const team = await getTeamFromContext(context); + const client = getClientFromOAuthState(context); + /** Fetch the user's profile */ + const profile: RESTGetAPICurrentUserResult = await request( "GET", - "https://discord.com/api/users/@me/guilds", + "https://discord.com/api/users/@me", accessToken ); - /** Find the guild that matches the configured server ID */ - const guild = guilds?.find((g) => g.id === env.DISCORD_SERVER_ID); - - /** If the user is not in the server, throw an error */ - if (!guild) { - throw DiscordGuildError(); + const email = profile.email; + if (!email) { + /** We have the email scope, so this should never happen */ + throw InvalidRequestError("Discord profile email is missing"); } + const { domain } = parseEmail(email); + + if (!domain) { + throw TeamDomainRequiredError(); + } + + /** Determine the user's language from the locale */ + const { locale } = profile; + const language = locale + ? languages.find((l) => l.startsWith(locale)) + : undefined; + + /** Default user and team names metadata */ + let userName = profile.username; + let teamName; + let userAvatarUrl: string = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.png`; + let teamAvatarUrl: string | undefined = undefined; + let subdomain = slugifyDomain(domain); /** - * Get the guild's icon - * https://discord.com/developers/docs/reference#image-formatting-cdn-endpoints - **/ - if (guild.icon) { - const isGif = guild.icon.startsWith("a_"); - if (isGif) { - teamAvatarUrl = `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.gif`; - } else { - teamAvatarUrl = `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png`; - } - } - - teamName = guild.name; - subdomain = slugify(guild.name); - - /** If the guild name is a URL, use the subdomain instead – we do not allow URLs in names. */ - if ( - isURL(teamName, { - require_host: false, - require_protocol: false, - }) - ) { - teamName = subdomain; - } - - /** Fetch the user's member object in the server for nickname and roles */ - const guildMember: RESTGetCurrentUserGuildMemberResult = - await request( + * If a Discord server is configured, we will check if the user is a member of the server + * Additionally, we can get the user's nickname in the server if it exists + */ + if (env.DISCORD_SERVER_ID) { + /** Fetch the guilds a user is in */ + const guilds: RESTGetAPICurrentUserGuildsResult = await request( "GET", - `https://discord.com/api/users/@me/guilds/${env.DISCORD_SERVER_ID}/member`, + "https://discord.com/api/users/@me/guilds", accessToken ); - /** If the user has a nickname in the server, use that as the name */ - if (guildMember.nick) { - userName = guildMember.nick; - } + /** Find the guild that matches the configured server ID */ + const guild = guilds?.find((g) => g.id === env.DISCORD_SERVER_ID); - /** If the user has a custom avatar in the server, use that as the avatar */ - if (guildMember.avatar) { - userAvatarUrl = `https://cdn.discordapp.com/guilds/${guild.id}/users/${profile.id}/avatars/${guildMember.avatar}.png`; - } + /** If the user is not in the server, throw an error */ + if (!guild) { + throw DiscordGuildError(); + } - /** If server roles are configured, check if the user has any of the roles */ - if (env.DISCORD_SERVER_ROLES) { - const { roles } = guildMember; - const hasRole = roles?.some((role) => - env.DISCORD_SERVER_ROLES?.includes(role) - ); + /** + * Get the guild's icon + * https://discord.com/developers/docs/reference#image-formatting-cdn-endpoints + **/ + if (guild.icon) { + const isGif = guild.icon.startsWith("a_"); + if (isGif) { + teamAvatarUrl = `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.gif`; + } else { + teamAvatarUrl = `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png`; + } + } - /** If the user does not have any of the roles, throw an error */ - if (!hasRole) { - throw DiscordGuildRoleError(); + teamName = guild.name; + subdomain = slugify(guild.name); + + /** If the guild name is a URL, use the subdomain instead – we do not allow URLs in names. */ + if ( + isURL(teamName, { + require_host: false, + require_protocol: false, + }) + ) { + teamName = subdomain; + } + + /** Fetch the user's member object in the server for nickname and roles */ + const guildMember: RESTGetCurrentUserGuildMemberResult = + await request( + "GET", + `https://discord.com/api/users/@me/guilds/${env.DISCORD_SERVER_ID}/member`, + accessToken + ); + + /** If the user has a nickname in the server, use that as the name */ + if (guildMember.nick) { + userName = guildMember.nick; + } + + /** If the user has a custom avatar in the server, use that as the avatar */ + if (guildMember.avatar) { + userAvatarUrl = `https://cdn.discordapp.com/guilds/${guild.id}/users/${profile.id}/avatars/${guildMember.avatar}.png`; + } + + /** If server roles are configured, check if the user has any of the roles */ + if (env.DISCORD_SERVER_ROLES) { + const { roles } = guildMember; + const hasRole = roles?.some((role) => + env.DISCORD_SERVER_ROLES?.includes(role) + ); + + /** If the user does not have any of the roles, throw an error */ + if (!hasRole) { + throw DiscordGuildRoleError(); + } } } - } - const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); + const user = + context.state?.auth?.user ?? + (await getUserFromOAuthState(context)); - // if a team can be inferred, we assume the user is only interested in signing into - // that team in particular; otherwise, we will do a best effort at finding their account - // or provisioning a new one (within AccountProvisioner) - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); - const result = await accountProvisioner(ctx, { - team: { - teamId: team?.id, - name: teamName, - domain, - subdomain, - avatarUrl: teamAvatarUrl, - }, - user: { - email, - emailVerified: profile.verified, - name: userName, - language, - avatarUrl: userAvatarUrl, - }, - authenticationProvider: { - name: config.id, - providerId: env.DISCORD_SERVER_ID ?? "", - }, - authentication: { - providerId: profile.id, - accessToken, - refreshToken, - expiresIn: params.expires_in, - scopes: scope, - }, - }); - return done(null, result.user, { ...result, client }); - } catch (err) { - return done(toError(err), null); + // if a team can be inferred, we assume the user is only interested in signing into + // that team in particular; otherwise, we will do a best effort at finding their account + // or provisioning a new one (within AccountProvisioner) + const ctx = createContext({ + ip: context.ip, + user, + authType: context.state?.auth?.type, + }); + const result = await accountProvisioner(ctx, { + team: { + teamId: team?.id, + name: teamName, + domain, + subdomain, + avatarUrl: teamAvatarUrl, + }, + user: { + email, + emailVerified: profile.verified, + name: userName, + language, + avatarUrl: userAvatarUrl, + }, + authenticationProvider: { + name: config.id, + providerId: env.DISCORD_SERVER_ID ?? "", + }, + authentication: { + providerId: profile.id, + accessToken, + refreshToken, + expiresIn: params.expires_in, + scopes: scope, + }, + }); + return done(null, result.user, { ...result, client }); + } catch (err) { + return done(toError(err), null); + } } - } + ) ) ); diff --git a/plugins/google/server/auth/google.ts b/plugins/google/server/auth/google.ts index f1d6d74774..e2f6e5d80d 100644 --- a/plugins/google/server/auth/google.ts +++ b/plugins/google/server/auth/google.ts @@ -21,6 +21,7 @@ import { getClientFromOAuthState, getUserFromOAuthState, startOAuthFlow, + withProxyAgent, } from "@server/utils/passport"; import config from "../../plugin.json"; import env from "../env"; @@ -43,130 +44,130 @@ type GoogleProfile = Profile & { }; if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { - passport.use( - new GoogleStrategy( - { - clientID: env.GOOGLE_CLIENT_ID, - clientSecret: env.GOOGLE_CLIENT_SECRET, - callbackURL: `${env.URL}/auth/${config.id}.callback`, - passReqToCallback: true, - // @ts-expect-error StateStore - store: new StateStore(), - scope: scopes, - }, - async function ( - req: Request, - accessToken: string, - refreshToken: string, - params: { expires_in: number; scope?: string }, - profile: GoogleProfile, - done: ( - err: Error | null, - user: User | null, - result?: AuthenticationResult - ) => void - ) { - const context = req.ctx; - try { - // "domain" is the Google Workspaces domain - const domain = profile._json.hd; - let team = await getTeamFromContext(context); - const client = getClientFromOAuthState(context); - const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); + const strategy = new GoogleStrategy( + { + clientID: env.GOOGLE_CLIENT_ID, + clientSecret: env.GOOGLE_CLIENT_SECRET, + callbackURL: `${env.URL}/auth/${config.id}.callback`, + passReqToCallback: true, + // @ts-expect-error StateStore + store: new StateStore(), + scope: scopes, + }, + async function ( + req: Request, + accessToken: string, + refreshToken: string, + params: { expires_in: number; scope?: string }, + profile: GoogleProfile, + done: ( + err: Error | null, + user: User | null, + result?: AuthenticationResult + ) => void + ) { + const context = req.ctx; + try { + // "domain" is the Google Workspaces domain + const domain = profile._json.hd; + let team = await getTeamFromContext(context); + const client = getClientFromOAuthState(context); + const user = + context.state?.auth?.user ?? (await getUserFromOAuthState(context)); - // No profile domain means a personal gmail account, and no team means - // the request came from the apex domain rather than a workspace - // subdomain. We can't infer the workspace from the domain, so resolve - // it from the verified email's existing accounts instead. - if (!domain && !team) { - const existingAccounts = await User.findAll({ - attributes: ["id", "teamId"], - where: { email: profile.email.toLowerCase() }, - include: [ - { - association: "team", - required: true, - }, - ], - }); - const teamIds = new Set( - existingAccounts.map((account) => account.teamId) - ); + // No profile domain means a personal gmail account, and no team means + // the request came from the apex domain rather than a workspace + // subdomain. We can't infer the workspace from the domain, so resolve + // it from the verified email's existing accounts instead. + if (!domain && !team) { + const existingAccounts = await User.findAll({ + attributes: ["id", "teamId"], + where: { email: profile.email.toLowerCase() }, + include: [ + { + association: "team", + required: true, + }, + ], + }); + const teamIds = new Set( + existingAccounts.map((account) => account.teamId) + ); - // A personal gmail account cannot be used to create a new workspace. - if (teamIds.size === 0) { - throw GmailAccountCreationError(); - } - - // When the email belongs to more than one workspace it is ambiguous - // which to sign into, so the user must start from its subdomain. - if (teamIds.size > 1) { - throw TeamDomainRequiredError(); - } - - // Belongs to exactly one workspace — resolve it and sign in there. - team = existingAccounts[0].team; + // A personal gmail account cannot be used to create a new workspace. + if (teamIds.size === 0) { + throw GmailAccountCreationError(); } - // remove the TLD and form a subdomain from the remaining - // subdomains of the form "foo.bar.com" are allowed as primary Google Workspaces domains - // see https://support.google.com/nonprofits/thread/19685140/using-a-subdomain-as-a-primary-domain - const subdomain = domain ? slugifyDomain(domain) : ""; - const teamName = capitalize(subdomain); + // When the email belongs to more than one workspace it is ambiguous + // which to sign into, so the user must start from its subdomain. + if (teamIds.size > 1) { + throw TeamDomainRequiredError(); + } - // Request a larger size profile picture than the default by tweaking - // the query parameter. - const avatarUrl = profile.picture.replace("=s96-c", "=s128-c"); - const locale = profile._json.locale; - const language = locale - ? languages.find((l) => l.startsWith(locale)) - : undefined; - - // if a team can be inferred, we assume the user is only interested in signing into - // that team in particular; otherwise, we will do a best effort at finding their account - // or provisioning a new one (within AccountProvisioner) - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); - const result = await accountProvisioner(ctx, { - team: { - teamId: team?.id, - name: teamName, - domain, - subdomain, - }, - user: { - email: profile.email, - // Google only returns confirmed workspace email addresses. - emailVerified: true, - name: profile.displayName, - language, - avatarUrl, - }, - authenticationProvider: { - name: config.id, - providerId: domain ?? "", - }, - authentication: { - providerId: profile.id, - accessToken, - refreshToken, - expiresIn: params.expires_in, - scopes: params.scope ? params.scope.split(" ") : scopes, - }, - }); - - return done(null, result.user, { ...result, client }); - } catch (err) { - return done(toError(err), null); + // Belongs to exactly one workspace — resolve it and sign in there. + team = existingAccounts[0].team; } + + // remove the TLD and form a subdomain from the remaining + // subdomains of the form "foo.bar.com" are allowed as primary Google Workspaces domains + // see https://support.google.com/nonprofits/thread/19685140/using-a-subdomain-as-a-primary-domain + const subdomain = domain ? slugifyDomain(domain) : ""; + const teamName = capitalize(subdomain); + + // Request a larger size profile picture than the default by tweaking + // the query parameter. + const avatarUrl = profile.picture.replace("=s96-c", "=s128-c"); + const locale = profile._json.locale; + const language = locale + ? languages.find((l) => l.startsWith(locale)) + : undefined; + + // if a team can be inferred, we assume the user is only interested in signing into + // that team in particular; otherwise, we will do a best effort at finding their account + // or provisioning a new one (within AccountProvisioner) + const ctx = createContext({ + ip: context.ip, + user, + authType: context.state?.auth?.type, + }); + const result = await accountProvisioner(ctx, { + team: { + teamId: team?.id, + name: teamName, + domain, + subdomain, + }, + user: { + email: profile.email, + // Google only returns confirmed workspace email addresses. + emailVerified: true, + name: profile.displayName, + language, + avatarUrl, + }, + authenticationProvider: { + name: config.id, + providerId: domain ?? "", + }, + authentication: { + providerId: profile.id, + accessToken, + refreshToken, + expiresIn: params.expires_in, + scopes: params.scope ? params.scope.split(" ") : scopes, + }, + }); + + return done(null, result.user, { ...result, client }); + } catch (err) { + return done(toError(err), null); } - ) + } ); + passport.use(withProxyAgent(strategy)); + router.get(config.id, startOAuthFlow, async (ctx, next) => { const team = await getTeamFromContext(ctx, { includeHostQueryParam: true, diff --git a/plugins/oidc/server/auth/OIDCStrategy.ts b/plugins/oidc/server/auth/OIDCStrategy.ts index 96d15d6a7f..f44afea834 100644 --- a/plugins/oidc/server/auth/OIDCStrategy.ts +++ b/plugins/oidc/server/auth/OIDCStrategy.ts @@ -1,6 +1,4 @@ import type { Request } from "express"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import type OAuth2Strategy from "passport-oauth2"; import { Strategy } from "passport-oauth2"; interface AuthenticateOptions { @@ -9,18 +7,6 @@ interface AuthenticateOptions { } export class OIDCStrategy extends Strategy { - constructor( - options: OAuth2Strategy.StrategyOptionsWithRequest, - verify: OAuth2Strategy.VerifyFunctionWithRequest - ) { - super(options, verify); - - if (process.env.https_proxy) { - const httpsProxyAgent = new HttpsProxyAgent(process.env.https_proxy); - this._oauth2.setAgent(httpsProxyAgent); - } - } - authenticate(req: Request, options: AuthenticateOptions) { options.originalQuery = req.query; super.authenticate(req, options); diff --git a/plugins/oidc/server/auth/oidcRouter.ts b/plugins/oidc/server/auth/oidcRouter.ts index e27bb470a4..295c13c29a 100644 --- a/plugins/oidc/server/auth/oidcRouter.ts +++ b/plugins/oidc/server/auth/oidcRouter.ts @@ -28,6 +28,7 @@ import { getUserFromOAuthState, request, startOAuthFlow, + withProxyAgent, } from "@server/utils/passport"; import config from "../../plugin.json"; import env from "../env"; @@ -59,228 +60,237 @@ export function createOIDCRouter( passport.use( config.id, - new OIDCStrategy( - { - authorizationURL: endpoints.authorizationURL, - tokenURL: endpoints.tokenURL, - clientID: env.OIDC_CLIENT_ID!, - clientSecret: env.OIDC_CLIENT_SECRET!, - callbackURL: `${env.URL}/auth/${config.id}.callback`, - passReqToCallback: true, - scope: env.OIDC_SCOPES, - // @ts-expect-error custom state store - store: new StateStore(endpoints.pkce), - state: true, - pkce: endpoints.pkce ?? false, - }, - // OpenID Connect standard profile claims can be found in the official - // specification. - // https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims - // Non-standard claims may be configured by individual identity providers. - // Any claim supplied in response to the userinfo request will be - // available on the `profile` parameter - async function ( - req: Request, - accessToken: string, - refreshToken: string, - params: { expires_in: number; id_token: string; scope?: string }, - _profile: unknown, - done: ( - err: Error | null, - user: User | null, - result?: AuthenticationResult - ) => void - ) { - const context = req.ctx; - try { - // Some providers require a POST request to the userinfo endpoint, add them as exceptions here. - const usePostMethod = [ - "https://api.dropboxapi.com/2/openid/userinfo", - ]; + withProxyAgent( + new OIDCStrategy( + { + authorizationURL: endpoints.authorizationURL, + tokenURL: endpoints.tokenURL, + clientID: env.OIDC_CLIENT_ID!, + clientSecret: env.OIDC_CLIENT_SECRET!, + callbackURL: `${env.URL}/auth/${config.id}.callback`, + passReqToCallback: true, + scope: env.OIDC_SCOPES, + // @ts-expect-error custom state store + store: new StateStore(endpoints.pkce), + state: true, + pkce: endpoints.pkce ?? false, + }, + // OpenID Connect standard profile claims can be found in the official + // specification. + // https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + // Non-standard claims may be configured by individual identity providers. + // Any claim supplied in response to the userinfo request will be + // available on the `profile` parameter + async function ( + req: Request, + accessToken: string, + refreshToken: string, + params: { expires_in: number; id_token: string; scope?: string }, + _profile: unknown, + done: ( + err: Error | null, + user: User | null, + result?: AuthenticationResult + ) => void + ) { + const context = req.ctx; + try { + // Some providers require a POST request to the userinfo endpoint, add them as exceptions here. + const usePostMethod = [ + "https://api.dropboxapi.com/2/openid/userinfo", + ]; - const profile = await request( - usePostMethod.includes(endpoints.userInfoURL) ? "POST" : "GET", - endpoints.userInfoURL, - accessToken - ); + const profile = await request( + usePostMethod.includes(endpoints.userInfoURL) ? "POST" : "GET", + endpoints.userInfoURL, + accessToken + ); - // Some providers, namely ADFS, don't provide anything more than the `sub` claim in the userinfo endpoint - // So, we'll decode the params.id_token and see if that contains what we need. - const token = (() => { - try { - const decoded = JWT.decode(params.id_token); + // Some providers, namely ADFS, don't provide anything more than the `sub` claim in the userinfo endpoint + // So, we'll decode the params.id_token and see if that contains what we need. + const token = (() => { + try { + const decoded = JWT.decode(params.id_token); - if (!decoded || typeof decoded !== "object") { - Logger.warn("Decoded id_token is not a valid object"); + if (!decoded || typeof decoded !== "object") { + Logger.warn("Decoded id_token is not a valid object"); + return {}; + } + + return decoded as { + email?: string; + email_verified?: boolean | string; + preferred_username?: string; + sub?: string; + }; + } catch (err) { + Logger.error("id_token decode threw error: ", toError(err)); return {}; } + })(); - return decoded as { - email?: string; - email_verified?: boolean | string; - preferred_username?: string; - sub?: string; - }; - } catch (err) { - Logger.error("id_token decode threw error: ", toError(err)); - return {}; - } - })(); + const email = profile.email ?? token.email ?? null; - const email = profile.email ?? token.email ?? null; - - if (!email) { - throw AuthenticationError( - `An email field was not returned in the profile or id_token parameter, but is required.` - ); - } - - // The email_verified claim is part of the OIDC standard claims. - // https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims - const emailVerifiedClaim = - profile.email_verified ?? token.email_verified; - const emailVerified = - emailVerifiedClaim === undefined - ? undefined - : emailVerifiedClaim === true || emailVerifiedClaim === "true"; - - const team = await getTeamFromContext(context); - const client = getClientFromOAuthState(context); - const user = - context.state?.auth?.user ?? (await getUserFromOAuthState(context)); - const { domain } = parseEmail(email); - - // Only a single OIDC provider is supported – find the existing, if any. - const authenticationProvider = team - ? ((await AuthenticationProvider.findOne({ - where: { - name: "oidc", - teamId: team.id, - providerId: domain, - }, - })) ?? - (await AuthenticationProvider.findOne({ - where: { - name: "oidc", - teamId: team.id, - }, - }))) - : undefined; - - // Derive a providerId from the OIDC location if there is no existing provider. - const oidcURL = new URL(endpoints.authorizationURL); - const providerId = - authenticationProvider?.providerId ?? oidcURL.hostname; - - if (!domain) { - throw OIDCMalformedUserInfoError(); - } - - // remove the TLD and form a subdomain from the remaining - const subdomain = slugifyDomain(domain); - - // Claim name can be overriden using an env variable. - // Default is 'preferred_username' as per OIDC spec. - // This will default to the profile.preferred_username, but will fall back to preferred_username from the id_token - const username = - get(profile, env.OIDC_USERNAME_CLAIM) ?? - get(token, env.OIDC_USERNAME_CLAIM); - const name = profile.name || username || profile.username; - const profileId = profile.sub ?? token.sub ?? profile.id; - - if (!name) { - throw AuthenticationError( - `Neither a ${env.OIDC_USERNAME_CLAIM}, "name" or "username" was returned in the profile loaded from ${endpoints.userInfoURL}, but at least one is required.` - ); - } - if (!profileId) { - throw AuthenticationError( - `A user id was not returned in the profile loaded from ${endpoints.userInfoURL}, searched in "sub" and "id" fields.` - ); - } - - // Check if the picture field is a Base64 data URL and filter it out - // to avoid validation errors in the User model - let avatarUrl = profile.picture; - if (profile.picture && isBase64Url(profile.picture)) { - Logger.debug( - "authentication", - "Filtering out Base64 data URL from avatar", - { - email, - } - ); - avatarUrl = null; - } - - const ctx = createContext({ - ip: context.ip, - user, - authType: context.state?.auth?.type, - }); - const result = await accountProvisioner(ctx, { - team: { - teamId: team?.id, - name: env.APP_NAME, - domain, - subdomain, - }, - user: { - name, - email, - emailVerified, - avatarUrl, - }, - authenticationProvider: { - name: config.id, - providerId, - }, - authentication: { - providerId: profileId, - accessToken, - refreshToken, - expiresIn: params.expires_in, - scopes: params.scope ? params.scope.split(" ") : scopes, - }, - }); - - // Persist the id_token so a later RP-initiated logout can pass it as - // the `id_token_hint`, allowing the provider to scope the logout to - // this session rather than terminating its global SSO session. The - // token is stored server-side keyed by a short session identifier; - // only that identifier goes in the cookie. - if (endpoints.logoutURL && params.id_token) { - try { - const sessionId = crypto.randomBytes(16).toString("hex"); - await Redis.defaultClient.set( - RedisPrefixHelper.getLogoutTokenKey(sessionId), - params.id_token, - "EX", - OIDC_LOGOUT_TOKEN_TTL_SECONDS + if (!email) { + throw AuthenticationError( + `An email field was not returned in the profile or id_token parameter, but is required.` ); - context.cookies.set(OIDC_SESSION_COOKIE, sessionId, { - httpOnly: true, - sameSite: "lax", - secure: env.isProduction, - path: OIDC_LOGOUT_PATH, - domain: getCookieDomain( - context.request.hostname, - env.isCloudHosted - ), - expires: addSeconds(new Date(), OIDC_LOGOUT_TOKEN_TTL_SECONDS), - }); - } catch (err) { - Logger.warn("Failed to persist OIDC logout token hint", { - error: toError(err).message, - }); } - } - return done(null, result.user, { ...result, client }); - } catch (err) { - return done(toError(err), null); + // The email_verified claim is part of the OIDC standard claims. + // https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims + const emailVerifiedClaim = + profile.email_verified ?? token.email_verified; + const emailVerified = + emailVerifiedClaim === undefined + ? undefined + : emailVerifiedClaim === true || emailVerifiedClaim === "true"; + + const team = await getTeamFromContext(context); + const client = getClientFromOAuthState(context); + const user = + context.state?.auth?.user ?? + (await getUserFromOAuthState(context)); + const { domain } = parseEmail(email); + + // Only a single OIDC provider is supported – find the existing, if any. + const authenticationProvider = team + ? ((await AuthenticationProvider.findOne({ + where: { + name: "oidc", + teamId: team.id, + providerId: domain, + }, + })) ?? + (await AuthenticationProvider.findOne({ + where: { + name: "oidc", + teamId: team.id, + }, + }))) + : undefined; + + // Derive a providerId from the OIDC location if there is no existing provider. + const oidcURL = new URL(endpoints.authorizationURL); + const providerId = + authenticationProvider?.providerId ?? oidcURL.hostname; + + if (!domain) { + throw OIDCMalformedUserInfoError(); + } + + // remove the TLD and form a subdomain from the remaining + const subdomain = slugifyDomain(domain); + + // Claim name can be overriden using an env variable. + // Default is 'preferred_username' as per OIDC spec. + // This will default to the profile.preferred_username, but will fall back to preferred_username from the id_token + const username = + get(profile, env.OIDC_USERNAME_CLAIM) ?? + get(token, env.OIDC_USERNAME_CLAIM); + const name = profile.name || username || profile.username; + const profileId = profile.sub ?? token.sub ?? profile.id; + + if (!name) { + throw AuthenticationError( + `Neither a ${env.OIDC_USERNAME_CLAIM}, "name" or "username" was returned in the profile loaded from ${endpoints.userInfoURL}, but at least one is required.` + ); + } + if (!profileId) { + throw AuthenticationError( + `A user id was not returned in the profile loaded from ${endpoints.userInfoURL}, searched in "sub" and "id" fields.` + ); + } + + // Check if the picture field is a Base64 data URL and filter it out + // to avoid validation errors in the User model + let avatarUrl = profile.picture; + if (profile.picture && isBase64Url(profile.picture)) { + Logger.debug( + "authentication", + "Filtering out Base64 data URL from avatar", + { + email, + } + ); + avatarUrl = null; + } + + const ctx = createContext({ + ip: context.ip, + user, + authType: context.state?.auth?.type, + }); + const result = await accountProvisioner(ctx, { + team: { + teamId: team?.id, + name: env.APP_NAME, + domain, + subdomain, + }, + user: { + name, + email, + emailVerified, + avatarUrl, + }, + authenticationProvider: { + name: config.id, + providerId, + }, + authentication: { + providerId: profileId, + accessToken, + refreshToken, + expiresIn: params.expires_in, + scopes: params.scope ? params.scope.split(" ") : scopes, + }, + }); + // Persist the id_token so a later RP-initiated logout can pass it as + // the `id_token_hint`, allowing the provider to scope the logout to + // this session rather than terminating its global SSO session. The + // token is stored server-side keyed by a short session identifier; + // only that identifier goes in the cookie. id_tokens can be large and + // storing one directly in the cookie inflates response headers enough + // to exceed reverse proxy buffers, resulting in a 502 on sign-in. + // This is best-effort: a Redis failure must not block sign-in, the + // logout simply falls back to omitting the `id_token_hint`. + if (endpoints.logoutURL && params.id_token) { + try { + const sessionId = crypto.randomBytes(16).toString("hex"); + await Redis.defaultClient.set( + RedisPrefixHelper.getLogoutTokenKey(sessionId), + params.id_token, + "EX", + OIDC_LOGOUT_TOKEN_TTL_SECONDS + ); + context.cookies.set(OIDC_SESSION_COOKIE, sessionId, { + httpOnly: true, + sameSite: "lax", + secure: env.isProduction, + path: OIDC_LOGOUT_PATH, + domain: getCookieDomain( + context.request.hostname, + env.isCloudHosted + ), + expires: addSeconds( + new Date(), + OIDC_LOGOUT_TOKEN_TTL_SECONDS + ), + }); + } catch (err) { + Logger.warn("Failed to persist OIDC logout token hint", { + error: toError(err).message, + }); + } + } + + return done(null, result.user, { ...result, client }); + } catch (err) { + return done(toError(err), null); + } } - } + ) ) ); diff --git a/plugins/slack/server/api/hooks.ts b/plugins/slack/server/api/hooks.ts index 3c1431f522..de385df66b 100644 --- a/plugins/slack/server/api/hooks.ts +++ b/plugins/slack/server/api/hooks.ts @@ -24,6 +24,7 @@ import { AuthenticationProvider, Comment, } from "@server/models"; +import { SearchQuerySource } from "@server/models/SearchQuery"; import SearchProviderManager from "@server/utils/SearchProviderManager"; import { can } from "@server/policies"; import type { APIContext } from "@server/types"; @@ -245,7 +246,7 @@ router.post( await SearchQuery.create({ userId: user ? user.id : null, teamId: user.teamId, - source: "slack", + source: SearchQuerySource.Slack, query: text, results: total, }); diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index 1f6fd52e32..1020ccbc06 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -27,6 +27,7 @@ import { getUserFromOAuthState, StateStore, startOAuthFlow, + withProxyAgent, } from "@server/utils/passport"; import { parseEmail } from "@shared/utils/email"; import env from "../env"; @@ -137,7 +138,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { // For some reason the author made the strategy name capatilised, I don't know // why but we need everything lowercase so we just monkey-patch it here. strategy.name = providerName; - passport.use(strategy); + passport.use(withProxyAgent(strategy)); router.get("slack", startOAuthFlow, passport.authenticate(providerName)); router.get("slack.callback", passportMiddleware(providerName)); diff --git a/plugins/storage/server/api/files.test.ts b/plugins/storage/server/api/files.test.ts index 2d9946172c..a57ccf34cf 100644 --- a/plugins/storage/server/api/files.test.ts +++ b/plugins/storage/server/api/files.test.ts @@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import FormData from "form-data"; import { ensureDirSync } from "fs-extra"; +import JWT from "jsonwebtoken"; import { FileOperationState, FileOperationType } from "@shared/types"; import env from "@server/env"; import AttachmentHelper, { @@ -194,6 +195,110 @@ describe("#files.create", () => { existsSync(path.join(env.FILE_STORAGE_LOCAL_ROOT_DIR, attachment.key)) ).toBe(true); }); + + it("should succeed with a valid upload signature and no session", async () => { + const user = await buildUser(); + const fileName = "images.docx"; + const attachment = await buildAttachment( + { + teamId: user.teamId, + userId: user.id, + contentType: + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }, + fileName + ); + + const sig = JWT.sign( + { key: attachment.key, type: "attachment-upload" }, + env.SECRET_KEY, + { expiresIn: 3600 } + ); + + const content = await readFile( + path.resolve(__dirname, "..", "test", "fixtures", fileName) + ); + const form = new FormData(); + form.append("key", attachment.key); + form.append("file", content, fileName); + form.append("sig", sig); + + const res = await server.post(`/api/files.create`, { + headers: form.getHeaders(), + body: form, + }); + + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.success).toEqual(true); + expect( + existsSync(path.join(env.FILE_STORAGE_LOCAL_ROOT_DIR, attachment.key)) + ).toBe(true); + }); + + it("should fail with a signature scoped to a different key", async () => { + const user = await buildUser(); + const fileName = "images.docx"; + const attachment = await buildAttachment( + { + teamId: user.teamId, + userId: user.id, + contentType: + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }, + fileName + ); + + const sig = JWT.sign( + { key: "public/foo/bar/other.png", type: "attachment-upload" }, + env.SECRET_KEY, + { expiresIn: 3600 } + ); + + const content = await readFile( + path.resolve(__dirname, "..", "test", "fixtures", fileName) + ); + const form = new FormData(); + form.append("key", attachment.key); + form.append("file", content, fileName); + form.append("sig", sig); + + const res = await server.post(`/api/files.create`, { + headers: form.getHeaders(), + body: form, + }); + expect(res.status).toEqual(401); + expect( + existsSync(path.join(env.FILE_STORAGE_LOCAL_ROOT_DIR, attachment.key)) + ).toBe(false); + }); + + it("should fail with status 401 when neither session nor signature is provided", async () => { + const user = await buildUser(); + const fileName = "images.docx"; + const attachment = await buildAttachment( + { + teamId: user.teamId, + userId: user.id, + contentType: + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }, + fileName + ); + + const content = await readFile( + path.resolve(__dirname, "..", "test", "fixtures", fileName) + ); + const form = new FormData(); + form.append("key", attachment.key); + form.append("file", content, fileName); + + const res = await server.post(`/api/files.create`, { + headers: form.getHeaders(), + body: form, + }); + expect(res.status).toEqual(401); + }); }); describe("#files.get", () => { diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index 9bfe73fe99..6547080375 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -30,7 +30,7 @@ const router = new Router(); router.post( "files.create", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), - auth(), + auth({ optional: true }), validate(T.FilesCreateSchema), timeout(30 * 60 * 1000), // 30 minutes for large file uploads multipart({ @@ -41,19 +41,27 @@ router.post( }), async (ctx: APIContext) => { const actor = ctx.state.auth.user; - const { key } = ctx.input.body; + const { key, sig } = ctx.input.body; const file = ctx.input.file; if (!file) { throw ValidationError("Request must include a file parameter"); } + // A short-lived signature authorizes the upload to this key without a session. + if (sig) { + verifyUploadSignature(sig, key); + } else if (!actor) { + throw AuthenticationError("Authentication required"); + } + const attachment = await Attachment.findOne({ where: { key }, rejectOnEmpty: true, }); - if (attachment.userId !== actor.id) { + // For session-based uploads, ensure the attachment belongs to the actor. + if (!sig && actor && attachment.userId !== actor.id) { throw AuthorizationError("Invalid key"); } @@ -186,6 +194,28 @@ function getByteRange( return { start, end }; } +/** + * Verifies a short-lived signature authorizing an upload to a single key. + * + * @param sig The signature to verify. + * @param key The key the upload is being made to. + * @throws AuthenticationError if the signature is invalid, expired, or scoped + * to a different key. + */ +function verifyUploadSignature(sig: string, key: string) { + const payload = getJWTPayload(sig); + + if (payload.type !== "attachment-upload" || payload.key !== key) { + throw AuthenticationError("Invalid signature"); + } + + try { + JWT.verify(sig, env.SECRET_KEY); + } catch (_err) { + throw AuthenticationError("Invalid signature"); + } +} + function getKeyFromContext(ctx: APIContext): string { const { key, sig } = ctx.input.query; if (sig) { diff --git a/plugins/storage/server/api/schema.ts b/plugins/storage/server/api/schema.ts index 0b99e2841b..8b06aff055 100644 --- a/plugins/storage/server/api/schema.ts +++ b/plugins/storage/server/api/schema.ts @@ -9,6 +9,7 @@ export const FilesCreateSchema = z.object({ .string() .refine(ValidateKey.isValid, { message: ValidateKey.message }) .transform(ValidateKey.sanitize), + sig: z.string().optional(), }), file: z.custom().optional(), }); diff --git a/server/migrations/20260714000000-add-mcp-to-search-queries-source.js b/server/migrations/20260714000000-add-mcp-to-search-queries-source.js new file mode 100644 index 0000000000..eb830360d7 --- /dev/null +++ b/server/migrations/20260714000000-add-mcp-to-search-queries-source.js @@ -0,0 +1,16 @@ +"use strict"; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "ALTER TYPE enum_search_queries_source ADD VALUE 'mcp'" + ); + }, + + async down(queryInterface, Sequelize) { + // Note: PostgreSQL doesn't support removing enum values easily + // This would require recreating the enum type and updating all references + throw new Error("Cannot rollback adding enum value to PostgreSQL"); + }, +}; diff --git a/server/models/Document.test.ts b/server/models/Document.test.ts index 11372c37dd..36611e4dd2 100644 --- a/server/models/Document.test.ts +++ b/server/models/Document.test.ts @@ -1,4 +1,4 @@ -import { EmptyResultError } from "sequelize"; +import { EmptyResultError, Op } from "sequelize"; import { CollectionPermission } from "@shared/types"; import slugify from "@shared/utils/slugify"; import { parser } from "@server/editor"; @@ -181,6 +181,80 @@ describe("#findAllChildDocumentIds", () => { expect(results[0]).toBe(document2.id); expect(results[1]).toBe(document3.id); }); + + test("should apply where filter and prune unmatched branches", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + userId: user.id, + teamId: team.id, + }); + const document = await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + title: "test", + }); + const publishedChild = await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + parentDocumentId: document.id, + title: "published", + }); + // A draft (unpublished) child, with its own nested child. + const draftChild = await buildDraftDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + parentDocumentId: document.id, + title: "draft", + }); + await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + parentDocumentId: draftChild.id, + title: "published under draft", + }); + + const results = await document.findAllChildDocumentIds({ + publishedAt: { + [Op.ne]: null, + }, + }); + // Only the published child is returned; the draft branch is pruned so its + // descendants are not traversed. + expect(results).toEqual([publishedChild.id]); + }); + + test("should include soft-deleted children when paranoid is false", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + userId: user.id, + teamId: team.id, + }); + const document = await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + title: "test", + }); + const child = await buildDocument({ + userId: user.id, + teamId: team.id, + collectionId: collection.id, + parentDocumentId: document.id, + title: "child", + }); + await child.destroy(); + + expect(await document.findAllChildDocumentIds()).toEqual([]); + expect( + await document.findAllChildDocumentIds(undefined, { paranoid: false }) + ).toEqual([child.id]); + }); }); describe("#findByPk", () => { diff --git a/server/models/Document.ts b/server/models/Document.ts index 09eb7daab5..d591ec37a7 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -10,7 +10,13 @@ import type { FindOptions, WhereOptions, } from "sequelize"; -import { Transaction, Op, EmptyResultError, Sequelize } from "sequelize"; +import { + Transaction, + Op, + EmptyResultError, + Sequelize, + QueryTypes, +} from "sequelize"; import { ForeignKey, BelongsTo, @@ -96,6 +102,16 @@ type AdditionalFindOptions = { rejectOnEmpty?: boolean | Error; }; +/** Sequelize types the query generator as unknown; this narrows to the single + * method used to build a raw SQL filter fragment. */ +interface QueryGeneratorWithWhere { + getWhereConditions( + where: WhereOptions, + tableName: string, + factory: typeof Document + ): string; +} + // @ts-expect-error Type 'Literal' is not assignable to type 'string | ProjectionAlias'. @DefaultScope(() => ({ include: [ @@ -984,34 +1000,46 @@ class Document extends ArchivableModel< where?: Omit, "parentDocumentId">, options?: FindOptions ): Promise => { - const findAllChildDocumentIds = async ( - ...parentDocumentId: string[] - ): Promise => { - // Unscoped as this method only ever reads the id column - const childDocuments = await (this.constructor as typeof Document) - .unscoped() - .findAll({ - attributes: ["id"], - where: { - parentDocumentId, - ...where, - }, - ...options, - }); + const model = this.constructor as typeof Document; + const queryGenerator = this.sequelize!.getQueryInterface() + .queryGenerator as QueryGeneratorWithWhere; - const childDocumentIds = childDocuments.map((doc) => doc.id); + const paranoid = options?.paranoid ?? true; + const whereConditions = queryGenerator.getWhereConditions( + { ...(paranoid ? { deletedAt: null } : {}), ...where }, + "documents", + model + ); + const anchorFilter = whereConditions ? `AND (${whereConditions})` : ""; + const recursiveFilter = whereConditions ? `WHERE (${whereConditions})` : ""; - if (childDocumentIds.length > 0) { - return [ - ...childDocumentIds, - ...(await findAllChildDocumentIds(...childDocumentIds)), - ]; + // A single recursive CTE walks the entire subtree in one round-trip rather + // than issuing one query per level of nesting (N+1). Rows are ordered by + // depth to ensure breadth-first result ordering. UNION ALL is safe as the + // tree is acyclic, so each descendant id is reached exactly once. + const rows = await this.sequelize!.query<{ id: string }>( + ` + WITH RECURSIVE children AS ( + SELECT documents.id, 1 AS depth + FROM documents + WHERE documents."parentDocumentId" = :parentDocumentId + ${anchorFilter} + UNION ALL + SELECT documents.id, children.depth + 1 + FROM documents + INNER JOIN children ON documents."parentDocumentId" = children.id + ${recursiveFilter} + ) + SELECT id FROM children ORDER BY depth + `, + { + replacements: { parentDocumentId: this.id }, + transaction: options?.transaction, + type: QueryTypes.SELECT, } + ); - return childDocumentIds; - }; - - return findAllChildDocumentIds(this.id); + return rows.map((row) => row.id); }; publish = async ( diff --git a/server/models/DocumentInsight.test.ts b/server/models/DocumentInsight.test.ts index 01e70f9812..8960fca998 100644 --- a/server/models/DocumentInsight.test.ts +++ b/server/models/DocumentInsight.test.ts @@ -15,14 +15,16 @@ const dayStr = (d: Date) => format(d, "yyyy-MM-dd"); describe("DocumentInsight.rollupPeriod", () => { it("writes nothing when no source activity exists in the window", async () => { const team = await buildTeam(); - await buildDocument({ teamId: team.id }); + const document = await buildDocument({ teamId: team.id }); + // Scope the partition to just this document so the global rollup count + // isn't affected by activity from other tests sharing the database. const upserted = await DocumentInsight.rollupPeriod({ periodStart: dayStr(subDays(new Date(), 1)), intervalDays: 1, period: DocumentInsightPeriod.Day, - startUuid: FULL_UUID_RANGE[0], - endUuid: FULL_UUID_RANGE[1], + startUuid: document.id, + endUuid: document.id, }); expect(upserted).toBe(0); diff --git a/server/models/SearchQuery.test.ts b/server/models/SearchQuery.test.ts new file mode 100644 index 0000000000..1e730852e3 --- /dev/null +++ b/server/models/SearchQuery.test.ts @@ -0,0 +1,168 @@ +import { buildTeam, buildUser } from "@server/test/factories"; +import SearchQuery, { SearchQuerySource } from "./SearchQuery"; + +describe("SearchQuery.record", () => { + it("updates the existing record when a query extends a recent one", async () => { + const user = await buildUser(); + const teamId = user.teamId; + + const first = await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conf", + results: 3, + duration: 10, + }); + + const second = await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conflue", + results: 5, + duration: 12, + }); + + expect(second.id).toEqual(first.id); + expect(second.query).toEqual("conflue"); + expect(second.results).toEqual(5); + expect(await SearchQuery.count({ where: { teamId } })).toEqual(1); + }); + + it("updates the existing record when a query is shortened", async () => { + const user = await buildUser(); + const teamId = user.teamId; + + const first = await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conflue", + results: 5, + duration: 12, + }); + + const second = await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conf", + results: 3, + duration: 10, + }); + + expect(second.id).toEqual(first.id); + expect(second.query).toEqual("conf"); + expect(await SearchQuery.count({ where: { teamId } })).toEqual(1); + }); + + it("creates a new record for an unrelated query", async () => { + const user = await buildUser(); + const teamId = user.teamId; + + await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conflue", + results: 5, + duration: 12, + }); + + await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "database", + results: 2, + duration: 8, + }); + + expect(await SearchQuery.count({ where: { teamId } })).toEqual(2); + }); + + it("does not collapse queries from different scopes", async () => { + const team = await buildTeam(); + const userA = await buildUser({ teamId: team.id }); + const userB = await buildUser({ teamId: team.id }); + + await SearchQuery.record({ + userId: userA.id, + teamId: team.id, + source: SearchQuerySource.App, + query: "conf", + results: 1, + duration: 5, + }); + + await SearchQuery.record({ + userId: userB.id, + teamId: team.id, + source: SearchQuerySource.App, + query: "conflue", + results: 1, + duration: 5, + }); + + expect(await SearchQuery.count({ where: { teamId: team.id } })).toEqual(2); + }); + + it("does not collapse when there is no user or share to scope by", async () => { + const team = await buildTeam(); + + await SearchQuery.record({ + teamId: team.id, + source: SearchQuerySource.API, + query: "conf", + results: 1, + duration: 5, + }); + + await SearchQuery.record({ + teamId: team.id, + source: SearchQuerySource.API, + query: "conflue", + results: 1, + duration: 5, + }); + + expect(await SearchQuery.count({ where: { teamId: team.id } })).toEqual(2); + }); + + it("creates a new record once the recency window has passed", async () => { + const user = await buildUser(); + const teamId = user.teamId; + + const first = await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conf", + results: 1, + duration: 5, + }); + + // Backdate the first record beyond the recency window. + await SearchQuery.sequelize!.query( + `UPDATE search_queries SET "createdAt" = :createdAt WHERE id = :id`, + { + replacements: { + createdAt: new Date(Date.now() - SearchQuery.recencyWindow - 1000), + id: first.id, + }, + } + ); + + await SearchQuery.record({ + userId: user.id, + teamId, + source: SearchQuerySource.App, + query: "conflue", + results: 1, + duration: 5, + }); + + expect(await SearchQuery.count({ where: { teamId } })).toEqual(2); + }); +}); diff --git a/server/models/SearchQuery.ts b/server/models/SearchQuery.ts index beb4c97184..c9e06bda5c 100644 --- a/server/models/SearchQuery.ts +++ b/server/models/SearchQuery.ts @@ -1,3 +1,4 @@ +import { Op } from "sequelize"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Table, @@ -10,12 +11,24 @@ import { DataType, Default, } from "sequelize-typescript"; +import { Second } from "@shared/utils/time"; import Share from "@server/models/Share"; import Team from "@server/models/Team"; import User from "@server/models/User"; import Model from "@server/models/base/Model"; import Fix from "./decorators/Fix"; +/** + * Where a search query originated. + */ +export enum SearchQuerySource { + Slack = "slack", + App = "app", + API = "api", + OAuth = "oauth", + MCP = "mcp", +} + @Table({ tableName: "search_queries", modelName: "search_query", @@ -26,6 +39,73 @@ class SearchQuery extends Model< InferAttributes, Partial> > { + /** + * The window during which a follow-up query for the same scope is treated as + * a continuation of the same "search as you type" session rather than a new + * search. + */ + public static recencyWindow = Second.ms * 30; + + /** + * Records a search query, collapsing rapid "search as you type" keystrokes + * into a single record. If a query was recorded for the same scope within the + * recency window and one query is a prefix of the other (i.e. the visitor kept + * typing or edited their term), the existing record is updated in place rather + * than inserting a new row. + * + * @param attrs the attributes of the search to record. + * @returns the created or updated search query record. + */ + public static async record(attrs: { + userId?: string | null; + teamId: string; + shareId?: string | null; + source: SearchQuerySource; + query: string; + results: number; + duration: number; + }): Promise { + const { userId, teamId, shareId, source, query, results, duration } = attrs; + + // Without a user or share to scope by, collapsing would merge unrelated + // searches across the team, so only ever record a new row. + const existing = + userId || shareId + ? await this.findOne({ + where: { + teamId, + userId: userId ?? null, + shareId: shareId ?? null, + source, + createdAt: { + [Op.gte]: new Date(Date.now() - SearchQuery.recencyWindow), + }, + }, + order: [["createdAt", "DESC"]], + }) + : null; + + if ( + existing && + (query.startsWith(existing.query) || existing.query.startsWith(query)) + ) { + existing.query = query; + existing.results = results; + existing.duration = duration; + return existing.save(); + } + + return this.create({ + userId, + teamId, + shareId, + source, + query, + results, + duration, + }); + } + @IsUUID(4) @PrimaryKey @Default(DataType.UUIDV4) @@ -38,8 +118,8 @@ class SearchQuery extends Model< /** * Where the query originated. */ - @Column(DataType.ENUM("slack", "app", "api", "oauth")) - source: string; + @Column(DataType.ENUM(...Object.values(SearchQuerySource))) + source: SearchQuerySource; /** * The number of results returned for this query. diff --git a/server/models/helpers/DocumentHelper.test.ts b/server/models/helpers/DocumentHelper.test.ts index 518517f29b..535eb9ed90 100644 --- a/server/models/helpers/DocumentHelper.test.ts +++ b/server/models/helpers/DocumentHelper.test.ts @@ -1041,7 +1041,10 @@ More install detail. Usage instructions here.`, }); - const result = DocumentHelper.getAnchorContent(document, "h-installation"); + const result = DocumentHelper.getAnchorContent( + document, + "h-installation" + ); expect(result).toBe( `## Installation diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index a2ca5521de..33cede6324 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -63,6 +63,7 @@ import { GroupMembership, FileOperation, } from "@server/models"; +import { SearchQuerySource } from "@server/models/SearchQuery"; import AttachmentHelper from "@server/models/helpers/AttachmentHelper"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; @@ -1173,11 +1174,14 @@ router.post( // duplicate search query records if (query && offset === 0) { const duration = Date.now() - searchStartedAt; - await SearchQuery.create({ + await SearchQuery.record({ userId: user?.id, teamId, shareId: share?.id, - source: ctx.state.auth.type || "app", // we'll consider anything that isn't "api" to be "app" + // auth.type values are a subset of search sources; unauthenticated share searches default to "app" + source: + (ctx.state.auth.type as unknown as SearchQuerySource) || + SearchQuerySource.App, query, results: total, duration, diff --git a/server/routes/api/searches/searches.test.ts b/server/routes/api/searches/searches.test.ts index 3dacdacba3..5794706490 100644 --- a/server/routes/api/searches/searches.test.ts +++ b/server/routes/api/searches/searches.test.ts @@ -1,5 +1,6 @@ import type { User } from "@server/models"; import { SearchQuery } from "@server/models"; +import { SearchQuerySource } from "@server/models/SearchQuery"; import { buildSearchQuery, buildUser } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; @@ -25,7 +26,7 @@ describe("#searches.list", () => { userId: user.id, teamId: user.teamId, query: "bar", - source: "api", + source: SearchQuerySource.API, }), ]); }); @@ -44,7 +45,7 @@ describe("#searches.list", () => { it("should allow filtering by source", async () => { const res = await server.post("/api/searches.list", user, { body: { - source: "api", + source: SearchQuerySource.API, }, }); const body = await res.json(); diff --git a/server/routes/api/templates/schema.ts b/server/routes/api/templates/schema.ts index ecaf1c05c4..705e6ad93e 100644 --- a/server/routes/api/templates/schema.ts +++ b/server/routes/api/templates/schema.ts @@ -29,6 +29,9 @@ export const TemplatesListSchema = BaseSchema.extend({ body: TemplatesSortParamsSchema.extend({ /** Id of the collection to which the template belongs */ collectionId: z.string().uuid().optional(), + + /** Search query to filter templates by title */ + query: z.string().optional(), }), }); diff --git a/server/routes/api/templates/templates.test.ts b/server/routes/api/templates/templates.test.ts index 947aa6c017..928037e8f4 100644 --- a/server/routes/api/templates/templates.test.ts +++ b/server/routes/api/templates/templates.test.ts @@ -53,6 +53,32 @@ describe("#templates.list", () => { expect(body.data[0].id).toEqual(template.id); }); + it("should filter templates by query", async () => { + const user = await buildUser(); + const template = await buildTemplate({ + userId: user.id, + teamId: user.teamId, + title: "Meeting notes", + }); + await buildTemplate({ + userId: user.id, + teamId: user.teamId, + title: "Project plan", + }); + + const res = await server.post("/api/templates.list", user, { + body: { + query: "meeting", + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.length).toEqual(1); + expect(body.data[0].id).toEqual(template.id); + expect(body.pagination.total).toEqual(1); + }); + it("should require authentication", async () => { const res = await server.post("/api/templates.list"); expect(res.status).toEqual(401); diff --git a/server/routes/api/templates/templates.ts b/server/routes/api/templates/templates.ts index 76a25e0bae..8e7d1d2821 100644 --- a/server/routes/api/templates/templates.ts +++ b/server/routes/api/templates/templates.ts @@ -1,6 +1,6 @@ import Router from "koa-router"; import type { WhereOptions } from "sequelize"; -import { Op } from "sequelize"; +import { Op, Sequelize } from "sequelize"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import { transaction } from "@server/middlewares/transaction"; @@ -72,7 +72,7 @@ router.post( pagination(), validate(T.TemplatesListSchema), async (ctx: APIContext) => { - const { sort, direction, collectionId } = ctx.input.body; + const { sort, direction, collectionId, query } = ctx.input.body; const { user } = ctx.state.auth; const where: WhereOptions