2023-01-12 14:02:26 +02:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
|
|
|
import Redis from 'ioredis';
|
|
|
|
import { In } from 'typeorm';
|
|
|
|
import type { Role, RoleAssignment, RoleAssignmentsRepository, RolesRepository, UsersRepository } from '@/models/index.js';
|
|
|
|
import { Cache } from '@/misc/cache.js';
|
2023-02-13 08:28:07 +02:00
|
|
|
import type { User } from '@/models/entities/User.js';
|
2023-01-12 14:02:26 +02:00
|
|
|
import { DI } from '@/di-symbols.js';
|
|
|
|
import { bindThis } from '@/decorators.js';
|
|
|
|
import { MetaService } from '@/core/MetaService.js';
|
2023-01-13 04:03:54 +02:00
|
|
|
import { UserCacheService } from '@/core/UserCacheService.js';
|
2023-01-15 01:33:07 +02:00
|
|
|
import type { RoleCondFormulaValue } from '@/models/entities/Role.js';
|
2023-01-13 04:03:54 +02:00
|
|
|
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
2023-01-14 01:27:23 +02:00
|
|
|
import { StreamMessages } from '@/server/api/stream/types.js';
|
2023-01-12 14:02:26 +02:00
|
|
|
import type { OnApplicationShutdown } from '@nestjs/common';
|
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
export type RolePolicies = {
|
2023-01-12 14:02:26 +02:00
|
|
|
gtlAvailable: boolean;
|
|
|
|
ltlAvailable: boolean;
|
|
|
|
canPublicNote: boolean;
|
2023-01-13 07:22:53 +02:00
|
|
|
canInvite: boolean;
|
2023-01-13 07:58:27 +02:00
|
|
|
canManageCustomEmojis: boolean;
|
2023-01-16 04:21:04 +02:00
|
|
|
canHideAds: boolean;
|
2023-01-12 14:02:26 +02:00
|
|
|
driveCapacityMb: number;
|
2023-01-14 11:04:56 +02:00
|
|
|
pinLimit: number;
|
2023-01-12 14:02:26 +02:00
|
|
|
antennaLimit: number;
|
2023-01-14 01:04:38 +02:00
|
|
|
wordMuteLimit: number;
|
2023-01-14 03:48:11 +02:00
|
|
|
webhookLimit: number;
|
2023-01-14 09:14:24 +02:00
|
|
|
clipLimit: number;
|
|
|
|
noteEachClipsLimit: number;
|
2023-01-14 10:38:16 +02:00
|
|
|
userListLimit: number;
|
|
|
|
userEachUserListsLimit: number;
|
2023-01-15 09:52:12 +02:00
|
|
|
rateLimitFactor: number;
|
2023-01-12 14:02:26 +02:00
|
|
|
};
|
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
export const DEFAULT_POLICIES: RolePolicies = {
|
2023-01-12 14:02:26 +02:00
|
|
|
gtlAvailable: true,
|
|
|
|
ltlAvailable: true,
|
|
|
|
canPublicNote: true,
|
2023-01-13 07:22:53 +02:00
|
|
|
canInvite: false,
|
2023-01-13 07:58:27 +02:00
|
|
|
canManageCustomEmojis: false,
|
2023-01-16 04:21:04 +02:00
|
|
|
canHideAds: false,
|
2023-01-12 14:02:26 +02:00
|
|
|
driveCapacityMb: 100,
|
2023-01-14 11:04:56 +02:00
|
|
|
pinLimit: 5,
|
2023-01-12 14:02:26 +02:00
|
|
|
antennaLimit: 5,
|
2023-01-14 01:04:38 +02:00
|
|
|
wordMuteLimit: 200,
|
2023-01-14 03:48:11 +02:00
|
|
|
webhookLimit: 3,
|
2023-01-14 09:14:24 +02:00
|
|
|
clipLimit: 10,
|
|
|
|
noteEachClipsLimit: 200,
|
2023-01-14 10:38:16 +02:00
|
|
|
userListLimit: 10,
|
|
|
|
userEachUserListsLimit: 50,
|
2023-01-15 09:52:12 +02:00
|
|
|
rateLimitFactor: 1,
|
2023-01-12 14:02:26 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class RoleService implements OnApplicationShutdown {
|
|
|
|
private rolesCache: Cache<Role[]>;
|
|
|
|
private roleAssignmentByUserIdCache: Cache<RoleAssignment[]>;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.redisSubscriber)
|
|
|
|
private redisSubscriber: Redis.Redis,
|
|
|
|
|
|
|
|
@Inject(DI.usersRepository)
|
|
|
|
private usersRepository: UsersRepository,
|
|
|
|
|
|
|
|
@Inject(DI.rolesRepository)
|
|
|
|
private rolesRepository: RolesRepository,
|
|
|
|
|
|
|
|
@Inject(DI.roleAssignmentsRepository)
|
|
|
|
private roleAssignmentsRepository: RoleAssignmentsRepository,
|
|
|
|
|
|
|
|
private metaService: MetaService,
|
2023-01-13 04:03:54 +02:00
|
|
|
private userCacheService: UserCacheService,
|
|
|
|
private userEntityService: UserEntityService,
|
2023-01-12 14:02:26 +02:00
|
|
|
) {
|
|
|
|
//this.onMessage = this.onMessage.bind(this);
|
|
|
|
|
|
|
|
this.rolesCache = new Cache<Role[]>(Infinity);
|
|
|
|
this.roleAssignmentByUserIdCache = new Cache<RoleAssignment[]>(Infinity);
|
|
|
|
|
|
|
|
this.redisSubscriber.on('message', this.onMessage);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
private async onMessage(_: string, data: string): Promise<void> {
|
|
|
|
const obj = JSON.parse(data);
|
|
|
|
|
|
|
|
if (obj.channel === 'internal') {
|
2023-01-14 01:27:23 +02:00
|
|
|
const { type, body } = obj.message as StreamMessages['internal']['payload'];
|
2023-01-12 14:02:26 +02:00
|
|
|
switch (type) {
|
|
|
|
case 'roleCreated': {
|
|
|
|
const cached = this.rolesCache.get(null);
|
|
|
|
if (cached) {
|
2023-01-25 04:18:16 +02:00
|
|
|
cached.push({
|
|
|
|
...body,
|
|
|
|
createdAt: new Date(body.createdAt),
|
|
|
|
updatedAt: new Date(body.updatedAt),
|
|
|
|
lastUsedAt: new Date(body.lastUsedAt),
|
|
|
|
});
|
2023-01-12 14:02:26 +02:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case 'roleUpdated': {
|
|
|
|
const cached = this.rolesCache.get(null);
|
|
|
|
if (cached) {
|
|
|
|
const i = cached.findIndex(x => x.id === body.id);
|
|
|
|
if (i > -1) {
|
2023-01-25 04:18:16 +02:00
|
|
|
cached[i] = {
|
|
|
|
...body,
|
|
|
|
createdAt: new Date(body.createdAt),
|
|
|
|
updatedAt: new Date(body.updatedAt),
|
|
|
|
lastUsedAt: new Date(body.lastUsedAt),
|
|
|
|
};
|
2023-01-12 14:02:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case 'roleDeleted': {
|
|
|
|
const cached = this.rolesCache.get(null);
|
|
|
|
if (cached) {
|
|
|
|
this.rolesCache.set(null, cached.filter(x => x.id !== body.id));
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case 'userRoleAssigned': {
|
|
|
|
const cached = this.roleAssignmentByUserIdCache.get(body.userId);
|
|
|
|
if (cached) {
|
2023-01-25 04:18:16 +02:00
|
|
|
cached.push({
|
|
|
|
...body,
|
|
|
|
createdAt: new Date(body.createdAt),
|
|
|
|
});
|
2023-01-12 14:02:26 +02:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
case 'userRoleUnassigned': {
|
|
|
|
const cached = this.roleAssignmentByUserIdCache.get(body.userId);
|
|
|
|
if (cached) {
|
|
|
|
this.roleAssignmentByUserIdCache.set(body.userId, cached.filter(x => x.id !== body.id));
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-13 04:03:54 +02:00
|
|
|
@bindThis
|
|
|
|
private evalCond(user: User, value: RoleCondFormulaValue): boolean {
|
|
|
|
try {
|
|
|
|
switch (value.type) {
|
|
|
|
case 'and': {
|
|
|
|
return value.values.every(v => this.evalCond(user, v));
|
|
|
|
}
|
|
|
|
case 'or': {
|
|
|
|
return value.values.some(v => this.evalCond(user, v));
|
|
|
|
}
|
|
|
|
case 'not': {
|
|
|
|
return !this.evalCond(user, value.value);
|
|
|
|
}
|
|
|
|
case 'isLocal': {
|
|
|
|
return this.userEntityService.isLocalUser(user);
|
|
|
|
}
|
|
|
|
case 'isRemote': {
|
|
|
|
return this.userEntityService.isRemoteUser(user);
|
|
|
|
}
|
|
|
|
case 'createdLessThan': {
|
|
|
|
return user.createdAt.getTime() > (Date.now() - (value.sec * 1000));
|
|
|
|
}
|
|
|
|
case 'createdMoreThan': {
|
|
|
|
return user.createdAt.getTime() < (Date.now() - (value.sec * 1000));
|
|
|
|
}
|
2023-01-14 01:27:23 +02:00
|
|
|
case 'followersLessThanOrEq': {
|
|
|
|
return user.followersCount <= value.value;
|
|
|
|
}
|
|
|
|
case 'followersMoreThanOrEq': {
|
|
|
|
return user.followersCount >= value.value;
|
|
|
|
}
|
|
|
|
case 'followingLessThanOrEq': {
|
|
|
|
return user.followingCount <= value.value;
|
|
|
|
}
|
|
|
|
case 'followingMoreThanOrEq': {
|
|
|
|
return user.followingCount >= value.value;
|
|
|
|
}
|
2023-01-13 04:03:54 +02:00
|
|
|
default:
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
// TODO: log error
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-12 14:02:26 +02:00
|
|
|
@bindThis
|
|
|
|
public async getUserRoles(userId: User['id']) {
|
|
|
|
const assigns = await this.roleAssignmentByUserIdCache.fetch(userId, () => this.roleAssignmentsRepository.findBy({ userId }));
|
|
|
|
const assignedRoleIds = assigns.map(x => x.roleId);
|
|
|
|
const roles = await this.rolesCache.fetch(null, () => this.rolesRepository.findBy({}));
|
2023-01-13 04:03:54 +02:00
|
|
|
const assignedRoles = roles.filter(r => assignedRoleIds.includes(r.id));
|
|
|
|
const user = roles.some(r => r.target === 'conditional') ? await this.userCacheService.findById(userId) : null;
|
|
|
|
const matchedCondRoles = roles.filter(r => r.target === 'conditional' && this.evalCond(user!, r.condFormula));
|
|
|
|
return [...assignedRoles, ...matchedCondRoles];
|
2023-01-12 14:02:26 +02:00
|
|
|
}
|
|
|
|
|
2023-02-05 03:37:03 +02:00
|
|
|
/**
|
|
|
|
* 指定ユーザーのバッジロール一覧取得
|
|
|
|
*/
|
|
|
|
@bindThis
|
|
|
|
public async getUserBadgeRoles(userId: User['id']) {
|
|
|
|
const assigns = await this.roleAssignmentByUserIdCache.fetch(userId, () => this.roleAssignmentsRepository.findBy({ userId }));
|
|
|
|
const assignedRoleIds = assigns.map(x => x.roleId);
|
|
|
|
const roles = await this.rolesCache.fetch(null, () => this.rolesRepository.findBy({}));
|
|
|
|
const assignedBadgeRoles = roles.filter(r => r.asBadge && assignedRoleIds.includes(r.id));
|
2023-02-11 02:03:43 +02:00
|
|
|
const badgeCondRoles = roles.filter(r => r.asBadge && (r.target === 'conditional'));
|
|
|
|
if (badgeCondRoles.length > 0) {
|
|
|
|
const user = roles.some(r => r.target === 'conditional') ? await this.userCacheService.findById(userId) : null;
|
|
|
|
const matchedBadgeCondRoles = badgeCondRoles.filter(r => this.evalCond(user!, r.condFormula));
|
|
|
|
return [...assignedBadgeRoles, ...matchedBadgeCondRoles];
|
|
|
|
} else {
|
|
|
|
return assignedBadgeRoles;
|
|
|
|
}
|
2023-02-05 03:37:03 +02:00
|
|
|
}
|
|
|
|
|
2023-01-12 14:02:26 +02:00
|
|
|
@bindThis
|
2023-01-15 13:52:53 +02:00
|
|
|
public async getUserPolicies(userId: User['id'] | null): Promise<RolePolicies> {
|
2023-01-12 14:02:26 +02:00
|
|
|
const meta = await this.metaService.fetch();
|
2023-01-15 13:52:53 +02:00
|
|
|
const basePolicies = { ...DEFAULT_POLICIES, ...meta.policies };
|
2023-01-12 14:02:26 +02:00
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
if (userId == null) return basePolicies;
|
2023-01-12 14:02:26 +02:00
|
|
|
|
|
|
|
const roles = await this.getUserRoles(userId);
|
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
function calc<T extends keyof RolePolicies>(name: T, aggregate: (values: RolePolicies[T][]) => RolePolicies[T]) {
|
|
|
|
if (roles.length === 0) return basePolicies[name];
|
2023-01-15 12:10:39 +02:00
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
const policies = roles.map(role => role.policies[name] ?? { priority: 0, useDefault: true });
|
2023-01-15 12:10:39 +02:00
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
const p2 = policies.filter(policy => policy.priority === 2);
|
|
|
|
if (p2.length > 0) return aggregate(p2.map(policy => policy.useDefault ? basePolicies[name] : policy.value));
|
2023-01-15 12:10:39 +02:00
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
const p1 = policies.filter(policy => policy.priority === 1);
|
2023-01-15 20:16:44 +02:00
|
|
|
if (p1.length > 0) return aggregate(p1.map(policy => policy.useDefault ? basePolicies[name] : policy.value));
|
2023-01-15 12:10:39 +02:00
|
|
|
|
2023-01-15 13:52:53 +02:00
|
|
|
return aggregate(policies.map(policy => policy.useDefault ? basePolicies[name] : policy.value));
|
2023-01-12 14:02:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2023-01-15 12:10:39 +02:00
|
|
|
gtlAvailable: calc('gtlAvailable', vs => vs.some(v => v === true)),
|
|
|
|
ltlAvailable: calc('ltlAvailable', vs => vs.some(v => v === true)),
|
|
|
|
canPublicNote: calc('canPublicNote', vs => vs.some(v => v === true)),
|
|
|
|
canInvite: calc('canInvite', vs => vs.some(v => v === true)),
|
|
|
|
canManageCustomEmojis: calc('canManageCustomEmojis', vs => vs.some(v => v === true)),
|
2023-01-16 04:21:04 +02:00
|
|
|
canHideAds: calc('canHideAds', vs => vs.some(v => v === true)),
|
2023-01-15 12:10:39 +02:00
|
|
|
driveCapacityMb: calc('driveCapacityMb', vs => Math.max(...vs)),
|
|
|
|
pinLimit: calc('pinLimit', vs => Math.max(...vs)),
|
|
|
|
antennaLimit: calc('antennaLimit', vs => Math.max(...vs)),
|
|
|
|
wordMuteLimit: calc('wordMuteLimit', vs => Math.max(...vs)),
|
|
|
|
webhookLimit: calc('webhookLimit', vs => Math.max(...vs)),
|
|
|
|
clipLimit: calc('clipLimit', vs => Math.max(...vs)),
|
|
|
|
noteEachClipsLimit: calc('noteEachClipsLimit', vs => Math.max(...vs)),
|
|
|
|
userListLimit: calc('userListLimit', vs => Math.max(...vs)),
|
|
|
|
userEachUserListsLimit: calc('userEachUserListsLimit', vs => Math.max(...vs)),
|
|
|
|
rateLimitFactor: calc('rateLimitFactor', vs => Math.max(...vs)),
|
2023-01-12 14:02:26 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async isModerator(user: { id: User['id']; isRoot: User['isRoot'] } | null): Promise<boolean> {
|
|
|
|
if (user == null) return false;
|
|
|
|
return user.isRoot || (await this.getUserRoles(user.id)).some(r => r.isModerator || r.isAdministrator);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async isAdministrator(user: { id: User['id']; isRoot: User['isRoot'] } | null): Promise<boolean> {
|
|
|
|
if (user == null) return false;
|
|
|
|
return user.isRoot || (await this.getUserRoles(user.id)).some(r => r.isAdministrator);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async getModeratorIds(includeAdmins = true): Promise<User['id'][]> {
|
|
|
|
const roles = await this.rolesCache.fetch(null, () => this.rolesRepository.findBy({}));
|
|
|
|
const moderatorRoles = includeAdmins ? roles.filter(r => r.isModerator || r.isAdministrator) : roles.filter(r => r.isModerator);
|
|
|
|
const assigns = moderatorRoles.length > 0 ? await this.roleAssignmentsRepository.findBy({
|
|
|
|
roleId: In(moderatorRoles.map(r => r.id)),
|
|
|
|
}) : [];
|
|
|
|
// TODO: isRootなアカウントも含める
|
|
|
|
return assigns.map(a => a.userId);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async getModerators(includeAdmins = true): Promise<User[]> {
|
|
|
|
const ids = await this.getModeratorIds(includeAdmins);
|
|
|
|
const users = ids.length > 0 ? await this.usersRepository.findBy({
|
|
|
|
id: In(ids),
|
|
|
|
}) : [];
|
|
|
|
return users;
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async getAdministratorIds(): Promise<User['id'][]> {
|
|
|
|
const roles = await this.rolesCache.fetch(null, () => this.rolesRepository.findBy({}));
|
|
|
|
const administratorRoles = roles.filter(r => r.isAdministrator);
|
|
|
|
const assigns = administratorRoles.length > 0 ? await this.roleAssignmentsRepository.findBy({
|
|
|
|
roleId: In(administratorRoles.map(r => r.id)),
|
|
|
|
}) : [];
|
|
|
|
// TODO: isRootなアカウントも含める
|
|
|
|
return assigns.map(a => a.userId);
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async getAdministrators(): Promise<User[]> {
|
|
|
|
const ids = await this.getAdministratorIds();
|
|
|
|
const users = ids.length > 0 ? await this.usersRepository.findBy({
|
|
|
|
id: In(ids),
|
|
|
|
}) : [];
|
|
|
|
return users;
|
|
|
|
}
|
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public onApplicationShutdown(signal?: string | undefined) {
|
|
|
|
this.redisSubscriber.off('message', this.onMessage);
|
|
|
|
}
|
|
|
|
}
|