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.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 写操作适配器:把 start / stop / restart / sendCommand / getStatus
3
+ * 从「写死调 PowerShell」里抽出来,换成可替换的实现。
4
+ *
5
+ * local —— 本机直接跑 ops/mcadmin.ps1(Windows)或 ops/rcon.mjs(其它平台),行为不变
6
+ * panel —— Pterodactyl 面板 HTTP API,适合把服务器托管在别人机器上的情况
7
+ *
8
+ * 只读路径(status / players / logs / crashinfo)不经过这里,仍然走原来的逻辑。
9
+ */
10
+
11
+ import { LocalShellAdapter } from './local.mjs'
12
+ import { PterodactylAdapter } from './pterodactyl.mjs'
13
+
14
+ export { LocalShellAdapter } from './local.mjs'
15
+ export { PterodactylAdapter } from './pterodactyl.mjs'
16
+
17
+ /** 配置文件里 adapter 字段的合法取值。 */
18
+ export const ADAPTER_KINDS = ['local', 'panel']
19
+
20
+ /**
21
+ * @param {string} kind 'local' | 'panel'
22
+ * @param {object} options 适配器需要的依赖(本地:runMcAdmin/runNodeOps;面板:url/serverId/clientApiKey)
23
+ * @returns {{kind: string, start: Function, stop: Function, restart: Function, sendCommand: Function, getStatus: Function}}
24
+ */
25
+ export function createAdapter(kind, options = {}) {
26
+ const which = String(kind || 'local').toLowerCase()
27
+ if (which === 'panel') {
28
+ const panel = options.panel || {}
29
+ return new PterodactylAdapter({
30
+ url: panel.url,
31
+ serverId: panel.serverId,
32
+ clientApiKey: panel.clientApiKey,
33
+ fetchImpl: options.fetchImpl,
34
+ })
35
+ }
36
+ return new LocalShellAdapter(options)
37
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * 本机适配器:行为和改造前一模一样,只是收进了统一接口。
3
+ *
4
+ * Windows 上走 powershell + ops/mcadmin.ps1(信息最全、能改文件、能看进程);
5
+ * 其它平台上 open/close 类动作走 ops/rcon.mjs(纯 Node,无 PowerShell 依赖)。
6
+ */
7
+
8
+ const DEFAULT_TIMEOUT = 170000
9
+
10
+ export class LocalShellAdapter {
11
+ /**
12
+ * @param {object} deps
13
+ * @param {(argv: string[], timeoutMs: number) => Promise<{ok:boolean,text:string}>} deps.runMcAdmin
14
+ * @param {(action: string, arg: string, timeoutMs: number, owner: boolean) => Promise<{ok:boolean,text:string}>} deps.runNodeOps
15
+ * @param {boolean} deps.isWindows
16
+ * @param {Set<string>} deps.nodeActions 非 Windows 上可以走 Node 的动作
17
+ */
18
+ constructor(deps = {}) {
19
+ this.kind = 'local'
20
+ this.runMcAdmin = deps.runMcAdmin
21
+ this.runNodeOps = deps.runNodeOps
22
+ this.isWindows = deps.isWindows !== false
23
+ this.nodeActions = deps.nodeActions || new Set()
24
+ }
25
+
26
+ async start(opts) { return this._act('start', '', opts) }
27
+ async stop(opts) { return this._act('stop', '', opts) }
28
+ async restart(opts) { return this._act('restart', '', opts) }
29
+ async sendCommand(cmd, opts) { return this._act('cmd', String(cmd || ''), opts) }
30
+ async getStatus(opts) { return this._act('status', '', opts) }
31
+
32
+ async _act(action, arg, opts = {}) {
33
+ if (!this.isWindows && this.nodeActions.has(action) && typeof this.runNodeOps === 'function') {
34
+ return this.runNodeOps(action, arg, 60000, !!opts.owner)
35
+ }
36
+ if (typeof this.runMcAdmin !== 'function') {
37
+ return { ok: false, text: '本机适配器没有拿到 mcadmin 的执行入口。' }
38
+ }
39
+ const cli = ['-Action', action, '-Actor', String(opts.actor || ''), '-Channel', String(opts.channel || 'console')]
40
+ if (arg !== '') cli.push('-Arg', arg)
41
+ return this.runMcAdmin(cli, opts.timeoutMs || DEFAULT_TIMEOUT)
42
+ }
43
+ }
44
+
45
+ export default LocalShellAdapter
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Pterodactyl 面板适配器(翼龙面板,客户端 API)。
3
+ *
4
+ * 只用到四个客户端接口:
5
+ * POST /api/client/servers/{id}/power body {"signal":"start"|"stop"|"restart"|"kill"}
6
+ * POST /api/client/servers/{id}/command body {"command":"say hi"}
7
+ * GET /api/client/servers/{id}/resources 取 current_state / CPU / 内存 / 运行时长
8
+ *
9
+ * 鉴权用客户端 API Key(ptlc_ 开头那个),不是账号密码,也不是 application key。
10
+ * 配置在插件设置里:面板地址、服务器 ID(短 UUID)、客户端 Key。
11
+ */
12
+
13
+ const DEFAULT_TIMEOUT = 15000
14
+
15
+ export class PterodactylAdapter {
16
+ constructor(options = {}) {
17
+ this.kind = 'panel'
18
+ this.url = String(options.url || '').replace(/\/+$/, '')
19
+ this.serverId = String(options.serverId || '')
20
+ this.clientApiKey = String(options.clientApiKey || '')
21
+ this.fetchImpl = options.fetchImpl || globalThis.fetch
22
+ this.timeoutMs = Number(options.timeoutMs) || DEFAULT_TIMEOUT
23
+ }
24
+
25
+ /** 配置齐不齐。缺哪项就说哪项,别让用户猜。 */
26
+ configProblem() {
27
+ const missing = []
28
+ if (!this.url) missing.push('面板地址(如 https://panel.example.com)')
29
+ if (!this.serverId) missing.push('服务器 ID')
30
+ if (!this.clientApiKey) missing.push('客户端 API Key')
31
+ if (missing.length) return '面板适配器还没配好,缺少:' + missing.join('、')
32
+ if (!/^https?:\/\//i.test(this.url)) return '面板地址要以 http:// 或 https:// 开头。'
33
+ if (typeof this.fetchImpl !== 'function') return '当前运行环境没有 fetch,面板适配器用不了。'
34
+ return ''
35
+ }
36
+
37
+ _endpoint(tail) {
38
+ return `${this.url}/api/client/servers/${encodeURIComponent(this.serverId)}/${tail}`
39
+ }
40
+
41
+ async _request(method, tail, body) {
42
+ const problem = this.configProblem()
43
+ if (problem) return { ok: false, text: problem }
44
+ const init = {
45
+ method,
46
+ headers: {
47
+ Authorization: 'Bearer ' + this.clientApiKey,
48
+ Accept: 'application/json',
49
+ 'Content-Type': 'application/json',
50
+ },
51
+ signal: typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(this.timeoutMs) : undefined,
52
+ }
53
+ if (body !== undefined) init.body = JSON.stringify(body)
54
+ let res
55
+ try {
56
+ res = await this.fetchImpl(this._endpoint(tail), init)
57
+ } catch (error) {
58
+ const message = error && error.message ? error.message : String(error)
59
+ return { ok: false, text: '连不上面板:' + message }
60
+ }
61
+ const text = await res.text().catch(() => '')
62
+ if (!res.ok) {
63
+ let detail = text
64
+ try { detail = JSON.parse(text).errors?.[0]?.detail || text } catch { /* 原样 */ }
65
+ return { ok: false, text: `面板返回 ${res.status}:${String(detail || '(无内容)').slice(0, 300)}` }
66
+ }
67
+ return { ok: true, text }
68
+ }
69
+
70
+ /** @param {'start'|'stop'|'restart'|'kill'} signal */
71
+ async _power(signal, label) {
72
+ const r = await this._request('POST', 'power', { signal })
73
+ if (!r.ok) return r
74
+ return { ok: true, text: `${label}指令已发给面板(signal=${signal})` }
75
+ }
76
+
77
+ async start() { return this._power('start', '启动') }
78
+ async stop() { return this._power('stop', '停止') }
79
+ async restart() { return this._power('restart', '重启') }
80
+ async kill() { return this._power('kill', '强杀') }
81
+
82
+ async sendCommand(cmd) {
83
+ const command = String(cmd || '').trim().replace(/^\/+/, '')
84
+ if (!command) return { ok: false, text: '空命令,没东西要发。' }
85
+ const r = await this._request('POST', 'command', { command })
86
+ if (!r.ok) return r
87
+ return { ok: true, text: '已通过面板执行:' + command }
88
+ }
89
+
90
+ async getStatus() {
91
+ const r = await this._request('GET', 'resources')
92
+ if (!r.ok) return r
93
+ let attrs = {}
94
+ try { attrs = JSON.parse(r.text || '{}').attributes || {} } catch { /* 忽略 */ }
95
+ const state = attrs.current_state || 'unknown'
96
+ const stateText = { running: '运行中', starting: '启动中', stopping: '停止中', offline: '未运行' }[state] || state
97
+ const res = attrs.resources || {}
98
+ const mem = res.memory_bytes ? (res.memory_bytes / 1024 / 1024).toFixed(0) + ' MB' : '-'
99
+ const cpu = typeof res.cpu_absolute === 'number' ? res.cpu_absolute.toFixed(1) + '%' : '-'
100
+ const up = typeof res.uptime === 'number' ? (res.uptime / 60000).toFixed(0) + ' 分钟' : '-'
101
+ return { ok: true, text: `面板:${stateText} CPU: ${cpu} 内存: ${mem} 运行时长: ${up}` }
102
+ }
103
+ }
104
+
105
+ export default PterodactylAdapter
@@ -0,0 +1,102 @@
1
+ /**
2
+ * 静态命令拦截器 —— RCON 命令出网前的最后一道闸。
3
+ *
4
+ * 只拦「大规模杀伤 / 不可逆」这一类:一条命令就能把整个服务器搞崩、
5
+ * 或者把所有人的号踢下线,事后只能回档。其余命令交给上层判断
6
+ * (权限校验 + 投票放行),这里不做业务判断。
7
+ *
8
+ * 用法:
9
+ * import { guardCommand } from './command-guard.mjs'
10
+ * const v = guardCommand('kill @a', { id: 'xxx', owner: false })
11
+ * if (!v.ok) throw new Error(v.reason)
12
+ *
13
+ * 分级(按服主定的策略):
14
+ * - kill @a / kill @e / kill @r / kill * —— 谁都不行
15
+ * - kick @a / kick @e —— 谁都不行
16
+ * - whitelist off / whitelist clear —— 谁都不行
17
+ * - execute ... run kill @a|@e —— 谁都不行(换个写法绕不过去)
18
+ * - stop —— 非服主不行
19
+ */
20
+
21
+ /** 起手就是聊天/标题类指令时不拦(内容里出现 kill @a 只是打字,不会执行)。 */
22
+ const CHAT_PREFIX = /^(say|tell|msg|w|tellraw|me|title|subtitle|actionbar|broadcast)\b/i
23
+
24
+ /** 谁都不许发的命令。 */
25
+ const BLOCKED_ALL = [
26
+ {
27
+ re: /^kill\s+(@[ae]\b|@r\b|\*)/i,
28
+ reason: 'kill @a / @e / @r 会一次干掉全部玩家或实体,服务器基本等于当场崩掉。真要清场用 kick 单个玩家,或者先备份再动手。',
29
+ },
30
+ {
31
+ re: /^kick\s+@[ae]\b/i,
32
+ reason: 'kick @a / @e 一次踢光所有人,正在跑的任务和区块加载全会断。要踢人请写具体名字。',
33
+ },
34
+ {
35
+ re: /^whitelist\s+(off|clear)\b/i,
36
+ reason: '关白名单/清空白名单会让任何知道地址的人都能进来。要临时放人可以 whitelist add 具体名字。',
37
+ },
38
+ {
39
+ re: /^execute\b[\s\S]*\brun\s+kill\s+(@[ae]\b|@r\b|\*)/i,
40
+ reason: 'execute ... run kill @a 绕了一道照样是清场,拦。',
41
+ },
42
+ ]
43
+
44
+ /** 只有服主能发的命令。 */
45
+ const BLOCKED_PLAYER = [
46
+ {
47
+ re: /^stop\b/i,
48
+ reason: '停服只有服主能做(会断开所有在线玩家,world 也可能来不及存盘)。',
49
+ },
50
+ ]
51
+
52
+ /** 归一化:去前导斜杠、压空白,让 `/kill @a` 和 `kill @a` 一样被识别。 */
53
+ function normalize(cmd) {
54
+ let s = String(cmd === undefined || cmd === null ? '' : cmd).trim()
55
+ if (s.startsWith('/')) s = s.slice(1).trim()
56
+ return s.replace(/\s+/g, ' ')
57
+ }
58
+
59
+ /**
60
+ * 判断 actor 是不是服主。
61
+ * 既接受 '34EB...' 这种裸 ID,也接受 { id, owner } 这种已判定过的对象。
62
+ */
63
+ export function isOwnerActor(actor) {
64
+ if (actor && typeof actor === 'object') return actor.owner === true
65
+ return false
66
+ }
67
+
68
+ /**
69
+ * 拦截判定。
70
+ * @param {string} cmd 要发给 RCON 的原始命令(不带前导斜杠也可以)
71
+ * @param {string|{id?:string,owner?:boolean}} actor 发起人;对象形式可带 owner 标记
72
+ * @returns {{ok: boolean, reason?: string, rule?: string}}
73
+ */
74
+ export function guardCommand(cmd, actor) {
75
+ const text = normalize(cmd)
76
+ if (!text) return { ok: false, reason: '空命令,没东西要发。', rule: 'empty' }
77
+
78
+ // 聊天类指令只是把字打在公屏上,不执行,放行
79
+ if (CHAT_PREFIX.test(text)) return { ok: true }
80
+
81
+ for (const rule of BLOCKED_ALL) {
82
+ if (rule.re.test(text)) return { ok: false, reason: rule.reason, rule: rule.re.source }
83
+ }
84
+
85
+ if (!isOwnerActor(actor)) {
86
+ for (const rule of BLOCKED_PLAYER) {
87
+ if (rule.re.test(text)) return { ok: false, reason: rule.reason, rule: rule.re.source }
88
+ }
89
+ }
90
+
91
+ return { ok: true }
92
+ }
93
+
94
+ /** 方便日志/报错用的一行摘要。 */
95
+ export function describeActor(actor) {
96
+ if (actor && typeof actor === 'object') {
97
+ return (actor.id ? String(actor.id) : 'unknown') + (actor.owner ? '(owner)' : '(player)')
98
+ }
99
+ return String(actor || 'unknown')
100
+ }
101
+
102
+ export default guardCommand