dsh-mc-server-ops 0.0.0-stage → 0.4.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,408 @@
1
+ /**
2
+ * 群服互通 P0:游戏聊天 → QQ 群(**不经过 AI,不产生 token 消耗**)
3
+ *
4
+ * 链路:
5
+ * logs/latest.log 增量读取 → 解析出聊天/进出事件 → 聚合 → 直连 QQ 开放平台 HTTP API
6
+ *
7
+ * 为什么不走 qqbot 插件:它的入站链路是 中间件 → handleInbound → agent.followup,
8
+ * 出站也只能由模型调用工具触发。这条链路完全绕开它,自己拿 appId/appSecret 发消息。
9
+ *
10
+ * 不依赖任何外部包,只用 Node 内置模块。
11
+ */
12
+ import { closeSync, existsSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+
15
+ // ─────────────────────────── QQ 开放平台 ───────────────────────────
16
+
17
+ const TOKEN_URL = 'https://bots.qq.com/app/getAppAccessToken'
18
+ const DEFAULT_API = 'https://api.bot.qq.com'
19
+ const TOKEN_SAFETY_MS = 60 * 1000
20
+
21
+ export class QqApi {
22
+ constructor(options = {}) {
23
+ this.appId = String(options.appId || '')
24
+ this.appSecret = String(options.appSecret || '')
25
+ this.apiBase = String(options.apiBase || DEFAULT_API).replace(/\/+$/, '')
26
+ this.tokenUrl = String(options.tokenUrl || TOKEN_URL)
27
+ this.fetchImpl = options.fetchImpl || globalThis.fetch
28
+ this.tokenValue = ''
29
+ this.tokenExpiresAt = 0
30
+ this.tokenPromise = null
31
+ }
32
+
33
+ configProblem() {
34
+ if (!this.appId) return '缺少 AppID'
35
+ if (!this.appSecret) return '缺少 AppSecret'
36
+ if (typeof this.fetchImpl !== 'function') return '当前 Node 没有 fetch(需要 18+)'
37
+ return ''
38
+ }
39
+
40
+ /** 拿 access_token,带缓存;并发时只发一次请求。 */
41
+ async token() {
42
+ const now = Date.now()
43
+ if (this.tokenValue && now < this.tokenExpiresAt) return this.tokenValue
44
+ if (this.tokenPromise) return this.tokenPromise
45
+ const problem = this.configProblem()
46
+ if (problem) throw new Error(problem)
47
+ this.tokenPromise = (async () => {
48
+ const res = await this.fetchImpl(this.tokenUrl, {
49
+ method: 'POST',
50
+ headers: { 'Content-Type': 'application/json' },
51
+ body: JSON.stringify({ appId: this.appId, clientSecret: this.appSecret }),
52
+ signal: AbortSignal.timeout ? AbortSignal.timeout(15000) : undefined,
53
+ })
54
+ const text = await res.text()
55
+ let doc = {}
56
+ try { doc = JSON.parse(text) } catch { /* 原样 */ }
57
+ if (!res.ok || !doc.access_token) {
58
+ throw new Error(`拿 token 失败(HTTP ${res.status}):${String(doc.message || doc.error || text).slice(0, 200)}`)
59
+ }
60
+ const ttl = Math.max(60, Number(doc.expires_in) || 7200)
61
+ this.tokenValue = String(doc.access_token)
62
+ this.tokenExpiresAt = Date.now() + ttl * 1000 - TOKEN_SAFETY_MS
63
+ return this.tokenValue
64
+ })()
65
+ try {
66
+ return await this.tokenPromise
67
+ } finally {
68
+ this.tokenPromise = null
69
+ }
70
+ }
71
+
72
+ async request(method, path, body) {
73
+ const token = await this.token()
74
+ const init = {
75
+ method,
76
+ headers: {
77
+ Authorization: 'QQBot ' + token,
78
+ 'Content-Type': 'application/json',
79
+ 'X-Union-Appid': this.appId,
80
+ },
81
+ signal: AbortSignal.timeout ? AbortSignal.timeout(15000) : undefined,
82
+ }
83
+ if (body !== undefined) init.body = JSON.stringify(body)
84
+ const res = await this.fetchImpl(this.apiBase + path, init)
85
+ const text = await res.text()
86
+ let doc = {}
87
+ try { doc = text ? JSON.parse(text) : {} } catch { /* 非 JSON */ }
88
+ if (!res.ok) {
89
+ const detail = doc.message || doc.msg || text
90
+ const err = new Error(`QQ API ${method} ${path} → HTTP ${res.status}:${String(detail).slice(0, 200)}`)
91
+ err.status = res.status
92
+ err.body = doc
93
+ throw err
94
+ }
95
+ return doc
96
+ }
97
+
98
+ /** 机器人加入的群列表(需要「群管理」权限)。 */
99
+ async listGroups() {
100
+ const doc = await this.request('GET', '/v2/users/@me/groups')
101
+ const list = Array.isArray(doc) ? doc : (Array.isArray(doc.data) ? doc.data : [])
102
+ return list.map((g) => ({
103
+ openid: String(g.group_openid || g.openid || ''),
104
+ name: String(g.group_name || g.name || ''),
105
+ })).filter((g) => g.openid)
106
+ }
107
+
108
+ /**
109
+ * 往群里发一条纯文本。
110
+ * @param {string} openid 群 openid
111
+ * @param {string} content 文本(已截断、已清洗)
112
+ * @param {object} opts msgId=被动回复;msgSeq 用于区分同一条 msg_id 的多次回复
113
+ */
114
+ async sendGroupMessage(openid, content, opts = {}) {
115
+ const body = { msg_type: 0, content, msg_seq: Number(opts.msgSeq) || 1 }
116
+ if (opts.msgId) body.msg_id = String(opts.msgId)
117
+ return this.request('POST', `/v2/groups/${encodeURIComponent(openid)}/messages`, body)
118
+ }
119
+ }
120
+
121
+ // ─────────────────────────── 日志增量读取 ───────────────────────────
122
+
123
+ const COLOR_CODE = /§[0-9a-fk-orx]/gi
124
+ const STRIP_PREFIX = /^\[(Not Secure|Not Secure: )\]\s*/i
125
+
126
+ export function cleanText(text) {
127
+ return String(text || '')
128
+ .replace(COLOR_CODE, '')
129
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '')
130
+ .replace(/\r?\n/g, ' ')
131
+ .trim()
132
+ }
133
+
134
+ /** 解析一行 MC 日志;不是我们关心的事件就返回 null。 */
135
+ export function parseLogLine(line) {
136
+ if (!line || line[0] !== '[' && !/^\s*\[/.test(line)) return null
137
+ const m = /\[(?:Server thread|Server\/INFO)[^\]]*\/INFO\]\s*\[[^\]]*\]:\s*(.*)$/.exec(line)
138
+ if (!m) return null
139
+ let rest = m[1].trim()
140
+ if (!rest) return null
141
+ rest = rest.replace(STRIP_PREFIX, '')
142
+
143
+ let hit = /^<([A-Za-z0-9_]{1,16})>\s*(.*)$/.exec(rest)
144
+ if (hit) return { type: 'chat', player: hit[1], text: cleanText(hit[2]) }
145
+
146
+ hit = /^([A-Za-z0-9_]{1,16}) joined the game\.?$/.exec(rest)
147
+ if (hit) return { type: 'join', player: hit[1] }
148
+
149
+ hit = /^([A-Za-z0-9_]{1,16}) left the game\.?$/.exec(rest)
150
+ if (hit) return { type: 'leave', player: hit[1] }
151
+
152
+ hit = /^([A-Za-z0-9_]{1,16}) (was |drowned|blew up|hit the ground|fell|burned|died|starved|suffocated|withered|killed|slain|walked into|tried to swim|discovered)/.exec(rest)
153
+ if (hit) return { type: 'death', player: hit[1], text: cleanText(rest) }
154
+
155
+ return null
156
+ }
157
+
158
+ /**
159
+ * 解码日志字节。
160
+ * 服务器的 latest.log 用的是系统编码:中文 Windows 下是 GBK,不是 UTF-8。
161
+ * 先按 UTF-8 解,出现替换字符(U+FFFD)就退回 GBK。
162
+ */
163
+ const gbkDecoder = (() => {
164
+ try { return new TextDecoder('gbk') } catch { return null }
165
+ })()
166
+
167
+ export function decodeLogBytes(bytes) {
168
+ const utf8 = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes)
169
+ if (!utf8.includes('\uFFFD') || !gbkDecoder) return utf8
170
+ try { return gbkDecoder.decode(bytes) } catch { return utf8 }
171
+ }
172
+
173
+ /**
174
+ * 增量跟踪 logs/latest.log。
175
+ * 用轮询而不是 fs.watch:Windows 上 watch 在日志轮转(每天 0 点重命名)时会丢事件。
176
+ */
177
+ export function createLogTail(serverDir, onEvent, opts = {}) {
178
+ const file = join(serverDir, 'logs', 'latest.log')
179
+ const intervalMs = Math.max(200, Number(opts.intervalMs) || 500)
180
+ let offset = 0
181
+ let pending = Buffer.alloc(0)
182
+ let timer = null
183
+ let lastSize = -1
184
+
185
+ function readNew() {
186
+ let st
187
+ try { st = statSync(file) } catch { return } // 还没生成
188
+ if (st.size < offset) { offset = 0; pending = Buffer.alloc(0) } // 轮转了,从头来
189
+ if (st.size === offset) return
190
+ let fd
191
+ try {
192
+ fd = openSync(file, 'r')
193
+ const length = st.size - offset
194
+ const buf = Buffer.alloc(length)
195
+ readSync(fd, buf, 0, length, offset)
196
+ offset = st.size
197
+ // 按字节切行:中文是多字节,先转字符串再切会在块边界切坏字符
198
+ pending = pending.length ? Buffer.concat([pending, buf]) : buf
199
+ let nl = pending.lastIndexOf(0x0a)
200
+ if (nl < 0) return
201
+ const chunk = pending.subarray(0, nl)
202
+ pending = pending.subarray(nl + 1)
203
+ const text = decodeLogBytes(chunk)
204
+ for (const line of text.split('\n')) {
205
+ const evt = parseLogLine(line.trim())
206
+ if (evt) {
207
+ try { onEvent(evt) } catch { /* 单个事件失败不影响后续 */ }
208
+ }
209
+ }
210
+ } catch { /* 读失败下次再来 */ }
211
+ finally { if (fd !== undefined) { try { closeSync(fd) } catch { } } }
212
+ }
213
+
214
+ return {
215
+ /** 从文件末尾开始(只看新内容) */
216
+ startAtEnd() {
217
+ try { offset = statSync(file).size; lastSize = offset } catch { offset = 0 }
218
+ },
219
+ start({ fromStart = false } = {}) {
220
+ if (fromStart) { offset = 0 } else if (offset === 0) { try { offset = statSync(file).size } catch { } }
221
+ if (timer) return
222
+ timer = setInterval(readNew, intervalMs)
223
+ if (timer.unref) timer.unref()
224
+ },
225
+ stop() { if (timer) { clearInterval(timer); timer = null } },
226
+ }
227
+ }
228
+
229
+ // ─────────────────────────── 桥本身 ───────────────────────────
230
+
231
+ const MAX_QQ_CHARS = 900
232
+ const URL_RE = /https?:\/\/\S+/gi
233
+
234
+ /** 把一批游戏消息拼成一条 QQ 消息。 */
235
+ export function formatBatch(events, opts = {}) {
236
+ const gamePrefix = String(opts.gamePrefix || '')
237
+ const lines = []
238
+ for (const e of events) {
239
+ if (e.type === 'chat') lines.push((gamePrefix ? gamePrefix + ' ' : '') + '<' + e.player + '> ' + e.text)
240
+ else if (e.type === 'join') lines.push('· ' + e.player + ' 加入了游戏')
241
+ else if (e.type === 'leave') lines.push('· ' + e.player + ' 离开了游戏')
242
+ else if (e.type === 'death') lines.push('· ' + e.text)
243
+ }
244
+ if (!lines.length) return ''
245
+ let text = lines.join('\n')
246
+ if (opts.stripUrls !== false) text = text.replace(URL_RE, '[链接]')
247
+ if (text.length > MAX_QQ_CHARS) text = text.slice(0, MAX_QQ_CHARS - 1) + '…'
248
+ return text
249
+ }
250
+
251
+ /**
252
+ * @param {object} deps
253
+ * @param {string} deps.serverDir
254
+ * @param {() => object} deps.readConfig 每次用最新配置
255
+ * @param {(msg: string) => void} [deps.log]
256
+ */
257
+ export function createBridge(deps) {
258
+ const serverDir = deps.serverDir
259
+ const log = deps.log || (() => { })
260
+ const api = new QqApi({
261
+ appId: deps.appId,
262
+ appSecret: deps.appSecret,
263
+ apiBase: deps.apiBase,
264
+ tokenUrl: deps.tokenUrl,
265
+ fetchImpl: deps.fetchImpl,
266
+ })
267
+ const online = new Set()
268
+ let queue = []
269
+ let flushTimer = null
270
+ let tail = null
271
+ let running = false
272
+ let sentToday = 0
273
+ let dayKey = new Date().toISOString().slice(0, 10)
274
+ let lastError = ''
275
+ let lastSentAt = ''
276
+ const stats = { chats: 0, joins: 0, leaves: 0, deaths: 0, sent: 0, dropped: 0, suppressed: 0 }
277
+
278
+ function cfg() {
279
+ const c = deps.readConfig() || {}
280
+ return {
281
+ enabled: c.enabled === true,
282
+ mode: String(c.mode || 'auto'),
283
+ groups: Array.isArray(c.groups) ? c.groups.map(String).filter(Boolean) : [],
284
+ events: Object.assign({ join: true, leave: true, death: false }, c.events || {}),
285
+ coalesceMs: Math.max(500, Number(c.coalesceMs) || 3000),
286
+ maxPerDay: Math.max(1, Number(c.maxPerDay) || 900),
287
+ gamePrefix: String(c.gamePrefix || ''),
288
+ stripUrls: c.stripUrls !== false,
289
+ }
290
+ }
291
+
292
+ /** 有玩家时开启:只在 online 非空时转发 */
293
+ function shouldForward(c) {
294
+ if (!c.enabled) return false
295
+ if (c.mode === 'off') return false
296
+ if (c.mode === 'on') return true
297
+ return online.size > 0
298
+ }
299
+
300
+ function rollDay() {
301
+ const key = new Date().toISOString().slice(0, 10)
302
+ if (key !== dayKey) { dayKey = key; sentToday = 0 }
303
+ }
304
+
305
+ async function flush() {
306
+ flushTimer = null
307
+ const c = cfg()
308
+ if (!queue.length) return
309
+ const batch = queue
310
+ queue = []
311
+ if (!shouldForward(c)) { stats.suppressed += batch.length; return }
312
+ if (!c.groups.length) { stats.dropped += batch.length; lastError = '还没配置要转发到哪个群'; return }
313
+ const text = formatBatch(batch, { gamePrefix: c.gamePrefix, stripUrls: c.stripUrls })
314
+ if (!text) return
315
+ rollDay()
316
+ if (sentToday >= c.maxPerDay) { stats.dropped += batch.length; lastError = '今日主动消息配额已用完(本地保护上限 ' + c.maxPerDay + ')'; return }
317
+ for (const group of c.groups) {
318
+ try {
319
+ sentToday += 1
320
+ await api.sendGroupMessage(group, text, { msgSeq: sentToday })
321
+ stats.sent += 1
322
+ lastSentAt = new Date().toISOString()
323
+ lastError = ''
324
+ } catch (error) {
325
+ lastError = error && error.message ? error.message : String(error)
326
+ stats.dropped += batch.length
327
+ log('[bridge] 发送失败:' + lastError)
328
+ break
329
+ }
330
+ }
331
+ }
332
+
333
+ function onEvent(evt) {
334
+ if (evt.type === 'join') { online.add(evt.player); stats.joins += 1 }
335
+ else if (evt.type === 'leave') { online.delete(evt.player); stats.leaves += 1 }
336
+ else if (evt.type === 'death') stats.deaths += 1
337
+ else if (evt.type === 'chat') stats.chats += 1
338
+ else return
339
+
340
+ const c = cfg()
341
+ if (evt.type === 'join' && !c.events.join) return
342
+ if (evt.type === 'leave' && !c.events.leave) return
343
+ if (evt.type === 'death' && !c.events.death) return
344
+ // 自己发的消息(游戏内回显的 QQ 转发)不该再回环:以 [群] 开头的不转发
345
+ if (evt.type === 'chat' && /^\[(群|QQ)\]/.test(evt.text)) return
346
+
347
+ queue.push(evt)
348
+ if (!flushTimer) {
349
+ flushTimer = setTimeout(() => { void flush() }, c.coalesceMs)
350
+ if (flushTimer.unref) flushTimer.unref()
351
+ }
352
+ }
353
+
354
+ async function seedOnline() {
355
+ // 用 RCON list 补一次,避免 DSH 重启期间漏掉的进出事件
356
+ try {
357
+ const { probePlayers } = await import('./rcon-probe.mjs')
358
+ const names = await probePlayers(serverDir)
359
+ for (const n of names) online.add(n)
360
+ log('[bridge] 启动时在线玩家:' + (names.join(', ') || '无'))
361
+ } catch (error) {
362
+ log('[bridge] 探测在线玩家失败(不影响聊天转发):' + (error && error.message ? error.message : String(error)))
363
+ }
364
+ }
365
+
366
+ return {
367
+ async start() {
368
+ if (running) return
369
+ running = true
370
+ tail = createLogTail(serverDir, onEvent, { intervalMs: 500 })
371
+ tail.startAtEnd()
372
+ tail.start()
373
+ await seedOnline()
374
+ log('[bridge] 已启动,模式=' + cfg().mode)
375
+ },
376
+ stop() {
377
+ running = false
378
+ if (tail) tail.stop()
379
+ if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
380
+ queue = []
381
+ },
382
+ isRunning: () => running,
383
+ status() {
384
+ return {
385
+ running,
386
+ mode: cfg().mode,
387
+ online: [...online],
388
+ queued: queue.length,
389
+ sentToday,
390
+ stats: Object.assign({}, stats),
391
+ lastError,
392
+ lastSentAt,
393
+ }
394
+ },
395
+ /** 只用于测试/调试:直接喂一条事件 */
396
+ _feed: onEvent,
397
+ api,
398
+ }
399
+ }
400
+
401
+ /** 把运行状态落盘,方便面板/排查 */
402
+ export function writeBridgeState(serverDir, state) {
403
+ try {
404
+ const dir = join(serverDir, 'ops', 'data')
405
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
406
+ writeFileSync(join(dir, 'bridge-state.json'), JSON.stringify(Object.assign({ at: new Date().toISOString() }, state), null, 2), 'utf8')
407
+ } catch { /* 状态文件写不了不影响主流程 */ }
408
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 极简 RCON 探测:只为了拿「当前在线玩家名单」。
3
+ *
4
+ * 单独一个文件是为了避免 import rcon.mjs —— 那个文件在被 import 时会执行 main()。
5
+ */
6
+ import { createConnection } from 'node:net'
7
+ import { existsSync, readFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+
10
+ function readProperties(dir) {
11
+ const map = {}
12
+ try {
13
+ const file = join(dir, 'server.properties')
14
+ if (!existsSync(file)) return map
15
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
16
+ const m = /^([^=#][^=]*)=(.*)$/.exec(line)
17
+ if (m) map[m[1].trim()] = m[2]
18
+ }
19
+ } catch { /* 读不到就当没有 */ }
20
+ return map
21
+ }
22
+
23
+ function packet(id, type, body) {
24
+ const payload = Buffer.from(body, 'utf8')
25
+ const buf = Buffer.alloc(14 + payload.length)
26
+ buf.writeInt32LE(10 + payload.length, 0)
27
+ buf.writeInt32LE(id, 4)
28
+ buf.writeInt32LE(type, 8)
29
+ payload.copy(buf, 12)
30
+ buf.writeInt16LE(0, 12 + payload.length)
31
+ return buf
32
+ }
33
+
34
+ export function rconCommand(port, password, command, timeoutMs = 4000) {
35
+ return new Promise((resolve, reject) => {
36
+ const socket = createConnection({ host: '127.0.0.1', port })
37
+ let buf = Buffer.alloc(0)
38
+ let authed = false
39
+ const timer = setTimeout(() => { socket.destroy(); reject(new Error('RCON 超时')) }, timeoutMs)
40
+ const done = (err, value) => {
41
+ clearTimeout(timer)
42
+ try { socket.destroy() } catch { }
43
+ if (err) reject(err); else resolve(value)
44
+ }
45
+ socket.on('connect', () => socket.write(packet(1, 3, password)))
46
+ socket.on('error', (e) => done(e))
47
+ socket.on('data', (chunk) => {
48
+ buf = Buffer.concat([buf, chunk])
49
+ while (buf.length >= 12) {
50
+ const len = buf.readInt32LE(0)
51
+ if (buf.length < len + 4) break
52
+ const id = buf.readInt32LE(4)
53
+ const type = buf.readInt32LE(8)
54
+ const body = buf.subarray(12, len + 2).toString('utf8')
55
+ buf = buf.subarray(len + 4)
56
+ if (type === 2 && id === -1) return done(new Error('RCON 密码不对'))
57
+ if (!authed) {
58
+ if (type !== 2) continue
59
+ authed = true
60
+ socket.write(packet(2, 2, command))
61
+ continue
62
+ }
63
+ return done(null, body)
64
+ }
65
+ })
66
+ })
67
+ }
68
+
69
+ /** @returns {Promise<string[]>} 在线玩家名 */
70
+ export async function probePlayers(serverDir) {
71
+ const props = readProperties(serverDir)
72
+ const enabled = String(props['enable-rcon'] || '').toLowerCase() === 'true'
73
+ if (!enabled) return []
74
+ const port = Number(props['rcon.port'] || 25575)
75
+ const password = props['rcon.password'] || ''
76
+ if (!password) return []
77
+ const out = await rconCommand(port, password, 'list', 4000)
78
+ // "There are 1 of a max of 20 players online: Steve, Alex"
79
+ const idx = out.indexOf(':')
80
+ if (idx < 0) return []
81
+ return out.slice(idx + 1).split(',').map((s) => s.trim()).filter(Boolean)
82
+ }
83
+
84
+ /** 直接发一条指令(给 QQ→游戏 的 P1 预留) */
85
+ export async function rconSay(serverDir, command) {
86
+ const props = readProperties(serverDir)
87
+ const port = Number(props['rcon.port'] || 25575)
88
+ const password = props['rcon.password'] || ''
89
+ if (!password) throw new Error('server.properties 里没有 rcon.password')
90
+ return rconCommand(port, password, command, 5000)
91
+ }