Files
outline/server/routes/api/users/users.ts
T
Tom MoorandClaude Opus 5 41616f73cc feat: Filter DSL for users.list (#13456)
* feat: Filter DSL for users.list

Add the structured filter expression language already used by documents.list
and documents.search to users.list, over an allowlist of id, name, email,
role, createdAt, updatedAt, lastActiveAt and suspendedAt.

Supersedes the ad-hoc ids, emails, role and filter parameters, which are now
deprecated and translated into the DSL so a single path builds the query. The
same translation backs the list_users MCP tool, which held a duplicate copy of
the status handling.

Field specs gain an optional value allowlist, so an unknown role is rejected
at the input layer rather than reaching the enum column. Suspended users
remain invisible to non-admins and excluded by default, unless the expression
references suspendedAt.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: Collapse the duplicate suspended user predicate

The non-admin invariant and the default exclusion pushed the same clause for
non-admins in the default case. Both rules are now one predicate: suspended
users are visible to admins only, and then only on request.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor: Drop the legacy parameters from the list_users MCP tool

The MCP surface has no backwards compatibility burden, so it takes the filter
DSL directly instead of the deprecated role and status parameters. This gives
the model date ranges, OR groups and name matching, which the old enum pair
could not express.

The field allowlist moves next to the other user filter helpers so the REST
schema and the tool share one definition rather than the tools directory
reaching into the routes.

Drops the unreachable Date member of FilterValue. Dates cross the wire as ISO
8601 strings, a Date instance fails every field kind, and zod cannot represent
it in the JSON Schema the MCP tool list is built from.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* revert: Retain legacy role/filter params in the list_users MCP tool for now

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert MCP changes

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 10:47:32 -04:00

681 lines
17 KiB
TypeScript

import Router from "koa-router";
import type { WhereOptions } from "sequelize";
import { Op, Sequelize } from "sequelize";
import { NotificationEventType, UserRole } from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import { settingsPath } from "@shared/utils/routeHelpers";
import { UserValidation } from "@shared/validations";
import userInviter from "@server/commands/userInviter";
import ConfirmUpdateEmail from "@server/emails/templates/ConfirmUpdateEmail";
import ConfirmUserDeleteEmail from "@server/emails/templates/ConfirmUserDeleteEmail";
import InviteEmail from "@server/emails/templates/InviteEmail";
import env from "@server/env";
import { ValidationError } from "@server/errors";
import logger from "@server/logging/Logger";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import { User, Team } from "@server/models";
import {
buildWhere,
combineFilters,
hasFieldInFilter,
legacyUserParamsToFilter,
} from "@server/models/helpers/Filters";
import { UserFlag } from "@server/models/User";
import { can, authorize } from "@server/policies";
import { presentUser, presentPolicies } from "@server/presenters";
import type { APIContext } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { safeEqual } from "@server/utils/crypto";
import { QueryHelper } from "@server/storage/QueryHelper";
import { getDetailsForEmailUpdateToken } from "@server/utils/jwt";
import pagination from "../middlewares/pagination";
import * as T from "./schema";
const router = new Router();
router.post(
"users.list",
auth(),
pagination(),
validate(T.UsersListSchema),
async (ctx: APIContext<T.UsersListReq>) => {
const {
sort,
direction,
query,
role,
filter: statusFilter,
ids,
emails,
filters: rawFilters,
} = ctx.input.body;
const actor = ctx.state.auth.user;
authorize(actor, "listUsers", actor.team);
const where: WhereOptions<User> & {
[Op.and]: WhereOptions<User>[];
} = {
teamId: actor.teamId,
[Op.and]: [],
};
// The schema rejects callers that combine `filters` with the deprecated
// top-level params, so exactly one of these is set.
const filter =
combineFilters(rawFilters) ??
legacyUserParamsToFilter({
ids,
emails,
role,
status: statusFilter,
isAdmin: actor.isAdmin,
});
// Suspended users are only ever visible to admins, and then only when the
// request targets a specific status or references suspendedAt itself.
const includeSuspended =
actor.isAdmin &&
(!!statusFilter ||
(filter !== undefined && hasFieldInFilter(filter, "suspendedAt")));
if (!includeSuspended) {
where[Op.and].push({ suspendedAt: { [Op.is]: null } });
}
if (filter) {
where[Op.and].push(buildWhere<User>(filter));
}
if (query) {
where[Op.and].push({
[Op.or]: [
Sequelize.literal(
`unaccent(LOWER("user"."email")) like unaccent(LOWER(:query))`
),
Sequelize.literal(
`unaccent(LOWER("user"."name")) like unaccent(LOWER(:query))`
),
],
});
}
const replacements = { query: QueryHelper.likeContains(query ?? "") };
const [users, total] = await Promise.all([
User.findAll({
where,
replacements,
// Only admins can see who invited a user.
include: actor.isAdmin
? [{ association: "invitedBy", required: false }]
: undefined,
order: [[sort, direction]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
User.count({
where,
// @ts-expect-error Types are incorrect for count
replacements,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: users.map((user) =>
presentUser(user, {
includeEmail: !!can(actor, "readEmail", user),
includeDetails: !!can(actor, "readDetails", user),
})
),
policies: presentPolicies(actor, users),
};
}
);
router.post(
"users.info",
auth(),
validate(T.UsersInfoSchema),
async (ctx: APIContext<T.UsersInfoReq>) => {
const { id } = ctx.input.body;
const actor = ctx.state.auth.user;
const user = id ? await User.findByPk(id) : actor;
authorize(actor, "read", user);
const includeDetails = !!can(actor, "readDetails", user);
ctx.body = {
data: presentUser(user, {
includeDetails,
}),
policies: presentPolicies(actor, [user]),
};
}
);
router.post(
"users.updateEmail",
rateLimiter(RateLimiterStrategy.TenPerHour),
auth(),
validate(T.UsersUpdateEmailSchema),
async (ctx: APIContext<T.UsersUpdateEmailReq>) => {
if (!env.EMAIL_ENABLED) {
throw ValidationError("Email support is not setup for this instance");
}
const { user: actor } = ctx.state.auth;
const { id } = ctx.input.body;
const { team } = actor;
const user = id ? await User.findByPk(id) : actor;
const email = ctx.input.body.email.trim().toLowerCase();
authorize(actor, "update", user);
// Check if email domain is allowed
if (!(await team.isDomainAllowed(email))) {
throw ValidationError("The domain is not allowed for this workspace");
}
// Check if email already exists in workspace
if (await User.findByEmail(ctx, email)) {
throw ValidationError("User with email already exists");
}
await new ConfirmUpdateEmail({
to: email,
language: user.language,
previous: user.email,
code: user.getEmailUpdateToken(email),
teamUrl: team.url,
}).schedule();
ctx.body = {
success: true,
};
}
);
router.get(
"users.updateEmail",
rateLimiter(RateLimiterStrategy.TenPerHour),
auth(),
transaction(),
validate(T.UsersUpdateEmailConfirmSchema),
async (ctx: APIContext<T.UsersUpdateEmailConfirmReq>) => {
if (!env.EMAIL_ENABLED) {
throw ValidationError("Email support is not setup for this instance");
}
const { transaction } = ctx.state;
const { code, follow } = ctx.input.query;
// The link in the email does not include the follow query param, this
// is to help prevent anti-virus, and email clients from pre-fetching the link
if (!follow) {
return ctx.redirectOnClient(ctx.request.href + "&follow=true");
}
let user: User;
let email: string;
try {
const res = await getDetailsForEmailUpdateToken(code as string, {
transaction,
lock: transaction.LOCK.UPDATE,
});
user = res.user;
email = res.email;
} catch (_err) {
ctx.redirect(`/?notice=expired-token`);
return;
}
const { user: actor } = ctx.state.auth;
authorize(actor, "update", user);
// Check if email domain is allowed
if (!(await actor.team.isDomainAllowed(email))) {
throw ValidationError("The domain is not allowed for this workspace");
}
// Check if email already exists in workspace
if (await User.findByEmail(ctx, email)) {
throw ValidationError("User with email already exists");
}
await user.updateWithCtx(ctx, { email });
ctx.redirect(settingsPath());
}
);
router.post(
"users.update",
auth(),
validate(T.UsersUpdateSchema),
transaction(),
async (ctx: APIContext<T.UsersUpdateReq>) => {
const { auth, transaction } = ctx.state;
const actor = auth.user;
const { id, name, avatarUrl, language, preferences, timezone } =
ctx.input.body;
let user: User | null = actor;
if (id) {
user = await User.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
}
authorize(actor, "update", user);
const includeDetails = !!can(actor, "readDetails", user);
if (name) {
user.name = name;
}
if (avatarUrl !== undefined) {
user.avatarUrl = avatarUrl;
// Mark that the user has manually changed their avatar
// This prevents automatic syncing from identity providers
user.setFlag(UserFlag.AvatarUpdated, avatarUrl ? true : false);
}
if (language) {
user.language = language;
}
if (preferences) {
user.preferences = {
...user.preferences,
...preferences,
};
}
if (timezone) {
user.timezone = timezone;
}
await user.saveWithCtx(ctx);
ctx.body = {
data: presentUser(user, {
includeDetails,
}),
};
}
);
// Admin specific
/**
* Promote a user to an admin.
*
* @deprecated Use `users.update_role` instead.
*/
router.post(
"users.promote",
auth({ role: UserRole.Admin }),
validate(T.UsersPromoteSchema),
transaction(),
(ctx: APIContext<T.UsersPromoteReq>) => {
const forward = ctx as unknown as APIContext<T.UsersChangeRoleReq>;
forward.input = {
...ctx.input,
body: {
id: ctx.input.body.id,
role: UserRole.Admin,
},
};
return updateRole(forward);
}
);
/**
* Demote a user to another role.
*
* @deprecated Use `users.update_role` instead.
*/
router.post(
"users.demote",
auth({ role: UserRole.Admin }),
validate(T.UsersDemoteSchema),
transaction(),
(ctx: APIContext<T.UsersDemoteReq>) => {
const forward = ctx as unknown as APIContext<T.UsersChangeRoleReq>;
forward.input = {
...ctx.input,
body: {
id: ctx.input.body.id,
role: ctx.input.body.to,
},
};
return updateRole(forward);
}
);
router.post(
"users.update_role",
auth({ role: UserRole.Admin }),
validate(T.UsersChangeRoleSchema),
transaction(),
updateRole
);
async function updateRole(ctx: APIContext<T.UsersChangeRoleReq>) {
const { transaction } = ctx.state;
const userId = ctx.input.body.id;
const role = ctx.input.body.role;
const actor = ctx.state.auth.user;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
await Team.findByPk(user.teamId, {
transaction,
lock: transaction.LOCK.UPDATE,
});
let name;
if (user.role === role) {
throw ValidationError("User is already in that role");
}
if (user.id === actor.id) {
throw ValidationError("You cannot change your own role");
}
if (UserRoleHelper.canDemote(user, role)) {
name = "demote";
authorize(actor, "demote", user);
}
if (UserRoleHelper.canPromote(user, role)) {
name = "promote";
authorize(actor, "promote", user);
}
await user.updateWithCtx(ctx, { role }, { name });
const includeDetails = !!can(actor, "readDetails", user);
ctx.body = {
data: presentUser(user, {
includeDetails,
}),
policies: presentPolicies(actor, [user]),
};
}
router.post(
"users.suspend",
auth(),
validate(T.UsersSuspendSchema),
transaction(),
async (ctx: APIContext<T.UsersSuspendReq>) => {
const { transaction } = ctx.state;
const userId = ctx.input.body.id;
const actor = ctx.state.auth.user;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
authorize(actor, "suspend", user);
await user.updateWithCtx(
ctx,
{
suspendedById: actor.id,
suspendedAt: new Date(),
},
{
name: "suspend",
}
);
const includeDetails = !!can(actor, "readDetails", user);
ctx.body = {
data: presentUser(user, {
includeDetails,
}),
policies: presentPolicies(actor, [user]),
};
}
);
router.post(
"users.activate",
auth(),
validate(T.UsersActivateSchema),
transaction(),
async (ctx: APIContext<T.UsersActivateReq>) => {
const { transaction } = ctx.state;
const userId = ctx.input.body.id;
const actor = ctx.state.auth.user;
const user = await User.findByPk(userId, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
authorize(actor, "activate", user);
await user.updateWithCtx(
ctx,
{
suspendedById: null,
suspendedAt: null,
},
{
name: "activate",
}
);
const includeDetails = !!can(actor, "readDetails", user);
ctx.body = {
data: presentUser(user, {
includeDetails,
}),
policies: presentPolicies(actor, [user]),
};
}
);
router.post(
"users.invite",
rateLimiter(RateLimiterStrategy.FiftyPerHour),
auth(),
validate(T.UsersInviteSchema),
transaction(),
async (ctx: APIContext<T.UsersInviteReq>) => {
const { invites, suppressEmail } = ctx.input.body;
const { user } = ctx.state.auth;
if (invites.length > UserValidation.maxInvitesPerRequest) {
throw ValidationError(
`You can only invite up to ${UserValidation.maxInvitesPerRequest} users at a time`
);
}
authorize(user, "inviteUser", user.team);
const response = await userInviter(ctx, { invites, suppressEmail });
ctx.body = {
data: {
sent: response.sent,
unsent: response.unsent,
users: response.users.map((user) =>
presentUser(user, { includeEmail: !!can(user, "readEmail", user) })
),
},
};
}
);
router.post(
"users.resendInvite",
auth(),
validate(T.UsersResendInviteSchema),
transaction(),
async (ctx: APIContext<T.UsersResendInviteReq>) => {
const { id } = ctx.input.body;
const { auth, transaction } = ctx.state;
const actor = auth.user;
const user = await User.findByPk(id, {
lock: transaction.LOCK.UPDATE,
transaction,
});
authorize(actor, "resendInvite", user);
if (user.getFlag(UserFlag.InviteSent) > 2) {
throw ValidationError("This invite has been sent too many times");
}
await new InviteEmail({
to: user.email,
language: user.language,
name: user.name,
actorName: actor.name,
actorEmail: actor.email,
teamName: actor.team.name,
teamUrl: actor.team.url,
}).schedule();
user.incrementFlag(UserFlag.InviteSent);
await user.save({ transaction });
if (env.isDevelopment) {
logger.info(
"email",
`Sign in immediately: ${
env.URL
}/auth/email.callback?token=${user.getEmailSigninToken(ctx)}`
);
}
ctx.body = {
success: true,
};
}
);
router.post(
"users.requestDelete",
rateLimiter(RateLimiterStrategy.FivePerHour),
auth(),
async (ctx: APIContext) => {
if (!env.EMAIL_ENABLED) {
throw ValidationError("Email support is not setup for this instance");
}
const { user } = ctx.state.auth;
authorize(user, "delete", user);
await new ConfirmUserDeleteEmail({
to: user.email,
language: user.language,
deleteConfirmationCode: user.deleteConfirmationCode,
teamName: user.team.name,
teamUrl: user.team.url,
}).schedule();
ctx.body = {
success: true,
};
}
);
router.post(
"users.delete",
rateLimiter(RateLimiterStrategy.TenPerHour),
auth(),
validate(T.UsersDeleteSchema),
transaction(),
async (ctx: APIContext<T.UsersDeleteSchemaReq>) => {
const { transaction } = ctx.state;
const { id, code } = ctx.input.body;
const actor = ctx.state.auth.user;
let user: User;
if (id) {
user = await User.findByPk(id, {
rejectOnEmpty: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
} else {
user = actor;
}
authorize(actor, "delete", user);
// If we're attempting to delete our own account then a confirmation code
// is required. This acts as CSRF protection.
if ((!id || id === actor.id) && env.EMAIL_ENABLED) {
const deleteConfirmationCode = user.deleteConfirmationCode;
if (!safeEqual(code, deleteConfirmationCode)) {
throw ValidationError("The confirmation code was incorrect");
}
}
await user.destroyWithCtx(ctx);
ctx.body = {
success: true,
};
}
);
router.post(
"users.notificationsSubscribe",
auth(),
validate(T.UsersNotificationsSubscribeSchema),
transaction(),
async (ctx: APIContext<T.UsersNotificationsSubscribeReq>) => {
const { eventType } = ctx.input.body;
const { user } = ctx.state.auth;
const eventTypes = eventType
? [eventType]
: Object.values(NotificationEventType);
for (const type of eventTypes) {
user.setNotificationEventType(type, true);
}
await user.saveWithCtx(ctx);
ctx.body = {
data: presentUser(user, { includeDetails: true }),
};
}
);
router.post(
"users.notificationsUnsubscribe",
auth(),
validate(T.UsersNotificationsUnsubscribeSchema),
transaction(),
async (ctx: APIContext<T.UsersNotificationsUnsubscribeReq>) => {
const { eventType } = ctx.input.body;
const { user } = ctx.state.auth;
const eventTypes = eventType
? [eventType]
: Object.values(NotificationEventType);
for (const type of eventTypes) {
user.setNotificationEventType(type, false);
}
await user.saveWithCtx(ctx);
ctx.body = {
data: presentUser(user, { includeDetails: true }),
};
}
);
export default router;