dsh-mc-server-ops 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +215 -3
- package/client.js +300 -0
- package/cordis.patch.yml +17 -0
- package/index.js +780 -0
- package/ops/adapters/index.mjs +37 -0
- package/ops/adapters/local.mjs +45 -0
- package/ops/adapters/pterodactyl.mjs +105 -0
- package/ops/command-guard.mjs +102 -0
- package/ops/mcadmin.ps1 +982 -0
- package/ops/rcon.mjs +471 -0
- package/ops/server-console.ps1 +92 -0
- package/ops/watchdog.ps1 +117 -0
- package/package.json +67 -4
package/index.js
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
6
|
+
import { guardCommand } from './ops/command-guard.mjs'
|
|
7
|
+
import { createAdapter } from './ops/adapters/index.mjs'
|
|
8
|
+
|
|
9
|
+
// 运行期路径:apply() 里按配置初始化。服务器目录、脚本位置都可以在设置里改。
|
|
10
|
+
const paths = { serverDir: '', script: '', ownersFile: '', flipLog: '' }
|
|
11
|
+
|
|
12
|
+
// 本机界面会话(桌面端 / CLI)的 id 形如 session-xxxx;QQ 机器人建出来的会话是纯 UUID。
|
|
13
|
+
function isLocalSession(id) { return /^(session-|local-)/i.test(String(id || '')) }
|
|
14
|
+
|
|
15
|
+
// 人设默认值。安装后可以在设置里改名字和语气,这里只是小铜的出厂设定。
|
|
16
|
+
const DEFAULT_PERSONA = '你在 QQ 群里叫「小铜」,二十来岁,平时就泡在这台 Minecraft 服务器里,机器、物流、红石都能聊两句,服务器出毛病也能修。你不是客服,说话自然点,别端着,也别卖萌。'
|
|
17
|
+
// 服主用 mc_server 执行过一次操作后,10 分钟内允许该会话使用文件/命令类工具。
|
|
18
|
+
const GRANT_MS = 12 * 60 * 60 * 1000
|
|
19
|
+
// 任何会话都能用的只读工具
|
|
20
|
+
const OPEN_READ_TOOLS = ['read', 'glob', 'grep']
|
|
21
|
+
// 需要服主授权才能用的工具
|
|
22
|
+
const GUARDED_TOOLS = ['write', 'edit', 'pwsh', 'web_fetch', 'web_search']
|
|
23
|
+
// 发文件到 QQ 的工具(玩家可用,但敏感文件除外)
|
|
24
|
+
const SEND_TOOLS = ['qqbot_send_file', 'present']
|
|
25
|
+
const SENSITIVE_PATH = /(server\.properties|ops[\\/]+data[\\/]+|\.credentials|\.env\b|owners\.json|config\.json|\.pem\b|\.key\b)/i
|
|
26
|
+
// 玩家可以改的范围:KubeJS 的 server_scripts(配方脚本)
|
|
27
|
+
// 玩家可以改的范围:服务器目录下除敏感区之外的文件(修配置、修脚本用)
|
|
28
|
+
function normalizePath(p) { return String(p || '').replace(/\//g, '\\').toLowerCase() }
|
|
29
|
+
|
|
30
|
+
// 永远不许玩家碰的东西(和投票无关,改设置也解不开)
|
|
31
|
+
const ALWAYS_DENY_SOURCE = '\\.dsh|credential|\\.key$|\\.pem$|\\.env$|ops\\.json|banned-|usercache\\.json|eula\\.txt|server\\.jar|\\.exe$|\\.dll$|\\.lnk$'
|
|
32
|
+
// 受保护路径:可在设置里改(默认 world / ops/data / whitelist),改动这些位置要走群友投票
|
|
33
|
+
const DEFAULT_PROTECTED = ['world', 'ops/data', 'whitelist']
|
|
34
|
+
let PROTECTED_PATHS = DEFAULT_PROTECTED.slice()
|
|
35
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
36
|
+
function protectedSource() {
|
|
37
|
+
const parts = PROTECTED_PATHS.map((raw) => {
|
|
38
|
+
const p = String(raw || '').trim()
|
|
39
|
+
if (!p) return ''
|
|
40
|
+
const n = normalizePath(p).replace(/\\+$/, '')
|
|
41
|
+
if (n === 'world') return 'world(_nether|_the_end)?[\\\\/]'
|
|
42
|
+
if (n === 'ops\\data') return 'ops[\\\\/]+data'
|
|
43
|
+
if (n === 'whitelist' || n === 'whitelist.json') return 'whitelist\\.json'
|
|
44
|
+
return escapeRegExp(n) + '(?:[\\\\/]|$)'
|
|
45
|
+
}).filter(Boolean)
|
|
46
|
+
return '(' + parts.concat([ALWAYS_DENY_SOURCE]).join('|') + ')'
|
|
47
|
+
}
|
|
48
|
+
function isProtectedPath(target) { return new RegExp(protectedSource(), 'i').test(normalizePath(target)) }
|
|
49
|
+
function setProtectedPaths(list) {
|
|
50
|
+
const next = Array.isArray(list) ? list.map((x) => String(x)).filter((x) => x.trim()) : []
|
|
51
|
+
PROTECTED_PATHS = next.length ? next : DEFAULT_PROTECTED.slice()
|
|
52
|
+
}
|
|
53
|
+
function isPlayerWritable(target) {
|
|
54
|
+
const root = normalizePath(paths.serverDir).replace(/\\+$/, '') + '\\'
|
|
55
|
+
const t = normalizePath(target)
|
|
56
|
+
if (!root || !t.startsWith(root)) return false
|
|
57
|
+
if (t.includes('..')) return false
|
|
58
|
+
return !isProtectedPath(t)
|
|
59
|
+
}
|
|
60
|
+
// 只读命令白名单:只允许这些开头/包含的命令查询
|
|
61
|
+
const READONLY_CMD = /\b(Get-Content|Get-ChildItem|Get-Item|Get-ItemProperty|Select-String|Select-Object|Where-Object|Sort-Object|Measure-Object|Format-Table|Format-List|Write-Output|Write-Host|Test-Path|Resolve-Path|Split-Path|Join-Path|Get-Process|Get-Service|Get-CimInstance|Get-ComputerInfo|Get-Date|Get-Location|Get-FileHash|Get-Acl|whoami|hostname|systeminfo|tasklist|dir|ls|cat|type|more|findstr|tree)\b/i
|
|
62
|
+
// 写文件 / 执行 / 联网下载 / 进程控制等危险命令
|
|
63
|
+
const DANGEROUS_CMD = /(Remove-Item|Move-Item|Copy-Item|Rename-Item|New-Item|Set-Content|Add-Content|Out-File|Clear-Content|Set-Item|Set-ItemProperty|New-ItemProperty|Start-Process|Stop-Process|Invoke-Expression|\biex\b|Invoke-WebRequest|Invoke-RestMethod|\bcurl\b|\bwget\b|Start-Job|schtasks|\breg\b|\bsc\b|format|diskpart|shutdown|taskkill|Stop-Computer|Restart-Computer|Set-ExecutionPolicy|New-Service|Set-Service|WriteAll| AppendAll|::Delete|CreateDirectory|DownloadFile|DownloadString|\bdel\b|\berase\b|\brd\b|rmdir|\brm\b)/i
|
|
64
|
+
|
|
65
|
+
const grants = new Map()
|
|
66
|
+
|
|
67
|
+
function readOwners() {
|
|
68
|
+
if (!paths.ownersFile) return []
|
|
69
|
+
try {
|
|
70
|
+
const raw = readFileSync(paths.ownersFile, 'utf8').replace(/^\uFEFF/, '')
|
|
71
|
+
const doc = JSON.parse(raw)
|
|
72
|
+
return Array.isArray(doc.owners) ? doc.owners.map((x) => String(x)) : []
|
|
73
|
+
} catch {
|
|
74
|
+
return []
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isOwner(actor) {
|
|
79
|
+
return readOwners().includes(actor)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function grantTools(agentId) {
|
|
83
|
+
if (agentId) grants.set(String(agentId), Date.now() + GRANT_MS)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function hasToolGrant(agentId) {
|
|
87
|
+
const until = grants.get(String(agentId)) ?? 0
|
|
88
|
+
return until > Date.now()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const ACTIONS = [
|
|
92
|
+
'status', 'players', 'say', 'cmd', 'start', 'stop', 'restart',
|
|
93
|
+
'logs', 'crashinfo', 'whoami', 'help', 'gamemode',
|
|
94
|
+
'bind-player', 'unbind-player', 'my-players', 'bindings', 'whitelist-sync',
|
|
95
|
+
'kubejs-backup', 'kubejs-reload', 'vote-start', 'vote-approve', 'vote-reject', 'vote-status',
|
|
96
|
+
'export-data', 'import-data',
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
function runMcAdmin(args, timeoutMs) {
|
|
100
|
+
return new Promise((resolve) => {
|
|
101
|
+
let child
|
|
102
|
+
try {
|
|
103
|
+
child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', paths.script, '-ServerDir', paths.serverDir, ...args], {
|
|
104
|
+
windowsHide: true,
|
|
105
|
+
cwd: paths.serverDir,
|
|
106
|
+
})
|
|
107
|
+
} catch (error) {
|
|
108
|
+
resolve({ ok: false, text: '无法启动 powershell: ' + (error && error.message ? error.message : String(error)) })
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
const chunks = []
|
|
112
|
+
const errChunks = []
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
try { child.kill() } catch { /* ignore */ }
|
|
115
|
+
}, timeoutMs)
|
|
116
|
+
child.stdout.on('data', (data) => chunks.push(Buffer.from(data)))
|
|
117
|
+
child.stderr.on('data', (data) => errChunks.push(Buffer.from(data)))
|
|
118
|
+
child.on('error', (error) => {
|
|
119
|
+
clearTimeout(timer)
|
|
120
|
+
resolve({ ok: false, text: String(error && error.message ? error.message : error) })
|
|
121
|
+
})
|
|
122
|
+
child.on('close', (code) => {
|
|
123
|
+
clearTimeout(timer)
|
|
124
|
+
const stdout = Buffer.concat(chunks).toString('utf8').trim()
|
|
125
|
+
const stderr = Buffer.concat(errChunks).toString('utf8').trim()
|
|
126
|
+
if (code === 0) {
|
|
127
|
+
resolve({ ok: true, text: stdout || '(无输出)' })
|
|
128
|
+
} else {
|
|
129
|
+
resolve({ ok: false, text: stderr || stdout || ('退出码 ' + code) })
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const DESCRIPTION = [
|
|
136
|
+
'Minecraft 服务器的操作入口。',
|
|
137
|
+
'它在宿主进程里直接执行 mcadmin.ps1,不受 shell 沙箱限制、不会触发“允许/拒绝”审批。',
|
|
138
|
+
'',
|
|
139
|
+
'action 取值与权限:',
|
|
140
|
+
'- status:运行状态、在线人数、CPU、内存、TPS、磁盘、运行时长,并带“健康”判定(正常 / 卡顿 / 无响应假死 / 启动中)(任何人可用)',
|
|
141
|
+
'- players:在线玩家名单(任何人)',
|
|
142
|
+
'- say:游戏内广播,arg 为内容,200 字以内、5 秒限流(任何人)',
|
|
143
|
+
'- logs:最近日志,已过滤 RCON 噪音(任何人)',
|
|
144
|
+
'- crashinfo:最近一次崩溃前后 20 行(任何人)',
|
|
145
|
+
'- help / whoami:指令表 / 查自己的身份(任何人)',
|
|
146
|
+
'- start:启动服务器。确认关闭时任何人可用;在线或启动中仅服主;假死时会提示改用 restart',
|
|
147
|
+
'- stop:停服,仅服主',
|
|
148
|
+
'- restart:服务器确认关闭、或健康=无响应(假死)时任何人可用(假死会自动强杀重启);健康=正常或启动中时仅服主',
|
|
149
|
+
'- gamemode:切换游戏模式,arg 形如 spectator 玩家名。玩家只能切 survival / spectator,且目标必须是自己绑定的游戏名;creative / adventure 和切别人仅服主',
|
|
150
|
+
'- cmd:执行任意后台指令(op/deop/ban/kick/whitelist 等),仅服主',
|
|
151
|
+
'',
|
|
152
|
+
'玩家还能做:用 read / glob / grep 看服务器文件、用只读的 pwsh 命令查信息、用 qqbot_send_file 把普通文件发到群里(口令/密钥类文件除外)。',
|
|
153
|
+
'玩家不能:改文件、删文件、新建文件、执行危险命令、设置创造模式。',
|
|
154
|
+
'- bind-player:把游戏名绑定到当前 QQ(同时加入服务器白名单),arg 为游戏名(1-16 位字母/数字/下划线),一个 QQ 最多 10 个,一个游戏名最多被 3 个 QQ 绑定',
|
|
155
|
+
'- unbind-player:解绑自己的某个游戏名(若该名字已无其它 QQ 绑定,同时移出白名单),arg 为游戏名',
|
|
156
|
+
'- my-players:列出自己绑定的游戏名和在线状态(任何人可用)',
|
|
157
|
+
'- whitelist-sync:把所有绑定名同步进服务器白名单并开启白名单,仅服主',
|
|
158
|
+
'- kubejs-backup:备份 kubejs/server_scripts 到带时间戳的目录(改配方前先跑)',
|
|
159
|
+
'- kubejs-reload:重载 KubeJS 脚本 + 数据包(改完配方后跑,让配方立即生效)',
|
|
160
|
+
'- vote-start:发起“需要更高权限”的确认投票,arg 为要做什么的一句话说明;返回投票编号',
|
|
161
|
+
'- vote-approve:群友投同意票,arg 为投票编号;同一 QQ 只能投一次,满 2 人即通过,通过后本会话获得 10 分钟高权限',
|
|
162
|
+
'- vote-reject:群友投反对票,arg 为投票编号;只要在满 2 票之前有人否决,这个投票立刻作废、不授权,之后再点同意也不算;已经通过的投票再否决无效',
|
|
163
|
+
'- vote-status:查看投票进度(可带编号)',
|
|
164
|
+
'- export-data:把 ops\\data(绑定、投票、服主名单、口令)打成 zip,arg 为目标路径,仅服主',
|
|
165
|
+
'- import-data:从 zip 恢复 ops\\data,arg 为 zip 路径,仅服主',
|
|
166
|
+
'',
|
|
167
|
+
'玩家可以改服务器目录下除敏感区(ops\\data、world、白名单、eula、jar/exe/dll、密钥)之外的文件:kubejs 配方、config/defaultconfigs 配置、server.properties 等,write/edit 直接放行;改之前先备份,改完按需 reload。',
|
|
168
|
+
'玩家不能改 kubejs 目录以外的任何文件。',
|
|
169
|
+
'- bindings:列出所有 QQ 与游戏名的绑定,仅服主',
|
|
170
|
+
'',
|
|
171
|
+
'判断服务器是否真的活着要看 status 的“健康”字段:进程还在但 RCON 无响应 = 假死,不要当成正常;TPS < 3 = 卡顿。',
|
|
172
|
+
'永远不要只凭“进程存在”就告诉用户服务器没事。',
|
|
173
|
+
'',
|
|
174
|
+
'服主可以用 whoami 确认身份;确认是 owner 后,该会话在 12 小时内可以使用 write / edit / pwsh / read 等 DSH 工具改文件、下载、删除、执行命令。',
|
|
175
|
+
'玩家身份调用 whoami 只会得到 player,不会获得这些权限。',
|
|
176
|
+
'',
|
|
177
|
+
'actor 必填:必须是 QQ 群消息开头 `[昵称 (ID)]` 里的那个 ID,原样传入,不得改写或猜测;',
|
|
178
|
+
'私聊没有该标记时请让对方到群里操作。权限由脚本按 owners.json 校验,玩家传服主 ID 也会被识别行为日志记录。',
|
|
179
|
+
].join('\n')
|
|
180
|
+
|
|
181
|
+
export const name = 'mc-server-ops'
|
|
182
|
+
export const inject = ['tools']
|
|
183
|
+
// 诊断/测试用:判断某个路径是否落在受保护区域,以及临时改一份受保护清单
|
|
184
|
+
export { isProtectedPath, setProtectedPaths }
|
|
185
|
+
|
|
186
|
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
|
|
187
|
+
// 跨平台的只读动作:Windows 上走 PowerShell(信息更全),其它平台走 Node 核心
|
|
188
|
+
const NODE_RUNNER = join(SCRIPT_DIR, 'ops', 'rcon.mjs')
|
|
189
|
+
const NODE_ACTIONS = new Set(['status', 'players', 'say', 'cmd', 'logs', 'start', 'stop', 'restart'])
|
|
190
|
+
|
|
191
|
+
/** 插件配置:会完整渲染进 DSH 设置界面。 */
|
|
192
|
+
export const Config = Schema.object({
|
|
193
|
+
server: Schema.object({
|
|
194
|
+
dir: Schema.string().default('').description('Minecraft 服务器目录(含 server.properties、mods、java 子目录)。留空则用环境变量 MC_SERVER_DIR,再不行用 D:\\server'),
|
|
195
|
+
rconPort: Schema.number().default(25575).description('RCON 端口(需在 server.properties 里开启 enable-rcon)'),
|
|
196
|
+
rconPassword: Schema.string().default('').description('RCON 密码;留空则从 server.properties 读取'),
|
|
197
|
+
}).description('服务器'),
|
|
198
|
+
|
|
199
|
+
persona: Schema.object({
|
|
200
|
+
enabled: Schema.boolean().default(true).description('是否把下面的人设注入 QQ 会话'),
|
|
201
|
+
name: Schema.string().default('小铜').description('助手在群里的名字'),
|
|
202
|
+
text: Schema.string().default('').description('人设正文。留空使用内置默认(小铜)。改名字/口吻都改这里,不用改代码'),
|
|
203
|
+
scope: Schema.union(['qq', 'all', 'none']).default('qq').description('注入范围:qq=只注入 QQ 群/私聊;all=所有会话;none=关闭'),
|
|
204
|
+
}).description('人设'),
|
|
205
|
+
|
|
206
|
+
ops: Schema.object({
|
|
207
|
+
allowPlayerWrite: Schema.boolean().default(true).description('允许玩家改服务器目录下除敏感区(ops\\data、world、白名单、jar/exe/dll)之外的文件'),
|
|
208
|
+
grantHours: Schema.number().default(12).description('服主确认后,该会话可编辑文件/执行命令的有效时长(小时)'),
|
|
209
|
+
riskApprovalSeconds: Schema.number().default(30).description('创建服主口令的冷却(秒),防止被刷'),
|
|
210
|
+
}).description('权限'),
|
|
211
|
+
|
|
212
|
+
permissions: Schema.object({
|
|
213
|
+
voteEscalation: Schema.boolean().default(true).description('允许群友投票放权(改 world / ops\\data / 白名单)。关掉后只有服主能改'),
|
|
214
|
+
kubejsEdit: Schema.boolean().default(true).description('允许玩家改 KubeJS 配方脚本(kubejs/ 目录)'),
|
|
215
|
+
configEdit: Schema.boolean().default(true).description('允许玩家改 config / defaultconfigs / server.properties'),
|
|
216
|
+
playerStart: Schema.boolean().default(true).description('服务器关闭时,玩家可以用 start 开服'),
|
|
217
|
+
playerRestart: Schema.boolean().default(true).description('服务器崩溃或假死时,玩家可以 restart'),
|
|
218
|
+
playerStop: Schema.boolean().default(false).description('允许玩家停服(默认关闭,只有服主能停)'),
|
|
219
|
+
gamemodeSwitch: Schema.boolean().default(true).description('允许玩家把自己在生存 / 旁观之间切换'),
|
|
220
|
+
say: Schema.boolean().default(true).description('允许玩家用 say 在游戏里广播'),
|
|
221
|
+
fileSend: Schema.boolean().default(true).description('允许玩家把普通文件发到群里'),
|
|
222
|
+
}).description('功能开关'),
|
|
223
|
+
|
|
224
|
+
vote: Schema.object({
|
|
225
|
+
approveNeed: Schema.number().min(1).default(2).description('通过需要多少位群友同意'),
|
|
226
|
+
rejectNeed: Schema.number().min(1).default(1).description('多少位群友反对就作废(1 = 一票否决)'),
|
|
227
|
+
timeoutMinutes: Schema.number().min(1).default(15).description('投票多少分钟没凑够门槛就自动作废'),
|
|
228
|
+
vetoEnabled: Schema.boolean().default(true).description('允许一票否决:凑够同意票之前有人反对就作废。关掉后反对票只记录、不作废'),
|
|
229
|
+
protectedPaths: Schema.array(Schema.string()).default(['world', 'ops/data', 'whitelist'])
|
|
230
|
+
.description('受保护路径:改动这些位置需要群友投票放行。默认 world, ops/data, whitelist'),
|
|
231
|
+
}).description('投票'),
|
|
232
|
+
|
|
233
|
+
adapter: Schema.union(['local', 'panel']).default('local')
|
|
234
|
+
.description('写操作走哪条路:local=本机直接跑脚本(默认);panel=通过 Pterodactyl 面板的 HTTP API 启停/发指令'),
|
|
235
|
+
panel: Schema.object({
|
|
236
|
+
url: Schema.string().default('').description('面板地址,例如 https://panel.example.com(不要带结尾斜杠)'),
|
|
237
|
+
serverId: Schema.string().default('').description('服务器 ID:面板里该服务器 URL 的最后一段(8 位短 UUID)'),
|
|
238
|
+
clientApiKey: Schema.string().default('').description('客户端 API Key(ptlc_ 开头,面板 → Account → API Credentials 里生成)'),
|
|
239
|
+
}).description('Pterodactyl 面板(adapter 选 panel 时才用)'),
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
export function apply(ctx, config) {
|
|
243
|
+
const perms = Object.assign({
|
|
244
|
+
voteEscalation: true,
|
|
245
|
+
kubejsEdit: true,
|
|
246
|
+
configEdit: true,
|
|
247
|
+
playerStart: true,
|
|
248
|
+
playerRestart: true,
|
|
249
|
+
playerStop: false,
|
|
250
|
+
gamemodeSwitch: true,
|
|
251
|
+
say: true,
|
|
252
|
+
fileSend: true,
|
|
253
|
+
}, (config && config.permissions) || {})
|
|
254
|
+
const cfgServer = (config && config.server) || {}
|
|
255
|
+
const serverDir = String(cfgServer.dir || process.env.MC_SERVER_DIR || 'D:\\server').replace(/[\\/]+$/, '')
|
|
256
|
+
paths.serverDir = serverDir
|
|
257
|
+
const opsDir = join(serverDir, 'ops')
|
|
258
|
+
const bundledDir = join(SCRIPT_DIR, 'ops')
|
|
259
|
+
const bundled = join(bundledDir, 'mcadmin.ps1')
|
|
260
|
+
const installed = join(opsDir, 'mcadmin.ps1')
|
|
261
|
+
// 旧版脚本没有 -ServerDir 参数:把包内脚本补/升级到服务器目录,保证参数一致。
|
|
262
|
+
ensureOpsScripts(bundledDir, opsDir)
|
|
263
|
+
paths.script = existsSync(installed) ? installed : bundled
|
|
264
|
+
paths.ownersFile = join(opsDir, 'data', 'owners.json')
|
|
265
|
+
paths.flipLog = join(opsDir, 'data', 'preset-flip.log')
|
|
266
|
+
|
|
267
|
+
// 设置页:插件详情里渲染自己的表单(client.js),表单通过下面这两个 HTTP 路由读写配置。
|
|
268
|
+
const settingsService = ctx.get('settings')
|
|
269
|
+
if (settingsService && typeof settingsService.configure === 'function') {
|
|
270
|
+
ctx.effect(() => settingsService.configure({ auto: true }))
|
|
271
|
+
}
|
|
272
|
+
// 诊断:等服务起来后把客户端模块图落盘,确认本包的 client 半屏有没有被加载。
|
|
273
|
+
setTimeout(() => {
|
|
274
|
+
const out = join(paths.serverDir, 'ops', 'data', 'client-graph.json')
|
|
275
|
+
const payload = { at: new Date().toISOString(), error: null, entryCount: 0, mine: [], sample: [] }
|
|
276
|
+
try {
|
|
277
|
+
const cm = ctx.get('clientModules')
|
|
278
|
+
if (!cm || typeof cm.graph !== 'function') payload.error = 'no clientModules service'
|
|
279
|
+
else {
|
|
280
|
+
const graph = cm.graph()
|
|
281
|
+
payload.entryCount = (graph.entries || []).length
|
|
282
|
+
payload.mine = (graph.entries || []).filter((e) => JSON.stringify(e).includes('mc-server-ops'))
|
|
283
|
+
payload.sample = (graph.entries || []).filter((e) => JSON.stringify(e).includes('qqbot'))
|
|
284
|
+
}
|
|
285
|
+
} catch (error) {
|
|
286
|
+
payload.error = String(error && error.message ? error.message : error)
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
mkdirSync(dirname(out), { recursive: true })
|
|
290
|
+
writeFileSync(out, JSON.stringify(payload, null, 2), 'utf8')
|
|
291
|
+
} catch (error) { }
|
|
292
|
+
}, 8000)
|
|
293
|
+
// 面板读写用:内存里存一份当前配置,作为 settings/configEditor 都不可用时的兜底。
|
|
294
|
+
let liveConfig = {
|
|
295
|
+
server: Object.assign({ rconPort: 25575, rconPassword: '' }, (config && config.server) || {}, { dir: serverDir }),
|
|
296
|
+
persona: Object.assign({ enabled: true, name: '小铜', text: '', scope: 'qq' }, (config && config.persona) || {}),
|
|
297
|
+
ops: Object.assign({ allowPlayerWrite: true, grantHours: 12, riskApprovalSeconds: 30 }, (config && config.ops) || {}),
|
|
298
|
+
adapter: String((config && config.adapter) || 'local'),
|
|
299
|
+
panel: Object.assign({ url: '', serverId: '', clientApiKey: '' }, (config && config.panel) || {}),
|
|
300
|
+
}
|
|
301
|
+
const memoryConfig = {
|
|
302
|
+
get: () => liveConfig,
|
|
303
|
+
set: (next) => {
|
|
304
|
+
liveConfig = Object.assign({}, liveConfig, next && typeof next === 'object' ? next : {})
|
|
305
|
+
writeVoteConfig(opsDir, liveConfig.vote)
|
|
306
|
+
setProtectedPaths(liveConfig.vote && liveConfig.vote.protectedPaths)
|
|
307
|
+
},
|
|
308
|
+
}
|
|
309
|
+
// 启动时先落一份,保证脚本读到的是当前设置
|
|
310
|
+
writeVoteConfig(opsDir, (config && config.vote) || null)
|
|
311
|
+
setProtectedPaths(config && config.vote && config.vote.protectedPaths)
|
|
312
|
+
// 面板上刚保存的开关要立刻生效,所以每次都合并一次 liveConfig,而不是只用启动时读到的值。
|
|
313
|
+
const currentPerms = () => Object.assign({}, perms, (liveConfig && liveConfig.permissions) || {})
|
|
314
|
+
// 写操作统一走适配器:local 包装 mcadmin.ps1 / rcon.mjs,panel 打 Pterodactyl 的 HTTP API。
|
|
315
|
+
// 每次调用时按当前配置现建一个,面板里改完地址不用重启。
|
|
316
|
+
const ADAPTER_ACTIONS = new Set(['start', 'stop', 'restart', 'cmd'])
|
|
317
|
+
const currentAdapter = () => createAdapter(liveConfig && liveConfig.adapter, {
|
|
318
|
+
runMcAdmin,
|
|
319
|
+
runNodeOps,
|
|
320
|
+
isWindows: process.platform === 'win32',
|
|
321
|
+
nodeActions: NODE_ACTIONS,
|
|
322
|
+
panel: (liveConfig && liveConfig.panel) || {},
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
// 依赖可能比本插件晚就绪,用 ctx.inject 等它们可用再挂路由。
|
|
326
|
+
if (typeof ctx.inject === 'function') {
|
|
327
|
+
ctx.inject(['settings', 'webServer'], (scope) => {
|
|
328
|
+
const webServer = scope.get('webServer')
|
|
329
|
+
if (!webServer || typeof webServer.register !== 'function') return
|
|
330
|
+
scope.effect(() => webServer.register({
|
|
331
|
+
kind: 'prefix',
|
|
332
|
+
path: '/mc-ops/config',
|
|
333
|
+
handler: (req, res) => handleConfigRoute(req, res, { settings: scope.get('settings'), editor: scope.get('configEditor') }, memoryConfig),
|
|
334
|
+
}))
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
const tools = ctx.get('tools')
|
|
338
|
+
if (!tools || typeof tools.register !== 'function') return
|
|
339
|
+
|
|
340
|
+
ctx.effect(() => tools.register({
|
|
341
|
+
name: 'mc_server',
|
|
342
|
+
// 工具描述必须是字符串(API 侧 schema 只接受 string)。DESCRIPTION 已经是 join 后的字符串,
|
|
343
|
+
// 这里按行切分后替换首行,再拼回字符串。
|
|
344
|
+
description: ['Minecraft 服务器(' + paths.serverDir + ')的操作入口。', ...DESCRIPTION.split('\n').slice(1)].join('\n'),
|
|
345
|
+
parameters: {
|
|
346
|
+
type: 'object',
|
|
347
|
+
properties: {
|
|
348
|
+
action: {
|
|
349
|
+
type: 'string',
|
|
350
|
+
enum: ACTIONS,
|
|
351
|
+
description: '要执行的操作',
|
|
352
|
+
},
|
|
353
|
+
arg: {
|
|
354
|
+
type: 'string',
|
|
355
|
+
description: 'say 的内容、cmd 的指令(不带斜杠)、口令,其它操作为空',
|
|
356
|
+
},
|
|
357
|
+
channel: {
|
|
358
|
+
type: 'string',
|
|
359
|
+
enum: ['c2c', 'group', 'unknown'],
|
|
360
|
+
description: '当前对话类型:私聊填 c2c,群聊填 group。绑定服主口令只接受 c2c。',
|
|
361
|
+
},
|
|
362
|
+
actor: {
|
|
363
|
+
type: 'string',
|
|
364
|
+
description: '发送者 ID:原样取自群消息开头的 [昵称 (ID)] 标记',
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
required: ['action', 'actor'],
|
|
368
|
+
additionalProperties: false,
|
|
369
|
+
},
|
|
370
|
+
timeoutMs: 180000,
|
|
371
|
+
isConcurrencySafe: () => false,
|
|
372
|
+
async execute(args, exec) {
|
|
373
|
+
const action = String((args && args.action) || '')
|
|
374
|
+
if (!ACTIONS.includes(action)) throw new Error('mc_server: 不支持的 action: ' + action)
|
|
375
|
+
const actor = String((args && args.actor) || '').trim()
|
|
376
|
+
if (!actor) throw new Error('mc_server: actor 不能为空(必须取自 [昵称 (ID)] 标记)')
|
|
377
|
+
const agentIdForGate = exec && exec.agent && exec.agent.id ? String(exec.agent.id) : ''
|
|
378
|
+
if ((action === 'owner-add' || action === 'owner-del') && !isLocalSession(agentIdForGate)) {
|
|
379
|
+
return { ok: false, text: '增删服主只能在设置面板里做,或者到服务器本机执行。' }
|
|
380
|
+
}
|
|
381
|
+
if (!isOwner(actor)) {
|
|
382
|
+
if (action === 'cmd') return { ok: false, text: '执行后台命令只有服主能做。' }
|
|
383
|
+
if (action === 'export-data' || action === 'import-data' || action === 'whitelist-sync' || action === 'bindings') {
|
|
384
|
+
return { ok: false, text: '这个操作只有服主能做。' }
|
|
385
|
+
}
|
|
386
|
+
const denied = checkActionAllowed(action, currentPerms())
|
|
387
|
+
if (denied) return { ok: false, text: denied }
|
|
388
|
+
}
|
|
389
|
+
// Channel 由会话决定,不信模型自己填:本机会话=console,QQ 会话=group,只有私聊且模型声明 c2c 才算 c2c
|
|
390
|
+
const channel = isLocalSession(agentIdForGate) ? 'console' : (String((args && args.channel) || '') === 'c2c' ? 'c2c' : 'group')
|
|
391
|
+
const cli = ['-Action', action, '-Actor', actor, '-Channel', channel]
|
|
392
|
+
const arg = args && args.arg !== undefined && args.arg !== null ? String(args.arg) : ''
|
|
393
|
+
if (arg !== '') cli.push('-Arg', arg)
|
|
394
|
+
// ── 出网前的三道闸 ──
|
|
395
|
+
// ① 权限校验:上面已经拦掉服主专属动作和设置里关掉的功能
|
|
396
|
+
// ② 投票放行:服主本人,或本会话刚通过群友投票(grant 窗口)
|
|
397
|
+
// ③ 静态拦截:command-guard.mjs 只拦“一条命令搞崩整个服”的类型
|
|
398
|
+
// 三道全过才真正发给 RCON。
|
|
399
|
+
if (action === 'cmd' || action === 'say') {
|
|
400
|
+
const owner = isOwner(actor)
|
|
401
|
+
const voteCleared = hasToolGrant(agentIdForGate)
|
|
402
|
+
const raw = action === 'say' ? 'say ' + arg : arg
|
|
403
|
+
const verdict = guardCommand(raw, { id: actor, owner })
|
|
404
|
+
if (!verdict.ok) {
|
|
405
|
+
const who = owner ? '服主' : (voteCleared ? '已投票放行的会话' : '玩家')
|
|
406
|
+
return { ok: false, text: '⛔ 命令被拦截(' + who + '):' + verdict.reason }
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const isWindows = process.platform === 'win32'
|
|
411
|
+
if (!isWindows && !NODE_ACTIONS.has(action)) {
|
|
412
|
+
return { ok: false, text: `(${process.platform})${action} 还没跨平台,目前只在 Windows 上可用。跨平台可用的是:${[...NODE_ACTIONS].join(' / ')}` }
|
|
413
|
+
}
|
|
414
|
+
const useNode = !isWindows && NODE_ACTIONS.has(action) && existsSync(NODE_RUNNER)
|
|
415
|
+
let result
|
|
416
|
+
if (ADAPTER_ACTIONS.has(action)) {
|
|
417
|
+
const adapter = currentAdapter()
|
|
418
|
+
const adapterOpts = { actor, channel, owner: isOwner(actor), timeoutMs: 170000 }
|
|
419
|
+
result = action === 'cmd'
|
|
420
|
+
? await adapter.sendCommand(arg, adapterOpts)
|
|
421
|
+
: await adapter[action](adapterOpts)
|
|
422
|
+
} else {
|
|
423
|
+
result = useNode ? await runNodeOps(action, arg, 60000, isOwner(actor)) : await runMcAdmin(cli, 170000)
|
|
424
|
+
}
|
|
425
|
+
if (isOwner(actor)) {
|
|
426
|
+
grantTools(exec && exec.agent ? exec.agent.id : undefined)
|
|
427
|
+
}
|
|
428
|
+
else if (action === 'vote-approve' && /投票通过/.test(result.text)) {
|
|
429
|
+
// 两人确认通过后,给这个会话 10 分钟高权限窗口,用来做约定的修复
|
|
430
|
+
grantTools(exec && exec.agent ? exec.agent.id : undefined)
|
|
431
|
+
}
|
|
432
|
+
return { ok: result.ok, text: result.text }
|
|
433
|
+
},
|
|
434
|
+
output: {
|
|
435
|
+
schema: {
|
|
436
|
+
type: 'object',
|
|
437
|
+
properties: {
|
|
438
|
+
ok: { type: 'boolean' },
|
|
439
|
+
text: { type: 'string' },
|
|
440
|
+
},
|
|
441
|
+
required: ['ok', 'text'],
|
|
442
|
+
additionalProperties: false,
|
|
443
|
+
},
|
|
444
|
+
render: (_args, value) => {
|
|
445
|
+
const v = value && typeof value === 'object' ? value : { ok: false, text: String(value) }
|
|
446
|
+
return [{ type: 'text', text: String(v.text || '') }]
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
}))
|
|
450
|
+
|
|
451
|
+
// QQ 侧根会话强制用 danger-full-access。
|
|
452
|
+
// 会话权限在创建时就定格了,只改 defaultPreset 追不到老会话,于是老群会话一直
|
|
453
|
+
// 停在 workspace-write:pwsh 在该模式下起不来(0xC0000142),每次都申请提权 -> 群里点允许。
|
|
454
|
+
// 这里在每轮 turn/start(工具开跑之前)把非本机的根会话纠正一次,老会话也能立刻恢复。
|
|
455
|
+
if (typeof ctx.on === 'function') {
|
|
456
|
+
// session/event 是在会话提交过程中派发的,此时直接 append 会报
|
|
457
|
+
// "session append cannot reenter while another append is being published",
|
|
458
|
+
// 所以丢到下一个宏任务里做,并对「正在发布」这类错误重试。
|
|
459
|
+
const flipToFullAccess = (session, attempt) => {
|
|
460
|
+
try {
|
|
461
|
+
const header = session && session.header
|
|
462
|
+
if (!header) return
|
|
463
|
+
const id = String(header.id ?? '')
|
|
464
|
+
if (!id || isLocalSession(id)) return
|
|
465
|
+
if (header.parentSession || header.origin === 'subagent') return
|
|
466
|
+
const presets = ctx.get('permissionPresets')
|
|
467
|
+
if (!presets || typeof presets.set !== 'function') return
|
|
468
|
+
let current = ''
|
|
469
|
+
try { current = presets.current(session) } catch { current = '' }
|
|
470
|
+
if (current === 'danger-full-access') return
|
|
471
|
+
presets.set(session, 'danger-full-access')
|
|
472
|
+
try { appendFileSync(paths.flipLog, new Date().toISOString() + ' flip ' + id + ' from=' + (current || 'unknown') + '\n') } catch { }
|
|
473
|
+
} catch (error) {
|
|
474
|
+
const message = String(error && error.message ? error.message : error)
|
|
475
|
+
if (attempt > 0 && /reenter|being published/i.test(message)) {
|
|
476
|
+
setTimeout(() => flipToFullAccess(session, attempt - 1), 300)
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
try { appendFileSync(paths.flipLog, new Date().toISOString() + ' error ' + message + '\n') } catch { }
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
ctx.effect(() => ctx.on('session/event', (session, event) => {
|
|
483
|
+
if (!event || event.type !== 'turn/start') return
|
|
484
|
+
setTimeout(() => flipToFullAccess(session, 3), 0)
|
|
485
|
+
}, { global: true }))
|
|
486
|
+
}
|
|
487
|
+
// 权限守卫(QQ 侧会话):
|
|
488
|
+
// - read / glob / grep:任何人可用,玩家可以查文件;
|
|
489
|
+
// - qqbot_send_file / present:任何人可用,但敏感文件(口令、owners.json 等)拒绝;
|
|
490
|
+
// - pwsh:玩家只放行只读命令;写文件、启进程、联网下载、删改一律拦下;
|
|
491
|
+
// - write / edit / web_*:需要服主授权(12 小时窗口)。
|
|
492
|
+
ctx.effect(() => tools.guard((exec) => {
|
|
493
|
+
const id = exec.agent && exec.agent.id ? String(exec.agent.id) : ''
|
|
494
|
+
if (isLocalSession(id)) return undefined
|
|
495
|
+
if (exec.name === 'mc_server') return undefined
|
|
496
|
+
|
|
497
|
+
const args = exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {}
|
|
498
|
+
|
|
499
|
+
if (OPEN_READ_TOOLS.includes(exec.name)) return undefined
|
|
500
|
+
|
|
501
|
+
if (SEND_TOOLS.includes(exec.name)) {
|
|
502
|
+
const target = String(args.file_path || args.path || '')
|
|
503
|
+
if (!currentPerms().fileSend) {
|
|
504
|
+
return '发文件到群里已经在设置里关掉了。'
|
|
505
|
+
}
|
|
506
|
+
if (SENSITIVE_PATH.test(target)) {
|
|
507
|
+
return '这个文件含口令/密钥或内部配置,不能发到群里;需要的话让服主自己取。'
|
|
508
|
+
}
|
|
509
|
+
return undefined
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if (exec.name === 'pwsh') {
|
|
513
|
+
let raw = ''
|
|
514
|
+
try { raw = JSON.stringify(args) } catch { raw = '' }
|
|
515
|
+
if (raw.includes('mcadmin.ps1')) {
|
|
516
|
+
return 'mc_server:服务器操作请用 mc_server 工具(action + actor),不要用 pwsh 直接调 mcadmin.ps1。'
|
|
517
|
+
}
|
|
518
|
+
const command = String(args.command || '')
|
|
519
|
+
const hasRedirect = /(^|[^>])>(?!>)/.test(command) || command.includes('>>')
|
|
520
|
+
const readOnly = READONLY_CMD.test(command) && !DANGEROUS_CMD.test(command) && !hasRedirect
|
|
521
|
+
if (readOnly) return undefined
|
|
522
|
+
if (hasToolGrant(id)) return undefined
|
|
523
|
+
return '玩家只能查询服务器信息(只读命令);修改/删除文件、启动进程、联网下载这些需要服主授权。'
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
if (exec.name === 'write' || exec.name === 'edit') {
|
|
527
|
+
const target = String(args.file_path || '')
|
|
528
|
+
if (isPlayerWritable(target)) {
|
|
529
|
+
const t = target.replace(/\//g, '\\').toLowerCase()
|
|
530
|
+
if (t.includes('\\kubejs\\') && !currentPerms().kubejsEdit) return '玩家改 KubeJS 配方已经在设置里关掉了,需要服主自己来。'
|
|
531
|
+
if ((t.includes('\\config\\') || t.includes('defaultconfigs') || t.endsWith('server.properties')) && !currentPerms().configEdit) return '玩家改配置已经在设置里关掉了,需要服主自己来。'
|
|
532
|
+
return undefined
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
if (!GUARDED_TOOLS.includes(exec.name)) return undefined
|
|
538
|
+
if (hasToolGrant(id)) return undefined
|
|
539
|
+
return '需要服主授权:请先用 mc_server 执行一次 whoami(actor 取当前消息里的 ID)确认为服主,12 小时内才能使用 '
|
|
540
|
+
+ exec.name + ' 等工具;如果当前说话的是玩家,请直接拒绝并让他找服主。'
|
|
541
|
+
}))
|
|
542
|
+
|
|
543
|
+
// ── 人设注入:按会话类型追加一段 system prompt,设置界面里可改 ──
|
|
544
|
+
const persona = (config && config.persona) || {}
|
|
545
|
+
if (typeof ctx.on === 'function') {
|
|
546
|
+
ctx.effect(() => ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
547
|
+
const assembled = await next()
|
|
548
|
+
if (persona.enabled === false) return assembled
|
|
549
|
+
const scope = String(persona.scope || 'qq')
|
|
550
|
+
if (scope === 'none') return assembled
|
|
551
|
+
const agentId = context && context.agent ? String(context.agent.id ?? '') : ''
|
|
552
|
+
if (!agentId) return assembled
|
|
553
|
+
if (scope === 'qq' && isLocalSession(agentId)) return assembled
|
|
554
|
+
const text = renderPersona(persona)
|
|
555
|
+
if (!text) return assembled
|
|
556
|
+
return {
|
|
557
|
+
...assembled,
|
|
558
|
+
sections: [...(assembled.sections ?? []), { name: 'mc-ops:persona', order: 91, text }],
|
|
559
|
+
}
|
|
560
|
+
}))
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function ensureOpsScripts(bundledDir, targetDir) {
|
|
565
|
+
if (!existsSync(bundledDir)) return
|
|
566
|
+
try { mkdirSync(targetDir, { recursive: true }) } catch { return }
|
|
567
|
+
for (const name of ['mcadmin.ps1', 'watchdog.ps1', 'server-console.ps1']) {
|
|
568
|
+
const src = join(bundledDir, name)
|
|
569
|
+
if (!existsSync(src)) continue
|
|
570
|
+
const dst = join(targetDir, name)
|
|
571
|
+
let need = true
|
|
572
|
+
if (existsSync(dst)) {
|
|
573
|
+
try { need = !readFileSync(dst, 'utf8').includes('[string]$ServerDir') } catch { need = true }
|
|
574
|
+
}
|
|
575
|
+
if (need) { try { copyFileSync(src, dst) } catch { } }
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function runNodeOps(action, arg, timeoutMs, owner) {
|
|
579
|
+
return new Promise((resolve) => {
|
|
580
|
+
let child
|
|
581
|
+
try {
|
|
582
|
+
const argv = [NODE_RUNNER, '--dir', paths.serverDir, '--action', action]
|
|
583
|
+
if (arg !== undefined && arg !== null && String(arg) !== '') argv.push('--arg', String(arg))
|
|
584
|
+
if (owner) argv.push('--owner')
|
|
585
|
+
child = spawn(process.execPath, argv, { windowsHide: true, cwd: paths.serverDir })
|
|
586
|
+
} catch (error) {
|
|
587
|
+
resolve({ ok: false, text: '无法启动 node: ' + (error && error.message ? error.message : String(error)) })
|
|
588
|
+
return
|
|
589
|
+
}
|
|
590
|
+
const chunks = []
|
|
591
|
+
const errChunks = []
|
|
592
|
+
const timer = setTimeout(() => { try { child.kill() } catch { } }, timeoutMs)
|
|
593
|
+
child.stdout.on('data', (d) => chunks.push(Buffer.from(d)))
|
|
594
|
+
child.stderr.on('data', (d) => errChunks.push(Buffer.from(d)))
|
|
595
|
+
child.on('error', (error) => { clearTimeout(timer); resolve({ ok: false, text: String(error && error.message ? error.message : error) }) })
|
|
596
|
+
child.on('close', (code) => {
|
|
597
|
+
clearTimeout(timer)
|
|
598
|
+
const stdout = Buffer.concat(chunks).toString('utf8').trim()
|
|
599
|
+
const stderr = Buffer.concat(errChunks).toString('utf8').trim()
|
|
600
|
+
if (code === 0) resolve({ ok: true, text: stdout || '(无输出)' })
|
|
601
|
+
else resolve({ ok: false, text: stderr || stdout || ('退出码 ' + code) })
|
|
602
|
+
})
|
|
603
|
+
})
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function readJsonBody(req) {
|
|
607
|
+
return new Promise((resolve) => {
|
|
608
|
+
const chunks = []
|
|
609
|
+
req.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
|
|
610
|
+
req.on('end', () => {
|
|
611
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { resolve(null) }
|
|
612
|
+
})
|
|
613
|
+
req.on('error', () => resolve(null))
|
|
614
|
+
})
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 在本插件的配置条目里找一个能用的 descriptor:ns 可能是 include:xxx / xxx / 包名。 */
|
|
618
|
+
function findSettingsEntry(list) {
|
|
619
|
+
const ids = ['mc-server-ops', 'dsh-mc-server-ops']
|
|
620
|
+
for (const d of list) {
|
|
621
|
+
const ns = String(d.ns || '')
|
|
622
|
+
if (ids.some((id) => ns.includes(id))) return d
|
|
623
|
+
}
|
|
624
|
+
for (const d of list) {
|
|
625
|
+
const v = d.value
|
|
626
|
+
if (v && typeof v === 'object' && (v.server || v.persona || v.ops)) return d
|
|
627
|
+
}
|
|
628
|
+
return undefined
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** 设置页的读写接口:GET 读当前配置,POST 合并保存。只服务本机 UI。 */
|
|
632
|
+
async function handleConfigRoute(req, res, services, fallbackConfig) {
|
|
633
|
+
const send = (code, obj) => {
|
|
634
|
+
try {
|
|
635
|
+
res.statusCode = code
|
|
636
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
637
|
+
res.end(JSON.stringify(obj))
|
|
638
|
+
} catch { }
|
|
639
|
+
}
|
|
640
|
+
const dataDir = join(paths.serverDir, 'ops', 'data')
|
|
641
|
+
try {
|
|
642
|
+
const settings = services.settings
|
|
643
|
+
const editor = services.editor
|
|
644
|
+
let list = []
|
|
645
|
+
try { list = settings && typeof settings.describe === 'function' ? settings.describe() : [] } catch (error) { list = [] }
|
|
646
|
+
const desc = findSettingsEntry(list)
|
|
647
|
+
|
|
648
|
+
// 每次读取都记一份诊断,方便判断走的是哪条路径。
|
|
649
|
+
try {
|
|
650
|
+
mkdirSync(dataDir, { recursive: true })
|
|
651
|
+
writeFileSync(join(dataDir, 'settings-debug.json'), JSON.stringify({
|
|
652
|
+
at: new Date().toISOString(),
|
|
653
|
+
nss: list.map((d) => String(d.ns || '')),
|
|
654
|
+
picked: desc ? String(desc.ns) : null,
|
|
655
|
+
hasEditor: !!(editor && typeof editor.edit === 'function'),
|
|
656
|
+
entryIds: editor && typeof editor.entries === 'function' ? editor.entries().map((e) => String(e && e.id ? e.id : '')) : null,
|
|
657
|
+
}, null, 2), 'utf8')
|
|
658
|
+
} catch { }
|
|
659
|
+
|
|
660
|
+
// 只服务本机面板:带自定义头的请求浏览器会先发预检,跨站页面伪造不了
|
|
661
|
+
const isPanel = String(req.headers['x-mc-ops-client'] || '') === '1'
|
|
662
|
+
if (!isPanel) return send(403, { error: '只接受来自设置面板的请求' })
|
|
663
|
+
|
|
664
|
+
if (req.method === 'GET') {
|
|
665
|
+
const opsPath = join(paths.serverDir, 'ops')
|
|
666
|
+
const owners = readOwnersList(opsPath)
|
|
667
|
+
if (desc) return send(200, { ns: String(desc.ns), value: desc.value, revision: desc.revision, via: 'settings', owners })
|
|
668
|
+
return send(200, { ns: '', value: fallbackConfig.get(), revision: 0, via: 'memory', owners })
|
|
669
|
+
}
|
|
670
|
+
if (req.method !== 'POST') return send(405, { error: '只支持 GET / POST' })
|
|
671
|
+
|
|
672
|
+
const body = await readJsonBody(req)
|
|
673
|
+
if (!body) return send(400, { error: '请求体不是合法 JSON' })
|
|
674
|
+
delete body.regenerateOwnerCode
|
|
675
|
+
const addOwner = typeof body.addOwner === 'string' ? body.addOwner.trim() : ''
|
|
676
|
+
delete body.addOwner
|
|
677
|
+
const removeOwner = typeof body.removeOwner === 'string' ? body.removeOwner.trim() : ''
|
|
678
|
+
delete body.removeOwner
|
|
679
|
+
if (addOwner || removeOwner) {
|
|
680
|
+
const target = addOwner || removeOwner
|
|
681
|
+
if (!/^[A-Za-z0-9:_-]{8,64}$/.test(target)) return send(400, { error: 'QQ 号格式看起来不对(应为群消息里 [昵称 (ID)] 括号中那串)' })
|
|
682
|
+
const cli = ['-Action', addOwner ? 'owner-add' : 'owner-del', '-Arg', target, '-Actor', 'LOCAL-CONSOLE', '-Channel', '']
|
|
683
|
+
const res = await runMcAdmin(cli, 30000)
|
|
684
|
+
if (!res.ok) return send(400, { error: res.text })
|
|
685
|
+
return send(200, { ok: true, owners: readOwnersList(join(paths.serverDir, 'ops')), result: res.text })
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const dirArg = body && body.server && typeof body.server.dir === 'string' ? body.server.dir.trim() : ''
|
|
689
|
+
if (dirArg && (/^[a-zA-Z]:[\\/]?$/.test(dirArg) || /^[\\/]+$/.test(dirArg))) {
|
|
690
|
+
return send(400, { error: '服务器目录不能填盘符根目录,请填具体目录(例如 D:\\server)。' })
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// 面板上「受保护路径」是一个逗号分隔的文本框,存之前转成数组
|
|
694
|
+
if (body && body.vote && typeof body.vote.protectedPaths === 'string') {
|
|
695
|
+
body.vote.protectedPaths = body.vote.protectedPaths.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
|
|
696
|
+
if (!body.vote.protectedPaths.length) body.vote.protectedPaths = ['world', 'ops/data', 'whitelist']
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (desc) {
|
|
700
|
+
await settings.update(desc.ns, body, desc.revision)
|
|
701
|
+
fallbackConfig.set(body)
|
|
702
|
+
return send(200, { ok: true, via: 'settings' })
|
|
703
|
+
}
|
|
704
|
+
if (editor && typeof editor.entries === 'function' && typeof editor.edit === 'function') {
|
|
705
|
+
const entries = editor.entries()
|
|
706
|
+
const entry = entries.find((e) => {
|
|
707
|
+
const id = String(e && e.id ? e.id : '')
|
|
708
|
+
const name = String(e && e.moduleName ? e.moduleName : '')
|
|
709
|
+
return id.includes('mc-server-ops') || name.includes('mc-server-ops')
|
|
710
|
+
})
|
|
711
|
+
if (entry) {
|
|
712
|
+
await editor.edit(entry, (current) => Object.assign({}, current || {}, body))
|
|
713
|
+
fallbackConfig.set(body)
|
|
714
|
+
return send(200, { ok: true, via: 'configEditor' })
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
try {
|
|
718
|
+
mkdirSync(dataDir, { recursive: true })
|
|
719
|
+
writeFileSync(join(dataDir, 'settings-debug.json'), JSON.stringify({
|
|
720
|
+
at: new Date().toISOString(),
|
|
721
|
+
nss: list.map((d) => String(d.ns || '')),
|
|
722
|
+
entryIds: editor && typeof editor.entries === 'function' ? editor.entries().map((e) => String(e && e.id ? e.id : '')) : 'no-editor',
|
|
723
|
+
}, null, 2), 'utf8')
|
|
724
|
+
} catch { }
|
|
725
|
+
return send(500, { error: '没有找到本插件的配置条目(已写入 ops\\data\\settings-debug.json)' })
|
|
726
|
+
} catch (error) {
|
|
727
|
+
send(500, { error: String(error && error.message ? error.message : error) })
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** 读服主名单 */
|
|
732
|
+
function readOwnersList(opsPath) {
|
|
733
|
+
try {
|
|
734
|
+
const file = join(opsPath, 'data', 'owners.json')
|
|
735
|
+
if (!existsSync(file)) return []
|
|
736
|
+
const doc = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
737
|
+
return Array.isArray(doc.owners) ? doc.owners.map((x) => String(x)) : []
|
|
738
|
+
} catch { return [] }
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
/** 把投票门槛写到 ops\data\vote-config.json,脚本每次调用时读它。 */
|
|
744
|
+
function writeVoteConfig(opsPath, voteCfg, fallback) {
|
|
745
|
+
try {
|
|
746
|
+
const src = voteCfg || fallback || {}
|
|
747
|
+
const approveNeed = Math.max(1, Number(src.approveNeed) || 2)
|
|
748
|
+
const rejectNeed = Math.max(1, Number(src.rejectNeed) || 1)
|
|
749
|
+
mkdirSync(join(opsPath, 'data'), { recursive: true })
|
|
750
|
+
const timeoutMinutes = Math.max(1, Number(src.timeoutMinutes) || 15)
|
|
751
|
+
const vetoEnabled = src.vetoEnabled !== false
|
|
752
|
+
const protectedPaths = Array.isArray(src.protectedPaths) && src.protectedPaths.length
|
|
753
|
+
? src.protectedPaths.map((x) => String(x)).filter(Boolean)
|
|
754
|
+
: ['world', 'ops/data', 'whitelist']
|
|
755
|
+
writeFileSync(join(opsPath, 'data', 'vote-config.json'), JSON.stringify({ approveNeed, rejectNeed, timeoutMinutes, vetoEnabled, protectedPaths }), 'utf8')
|
|
756
|
+
} catch { }
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** 玩家侧功能开关:设置里关掉的项直接拒绝,不用等脚本再判一遍。 */
|
|
760
|
+
function checkActionAllowed(action, perms) {
|
|
761
|
+
if (action.startsWith('vote-') && !perms.voteEscalation) return '投票放权已经在设置里关掉了,这个操作只有服主能直接做。'
|
|
762
|
+
if (action === 'say' && !perms.say) return '游戏内广播已经在设置里关掉了。'
|
|
763
|
+
if (action === 'start' && !perms.playerStart) return '开服现在只有服主能做。'
|
|
764
|
+
if (action === 'restart' && !perms.playerRestart) return '重启现在只有服主能做。'
|
|
765
|
+
if (action === 'stop' && !perms.playerStop) return '停服只有服主能做。'
|
|
766
|
+
if (action === 'gamemode' && !perms.gamemodeSwitch) return '切游戏模式现在只有服主能做。'
|
|
767
|
+
if ((action === 'kubejs-backup' || action === 'kubejs-reload') && !perms.kubejsEdit) return 'KubeJS 相关操作已经在设置里关掉了。'
|
|
768
|
+
return ''
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function renderPersona(persona) {
|
|
772
|
+
const p = persona || {}
|
|
773
|
+
const text = String(p.text || '').trim() || DEFAULT_PERSONA
|
|
774
|
+
const who = String(p.name || '').trim()
|
|
775
|
+
const lines = []
|
|
776
|
+
if (who) lines.push('## 人设\n你在 QQ 里的名字是「' + who + '」。')
|
|
777
|
+
lines.push(text)
|
|
778
|
+
lines.push('说话像真人打字:短句、口语,别端着也别卖萌;问到服务器的事就照实答,不确定就说不确定。')
|
|
779
|
+
return lines.join('\n')
|
|
780
|
+
}
|