Przeglądaj źródła

权限配置,有BUG未完成

枫林 3 miesięcy temu
rodzic
commit
7e2f97359d
4 zmienionych plików z 131 dodań i 14 usunięć
  1. 1 1
      package.json
  2. 23 0
      src/config/permission.yml
  3. 97 11
      src/lib/Plugins.ts
  4. 10 2
      src/lib/config.ts

+ 1 - 1
package.json

@@ -5,7 +5,7 @@
   "main": "index.js",
   "type": "module",
   "scripts": {
-    "build": "tsc && cp -R config/ resources/ dist/",
+    "build": "cp -R ./src/config/ ./dist/ && cp -R ./src/resources/ ./dist/ && tsc",
     "dev": "nodemon --exec \"node --no-warnings --loader ts-node/esm --import tsconfig-paths/register src/app.ts\"",
     "start": "npm run build && node dist/app.js"
   },

+ 23 - 0
src/config/permission.yml

@@ -0,0 +1,23 @@
+enable: true
+users:
+  default:  # 默认配置
+    plugins:
+      test:
+        enable: true
+        commands:
+          "*": true  # 通配符表示所有命令默认允许
+          
+  # 用户/群组特定配置(可选)
+  211249983:
+    plugins:
+      test:
+        commands:
+          dangerousCommand: false
+          
+  1008611:
+    plugins:
+      test:
+        enable: true
+        commands:
+          MyCommand: true
+          MyCommand2: false

+ 97 - 11
src/lib/Plugins.ts

@@ -14,10 +14,11 @@ import {
 import * as fs from 'fs'
 import * as path from 'path'
 // 获取指令前缀
-import {Botconfig as config} from './config.js'
+import {Botconfig as config, PermissionConfig} from './config.js'
 import { ImageSegment, ReplySegment,  TextSegment } from "node-napcat-ts/dist/Structs.js";
 import { fileURLToPath } from 'node:url';
 import { qqBot } from "../app.js";
+import { count } from "node:console";
 
 //WSSendParam
 
@@ -110,14 +111,6 @@ async function loadPlugins(): Promise<void> {
                                 author: pluginConfig.author,
                                 describe: pluginConfig.describe
                             };
-                            // // 注册插件
-                            // commandList.push(plugin);
-                            // botlogger.info(`注册插件[${plugin.id}]: ${plugin.name}`);
-                            // // 添加帮助命令
-                            // if (pluginConfig.help?.enabled !== false) {
-                            //     addHelpCommand(plugin, pluginConfig);
-                            // }
-
                             // 触发装饰器
                             await initializePluginCommands(instance);
 
@@ -180,6 +173,80 @@ async function initializeScheduledTasks(instance: any): Promise<void> {
         }
     }
 }
+async function IsPermission(id: number, plugin: string, command: string): Promise<boolean> {
+    try {
+        // 获取用户权限配置(带默认回退)
+        const userPermission = getUserPermission(id);
+        
+        // 获取插件配置(带默认回退)
+        const pluginConfig = getPluginConfig(userPermission, plugin);
+        
+        // 检查插件总开关
+        if (pluginConfig?.enable === false) return false;
+
+        // 获取命令权限配置
+        const commandPermission = getCommandPermission(pluginConfig, command);
+        
+        // 自动保存新配置
+        if (commandPermission === undefined) {
+            await saveNewCommandConfig(id, plugin, command);
+            return true; // 默认允许新命令
+        }
+        
+        return Boolean(commandPermission);
+    } catch (error) {
+        if (error instanceof Error) {
+            botlogger.error(`权限检查失败 [${id}/${plugin}/${command}]:${error.message}`);
+        } else {
+            botlogger.error(`权限检查失败 [${id}/${plugin}/${command}]:未知错误`);
+        }
+        return false; // 出错时默认拒绝
+    }
+}
+
+// 新增辅助函数
+function getUserPermission(id: number) {
+    // 确保默认配置层级存在
+    if (!PermissionConfig.users.default) {
+        PermissionConfig.users.default = { plugins: {} };
+    }
+    if (!PermissionConfig.users.default.plugins) {
+        PermissionConfig.users.default.plugins = {};
+    }
+    
+    // 深度合并用户配置与默认配置
+    return {
+        plugins: {
+            ...PermissionConfig.users.default.plugins,
+            ...(PermissionConfig.users[id]?.plugins || {})
+        }
+    };
+}
+
+async function saveNewCommandConfig(id: number, plugin: string, command: string) {
+    try {
+        // 初始化用户配置树
+        PermissionConfig.users[id] = PermissionConfig.users[id] || { plugins: {} };
+        PermissionConfig.users[id].plugins[plugin] = PermissionConfig.users[id].plugins[plugin] || { commands: {} };
+        PermissionConfig.users[id].plugins[plugin].commands = PermissionConfig.users[id].plugins[plugin].commands || {};
+        
+        // 设置新命令默认权限
+        PermissionConfig.users[id].plugins[plugin].commands[command] = true;
+        
+        await config.saveConfig('permission', PermissionConfig);
+        botlogger.info(`自动创建 [${id}] 的 ${plugin}.${command} 命令权限`);
+    } catch (error) {
+        botlogger.error(`配置保存失败:${error instanceof Error ? error.stack : error}`);
+    }
+}
+function getPluginConfig(userPermission: any, plugin: string) {
+    return userPermission?.plugin?.[plugin] ?? PermissionConfig.user.default.plugin[plugin];
+}
+
+function getCommandPermission(pluginConfig: any, command: string) {
+    return pluginConfig?.command?.[command];
+}
+
 
 // 修改 runplugins 函数
 export async function runplugins() {
@@ -191,7 +258,6 @@ export async function runplugins() {
         botlogger.info("开始注册插件...");
         // 自动加载插件
         await loadPlugins();
-        
         // 设置消息处理器
         qqBot.on('message', async (context) => {
             try {
@@ -242,7 +308,27 @@ export async function runplugins() {
                 }
 
                 botlogger.info(`找到命令: ${CMD_PREFIX}${plugin.id} ${command.cmd}`);
-
+                //指令权限检查
+                //if(context.message_type === 'private'){
+                //    if(!await IsPermission(context.user_id,plugin.id,command.cmd)){
+                //        botlogger.info(`[${context.user_id}]无权限执行命令: ${CMD_PREFIX}${plugin.id} ${command.cmd}`);
+                //        context.quick_action([{
+                //            type: 'text',
+                //            data: { text: `你没有权限执行此命令` }
+                //        }]);
+                //        return;
+                //    }
+                //}
+                //if(context.message_type === 'group'){
+                //    if(!await IsPermission(context.group_id,plugin.id,command.cmd)){
+                //        botlogger.info(`[${context.group_id}]无权限执行命令: ${CMD_PREFIX}${plugin.id} ${command.cmd}`);
+                //        context.quick_action([{
+                //            type: 'text',
+                //            data: { text: `你没有权限执行此命令` }
+                //        }])
+                //        return;
+                //    }
+                //}
                 // 执行命令
                 await handleCommand(context, plugin, command, args);
 

+ 10 - 2
src/lib/config.ts

@@ -5,5 +5,13 @@ import * as yaml from 'js-yaml'
 import { fileURLToPath } from 'node:url';
 
 const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const configPath = path.join(__dirname, '../config/bot.yml');  // 保持源码与编译后一致
-export const Botconfig = yaml.load(fs.readFileSync(configPath, 'utf8')) as any;
+async function loadConfig(file: string): Promise<any> {
+    const configPath = path.join(__dirname, `../config/${file}.yml`);  // 保持源码与编译后一致
+    return await yaml.load(fs.readFileSync(configPath, 'utf8')) as any;
+}
+export function saveConfig(file: string, data: any): void {
+    const configPath = path.join(__dirname, `../config/${file}.yml`);  // 保持源码与编译后一致
+    fs.writeFileSync(configPath, yaml.dump(data));
+}
+export const Botconfig = await loadConfig('bot');
+export const PermissionConfig = await loadConfig('permission');