implement conditional role tester

This commit is contained in:
bunnybeam 2025-08-04 19:40:00 +01:00
parent d77880aa4d
commit 683638b570
No known key found for this signature in database
9 changed files with 222 additions and 125 deletions

4
locales/index.d.ts vendored
View file

@ -7783,9 +7783,9 @@ export interface Locale extends ILocale {
*/
"remoteDataWarning": string;
/**
* Role tester
* Select a user to test the condition.
*/
"roleTester": string;
"selectTestUser": string;
};
"_sensitiveMediaDetection": {
/**

View file

@ -354,6 +354,39 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit {
}
}
@bindThis
public annotateCond(user: MiUser, roles: MiRole[], value: RoleCondFormulaValue, followStats: FollowStats, results: { [k: string]: boolean }): boolean {
let result: boolean;
try {
switch (value.type) {
case 'and': {
result = true;
// Don't use every(), since that short-circuits.
// We need to run annotateCond() on every condition.
value.values.forEach(v => result = this.annotateCond(user, roles, v, followStats, results) && result);
break;
}
case 'or': {
result = false;
value.values.forEach(v => result = this.annotateCond(user, roles, v, followStats, results) || result);
break;
}
case 'not': {
result = !this.annotateCond(user, roles, value.value, followStats, results);
break;
}
default: {
result = this.evalCond(user, roles, value, followStats);
}
}
} catch (err) {
// TODO: log error
result = false;
}
results[value.id] = result;
return result;
}
@bindThis
public async getRoles() {
const roles = await this.rolesCache.fetch(() => this.rolesRepository.findBy({}));

View file

@ -86,6 +86,7 @@ export * as 'admin/relays/list' from './endpoints/admin/relays/list.js';
export * as 'admin/relays/remove' from './endpoints/admin/relays/remove.js';
export * as 'admin/reset-password' from './endpoints/admin/reset-password.js';
export * as 'admin/resolve-abuse-user-report' from './endpoints/admin/resolve-abuse-user-report.js';
export * as 'admin/roles/annotate-condition' from './endpoints/admin/roles/annotate-condition.js';
export * as 'admin/roles/assign' from './endpoints/admin/roles/assign.js';
export * as 'admin/roles/create' from './endpoints/admin/roles/create.js';
export * as 'admin/roles/clone' from './endpoints/admin/roles/clone.js';

View file

@ -0,0 +1,71 @@
/*
* SPDX-FileCopyrightText: bunnybeam and other Sharkey contributors
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import type { UsersRepository } from '@/models/_.js';
import { DI } from '@/di-symbols.js';
import { ApiError } from '@/server/api/error.js';
import { RoleService } from '@/core/RoleService.js';
import { CacheService } from '@/core/CacheService.js';
export const meta = {
tags: ['admin', 'role'],
requireCredential: true,
requireModerator: true,
kind: 'read:admin:roles',
errors: {
noSuchUser: {
message: 'No such user.',
code: 'NO_SUCH_USER',
id: '34550050-3115-4443-b389-ce3e62eb9857',
},
},
res: {
type: 'object',
optional: false, nullable: false,
additionalProperties: { type: 'boolean' },
},
} as const;
export const paramDef = {
type: 'object',
properties: {
userId: { type: 'string', format: 'misskey:id' },
condFormula: { type: 'object' },
},
required: [
'userId',
'condFormula',
],
} as const;
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
constructor(
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private roleService: RoleService,
private cacheService: CacheService,
) {
super(meta, paramDef, async (ps) => {
const user = await this.usersRepository.findOneBy({ id: ps.userId });
if (user === null) {
throw new ApiError(meta.errors.noSuchUser);
}
const followStats = await this.cacheService.getFollowStats(ps.userId);
const roles = await this.roleService.getUserRoles(ps.userId);
const results: { [k: string]: boolean } = {};
roleService.annotateCond(user, roles, ps.condFormula, followStats, results);
return results;
});
}
}

View file

@ -6,6 +6,10 @@ SPDX-License-Identifier: AGPL-3.0-only
<template>
<div class="_gaps">
<div :class="$style.header">
<div style="display: flex; align-items: center;">
<i v-if="results !== null && results[v.id]" class="ti ti-check" :class="$style.testResultTrue"></i>
<i v-else-if="results !== null" class="ti ti-x" :class="$style.testResultFalse"></i>
</div>
<MkSelect v-model="type" :class="$style.typeSelect">
<option value="isLocal">{{ i18n.ts._role._condition.isLocal }}</option>
<option value="isRemote">{{ i18n.ts._role._condition.isRemote }}</option>
@ -50,7 +54,7 @@ SPDX-License-Identifier: AGPL-3.0-only
<template #item="{element}">
<div :class="$style.item">
<!-- divが無いとエラーになる https://github.com/SortableJS/vue.draggable.next/issues/189 -->
<RolesEditorFormula :modelValue="element" draggable @update:modelValue="updated => valuesItemUpdated(updated)" @remove="removeItem(element)"/>
<RolesEditorFormula :modelValue="element" :results="results" draggable @update:modelValue="updated => valuesItemUpdated(updated)" @remove="removeItem(element)"/>
</div>
</template>
</Sortable>
@ -58,7 +62,7 @@ SPDX-License-Identifier: AGPL-3.0-only
</div>
<div v-else-if="type === 'not'" :class="$style.item">
<RolesEditorFormula v-model="v.value"/>
<RolesEditorFormula v-model="v.value" :results="results"/>
</div>
<MkInput v-else-if="type === 'createdLessThan' || type === 'createdMoreThan'" v-model="v.sec" type="number">
@ -127,6 +131,7 @@ const emit = defineEmits<{
const props = defineProps<{
modelValue: any;
draggable?: boolean;
results: object | null;
}>();
const v = ref(deepClone(props.modelValue));
@ -229,4 +234,16 @@ function removeSelf() {
margin-right: 4px;
}
}
.testResultFalse {
color: var(--MI_THEME-error);
align-self: center;
margin-right: 10px;
}
.testResultTrue {
color: var(--MI_THEME-success);
align-self: center;
margin-right: 10px;
}
</style>

View file

@ -1,34 +0,0 @@
<!--
SPDX-FileCopyrightText: bunnybeam and other Sharkey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
<template>
<div class="_gaps">
<div v-if="type === 'and' || type === 'or'" class="_gaps">
<RolesTester v-for="formula in v.values" :key="formula.id" :modelValue="formula" :user="user"/>
</div>
<div v-else-if="type === 'not'" :class="$style.item">
<RolesTester v-model="v.value"/>
</div>
<div v-else>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import type * as Misskey from 'misskey-js';
import { deepClone } from '@/utility/clone.js';
const props = defineProps<{
modelValue: any;
user: Misskey.entities.UserDetailed;
}>();
const v = ref(deepClone(props.modelValue));
const type = v.value.type;
console.log(type);
</script>

View file

@ -48,7 +48,39 @@ SPDX-License-Identifier: AGPL-3.0-only
<MkFolder v-if="role.target === 'conditional'" defaultOpen>
<template #label>{{ i18n.ts._role.condition }}</template>
<div class="_gaps">
<RolesEditorFormula v-model="role.condFormula"/>
<RolesEditorFormula v-model="role.condFormula" :results="conditionResults"/>
<div>
<div :class="$style.userSelectLabel">{{ i18n.ts._role.selectTestUser }}</div>
<MkButton
v-if="conditionTestUser == null"
transparent
:class="$style.userSelectButton"
@click="selectUser"
>
<div :class="$style.userSelectButtonInner">
<span><i class="ti ti-plus"></i></span>
<span>{{ i18n.ts.selectUser }}</span>
</div>
</MkButton>
<div v-else :class="$style.userSelectedButtons">
<div style="overflow: hidden;">
<MkUserCardMini
:user="conditionTestUser"
:withChart="false"
:class="$style.userSelectedCard"
/>
</div>
<div>
<button
class="_button"
:class="$style.userSelectedSwitchButton"
@click="selectUser"
>
<i class="ph-user-switch ph-bold ph-lg"></i>
</button>
</div>
</div>
</div>
</div>
</MkFolder>
@ -823,10 +855,11 @@ SPDX-License-Identifier: AGPL-3.0-only
</template>
<script lang="ts" setup>
import { watch, ref, computed } from 'vue';
import { watch, ref, computed, shallowRef } from 'vue';
import { throttle } from 'throttle-debounce';
import { ROLE_POLICIES } from '@@/js/const.js';
import RolesEditorFormula from './RolesEditorFormula.vue';
import type * as Misskey from 'misskey-js';
import MkInput from '@/components/MkInput.vue';
import MkColorInput from '@/components/MkColorInput.vue';
import MkSelect from '@/components/MkSelect.vue';
@ -834,10 +867,14 @@ import MkTextarea from '@/components/MkTextarea.vue';
import MkFolder from '@/components/MkFolder.vue';
import MkSwitch from '@/components/MkSwitch.vue';
import MkRange from '@/components/MkRange.vue';
import MkButton from '@/components/MkButton.vue';
import MkUserCardMini from '@/components/MkUserCardMini.vue';
import FormSlot from '@/components/form/slot.vue';
import { i18n } from '@/i18n.js';
import { instance } from '@/instance.js';
import { deepClone } from '@/utility/clone.js';
import * as os from '@/os.js';
import { misskeyApi } from '@/utility/misskey-api.js';
const emit = defineEmits<{
(ev: 'update:modelValue', v: any): void;
@ -850,6 +887,10 @@ const props = defineProps<{
const role = ref(deepClone(props.modelValue));
const conditionTestUser = shallowRef<Misskey.entities.UserDetailed | null>(null);
const conditionResults = ref(null);
// fill missing policy
for (const ROLE_POLICY of ROLE_POLICIES) {
if (role.value.policies[ROLE_POLICY] == null) {
@ -888,6 +929,19 @@ function matchQuery(keywords: string[]): boolean {
return keywords.some(keyword => keyword.toLowerCase().includes(q.value.toLowerCase()));
}
async function updateTestResults() {
conditionResults.value = await misskeyApi('admin/roles/annotate-condition', { userId: conditionTestUser.value.id, condFormula: role.value.condFormula });
}
function selectUser() {
os.selectUser({
includeSelf: true,
}).then((_user) => {
conditionTestUser.value = _user;
updateTestResults();
});
}
const save = throttle(100, () => {
const data = {
name: role.value.name,
@ -906,6 +960,10 @@ const save = throttle(100, () => {
policies: role.value.policies,
};
if (conditionTestUser.value !== null) {
updateTestResults();
}
emit('update:modelValue', data);
});
@ -920,4 +978,36 @@ watch(role, save, { deep: true });
.priorityIndicator {
margin-left: 8px;
}
.userSelectLabel {
font-size: 0.85em;
padding: 0 0 8px;
user-select: none;
}
.userSelectButton {
width: 100%;
height: 100%;
padding: 12px;
border: 2px dashed color(from var(--MI_THEME-fg) srgb r g b / 0.5);
}
.userSelectButtonInner {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
min-height: 38px;
}
.userSelectedButtons {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
}
.userSelectedSwitchButton {
width: 32px;
height: 32px;
}
</style>

View file

@ -48,55 +48,15 @@ SPDX-License-Identifier: AGPL-3.0-only
</MkPagination>
</div>
</MkFolder>
<MkFolder v-else>
<template #icon><i class="ti ti-flask"></i></template>
<template #label>{{ i18n.ts._role.roleTester }}</template>
<div class="_gaps">
<div v-if="testUser == null">
<MkButton
transparent
:class="$style.userSelectButton"
@click="selectUser"
>
<div :class="$style.userSelectButtonInner">
<span><i class="ti ti-plus"></i></span>
<span>{{ i18n.ts.selectUser }}</span>
</div>
</MkButton>
</div>
<div v-else :class="$style.userSelectedButtons">
<div style="overflow: hidden;">
<MkUserCardMini
:user="testUser"
:withChart="false"
:class="$style.userSelectedCard"
/>
</div>
<div>
<button
class="_button"
:class="$style.userSelectedRemoveButton"
@click="removeUser"
>
<i class="ti ti-x"></i>
</button>
</div>
</div>
<div v-if="testUser != null">
<RolesTester v-model="role.condFormula" :user="testUser"/>
</div>
</div>
</MkFolder>
<MkInfo v-else>{{ i18n.ts._role.isConditionalRole }}</MkInfo>
</div>
</div>
</PageWithHeader>
</template>
<script lang="ts" setup>
import { computed, reactive, ref, shallowRef } from 'vue';
import { computed, reactive, ref } from 'vue';
import XEditor from './roles.editor.vue';
import RolesTester from './RolesTester.vue';
import type * as Misskey from 'misskey-js';
import MkFolder from '@/components/MkFolder.vue';
import * as os from '@/os.js';
import { misskeyApi } from '@/utility/misskey-api.js';
@ -104,9 +64,9 @@ import { i18n } from '@/i18n.js';
import { definePage } from '@/page.js';
import MkButton from '@/components/MkButton.vue';
import MkUserCardMini from '@/components/MkUserCardMini.vue';
import MkInfo from '@/components/MkInfo.vue';
import MkPagination from '@/components/MkPagination.vue';
import { useRouter } from '@/router.js';
import { instance } from '@/instance.js';
const router = useRouter();
@ -128,8 +88,6 @@ const role = reactive(await misskeyApi('admin/roles/show', {
roleId: props.id,
}));
const testUser = shallowRef<Misskey.entities.UserDetailed | null>(null);
function edit() {
router.push('/admin/roles/' + role.id + '/edit');
}
@ -215,18 +173,6 @@ definePage(() => ({
icon: 'ti ti-badge',
}));
function selectUser() {
os.selectUser({
includeSelf: true,
localOnly: instance.noteSearchableScope === 'local',
}).then(_user => {
testUser.value = _user;
});
}
function removeUser() {
testUser.value = null;
}
</script>
<style lang="scss" module>
@ -267,31 +213,4 @@ function removeUser() {
transform: rotateX(180deg);
}
}
.userSelectButton {
width: 100%;
height: 100%;
padding: 12px;
border: 2px dashed color(from var(--MI_THEME-fg) srgb r g b / 0.5);
}
.userSelectButtonInner {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
min-height: 38px;
}
.userSelectedButtons {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
}
.userSelectedRemoveButton {
width: 32px;
height: 32px;
color: #ff2a2a;
}
</style>

View file

@ -265,7 +265,7 @@ _role:
remoteFollowingLessThanOrEq: "Follows X or fewer remote accounts"
remoteFollowingMoreThanOrEq: "Follows X or more remote accounts"
remoteDataWarning: "This condition may be incorrect for remote users."
roleTester: "Role tester"
selectTestUser: "Select a user to test the condition."
_emailUnavailable:
banned: "This email address is banned"
_signup: