Merge branch 'main' of github.com:outline/outline into oauth-server

This commit is contained in:
Tom Moor committed 2025-04-27 20:12:44 -04:00
commit 17f54c0ed0
11 files changed
+183 -448

No files matched your search

+13 -7
View File
@@ -195,21 +195,27 @@ const PaginatedList = <T extends PaginatedItem>({
}
}, [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(
+12 -33
View File
@@ -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<T.GitHubCallbackReq>({
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<T.GitHubCallbackReq>) => {
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(
+19 -46
View File
@@ -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<T.LinearCallbackReq>({
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<T.LinearCallbackReq>) => {
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());
}
+1 -1
View File
@@ -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)}`;
}
+12 -41
View File
@@ -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<T.NotionCallbackReq>({
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<T.NotionCallbackReq>) => {
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));
-3
View File
@@ -227,9 +227,6 @@ router.post(
const options = {
query: text,
limit: 5,
searchConfig: {
boostRecent: true,
},
};
if (!user) {
+11 -27
View File
@@ -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<T.SlackPostReq>({
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<T.SlackPostReq>) => {
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: {
+54
View File
@@ -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<T>({
getTeamId,
getRedirectPath,
getErrorPath,
}: {
/** Get the team ID for the current request */
getTeamId: (ctx: APIContext<T>) => string | null | undefined;
/** Get the redirect URL for the given team ID */
getRedirectPath: (ctx: APIContext<T>, team: Team) => string;
/** Get the error URL for the current request */
getErrorPath: (ctx: APIContext<T>) => string;
}) {
return async function apexAuthRedirectMiddleware(
ctx: APIContext<T>,
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));
}
};
}
+50 -238
View File
@@ -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);
});
});
});
+11 -49
View File
@@ -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<SearchResponse> {
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<SearchResponse> {
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"]);
}
-3
View File
@@ -1060,9 +1060,6 @@ router.post(
limit,
snippetMinWords,
snippetMaxWords,
searchConfig: {
boostRecent: true,
},
});
}