Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
36.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import assert from 'node:assert/strict';
import {createRoleID, type GuildID, guildIdToRoleId, type RoleID, type UserID} from '@app/api/BrandedTypes';
import {valuesEqual} from '@app/api/database/CassandraVersionedUpdate';
import type {GuildRoleRow} from '@app/api/database/types/GuildTypes';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {mapGuildRoleToResponse} from '@app/api/guild/GuildModel';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {getGuildAuth} from '@app/api/guild/services/GuildMfaEnforcement';
import {withGuildMemberRoleWriteLock} from '@app/api/guild/services/member/GuildMemberRoleWriteLock';
import {computeMovedIds, getMemberListRoleOrderIds} from '@app/api/guild/services/role/RoleOrderAuditUtils';
import {
	resolveProtectedBitActor,
	shouldMaskThreadPermissionBits,
	stripThreadPermissionBits,
} from '@app/api/guild/services/ThreadPermissionBits';
import type {EntityAssetService, PreparedAssetUpload} from '@app/api/infrastructure/EntityAssetService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
import {Logger} from '@app/api/Logger';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
import {resolveLimitSafe} from '@app/api/limits/LimitConfigUtils';
import {createLimitMatchContext} from '@app/api/limits/LimitMatchContextBuilder';
import {GuildRole} from '@app/api/models/GuildRole';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {applyProtectedRolePermissions, permissionWriteMask, protectedThreadBits} from '@app/api/utils/featureUtils';
import {computePermissionsDiff} from '@app/api/utils/PermissionUtils';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
import {DEFAULT_PERMISSIONS, Permissions} from '@fluxer/constants/src/ChannelConstants';
import type {LimitKey} from '@fluxer/constants/src/LimitConfigMetadata';
import {MAX_GUILD_ROLES} from '@fluxer/constants/src/LimitConstants';
import {THREAD_AWARE_ALL_PERMISSIONS, withImplicitThreadBits} from '@fluxer/constants/src/ThreadPermissionUtils';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
import {ResourceLockedError} from '@fluxer/errors/src/domains/core/ResourceLockedError';
import {MaxGuildRolesError} from '@fluxer/errors/src/domains/guild/MaxGuildRolesError';
import {UnknownGuildRoleError} from '@fluxer/errors/src/domains/guild/UnknownGuildRoleError';
import type {
	GuildRoleCreateRequest,
	GuildRoleUpdateRequest,
} from '@fluxer/schema/src/domains/guild/GuildRequestSchemas';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';
import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';

const ROLE_REORDER_LOCK_TTL_SECONDS = 30;

type RoleUpdateData = Partial<{
	name: string;
	color: number;
	position: number;
	hoistPosition: number | null;
	permissions: bigint;
	hoist: boolean;
	mentionable: boolean;
}>;

interface RoleIconRequest {
	icon?: string | null;
	unicode_emoji?: string | null;
}

interface RoleIconChange {
	iconHash: string | null;
	unicodeEmoji: string | null;
	prepared: PreparedAssetUpload | null;
}

export class GuildRoleService {
	private async buildRoleManageCheck(
		guildId: GuildID,
		userId: UserID,
		guildData: GuildResponse,
		allRoles: Array<GuildRole>,
	): Promise<(role: GuildRole) => boolean> {
		const everyoneRoleId = guildIdToRoleId(guildId);
		const isOwner = guildData.owner_id === userId.toString();
		let myHighestRole: GuildRole | null = null;
		if (!isOwner) {
			const member = await this.guildRepository.getMember(guildId, userId);
			if (member) {
				myHighestRole = this.getUserHighestRole(member, allRoles);
			}
		}
		return (role: GuildRole) => {
			if (isOwner) {
				return true;
			}
			if (role.id === everyoneRoleId) {
				return false;
			}
			if (!myHighestRole) {
				return false;
			}
			return this.isRoleHigherThan(myHighestRole, role);
		};
	}

	constructor(
		private readonly guildRepository: GuildRepository,
		private readonly snowflakeService: ISnowflakeService,
		private readonly cacheService: ICacheService,
		private readonly gatewayService: IGatewayService,
		private readonly guildAuditLogService: GuildAuditLogService,
		private readonly limitConfigService: LimitConfigService,
		private readonly userRepository: UserRepository,
		private readonly entityAssetService: EntityAssetService,
	) {}

	async systemCreateRole(params: {
		initiatorId: UserID;
		guildId: GuildID;
		data: GuildRoleCreateRequest;
	}): Promise<GuildRoleResponse> {
		const {initiatorId, guildId, data} = params;
		const guildData = await this.gatewayService.getGuildData({guildId, userId: initiatorId, skipMembershipCheck: true});
		const currentRoleCount = await this.guildRepository.countRoles(guildId);
		const roleLimit = this.resolveGuildLimit(guildData.features, 'max_guild_roles', MAX_GUILD_ROLES);
		if (currentRoleCount >= roleLimit) {
			throw new MaxGuildRolesError(roleLimit);
		}
		const permissionMask = THREAD_AWARE_ALL_PERMISSIONS;
		const permissions = data.permissions !== undefined ? data.permissions & permissionMask : DEFAULT_PERMISSIONS;
		const roleId = createRoleID(await this.snowflakeService.generate());
		const position = 1;
		const role = await this.guildRepository.upsertRole({
			guild_id: guildId,
			role_id: roleId,
			name: data.name,
			permissions,
			position,
			hoist_position: null,
			color: data.color || 0,
			icon_hash: null,
			unicode_emoji: null,
			hoist: false,
			mentionable: false,
			version: 1,
		});
		await this.dispatchGuildRoleCreate({guildId, role});
		await this.guildAuditLogService.record({
			guildId,
			userId: initiatorId,
			action: AuditLogActionType.ROLE_CREATE,
			targetId: role.id,
			auditLogReason: null,
			changes: this.guildAuditLogService.computeChanges(null, this.serializeRoleForAudit(role)),
		});
		return mapGuildRoleToResponse(role);
	}

	async createRole(
		params: {
			userId: UserID;
			guildId: GuildID;
			data: GuildRoleCreateRequest;
			clientFeatures: ReadonlySet<string>;
			viewer?: ThreadViewer;
		},
		auditLogReason?: string | null,
	): Promise<GuildRoleResponse> {
		const {userId, guildId, data, clientFeatures, viewer} = params;
		const {checkPermission, getMyPermissions, guildData} = await getGuildAuth(
			this.gatewayService,
			this.userRepository,
			{userId, guildId},
		);
		await checkPermission(Permissions.MANAGE_ROLES);
		const currentRoleCount = await this.guildRepository.countRoles(guildId);
		const roleLimit = this.resolveGuildLimit(guildData.features, 'max_guild_roles', MAX_GUILD_ROLES);
		if (currentRoleCount >= roleLimit) {
			throw new MaxGuildRolesError(roleLimit);
		}
		const permissions =
			data.permissions !== undefined
				? await this.resolveRequestedPermissions({
						requestedPermissions: data.permissions,
						existingPermissions: 0n,
						clientFeatures,
						guildId,
						guildData,
						userId,
						viewer,
						getMyPermissions,
					})
				: ((await this.guildRepository.getRole(guildIdToRoleId(guildId), guildId))?.permissions ?? DEFAULT_PERMISSIONS);
		const roleId = createRoleID(await this.snowflakeService.generate());
		const position = 1;
		const iconChange =
			data.icon_source_role_id !== undefined
				? await this.prepareRoleIconCopy({guildId, roleId, sourceRoleId: createRoleID(data.icon_source_role_id)})
				: await this.prepareRoleIcon({
						guildId,
						roleId,
						current: {iconHash: null, unicodeEmoji: null},
						data,
					});
		const role = await this.writeRoleWithIcon(iconChange.prepared, {
			guild_id: guildId,
			role_id: roleId,
			name: data.name,
			permissions,
			position,
			hoist_position: null,
			color: data.color || 0,
			icon_hash: iconChange.iconHash,
			unicode_emoji: iconChange.unicodeEmoji,
			hoist: false,
			mentionable: false,
			version: 1,
		});
		await this.dispatchGuildRoleCreate({guildId, role});
		await this.guildAuditLogService.record({
			guildId,
			userId,
			action: AuditLogActionType.ROLE_CREATE,
			targetId: role.id,
			auditLogReason: auditLogReason ?? null,
			changes: this.guildAuditLogService.computeChanges(null, this.serializeRoleForAudit(role)),
		});
		return this.mapRoleForViewer(guildId, role, viewer);
	}

	private async resolveRequestedPermissions(params: {
		requestedPermissions: bigint;
		existingPermissions: bigint;
		clientFeatures: ReadonlySet<string>;
		guildId: GuildID;
		guildData: {
			owner_id: string;
		};
		userId: UserID;
		viewer?: ThreadViewer;
		getMyPermissions: () => Promise<bigint>;
	}): Promise<bigint> {
		const {requestedPermissions, existingPermissions, clientFeatures, guildData, userId, getMyPermissions} = params;
		const actor = await resolveProtectedBitActor({
			guildId: params.guildId,
			userId,
			clientFeatures,
			viewer: params.viewer,
			isBot: async () =>
				params.viewer?.kind === 'user'
					? params.viewer.bot
					: ((await this.userRepository.findUnique(userId))?.isBot ?? false),
		});
		const sanitizedPermissions = applyProtectedRolePermissions(
			requestedPermissions & permissionWriteMask(actor),
			existingPermissions,
			actor,
		);
		const isOwner = guildData && guildData.owner_id === userId.toString();
		if (!isOwner) {
			const myPermissions = withImplicitThreadBits(await getMyPermissions());
			if ((sanitizedPermissions & ~protectedThreadBits(actor) & ~myPermissions) !== 0n) {
				throw new MissingPermissionsError();
			}
		}
		return sanitizedPermissions;
	}

	private async mapRoleForViewer(
		guildId: GuildID,
		role: GuildRole,
		viewer: ThreadViewer | undefined,
	): Promise<GuildRoleResponse> {
		const response = mapGuildRoleToResponse(role);
		if (!(await shouldMaskThreadPermissionBits(guildId, viewer, [role.permissions]))) {
			return response;
		}
		return {...response, permissions: stripThreadPermissionBits(role.permissions).toString()};
	}

	async updateRole(
		params: {
			userId: UserID;
			guildId: GuildID;
			roleId: RoleID;
			data: GuildRoleUpdateRequest;
			clientFeatures: ReadonlySet<string>;
			viewer?: ThreadViewer;
		},
		auditLogReason?: string | null,
	): Promise<GuildRoleResponse> {
		const {userId, guildId, roleId, data, clientFeatures, viewer} = params;
		const {guildData, checkPermission, getMyPermissions} = await getGuildAuth(
			this.gatewayService,
			this.userRepository,
			{userId, guildId},
		);
		await checkPermission(Permissions.MANAGE_ROLES);
		const role = await this.guildRepository.getRole(roleId, guildId);
		if (!role || (role.id === guildIdToRoleId(guildId) && roleId !== guildIdToRoleId(guildId))) {
			throw new UnknownGuildRoleError();
		}
		const isOwner = guildData && guildData.owner_id === userId.toString();
		if (!isOwner) {
			const canManageRole = await this.checkCanManageRole({guildId, userId, targetRole: role});
			if (!canManageRole) {
				throw new MissingPermissionsError();
			}
		}
		if (role.id === guildIdToRoleId(guildId)) {
			this.rejectEveryoneRoleIcon(data);
		}
		const updateData = await this.buildRoleUpdateData({
			role,
			guildId,
			guildData,
			userId,
			data,
			clientFeatures,
			viewer,
			getMyPermissions,
		});
		const iconChange = await this.prepareRoleIcon({guildId, roleId: role.id, current: role, data});
		const liveRole = await this.guildRepository.getRole(role.id, guildId);
		if (!liveRole) {
			await this.queueRoleIconStaleCheck(iconChange.prepared);
			throw new UnknownGuildRoleError();
		}
		const previousSnapshot = this.serializeRoleForAudit(liveRole);
		const requestedRoleData = {
			...role.toRow(),
			name: updateData.name ?? role.name,
			color: updateData.color ?? role.color,
			position: updateData.position ?? role.position,
			hoist_position: updateData.hoistPosition !== undefined ? updateData.hoistPosition : role.hoistPosition,
			permissions: updateData.permissions ?? role.permissions,
			icon_hash: iconChange.iconHash,
			unicode_emoji: iconChange.unicodeEmoji,
			hoist: updateData.hoist ?? role.isHoisted,
			mentionable: updateData.mentionable ?? role.isMentionable,
		};
		const liveRow = liveRole.toRow();
		const updatedRole = await this.writeRoleWithIcon(
			iconChange.prepared,
			this.rebaseRoleRow(role.toRow(), requestedRoleData, liveRow),
			liveRow,
		);
		await this.commitRoleIcon(guildId, iconChange.prepared);
		await this.queueReplacedRoleIcon({
			guildId,
			roleId: role.id,
			replacedHash: liveRole.iconHash,
			newHash: updatedRole.iconHash,
			prepared: iconChange.prepared,
		});
		await this.dispatchGuildRoleUpdate({guildId, role: updatedRole});
		const changes = this.guildAuditLogService.computeChanges(previousSnapshot, this.serializeRoleForAudit(updatedRole));
		if (liveRole.permissions !== updatedRole.permissions) {
			const permissionsDiff = computePermissionsDiff(liveRole.permissions, updatedRole.permissions, {
				threads: true,
			});
			changes.push({key: 'permissions_diff', new_value: permissionsDiff});
		}
		await this.guildAuditLogService.record({
			guildId,
			userId,
			action: AuditLogActionType.ROLE_UPDATE,
			targetId: roleId,
			auditLogReason: auditLogReason ?? null,
			metadata: {role_name: updatedRole.name},
			changes,
		});
		return this.mapRoleForViewer(guildId, updatedRole, viewer);
	}

	async deleteRole(
		params: {
			userId: UserID;
			guildId: GuildID;
			roleId: RoleID;
		},
		auditLogReason?: string | null,
	): Promise<void> {
		const {userId, guildId, roleId} = params;
		const {checkPermission, guildData} = await getGuildAuth(this.gatewayService, this.userRepository, {
			userId,
			guildId,
		});
		await checkPermission(Permissions.MANAGE_ROLES);
		const role = await this.guildRepository.getRole(roleId, guildId);
		if (!role || role.id === guildIdToRoleId(guildId)) {
			throw new UnknownGuildRoleError();
		}
		const isOwner = guildData && guildData.owner_id === userId.toString();
		if (!isOwner) {
			const canManageRole = await this.checkCanManageRole({guildId, userId, targetRole: role});
			if (!canManageRole) {
				throw new MissingPermissionsError();
			}
		}
		const previousSnapshot = this.serializeRoleForAudit(role);
		const memberIds = await this.gatewayService.getMembersWithRole({guildId, roleId});
		await Promise.all(
			memberIds.map(async (memberId) => {
				await withGuildMemberRoleWriteLock(this.cacheService, guildId, memberId, async () => {
					const member = await this.guildRepository.getMember(guildId, memberId);
					if (!member?.roleIds.has(roleId)) return;
					const updatedRoleIds = new Set(member.roleIds);
					updatedRoleIds.delete(roleId);
					const previousRow = member.toRow();
					await this.guildRepository.upsertMember(
						{...previousRow, role_ids: updatedRoleIds.size > 0 ? updatedRoleIds : null},
						previousRow,
					);
				});
			}),
		);
		const liveRole = await this.guildRepository.getRole(role.id, guildId);
		await this.guildRepository.deleteRole(guildId, role.id);
		const iconHashes = new Set([role.iconHash, liveRole?.iconHash ?? null]);
		for (const iconHash of iconHashes) {
			if (!iconHash) continue;
			const {prepared} = await this.prepareRoleIcon({
				guildId,
				roleId: role.id,
				current: {iconHash, unicodeEmoji: null},
				data: {icon: null},
			});
			await this.commitRoleIcon(guildId, prepared);
		}
		await this.dispatchGuildRoleDelete({guildId, roleId: role.id});
		await this.guildAuditLogService.record({
			guildId,
			userId,
			action: AuditLogActionType.ROLE_DELETE,
			targetId: roleId,
			auditLogReason: auditLogReason ?? null,
			changes: this.guildAuditLogService.computeChanges(previousSnapshot, null),
		});
	}

	async updateRolePositions(
		params: {
			userId: UserID;
			guildId: GuildID;
			updates: Array<{
				roleId: RoleID;
				position?: number;
			}>;
		},
		auditLogReason?: string | null,
	): Promise<void> {
		const {userId, guildId, updates} = params;
		const {checkPermission} = await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});
		await checkPermission(Permissions.MANAGE_ROLES);
		const lockKey = `guild:${guildId}:role-positions`;
		const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);
		if (!lockToken) {
			throw new ResourceLockedError();
		}
		try {
			await this.updateRolePositionsByList({userId, guildId, updates, auditLogReason: auditLogReason ?? null});
		} finally {
			await this.cacheService.releaseLock(lockKey, lockToken);
		}
	}

	async listRoles(params: {
		userId: UserID;
		guildId: GuildID;
		viewer?: ThreadViewer;
	}): Promise<Array<GuildRoleResponse>> {
		const {userId, guildId, viewer} = params;
		await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});
		const roles = await this.guildRepository.listRoles(guildId);
		const sortedRoles = [...roles].sort((a, b) => {
			if (b.position !== a.position) {
				return b.position - a.position;
			}
			return compareSnowflakes(a.id, b.id);
		});
		const roleResponses = sortedRoles.map((role) => ({role, response: mapGuildRoleToResponse(role)}));
		if (
			!(await shouldMaskThreadPermissionBits(
				guildId,
				viewer,
				sortedRoles.map((role) => role.permissions),
			))
		) {
			return roleResponses.map(({response}) => response);
		}
		return roleResponses.map(({role, response}) => ({
			...response,
			permissions: stripThreadPermissionBits(role.permissions).toString(),
		}));
	}

	async updateHoistPositions(
		params: {
			userId: UserID;
			guildId: GuildID;
			updates: Array<{
				roleId: RoleID;
				hoistPosition: number;
			}>;
		},
		auditLogReason?: string | null,
	): Promise<void> {
		const {userId, guildId, updates} = params;
		const {checkPermission, guildData} = await getGuildAuth(this.gatewayService, this.userRepository, {
			userId,
			guildId,
		});
		await checkPermission(Permissions.MANAGE_ROLES);
		const lockKey = `guild:${guildId}:role-hoist-positions`;
		const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);
		if (!lockToken) {
			throw new ResourceLockedError();
		}
		try {
			const allRoles = await this.guildRepository.listRoles(guildId);
			const roleMap = new Map(allRoles.map((r) => [r.id, r]));
			const everyoneRoleId = guildIdToRoleId(guildId);
			const canManageRole = await this.buildRoleManageCheck(guildId, userId, guildData, allRoles);
			for (const update of updates) {
				if (update.roleId === everyoneRoleId) {
					throw InputValidationError.fromCode('id', ValidationErrorCodes.CANNOT_SET_HOIST_FOR_EVERYONE_ROLE);
				}
				const role = roleMap.get(update.roleId);
				if (!role) {
					throw InputValidationError.fromCode('id', ValidationErrorCodes.INVALID_ROLE_ID, {
						roleId: update.roleId.toString(),
					});
				}
				if (!canManageRole(role)) {
					throw new MissingPermissionsError();
				}
			}
			const changedRoles: Array<GuildRole> = [];
			for (const update of updates) {
				const role = roleMap.get(update.roleId);
				assert(role !== undefined);
				if (role.hoistPosition === update.hoistPosition) {
					continue;
				}
				await this.guildRepository.upsertRole({...role.toRow(), hoist_position: update.hoistPosition}, role.toRow());
				const updatedRole = await this.guildRepository.getRole(role.id, guildId);
				if (updatedRole) changedRoles.push(updatedRole);
			}
			if (changedRoles.length > 0) {
				await this.dispatchGuildRoleUpdateBulk({guildId, roles: changedRoles});
				await this.recordRolePositionAuditLogs({
					guildId,
					userId,
					roleMap,
					changedRoles,
					movedRoleIds: this.computeMovedHoistRoleIds({allRoles, changedRoles, everyoneRoleId}),
					auditLogReason,
					key: 'hoist_position',
				});
			}
		} finally {
			await this.cacheService.releaseLock(lockKey, lockToken);
		}
	}

	async resetHoistPositions(
		params: {
			userId: UserID;
			guildId: GuildID;
		},
		auditLogReason?: string | null,
	): Promise<void> {
		const {userId, guildId} = params;
		const {checkPermission} = await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});
		await checkPermission(Permissions.MANAGE_ROLES);
		const lockKey = `guild:${guildId}:role-hoist-positions`;
		const lockToken = await this.cacheService.acquireLock(lockKey, ROLE_REORDER_LOCK_TTL_SECONDS);
		if (!lockToken) {
			throw new ResourceLockedError();
		}
		try {
			const allRoles = await this.guildRepository.listRoles(guildId);
			const roleMap = new Map(allRoles.map((r) => [r.id, r]));
			const changedRoles: Array<GuildRole> = [];
			for (const role of allRoles) {
				if (role.hoistPosition === null) {
					continue;
				}
				await this.guildRepository.upsertRole({...role.toRow(), hoist_position: null}, role.toRow());
				const updatedRole = await this.guildRepository.getRole(role.id, guildId);
				if (updatedRole) changedRoles.push(updatedRole);
			}
			if (changedRoles.length > 0) {
				await this.dispatchGuildRoleUpdateBulk({guildId, roles: changedRoles});
				await this.recordRolePositionAuditLogs({
					guildId,
					userId,
					roleMap,
					changedRoles,
					movedRoleIds: this.computeMovedHoistRoleIds({
						allRoles,
						changedRoles,
						everyoneRoleId: guildIdToRoleId(guildId),
					}),
					auditLogReason,
					key: 'hoist_position',
				});
			}
		} finally {
			await this.cacheService.releaseLock(lockKey, lockToken);
		}
	}

	private rejectEveryoneRoleIcon(data: RoleIconRequest): void {
		if (data.icon != null) {
			throw InputValidationError.fromCode('icon', ValidationErrorCodes.CANNOT_SET_ICON_ON_EVERYONE_ROLE);
		}
		if (data.unicode_emoji != null) {
			throw InputValidationError.fromCode('unicode_emoji', ValidationErrorCodes.CANNOT_SET_ICON_ON_EVERYONE_ROLE);
		}
	}

	private async prepareRoleIcon(params: {
		guildId: GuildID;
		roleId: RoleID;
		current: {iconHash: string | null; unicodeEmoji: string | null};
		data: RoleIconRequest;
	}): Promise<RoleIconChange> {
		const {guildId, roleId, current, data} = params;
		let image = data.icon;
		let unicodeEmoji = data.unicode_emoji !== undefined ? data.unicode_emoji : current.unicodeEmoji;
		if (data.icon) {
			unicodeEmoji = null;
		}
		if (image === undefined && data.unicode_emoji) {
			image = null;
		}
		if (image === undefined) {
			return {iconHash: current.iconHash, unicodeEmoji, prepared: null};
		}
		if (image === null && current.iconHash === null) {
			return {iconHash: null, unicodeEmoji, prepared: null};
		}
		const prepared = await this.entityAssetService.prepareAssetUpload({
			assetType: 'role_icon',
			entityType: 'role',
			entityId: roleId,
			guildId,
			previousHash: current.iconHash,
			base64Image: image,
			errorPath: 'icon',
		});
		return {iconHash: prepared.newHash, unicodeEmoji, prepared};
	}

	private async prepareRoleIconCopy(params: {
		guildId: GuildID;
		roleId: RoleID;
		sourceRoleId: RoleID;
	}): Promise<RoleIconChange> {
		const {guildId, roleId, sourceRoleId} = params;
		const source = await this.guildRepository.getRole(sourceRoleId, guildId);
		if (!source) {
			throw new UnknownGuildRoleError();
		}
		if (!source.iconHash) {
			return {iconHash: null, unicodeEmoji: source.unicodeEmoji, prepared: null};
		}
		const prepared = await this.entityAssetService.prepareAssetCopy({
			assetType: 'role_icon',
			entityType: 'role',
			sourceEntityId: source.id,
			entityId: roleId,
			guildId,
			hash: source.iconHash,
			errorPath: 'icon_source_role_id',
		});
		return {iconHash: prepared?.newHash ?? null, unicodeEmoji: null, prepared};
	}

	private rebaseRoleRow(snapshot: GuildRoleRow, requested: GuildRoleRow, live: GuildRoleRow): GuildRoleRow {
		const rebased: Record<string, unknown> = {...live};
		const snapshotFields = snapshot as unknown as Record<string, unknown>;
		const requestedFields = requested as unknown as Record<string, unknown>;
		for (const [column, value] of Object.entries(requestedFields)) {
			if (!valuesEqual(value, snapshotFields[column])) {
				rebased[column] = value;
			}
		}
		if (
			!valuesEqual(requested.icon_hash, snapshot.icon_hash) ||
			!valuesEqual(requested.unicode_emoji, snapshot.unicode_emoji)
		) {
			rebased.icon_hash = requested.icon_hash;
			rebased.unicode_emoji = requested.unicode_emoji;
		}
		return rebased as unknown as GuildRoleRow;
	}

	private async writeRoleWithIcon(
		prepared: PreparedAssetUpload | null,
		row: GuildRoleRow,
		oldRow?: GuildRoleRow,
	): Promise<GuildRole> {
		try {
			return await this.guildRepository.upsertRole(row, oldRow);
		} catch (error) {
			await this.queueRoleIconStaleCheck(prepared);
			throw error;
		}
	}

	private async queueRoleIconStaleCheck(prepared: PreparedAssetUpload | null): Promise<void> {
		if (!prepared) return;
		await this.entityAssetService
			.queueUploadForStaleCheck(prepared)
			.catch((error) => Logger.error({error, s3Key: prepared.newS3Key}, 'Failed to queue role icon cleanup'));
	}

	private async queueReplacedRoleIcon(params: {
		guildId: GuildID;
		roleId: RoleID;
		replacedHash: string | null;
		newHash: string | null;
		prepared: PreparedAssetUpload | null;
	}): Promise<void> {
		const {guildId, roleId, replacedHash, newHash, prepared} = params;
		if (!replacedHash || replacedHash === newHash || replacedHash === prepared?.previousHash) return;
		try {
			const replaced = await this.entityAssetService.prepareAssetUpload({
				assetType: 'role_icon',
				entityType: 'role',
				entityId: roleId,
				guildId,
				previousHash: replacedHash,
				base64Image: null,
				errorPath: 'icon',
			});
			await this.entityAssetService.commitAssetChange(replaced);
		} catch (error) {
			Logger.error({error, guildId}, 'Failed to queue replaced role icon for deletion');
		}
	}

	private async commitRoleIcon(guildId: GuildID, prepared: PreparedAssetUpload | null): Promise<void> {
		if (!prepared) return;
		try {
			await this.entityAssetService.commitAssetChange(prepared);
			await this.entityAssetService.queueUploadForStaleCheck(prepared);
		} catch (error) {
			Logger.error({error, guildId}, 'Failed to queue role icon cleanup');
		}
	}

	private async checkCanManageRole(params: {
		guildId: GuildID;
		userId: UserID;
		targetRole: GuildRole;
	}): Promise<boolean> {
		const {guildId, userId, targetRole} = params;
		return this.gatewayService.canManageRole({guildId, userId, roleId: targetRole.id});
	}

	private getUserHighestRole(
		member: {
			roleIds: Set<RoleID>;
		},
		allRoles: Array<GuildRole>,
	): GuildRole | null {
		const roleMap = new Map(allRoles.map((r) => [r.id, r]));
		let highestRole: GuildRole | null = null;
		for (const roleId of member.roleIds) {
			const role = roleMap.get(roleId);
			if (!role) {
				continue;
			}
			if (!highestRole || this.isRoleHigherThan(role, highestRole)) {
				highestRole = role;
			}
		}
		return highestRole;
	}

	private isRoleHigherThan(roleA: GuildRole, roleB: GuildRole): boolean {
		if (roleA.position > roleB.position) {
			return true;
		}
		if (roleA.position === roleB.position) {
			return compareSnowflakes(roleA.id, roleB.id) < 0;
		}
		return false;
	}

	private async buildRoleUpdateData(params: {
		role: GuildRole;
		guildId: GuildID;
		guildData: {
			owner_id: string;
		};
		userId: UserID;
		data: GuildRoleUpdateRequest;
		clientFeatures: ReadonlySet<string>;
		viewer?: ThreadViewer;
		getMyPermissions: () => Promise<bigint>;
	}): Promise<RoleUpdateData> {
		const {role, guildId, guildData, userId, data, clientFeatures, viewer, getMyPermissions} = params;
		const updateData: RoleUpdateData = {};
		const isEveryoneRole = role.id === guildIdToRoleId(guildId);
		if (data.name !== undefined && !isEveryoneRole) {
			updateData.name = data.name;
		}
		if (data.color !== undefined) {
			updateData.color = data.color;
		}
		if (data.hoist !== undefined && !isEveryoneRole) {
			updateData.hoist = data.hoist;
		}
		if (data.hoist_position !== undefined && !isEveryoneRole) {
			updateData.hoistPosition = data.hoist_position;
		}
		if (data.mentionable !== undefined && !isEveryoneRole) {
			updateData.mentionable = data.mentionable;
		}
		if (data.permissions !== undefined) {
			updateData.permissions = await this.resolveRequestedPermissions({
				requestedPermissions: data.permissions,
				existingPermissions: role.permissions,
				clientFeatures,
				guildId,
				guildData,
				userId,
				viewer,
				getMyPermissions,
			});
		}
		return updateData;
	}

	private async updateRolePositionsByList(params: {
		userId: UserID;
		guildId: GuildID;
		updates: Array<{
			roleId: RoleID;
			position?: number;
		}>;
		auditLogReason?: string | null;
	}): Promise<void> {
		const {userId, guildId, updates, auditLogReason} = params;
		const {guildData} = await getGuildAuth(this.gatewayService, this.userRepository, {userId, guildId});
		const allRoles = await this.guildRepository.listRoles(guildId);
		const roleMap = new Map(allRoles.map((r) => [r.id, r]));
		const everyoneRoleId = guildIdToRoleId(guildId);
		for (const update of updates) {
			if (update.roleId === everyoneRoleId) {
				throw InputValidationError.fromCode('id', ValidationErrorCodes.CANNOT_REORDER_EVERYONE_ROLE);
			}
			if (!roleMap.has(update.roleId)) {
				throw InputValidationError.fromCode('id', ValidationErrorCodes.INVALID_ROLE_ID, {
					roleId: update.roleId.toString(),
				});
			}
		}
		const canManageRole = await this.buildRoleManageCheck(guildId, userId, guildData, allRoles);
		for (const update of updates) {
			const role = roleMap.get(update.roleId);
			assert(role !== undefined);
			if (canManageRole(role)) {
				continue;
			}
			if (update.position !== undefined && update.position !== role.position) {
				throw new MissingPermissionsError();
			}
		}
		const explicitPositions = new Map<RoleID, number>();
		for (const update of updates) {
			if (update.position !== undefined) {
				explicitPositions.set(update.roleId, update.position);
			}
		}
		const currentOrder = this.getCurrentRoleOrder(allRoles, everyoneRoleId);
		const targetOrder = this.mergeManageableRoleOrder({
			currentOrder,
			canManageRole,
			explicitPositions,
		});
		const reorderedIds = targetOrder.map((r) => r.id);
		const reorderedRoles = this.reorderRolePositions({allRoles, reorderedIds, guildId});
		const updatePromises = reorderedRoles.map((role) => {
			const listed = roleMap.get(role.id);
			assert(listed !== undefined);
			return this.guildRepository.upsertRole(role.toRow(), listed.toRow());
		});
		await Promise.all(updatePromises);
		const updatedRoles = await this.guildRepository.listRoles(guildId);
		const changedRoles = updatedRoles.filter((role) => {
			const oldRole = roleMap.get(role.id);
			return oldRole && oldRole.position !== role.position;
		});
		if (changedRoles.length > 0) {
			await this.dispatchGuildRoleUpdateBulk({guildId, roles: changedRoles});
			await this.recordRolePositionAuditLogs({
				guildId,
				userId,
				roleMap,
				changedRoles,
				movedRoleIds: computeMovedIds(
					currentOrder.map((role) => role.id),
					this.getCurrentRoleOrder(updatedRoles, everyoneRoleId).map((role) => role.id),
				),
				auditLogReason,
				key: 'position',
			});
		}
	}

	private computeMovedHoistRoleIds(params: {
		allRoles: Array<GuildRole>;
		changedRoles: Array<GuildRole>;
		everyoneRoleId: RoleID;
	}): Set<RoleID> {
		const {allRoles, changedRoles, everyoneRoleId} = params;
		const changedRoleMap = new Map(changedRoles.map((role) => [role.id, role]));
		const updatedRoles = allRoles.map((role) => changedRoleMap.get(role.id) ?? role);
		const afterOrderIds = getMemberListRoleOrderIds(updatedRoles, everyoneRoleId);
		const movedRoleIds = computeMovedIds(getMemberListRoleOrderIds(allRoles, everyoneRoleId), afterOrderIds);
		const memberListRoleIds = new Set(afterOrderIds);
		for (const role of changedRoles) {
			if (!memberListRoleIds.has(role.id)) {
				movedRoleIds.add(role.id);
			}
		}
		return movedRoleIds;
	}

	private getCurrentRoleOrder(allRoles: Array<GuildRole>, everyoneRoleId: RoleID): Array<GuildRole> {
		return allRoles
			.filter((role) => role.id !== everyoneRoleId)
			.sort((a, b) => b.position - a.position || compareSnowflakes(a.id, b.id));
	}

	private mergeManageableRoleOrder(params: {
		currentOrder: Array<GuildRole>;
		canManageRole: (role: GuildRole) => boolean;
		explicitPositions: Map<RoleID, number>;
	}): Array<GuildRole> {
		const {currentOrder, canManageRole, explicitPositions} = params;
		const manageableSlotIndices: Array<number> = [];
		const manageableRoles: Array<{role: GuildRole; index: number}> = [];
		for (const [index, role] of currentOrder.entries()) {
			if (!canManageRole(role)) {
				continue;
			}
			manageableSlotIndices.push(index);
			manageableRoles.push({role, index});
		}
		const sortedManageableRoles = [...manageableRoles].sort((a, b) => {
			const posA = explicitPositions.get(a.role.id) ?? a.role.position;
			const posB = explicitPositions.get(b.role.id) ?? b.role.position;
			if (posA !== posB) {
				return posB - posA;
			}
			return a.index - b.index;
		});
		const targetOrder = [...currentOrder];
		for (const [index, slot] of manageableSlotIndices.entries()) {
			const entry = sortedManageableRoles[index];
			assert(entry !== undefined);
			targetOrder[slot] = entry.role;
		}
		return targetOrder;
	}

	private reorderRolePositions({
		allRoles,
		reorderedIds,
		guildId,
	}: {
		allRoles: Array<GuildRole>;
		reorderedIds: Array<RoleID>;
		guildId: GuildID;
	}): Array<GuildRole> {
		const roleMap = new Map(allRoles.map((r) => [r.id, r]));
		const everyoneRole = roleMap.get(guildIdToRoleId(guildId));
		const reorderedRoleSet = new Set(reorderedIds);
		const nonReorderedRoles = allRoles
			.filter((role) => role.id !== guildIdToRoleId(guildId) && !reorderedRoleSet.has(role.id))
			.sort((a, b) => a.position - b.position || compareSnowflakes(a.id, b.id));
		const newRoles: Array<GuildRole> = [];
		if (everyoneRole) {
			newRoles.push(new GuildRole({...everyoneRole.toRow(), position: 0}));
		}
		let currentPosition = reorderedIds.length + nonReorderedRoles.length;
		for (const roleId of reorderedIds) {
			const role = roleMap.get(roleId);
			if (role && roleId !== guildIdToRoleId(guildId)) {
				newRoles.push(new GuildRole({...role.toRow(), position: currentPosition}));
				currentPosition--;
			}
		}
		for (const role of nonReorderedRoles) {
			newRoles.push(new GuildRole({...role.toRow(), position: currentPosition}));
			currentPosition--;
		}
		return newRoles;
	}

	private async recordRolePositionAuditLogs(params: {
		guildId: GuildID;
		userId: UserID;
		roleMap: Map<RoleID, GuildRole>;
		changedRoles: Array<GuildRole>;
		movedRoleIds: ReadonlySet<RoleID>;
		auditLogReason?: string | null;
		key: 'position' | 'hoist_position';
	}): Promise<void> {
		const {guildId, userId, roleMap, changedRoles, movedRoleIds, auditLogReason, key} = params;
		for (const role of changedRoles) {
			if (!movedRoleIds.has(role.id)) {
				continue;
			}
			const oldRole = roleMap.get(role.id);
			await this.guildAuditLogService.record({
				guildId,
				userId,
				action: AuditLogActionType.ROLE_UPDATE,
				targetId: role.id,
				auditLogReason: auditLogReason ?? null,
				metadata: {role_name: role.name},
				changes: this.guildAuditLogService
					.computeChanges(oldRole ? this.serializeRoleForAudit(oldRole) : null, this.serializeRoleForAudit(role))
					.filter((change) => change.key === key),
			});
		}
	}

	private serializeRoleForAudit(role: GuildRole): Record<string, unknown> {
		return {
			role_id: role.id.toString(),
			name: role.name,
			permissions: role.permissions.toString(),
			position: role.position,
			hoist_position: role.hoistPosition,
			color: role.color,
			icon_hash: role.iconHash ?? null,
			unicode_emoji: role.unicodeEmoji ?? null,
			hoist: role.isHoisted,
			mentionable: role.isMentionable,
		};
	}

	private async dispatchGuildRoleCreate({guildId, role}: {guildId: GuildID; role: GuildRole}): Promise<void> {
		await this.gatewayService.dispatchGuild({
			guildId,
			event: 'GUILD_ROLE_CREATE',
			data: {role: mapGuildRoleToResponse(role)},
		});
	}

	private async dispatchGuildRoleUpdate({guildId, role}: {guildId: GuildID; role: GuildRole}): Promise<void> {
		await this.gatewayService.dispatchGuild({
			guildId,
			event: 'GUILD_ROLE_UPDATE',
			data: {role: mapGuildRoleToResponse(role)},
		});
	}

	private async dispatchGuildRoleDelete({guildId, roleId}: {guildId: GuildID; roleId: RoleID}): Promise<void> {
		await this.gatewayService.dispatchGuild({
			guildId,
			event: 'GUILD_ROLE_DELETE',
			data: {role_id: roleId.toString()},
		});
	}

	private async dispatchGuildRoleUpdateBulk({
		guildId,
		roles,
	}: {
		guildId: GuildID;
		roles: Array<GuildRole>;
	}): Promise<void> {
		const roleResponses = roles.map((role) => mapGuildRoleToResponse(role));
		await this.gatewayService.dispatchGuild({
			guildId,
			event: 'GUILD_ROLE_UPDATE_BULK',
			data: {roles: roleResponses},
		});
	}

	private resolveGuildLimit(guildFeatures: Iterable<string> | null, key: LimitKey, fallback: number): number {
		const ctx = createLimitMatchContext({guildFeatures});
		return resolveLimitSafe(this.limitConfigService.getConfigSnapshot(), ctx, key, fallback);
	}
}