From a4ee81fa19168ae192648b454364d1595064c861 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 29 Apr 2025 22:43:21 -0400 Subject: [PATCH] OAuth server cloud compatibility (#9091) * Revert "Add recency boost to search results (#9038)" (#9065) This reverts commit 2bc47cfcef581f7736cebaf07ebac46280126364. * fix: Double fetch on refactored paginated list (#9068) * fix: Store Linear workspace logo only when it's available (#9072) * Extract subdomain auth redirect (#9070) * Extract subdomain auth redirect * docs * Switch Linear to actor=app method (#9074) * Basic /authorize framework for cloud auth * Handle logged out OAuth apex --------- Co-authored-by: Hemachandar <132386067+hmacr@users.noreply.github.com> --- app/actions/definitions/teams.tsx | 4 +- app/components/PaginatedList.tsx | 20 +- app/components/Sidebar/App.tsx | 6 +- app/hooks/useLoggedInSessions.ts | 14 + app/hooks/useRequest.ts | 2 +- .../{OrganizationMenu.tsx => TeamMenu.tsx} | 8 +- app/routes/authenticated.tsx | 3 - app/routes/index.tsx | 14 +- app/scenes/Login/Login.tsx | 13 +- app/scenes/Login/OAuthAuthorize.tsx | 73 +++-- app/scenes/Login/components/BackButton.tsx | 11 +- app/scenes/Login/components/ConnectHeader.tsx | 40 +++ app/scenes/Login/components/TeamSwitcher.tsx | 109 +++++++ plugins/github/server/api/github.ts | 45 +-- plugins/linear/server/api/linear.ts | 65 ++-- plugins/linear/shared/LinearUtils.ts | 2 +- plugins/notion/server/api/notion.ts | 53 +--- plugins/slack/server/api/hooks.ts | 3 - plugins/slack/server/auth/slack.ts | 38 +-- server/middlewares/apexAuthRedirect.ts | 54 ++++ server/models/helpers/SearchHelper.test.ts | 288 +++--------------- server/models/helpers/SearchHelper.ts | 60 +--- server/routes/api/documents/documents.ts | 3 - shared/i18n/locales/en_US/translation.json | 2 + 24 files changed, 418 insertions(+), 512 deletions(-) create mode 100644 app/hooks/useLoggedInSessions.ts rename app/menus/{OrganizationMenu.tsx => TeamMenu.tsx} (91%) create mode 100644 app/scenes/Login/components/ConnectHeader.tsx create mode 100644 app/scenes/Login/components/TeamSwitcher.tsx create mode 100644 server/middlewares/apexAuthRedirect.ts diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx index a9847551d7..02be788fd6 100644 --- a/app/actions/definitions/teams.tsx +++ b/app/actions/definitions/teams.tsx @@ -11,7 +11,7 @@ import { ActionContext } from "~/types"; import Desktop from "~/utils/Desktop"; import { TeamSection } from "../sections"; -export const createTeamsList = ({ stores }: { stores: RootStore }) => +export const switchTeamsList = ({ stores }: { stores: RootStore }) => stores.auth.availableTeams?.map((session) => ({ id: `switch-${session.id}`, name: session.name, @@ -44,7 +44,7 @@ export const switchTeam = createAction({ section: TeamSection, visible: ({ stores }) => !!stores.auth.availableTeams && stores.auth.availableTeams?.length > 1, - children: createTeamsList, + children: switchTeamsList, }); export const createTeam = createAction({ diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx index b289db622e..00e73a5e32 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -195,21 +195,27 @@ const PaginatedList = ({ } }, [allowLoadMore, isFetching, items?.length, renderCount, fetchResults]); - React.useEffect(() => { - void fetchResults(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - const prevFetch = usePrevious(fetch); const prevOptions = usePrevious(options); - // Equivalent to componentDidUpdate + // Initial fetch on mount React.useEffect(() => { + if (fetch) { + void fetchResults(); + } + }, [fetch]); + + // Handle updates to fetch or options + React.useEffect(() => { + if (!prevFetch || !prevOptions) { + return; // Skip on initial mount since it's handled by the above effect + } + if (prevFetch !== fetch || !isEqual(prevOptions, options)) { reset(); void fetchResults(); } - }, [fetch, options, reset, prevFetch, prevOptions, fetchResults]); + }, [fetch, options, reset, fetchResults, prevFetch, prevOptions]); // Computed property equivalent const itemsToRender = React.useMemo( diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index 1f89d2210c..633e3781fb 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -12,7 +12,7 @@ import useCurrentTeam from "~/hooks/useCurrentTeam"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; -import OrganizationMenu from "~/menus/OrganizationMenu"; +import TeamMenu from "~/menus/TeamMenu"; import { homePath, searchPath } from "~/utils/routeHelpers"; import TeamLogo from "../TeamLogo"; import Tooltip from "../Tooltip"; @@ -62,7 +62,7 @@ function AppSidebar() { - + {(props: SidebarButtonProps) => ( )} - +
; + +export function useLoggedInSessions(): Sessions { + return JSON.parse(getCookie("sessions") || "{}"); +} diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts index e5b6eed59a..4c40b81c68 100644 --- a/app/hooks/useRequest.ts +++ b/app/hooks/useRequest.ts @@ -59,7 +59,7 @@ export default function useRequest( if (makeRequestOnMount) { void request(); } - }, [request, makeRequestOnMount]); + }, []); return { data, loading, loaded, error, request }; } diff --git a/app/menus/OrganizationMenu.tsx b/app/menus/TeamMenu.tsx similarity index 91% rename from app/menus/OrganizationMenu.tsx rename to app/menus/TeamMenu.tsx index 1113476a71..6010ce7f7a 100644 --- a/app/menus/OrganizationMenu.tsx +++ b/app/menus/TeamMenu.tsx @@ -10,7 +10,7 @@ import { } from "~/actions/definitions/navigation"; import { createTeam, - createTeamsList, + switchTeamsList, desktopLoginTeam, } from "~/actions/definitions/teams"; import useActionContext from "~/hooks/useActionContext"; @@ -22,7 +22,7 @@ type Props = { children?: React.ReactNode; }; -const OrganizationMenu: React.FC = ({ children }: Props) => { +const TeamMenu: React.FC = ({ children }: Props) => { const menu = useMenuState({ unstable_offset: [4, -4], placement: "bottom-start", @@ -44,7 +44,7 @@ const OrganizationMenu: React.FC = ({ children }: Props) => { // menu is not cached at all. const actions = React.useMemo( () => [ - ...createTeamsList(context), + ...switchTeamsList(context), createTeam, desktopLoginTeam, separator(), @@ -64,4 +64,4 @@ const OrganizationMenu: React.FC = ({ children }: Props) => { ); }; -export default observer(OrganizationMenu); +export default observer(TeamMenu); diff --git a/app/routes/authenticated.tsx b/app/routes/authenticated.tsx index 0bfadfa57f..d778dc09f7 100644 --- a/app/routes/authenticated.tsx +++ b/app/routes/authenticated.tsx @@ -29,7 +29,6 @@ const Drafts = lazy(() => import("~/scenes/Drafts")); const Home = lazy(() => import("~/scenes/Home")); const Search = lazy(() => import("~/scenes/Search")); const Trash = lazy(() => import("~/scenes/Trash")); -const OAuthAuthorize = lazy(() => import("~/scenes/Login/OAuthAuthorize")); const RedirectDocument = ({ match, @@ -53,8 +52,6 @@ function AuthenticatedRoutes() { return ( - - import("~/components/Authenticated")); -const AuthenticatedRoutes = lazyWithRetry(() => import("./authenticated")); -const SharedDocument = lazyWithRetry(() => import("~/scenes/Document/Shared")); -const Login = lazyWithRetry(() => import("~/scenes/Login")); -const Logout = lazyWithRetry(() => import("~/scenes/Logout")); +const Authenticated = lazy(() => import("~/components/Authenticated")); +const AuthenticatedRoutes = lazy(() => import("./authenticated")); +const SharedDocument = lazy(() => import("~/scenes/Document/Shared")); +const Login = lazy(() => import("~/scenes/Login")); +const Logout = lazy(() => import("~/scenes/Logout")); +const OAuthAuthorize = lazy(() => import("~/scenes/Login/OAuthAuthorize")); export default function Routes() { useQueryNotices(); @@ -43,6 +44,7 @@ export default function Routes() { + diff --git a/app/scenes/Login/Login.tsx b/app/scenes/Login/Login.tsx index e35a35c48c..f41ac04f4a 100644 --- a/app/scenes/Login/Login.tsx +++ b/app/scenes/Login/Login.tsx @@ -42,9 +42,10 @@ import { getRedirectUrl, navigateToSubdomain } from "./urls"; type Props = { children?: (config?: Config) => React.ReactNode; + onBack?: () => void; }; -function Login({ children }: Props) { +function Login({ children, onBack }: Props) { const location = useLocation(); const query = useQuery(); const notice = query.get("notice"); @@ -110,7 +111,7 @@ function Login({ children }: Props) { if (error) { return ( - + @@ -142,7 +143,7 @@ function Login({ children }: Props) { if (isCloudHosted && isCustomDomain && !config.name) { return ( - + @@ -160,7 +161,7 @@ function Login({ children }: Props) { if (Desktop.isElectron() && notice === "domain-required") { return ( - + @@ -199,7 +200,7 @@ function Login({ children }: Props) { if (emailLinkSentTo) { return ( - + @@ -234,7 +235,7 @@ function Login({ children }: Props) { return ( - + diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx index 03027fa8ec..a35f625550 100644 --- a/app/scenes/Login/OAuthAuthorize.tsx +++ b/app/scenes/Login/OAuthAuthorize.tsx @@ -1,23 +1,49 @@ -import { MoreIcon } from "outline-icons"; import React from "react"; import { Trans, useTranslation } from "react-i18next"; import styled from "styled-components"; import Flex from "@shared/components/Flex"; import { s } from "@shared/styles"; -import { Avatar, AvatarSize } from "~/components/Avatar"; -import { AvatarVariant } from "~/components/Avatar/Avatar"; +import { parseDomain } from "@shared/utils/domains"; import ButtonLarge from "~/components/ButtonLarge"; +import ChangeLanguage from "~/components/ChangeLanguage"; import Heading from "~/components/Heading"; import LoadingIndicator from "~/components/LoadingIndicator"; import PageTitle from "~/components/PageTitle"; import Text from "~/components/Text"; +import env from "~/env"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import { useLoggedInSessions } from "~/hooks/useLoggedInSessions"; import useQuery from "~/hooks/useQuery"; import useRequest from "~/hooks/useRequest"; import { client } from "~/utils/ApiClient"; +import isCloudHosted from "~/utils/isCloudHosted"; +import { detectLanguage } from "~/utils/language"; +import Login from "./Login"; import { OAuthScopeHelper } from "./OAuthScopeHelper"; import { Background } from "./components/Background"; import { Centered } from "./components/Centered"; +import { ConnectHeader } from "./components/ConnectHeader"; +import { TeamSwitcher } from "./components/TeamSwitcher"; + +export default function OAuthAuthorize() { + const team = useCurrentTeam({ rejectOnEmpty: false }); + const sessions = useLoggedInSessions(); + + // We're self-hosted or on a team subdomain already, just show the authorize screen. + if (team) { + return ; + } + + // Cloud hosted and on root domain – show the workspace switcher. + const isAppRoot = + parseDomain(window.location.hostname).host === parseDomain(env.URL).host; + const hasLoggedInSessions = Object.keys(sessions).length > 0; + if (isCloudHosted && hasLoggedInSessions && isAppRoot) { + return ; + } + + return ; +} /** * Authorize component is responsible for handling the OAuth authorization process. @@ -40,17 +66,10 @@ function Authorize() { scope, } = Object.fromEntries(params); const [scopes] = React.useState(() => scope?.split(" ") ?? []); - const { - error: clientError, - data: response, - request, - } = useRequest(() => client.post("/oauthClients.info", { clientId })); - - React.useEffect(() => { - if (clientId) { - void request(); - } - }, []); + const { error: clientError, data: response } = useRequest( + () => client.post("/oauthClients.info", { clientId }), + true + ); const handleCancel = () => { if (window.history.length) { @@ -117,30 +136,10 @@ function Authorize() { return ( + - - - - - - - - - + {t(`{{ appName }} wants to access {{ teamName }}`, { appName: name, @@ -244,5 +243,3 @@ const Pre = styled.pre` font-size: 12px; white-space: pre-wrap; `; - -export default Authorize; diff --git a/app/scenes/Login/components/BackButton.tsx b/app/scenes/Login/components/BackButton.tsx index bf60efb344..477ce6992f 100644 --- a/app/scenes/Login/components/BackButton.tsx +++ b/app/scenes/Login/components/BackButton.tsx @@ -10,12 +10,21 @@ import isCloudHosted from "~/utils/isCloudHosted"; type Props = { config?: Config; + onBack?: () => void; }; -export function BackButton({ config }: Props) { +export function BackButton({ onBack, config }: Props) { const { t } = useTranslation(); const isSubdomain = !!config?.hostname; + if (onBack) { + return ( + + {t("Back")} + + ); + } + if (!isCloudHosted || parseDomain(window.location.origin).custom) { return null; } diff --git a/app/scenes/Login/components/ConnectHeader.tsx b/app/scenes/Login/components/ConnectHeader.tsx new file mode 100644 index 0000000000..4e7bb6d97c --- /dev/null +++ b/app/scenes/Login/components/ConnectHeader.tsx @@ -0,0 +1,40 @@ +import { MoreIcon } from "outline-icons"; +import * as React from "react"; +import Flex from "@shared/components/Flex"; +import Text from "@shared/components/Text"; +import type Team from "~/models/Team"; +import type OAuthClient from "~/models/oauth/OAuthClient"; +import { Avatar } from "~/components/Avatar"; +import { AvatarSize, AvatarVariant } from "~/components/Avatar/Avatar"; + +type Props = { + team: Team; + oauthClient: OAuthClient; +}; + +export function ConnectHeader({ team, oauthClient }: Props) { + return ( + + + + + + + + + + ); +} diff --git a/app/scenes/Login/components/TeamSwitcher.tsx b/app/scenes/Login/components/TeamSwitcher.tsx new file mode 100644 index 0000000000..a0007089ef --- /dev/null +++ b/app/scenes/Login/components/TeamSwitcher.tsx @@ -0,0 +1,109 @@ +import { ArrowIcon } from "outline-icons"; +import React from "react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import Text from "@shared/components/Text"; +import { s } from "@shared/styles"; +import { AvatarSize } from "~/components/Avatar"; +import Avatar, { AvatarVariant } from "~/components/Avatar/Avatar"; +import ChangeLanguage from "~/components/ChangeLanguage"; +import Heading from "~/components/Heading"; +import OutlineIcon from "~/components/Icons/OutlineIcon"; +import env from "~/env"; +import type { Sessions } from "~/hooks/useLoggedInSessions"; +import { detectLanguage } from "~/utils/language"; +import Login from "../Login"; +import { Background } from "./Background"; +import { Centered } from "./Centered"; + +type Props = { sessions: Sessions }; + +export function TeamSwitcher({ sessions }: Props) { + const { t } = useTranslation(); + const [showLogin, setShowLogin] = React.useState(false); + const url = new URL(window.location.href); + const appName = env.APP_NAME; + + if (showLogin) { + return setShowLogin(false)} />; + } + + return ( + + + + + + {t("Choose a workspace")} + + {t( + "Choose an {{ appName }} workspace or login to continue connecting this app", + { appName } + )} + . + + {Object.keys(sessions)?.map((teamId) => { + const session = sessions[teamId]; + const location = session.url + url.pathname + url.search; + return ( + + + {session.name} + + + ); + })} + setShowLogin(true)}> + + {t("Login to workspace")} + + + + ); +} + +const StyledArrowIcon = styled(ArrowIcon)` + position: absolute; + transition: all 0.2s ease-in-out; + opacity: 0; + right: 12px; +`; + +const TeamLink = styled.a` + position: relative; + left: -8px; + right: -8px; + display: flex; + align-items: center; + gap: 8px; + padding: 8px; + margin: 4px; + border-radius: 8px; + width: 100%; + color: ${s("text")}; + font-weight: ${s("fontWeightMedium")}; + + &:hover { + background: ${s("listItemHoverBackground")}; + + ${StyledArrowIcon} { + opacity: 1; + right: 8px; + } + } +`; + +const StyledHeading = styled(Heading).attrs({ + as: "h2", + centered: true, +})` + margin-top: 0; +`; diff --git a/plugins/github/server/api/github.ts b/plugins/github/server/api/github.ts index 993b630b94..b961df3132 100644 --- a/plugins/github/server/api/github.ts +++ b/plugins/github/server/api/github.ts @@ -1,13 +1,12 @@ import Router from "koa-router"; import find from "lodash/find"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; import { createContext } from "@server/context"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { IntegrationAuthentication, Integration, Team } from "@server/models"; +import { IntegrationAuthentication, Integration } from "@server/models"; import { APIContext } from "@server/types"; import { GitHubUtils } from "../../shared/GitHubUtils"; import { GitHub } from "../github"; @@ -17,10 +16,17 @@ const router = new Router(); router.get( "github.callback", - auth({ - optional: true, - }), + auth({ optional: true }), validate(T.GitHubCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => ctx.input.query.state, + getRedirectPath: (ctx, team) => + GitHubUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => GitHubUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { const { @@ -43,33 +49,6 @@ router.get( return; } - // this code block accounts for the root domain being unable to - // access authentication for subdomains. We must forward to the appropriate - // subdomain to complete the oauth flow - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - GitHubUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(GitHubUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(GitHubUtils.errorUrl("unauthenticated")); - } - } - const client = await GitHub.authenticateAsUser(code!, teamId); const installationsByUser = await client.requestAppInstallations(); const installation = find( diff --git a/plugins/linear/server/api/linear.ts b/plugins/linear/server/api/linear.ts index 033c2fde88..4b879a4f97 100644 --- a/plugins/linear/server/api/linear.ts +++ b/plugins/linear/server/api/linear.ts @@ -1,11 +1,10 @@ import Router from "koa-router"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { IntegrationAuthentication, Integration, Team } from "@server/models"; +import { IntegrationAuthentication, Integration } from "@server/models"; import { APIContext } from "@server/types"; import { Linear } from "../linear"; import UploadLinearWorkspaceLogoTask from "../tasks/UploadLinearWorkspaceLogoTask"; @@ -20,49 +19,21 @@ router.get( optional: true, }), validate(T.LinearCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => LinearUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + LinearUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => LinearUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { - const { code, state, error } = ctx.input.query; + const { code, error } = ctx.input.query; const { user } = ctx.state.auth; const { transaction } = ctx.state; - let parsedState; - try { - parsedState = LinearUtils.parseState(state); - } catch { - ctx.redirect(LinearUtils.errorUrl("invalid_state")); - return; - } - - const { teamId } = parsedState; - - // this code block accounts for the root domain being unable to - // access authentication for subdomains. We must forward to the appropriate - // subdomain to complete the oauth flow - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - LinearUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(LinearUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(LinearUtils.errorUrl("unauthenticated")); - } - } - // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { ctx.redirect(LinearUtils.errorUrl(error)); @@ -106,12 +77,14 @@ router.get( { transaction } ); - transaction.afterCommit(async () => { - await UploadLinearWorkspaceLogoTask.schedule({ - integrationId: integration.id, - logoUrl: workspace.logoUrl, + if (workspace.logoUrl) { + transaction.afterCommit(async () => { + await UploadLinearWorkspaceLogoTask.schedule({ + integrationId: integration.id, + logoUrl: workspace.logoUrl, + }); }); - }); + } ctx.redirect(LinearUtils.successUrl()); } diff --git a/plugins/linear/shared/LinearUtils.ts b/plugins/linear/shared/LinearUtils.ts index 0ebee10724..f600980ad0 100644 --- a/plugins/linear/shared/LinearUtils.ts +++ b/plugins/linear/shared/LinearUtils.ts @@ -46,7 +46,7 @@ export class LinearUtils { scope: this.oauthScopes, response_type: "code", prompt: "consent", - actor: "application", + actor: "app", }; return `${this.authBaseUrl}?${queryString.stringify(params)}`; } diff --git a/plugins/notion/server/api/notion.ts b/plugins/notion/server/api/notion.ts index 7a59eb7c4d..e9b534f204 100644 --- a/plugins/notion/server/api/notion.ts +++ b/plugins/notion/server/api/notion.ts @@ -1,11 +1,10 @@ import Router from "koa-router"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; -import Logger from "@server/logging/Logger"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { Integration, IntegrationAuthentication, Team } from "@server/models"; +import { Integration, IntegrationAuthentication } from "@server/models"; import { APIContext } from "@server/types"; import { NotionClient } from "../notion"; import * as T from "./schema"; @@ -17,49 +16,21 @@ router.get( "notion.callback", auth({ optional: true }), validate(T.NotionCallbackSchema), + apexAuthRedirect({ + getTeamId: (ctx) => NotionUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + NotionUtils.callbackUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => NotionUtils.errorUrl("unauthenticated"), + }), transaction(), async (ctx: APIContext) => { - const { code, state, error } = ctx.input.query; + const { code, error } = ctx.input.query; const { user } = ctx.state.auth; const { transaction } = ctx.state; - let parsedState; - try { - parsedState = NotionUtils.parseState(state); - } catch { - ctx.redirect(NotionUtils.errorUrl("invalid_state")); - return; - } - - const { teamId } = parsedState; - - // This code block accounts for the root domain being unable to access authentication for subdomains. - // We must forward to the appropriate subdomain to complete the oauth flow. - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - transaction, - }); - - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - NotionUtils.callbackUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - Logger.error(`Error fetching team for teamId: ${teamId}!`, err); - return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(NotionUtils.errorUrl("unauthenticated")); - } - } - // Check error after any sub-domain redirection. Otherwise, the user will be redirected to the root domain. if (error) { ctx.redirect(NotionUtils.errorUrl(error)); diff --git a/plugins/slack/server/api/hooks.ts b/plugins/slack/server/api/hooks.ts index 9b88c42348..f280673265 100644 --- a/plugins/slack/server/api/hooks.ts +++ b/plugins/slack/server/api/hooks.ts @@ -227,9 +227,6 @@ router.post( const options = { query: text, limit: 5, - searchConfig: { - boostRecent: true, - }, }; if (!user) { diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index 58064c779b..e703193353 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -4,16 +4,15 @@ import Router from "koa-router"; import { Profile } from "passport"; import { Strategy as SlackStrategy } from "passport-slack-oauth2"; import { IntegrationService, IntegrationType } from "@shared/types"; -import { parseDomain } from "@shared/utils/domains"; import accountProvisioner from "@server/commands/accountProvisioner"; import { ValidationError } from "@server/errors"; +import apexAuthRedirect from "@server/middlewares/apexAuthRedirect"; import auth from "@server/middlewares/authentication"; import passportMiddleware from "@server/middlewares/passport"; import validate from "@server/middlewares/validate"; import { IntegrationAuthentication, Integration, - Team, User, Collection, } from "@server/models"; @@ -126,6 +125,15 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { "slack.post", auth({ optional: true }), validate(T.SlackPostSchema), + apexAuthRedirect({ + getTeamId: (ctx) => SlackUtils.parseState(ctx.input.query.state)?.teamId, + getRedirectPath: (ctx, team) => + SlackUtils.connectUrl({ + baseUrl: team.url, + params: ctx.request.querystring, + }), + getErrorPath: () => SlackUtils.errorUrl("unauthenticated"), + }), async (ctx: APIContext) => { const { code, error, state } = ctx.input.query; const { user } = ctx.state.auth; @@ -144,31 +152,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { throw ValidationError("Invalid state"); } - const { teamId, collectionId, type } = parsedState; - - // This code block accounts for the root domain being unable to access authentication for - // subdomains. We must forward to the appropriate subdomain to complete the OAuth flow. - if (!user) { - if (teamId) { - try { - const team = await Team.findByPk(teamId, { - rejectOnEmpty: true, - }); - return parseDomain(ctx.host).teamSubdomain === team.subdomain - ? ctx.redirect("/") - : ctx.redirectOnClient( - SlackUtils.connectUrl({ - baseUrl: team.url, - params: ctx.request.querystring, - }) - ); - } catch (err) { - return ctx.redirect(SlackUtils.errorUrl("unauthenticated")); - } - } else { - return ctx.redirect(SlackUtils.errorUrl("unauthenticated")); - } - } + const { collectionId, type } = parsedState; switch (type) { case IntegrationType.Post: { diff --git a/server/middlewares/apexAuthRedirect.ts b/server/middlewares/apexAuthRedirect.ts new file mode 100644 index 0000000000..6b959b7273 --- /dev/null +++ b/server/middlewares/apexAuthRedirect.ts @@ -0,0 +1,54 @@ +import { Next } from "koa"; +import { parseDomain } from "@shared/utils/domains"; +import { Team } from "@server/models"; +import { APIContext } from "@server/types"; + +/** + * An authentication middleware that should be used on routes that return from external auth flows + * to the apex domain. In these cases the user will be redirected to the correct subdomain where + * they are authenticated. + * + * @param options Options for the middleware + * @returns Koa middleware function + */ +export default function apexAuthRedirect({ + getTeamId, + getRedirectPath, + getErrorPath, +}: { + /** Get the team ID for the current request */ + getTeamId: (ctx: APIContext) => string | null | undefined; + /** Get the redirect URL for the given team ID */ + getRedirectPath: (ctx: APIContext, team: Team) => string; + /** Get the error URL for the current request */ + getErrorPath: (ctx: APIContext) => string; +}) { + return async function apexAuthRedirectMiddleware( + ctx: APIContext, + next: Next + ) { + const { user } = ctx.state.auth; + if (user) { + return next(); + } + + const teamId = getTeamId(ctx); + + if (teamId) { + try { + const team = await Team.findByPk(teamId, { + attributes: ["id", "subdomain"], + rejectOnEmpty: true, + }); + + return parseDomain(ctx.host).teamSubdomain === team.subdomain + ? ctx.redirect("/") + : ctx.redirectOnClient(getRedirectPath(ctx, team)); + } catch (err) { + return ctx.redirect(getErrorPath(ctx)); + } + } else { + return ctx.redirect(getErrorPath(ctx)); + } + }; +} diff --git a/server/models/helpers/SearchHelper.test.ts b/server/models/helpers/SearchHelper.test.ts index 15836f2f15..e5f21f1441 100644 --- a/server/models/helpers/SearchHelper.test.ts +++ b/server/models/helpers/SearchHelper.test.ts @@ -1,25 +1,23 @@ -import { describe, expect } from "@jest/globals"; -import { subMonths } from "date-fns"; import { DocumentPermission, StatusFilter } from "@shared/types"; +import SearchHelper from "@server/models/helpers/SearchHelper"; import { - buildTeam, - buildUser, - buildCollection, buildDocument, buildDraftDocument, + buildCollection, + buildTeam, + buildUser, buildShare, } from "@server/test/factories"; import UserMembership from "../UserMembership"; -import SearchHelper from "./SearchHelper"; + +beforeEach(async () => { + jest.resetAllMocks(); + await buildDocument(); +}); describe("SearchHelper", () => { describe("#searchForTeam", () => { - beforeEach(async () => { - jest.resetAllMocks(); - await buildDocument(); - }); - - it("should return search results from public collections", async () => { + test("should return search results from public collections", async () => { const team = await buildTeam(); const collection = await buildCollection({ teamId: team.id, @@ -36,7 +34,7 @@ describe("SearchHelper", () => { expect(results[0].document?.id).toBe(document.id); }); - it("should return search results from a collection without search term", async () => { + test("should return search results from a collection without search term", async () => { const team = await buildTeam(); const collection = await buildCollection({ teamId: team.id, @@ -60,7 +58,7 @@ describe("SearchHelper", () => { ); }); - it("should not return results from private collections without providing collectionId", async () => { + test("should not return results from private collections without providing collectionId", async () => { const team = await buildTeam(); const collection = await buildCollection({ permission: null, @@ -77,7 +75,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); - it("should return results from private collections when collectionId is provided", async () => { + test("should return results from private collections when collectionId is provided", async () => { const team = await buildTeam(); const collection = await buildCollection({ permission: null, @@ -95,7 +93,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(1); }); - it("should return results from document tree of shared document", async () => { + test("should return results from document tree of shared document", async () => { const team = await buildTeam(); const collection = await buildCollection({ permission: null, @@ -125,7 +123,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(1); }); - it("should handle no collections", async () => { + test("should handle no collections", async () => { const team = await buildTeam(); const { results } = await SearchHelper.searchForTeam(team, { query: "test", @@ -133,7 +131,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); - it("should handle backslashes in search term", async () => { + test("should handle backslashes in search term", async () => { const team = await buildTeam(); const { results } = await SearchHelper.searchForTeam(team, { query: "\\\\", @@ -141,7 +139,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); - it("should return the total count of search results", async () => { + test("should return the total count of search results", async () => { const team = await buildTeam(); const collection = await buildCollection({ teamId: team.id, @@ -162,7 +160,7 @@ describe("SearchHelper", () => { expect(total).toBe(2); }); - it("should return the document when searched with their previous titles", async () => { + test("should return the document when searched with their previous titles", async () => { const team = await buildTeam(); const collection = await buildCollection({ teamId: team.id, @@ -180,7 +178,7 @@ describe("SearchHelper", () => { expect(total).toBe(1); }); - it("should not return the document when searched with neither the titles nor the previous titles", async () => { + test("should not return the document when searched with neither the titles nor the previous titles", async () => { const team = await buildTeam(); const collection = await buildCollection({ teamId: team.id, @@ -200,12 +198,7 @@ describe("SearchHelper", () => { }); describe("#searchForUser", () => { - beforeEach(async () => { - jest.resetAllMocks(); - await buildDocument(); - }); - - it("should return search results from collections", async () => { + test("should return search results from collections", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -233,7 +226,7 @@ describe("SearchHelper", () => { expect(results[0].document?.id).toBe(document.id); }); - it("should return search results for a user without search term", async () => { + test("should return search results for a user without search term", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -261,7 +254,7 @@ describe("SearchHelper", () => { ); }); - it("should return search results from a collection without search term", async () => { + test("should return search results from a collection without search term", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -291,7 +284,7 @@ describe("SearchHelper", () => { ); }); - it("should handle no collections", async () => { + test("should handle no collections", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const { results } = await SearchHelper.searchForUser(user, { @@ -300,7 +293,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); - it("should search only drafts created by user", async () => { + test("should search only drafts created by user", async () => { const user = await buildUser(); await buildDraftDocument({ title: "test", @@ -331,7 +324,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(1); }); - it("should not include drafts with user read permission", async () => { + test("should not include drafts with user read permission", async () => { const user = await buildUser(); await buildDraftDocument({ title: "test", @@ -356,7 +349,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(0); }); - it("should search only published created by user", async () => { + test("should search only published created by user", async () => { const user = await buildUser(); await buildDocument({ title: "test", @@ -387,7 +380,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(1); }); - it("should search only archived documents created by user", async () => { + test("should search only archived documents created by user", async () => { const user = await buildUser(); await buildDocument({ title: "test", @@ -424,7 +417,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(1); }); - it("should return results from archived and published", async () => { + test("should return results from archived and published", async () => { const user = await buildUser(); await buildDraftDocument({ teamId: user.teamId, @@ -452,7 +445,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(2); }); - it("should return results from drafts and published", async () => { + test("should return results from drafts and published", async () => { const user = await buildUser(); await buildDocument({ userId: user.id, @@ -480,7 +473,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(2); }); - it("should include results from drafts and archived", async () => { + test("should include results from drafts and archived", async () => { const user = await buildUser(); await buildDocument({ userId: user.id, @@ -508,7 +501,7 @@ describe("SearchHelper", () => { expect(results.length).toBe(2); }); - it("should return the total count of search results", async () => { + test("should return the total count of search results", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -533,7 +526,7 @@ describe("SearchHelper", () => { expect(total).toBe(2); }); - it("should return the document when searched with their previous titles", async () => { + test("should return the document when searched with their previous titles", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -554,7 +547,7 @@ describe("SearchHelper", () => { expect(total).toBe(1); }); - it("should not return the document when searched with neither the titles nor the previous titles", async () => { + test("should not return the document when searched with neither the titles nor the previous titles", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -575,7 +568,7 @@ describe("SearchHelper", () => { expect(total).toBe(0); }); - it("should find exact phrases", async () => { + test("should find exact phrases", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -596,7 +589,7 @@ describe("SearchHelper", () => { expect(total).toBe(1); }); - it("should correctly handle removal of trailing spaces", async () => { + test("should correctly handle removal of trailing spaces", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -619,12 +612,7 @@ describe("SearchHelper", () => { }); describe("#searchTitlesForUser", () => { - beforeEach(async () => { - jest.resetAllMocks(); - await buildDocument(); - }); - - it("should return search results from collections", async () => { + test("should return search results from collections", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -644,7 +632,7 @@ describe("SearchHelper", () => { expect(documents[0]?.id).toBe(document.id); }); - it("should filter to specific collection", async () => { + test("should filter to specific collection", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection = await buildCollection({ @@ -680,7 +668,7 @@ describe("SearchHelper", () => { expect(documents[0]?.id).toBe(document.id); }); - it("should handle no collections", async () => { + test("should handle no collections", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const documents = await SearchHelper.searchTitlesForUser(user, { @@ -689,7 +677,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(0); }); - it("should search only drafts created by user", async () => { + test("should search only drafts created by user", async () => { const user = await buildUser(); await buildDraftDocument({ title: "test", @@ -720,7 +708,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(1); }); - it("should search only published created by user", async () => { + test("should search only published created by user", async () => { const user = await buildUser(); await buildDocument({ title: "test", @@ -751,7 +739,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(1); }); - it("should search only archived documents created by user", async () => { + test("should search only archived documents created by user", async () => { const user = await buildUser(); await buildDocument({ title: "test", @@ -788,7 +776,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(1); }); - it("should return results from archived and published", async () => { + test("should return results from archived and published", async () => { const user = await buildUser(); await buildDraftDocument({ teamId: user.teamId, @@ -816,7 +804,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(2); }); - it("should return results from drafts and published", async () => { + test("should return results from drafts and published", async () => { const user = await buildUser(); await buildDocument({ userId: user.id, @@ -844,7 +832,7 @@ describe("SearchHelper", () => { expect(documents.length).toBe(2); }); - it("should include results from drafts and archived", async () => { + test("should include results from drafts and archived", async () => { const user = await buildUser(); await buildDocument({ userId: user.id, @@ -874,12 +862,7 @@ describe("SearchHelper", () => { }); describe("#searchCollectionsForUser", () => { - beforeEach(async () => { - jest.resetAllMocks(); - await buildDocument(); - }); - - it("should return search results from collections", async () => { + test("should return search results from collections", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection1 = await buildCollection({ @@ -901,7 +884,7 @@ describe("SearchHelper", () => { expect(results[0].id).toBe(collection1.id); }); - it("should return all collections when no query provided", async () => { + test("should return all collections when no query provided", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); const collection1 = await buildCollection({ @@ -924,196 +907,25 @@ describe("SearchHelper", () => { }); describe("webSearchQuery", () => { - it("should correctly sanitize query", () => { + test("should correctly sanitize query", () => { expect(SearchHelper.webSearchQuery("one/two")).toBe("one/two:*"); expect(SearchHelper.webSearchQuery("one\\two")).toBe("one\\\\two:*"); expect(SearchHelper.webSearchQuery("test''")).toBe("test"); }); - it("should wildcard unquoted queries", () => { + test("should wildcard unquoted queries", () => { expect(SearchHelper.webSearchQuery("test")).toBe("test:*"); expect(SearchHelper.webSearchQuery("'")).toBe(""); expect(SearchHelper.webSearchQuery("'quoted'")).toBe(`"quoted":*`); }); - it("should wildcard multi-word queries", () => { + test("should wildcard multi-word queries", () => { expect(SearchHelper.webSearchQuery("this is a test")).toBe( "this&is&a&test:*" ); }); - it("should not wildcard quoted queries", () => { + test("should not wildcard quoted queries", () => { expect(SearchHelper.webSearchQuery(`"this is a test"`)).toBe( `"this<->is<->a<->test"` ); }); }); - - describe("searchConfig", () => { - it("should boost recent documents when boostRecentMonths is set", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ teamId: team.id }); - const now = new Date(); - - const recentDoc = await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document recent", - text: "test search term recent", - }); - - // Set date 4 months ago - const olderDoc = await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document older", - text: "test search term older test", - createdAt: subMonths(now, 4), - updatedAt: subMonths(now, 4), - }); - - // Search without recency boost - const resultsWithoutBoost = await SearchHelper.searchForUser(user, { - query: "test search term", - }); - - // Search with recency boost - const resultsWithBoost = await SearchHelper.searchForUser(user, { - query: "test search term", - searchConfig: { - boostRecent: true, - boostRecentMonths: 6, - maxRecentBoost: 2.0, - }, - }); - - // Without boost, documents should be ordered by base relevance - expect(resultsWithoutBoost.results.length).toBe(2); - expect(resultsWithoutBoost.results[0].document.id).toBe(olderDoc.id); - expect(resultsWithoutBoost.results[1].document.id).toBe(recentDoc.id); - - // With boost, recent document should be ranked higher - expect(resultsWithBoost.results.length).toBe(2); - expect(resultsWithBoost.results[0].document.id).toBe(recentDoc.id); - expect(resultsWithBoost.results[1].document.id).toBe(olderDoc.id); - - // Recent document should have higher ranking - expect(resultsWithBoost.results[0].ranking).toBeGreaterThan( - resultsWithBoost.results[1].ranking - ); - }); - - it("should respect different time windows", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ teamId: team.id }); - const now = new Date(); - - const recentDoc = await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document recent", - text: "test search term recent", - }); - - // Set date 2 months ago - const twoMonthOldDoc = await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document two months", - text: "test search term two months", - createdAt: subMonths(now, 2), - updatedAt: subMonths(now, 2), - }); - - // Search with 1-month window - const resultsShortWindow = await SearchHelper.searchForUser(user, { - query: "test search term", - searchConfig: { - boostRecent: true, - boostRecentMonths: 1, - maxRecentBoost: 2.0, - }, - }); - - // Search with 3-month window - const resultsLongWindow = await SearchHelper.searchForUser(user, { - query: "test search term", - searchConfig: { - boostRecentMonths: 3, - maxRecentBoost: 2.0, - }, - }); - - // With 1-month window, two-month-old doc should have no boost - expect(resultsShortWindow.results[0].document.id).toBe(recentDoc.id); - expect(resultsShortWindow.results[1].document.id).toBe(twoMonthOldDoc.id); - expect(resultsShortWindow.results[0].ranking).toBeGreaterThan( - resultsShortWindow.results[1].ranking * 1.5 - ); - - // With 3-month window, two-month-old doc should have some boost - expect(resultsLongWindow.results[0].document.id).toBe(recentDoc.id); - expect(resultsLongWindow.results[1].document.id).toBe(twoMonthOldDoc.id); - const rankingRatio = - resultsLongWindow.results[0].ranking / - resultsLongWindow.results[1].ranking; - expect(rankingRatio).toBeLessThan(1.5); - expect(rankingRatio).toBeGreaterThan(1.0); - }); - - it("should respect custom boost factor", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ teamId: team.id }); - const now = new Date(); - - const recentDoc = await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document recent", - text: "test search term recent", - }); - - // Set date 2 months ago - await buildDocument({ - teamId: team.id, - collectionId: collection.id, - title: "test document older", - text: "test search term older", - createdAt: subMonths(now, 2), - updatedAt: subMonths(now, 2), - }); - - // Search with low boost factor - const resultsLowBoost = await SearchHelper.searchForUser(user, { - query: "test search term", - searchConfig: { - boostRecent: true, - boostRecentMonths: 6, - maxRecentBoost: 1.2, - }, - }); - - // Search with high boost factor - const resultsHighBoost = await SearchHelper.searchForUser(user, { - query: "test search term", - searchConfig: { - boostRecent: true, - boostRecentMonths: 6, - maxRecentBoost: 3.0, - }, - }); - - // Both searches should rank recent document higher - expect(resultsLowBoost.results[0].document.id).toBe(recentDoc.id); - expect(resultsHighBoost.results[0].document.id).toBe(recentDoc.id); - - // High boost should have greater difference in rankings - const lowBoostRatio = - resultsLowBoost.results[0].ranking / resultsLowBoost.results[1].ranking; - const highBoostRatio = - resultsHighBoost.results[0].ranking / - resultsHighBoost.results[1].ranking; - expect(highBoostRatio).toBeGreaterThan(lowBoostRatio); - }); - }); }); diff --git a/server/models/helpers/SearchHelper.ts b/server/models/helpers/SearchHelper.ts index c4759c97aa..e8a85d83b0 100644 --- a/server/models/helpers/SearchHelper.ts +++ b/server/models/helpers/SearchHelper.ts @@ -37,14 +37,6 @@ type SearchResponse = { total: number; }; -type SearchConfig = { - boostRecent?: boolean; - /** Time window in months for recent content boosting. When set, enables recency boosting. */ - boostRecentMonths?: number; - /** Maximum boost multiplier for recent content */ - maxRecentBoost?: number; -}; - type SearchOptions = { /** The query limit for pagination */ limit?: number; @@ -68,8 +60,6 @@ type SearchOptions = { snippetMinWords?: number; /** The maximum number of words to be returned in the contextual snippet */ snippetMaxWords?: number; - /** Configuration for search behavior */ - searchConfig?: SearchConfig; }; type RankedDocument = Document & { @@ -89,7 +79,7 @@ export default class SearchHelper { team: Team, options: SearchOptions = {} ): Promise { - const { limit = 15, offset = 0, query, searchConfig } = options; + const { limit = 15, offset = 0, query } = options; const where = await this.buildWhere(team, { ...options, @@ -111,7 +101,7 @@ export default class SearchHelper { }); } - const findOptions = this.buildFindOptions(query, searchConfig); + const findOptions = this.buildFindOptions(query); try { const resultsQuery = Document.unscoped().findAll({ @@ -246,11 +236,11 @@ export default class SearchHelper { user: User, options: SearchOptions = {} ): Promise { - const { limit = 15, offset = 0, query, searchConfig } = options; + const { limit = 15, offset = 0, query } = options; const where = await this.buildWhere(user, options); - const findOptions = this.buildFindOptions(query, searchConfig); + const findOptions = this.buildFindOptions(query); const include = [ { @@ -319,46 +309,18 @@ export default class SearchHelper { } } - private static buildFindOptions( - query?: string, - searchConfig?: SearchConfig - ): FindOptions { + private static buildFindOptions(query?: string): FindOptions { const attributes: FindAttributeOptions = ["id"]; const replacements: BindOrReplacements = {}; const order: Order = [["updatedAt", "DESC"]]; if (query) { - // Default values for recency boosting - const boostRecent = searchConfig?.boostRecent ?? false; - const boostRecentMonths = searchConfig?.boostRecentMonths ?? 2; - const maxRecentBoost = searchConfig?.maxRecentBoost ?? 2.0; - - if (boostRecent) { - // Calculate ranking with recency boost - // The formula creates a multiplier between 1.0 and maxRecentBoost based on document age - attributes.push([ - Sequelize.literal( - `( - ts_rank("searchVector", to_tsquery('english', :query)) * - (1 + (LEAST( - ${maxRecentBoost - 1}, - (1 - EXTRACT(EPOCH FROM (NOW() - document."updatedAt")) / - EXTRACT(EPOCH FROM INTERVAL '${boostRecentMonths} months')) - ) * ${maxRecentBoost})) - )` - ), - "searchRanking", - ]); - } else { - // Original ranking without recency boost - attributes.push([ - Sequelize.literal( - `ts_rank("searchVector", to_tsquery('english', :query))` - ), - "searchRanking", - ]); - } - + attributes.push([ + Sequelize.literal( + `ts_rank("searchVector", to_tsquery('english', :query))` + ), + "searchRanking", + ]); replacements["query"] = this.webSearchQuery(query); order.unshift(["searchRanking", "DESC"]); } diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 55b8cb2a59..a6a015c134 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1060,9 +1060,6 @@ router.post( limit, snippetMinWords, snippetMaxWords, - searchConfig: { - boostRecent: true, - }, }); } diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 5576e578f2..8ef4130f51 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -819,6 +819,8 @@ "Authentication failed – this login method was disabled by a workspace admin.": "Authentication failed – this login method was disabled by a workspace admin.", "The workspace you are trying to join requires an invite before you can create an account.<1>Please request an invite from your workspace admin and try again.": "The workspace you are trying to join requires an invite before you can create an account.<1>Please request an invite from your workspace admin and try again.", "Sorry, an unknown error occurred.": "Sorry, an unknown error occurred.", + "Choose a workspace": "Choose a workspace", + "Choose an {{ appName }} workspace or login to continue connecting this app": "Choose an {{ appName }} workspace or login to continue connecting this app", "Login": "Login", "Error": "Error", "Failed to load configuration.": "Failed to load configuration.",