Files
outline/server/routes/api/users/users.ts
T
Tom MoorandClaude Opus 5.5 5647621224 chore: Prune redundant comments and type suppressions (#14124)
* chore: Prune redundant comments and normalize lint directives

Removes comments that restate the following line and stale TODOs, drops
the passive event listener feature check now that all supported browsers
support it, and renames eslint directives to oxlint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BehTjuZwKbN5csMCp3H4QH

* fix: Evaluate restricted team domains at validation time

The restricted email provider list was captured when the model loaded, so
it could not follow the hosting environment and the tests that covered it
never reached the model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BehTjuZwKbN5csMCp3H4QH

* chore: Replace type suppressions with accurate types

Adds a Concrete helper type for registries of abstract classes, declares
missing Sequelize and refractor typings, uses public ProseMirror APIs, a
typed mock context helper in middleware tests, and a StaticLink component
for sidebar rows being edited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BehTjuZwKbN5csMCp3H4QH

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-17 17:07:39 -04:00

684 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 { AuthenticationType } 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,
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({ type: AuthenticationType.APP }),
validate(T.UsersUpdateEmailSchema),
async (ctx: APIContext<T.UsersUpdateEmailReq>) => {
if (!env.EMAIL_ENABLED) {
throw ValidationError("Email support is not set up 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({ type: AuthenticationType.APP }),
transaction(),
validate(T.UsersUpdateEmailConfirmSchema),
async (ctx: APIContext<T.UsersUpdateEmailConfirmReq>) => {
if (!env.EMAIL_ENABLED) {
throw ValidationError("Email support is not set up 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);
}
if (role === UserRole.Guest) {
authorize(actor, "addGuest", actor.team);
}
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 set up 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;