-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
583 lines (525 loc) · 21 KB
/
Copy pathindex.js
File metadata and controls
583 lines (525 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/*
* Webhook 插件(Yunzai v3:Miao-Yunzai / TRSS-Yunzai)
* 自定义 HTTP 接口(路径/请求方式/消息模板),收到请求后转发到指定 QQ(私聊/群聊)。
* 挂载方式 mode:auto(默认,优先复用 Bot.express,不可用回退独立端口)/ express / standalone。
* 占位符:{body.字段} {query.参数} {header.头名} {method} {path} {ip} {time} {raw} {json}。
* 命令(仅主人):#webhook帮助 / #webhook状态 / #webhook测试 <路径>
*/
import http from 'node:http'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { readConfig } from './components/config.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// ==================== 工具函数 ====================
/** 规范化接口路径:确保以 / 开头、去除末尾多余斜杠 */
function normalizePath (p) {
if (!p) return ''
let s = String(p).trim()
if (!s.startsWith('/')) s = '/' + s
s = s.replace(/\/+$/, '')
return s || '/'
}
/** 时间格式化:YYYY-MM-DD HH:mm:ss */
function formatTime (d) {
const pad = n => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ` +
`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
/** 把任意值转成可展示字符串 */
function tryStringify (v) {
if (v === undefined || v === null) return ''
if (typeof v === 'string') return v
if (Buffer.isBuffer(v)) return v.toString('utf8')
try { return JSON.stringify(v) } catch (e) { return String(v) }
}
/**
* 递归展开对象为「点路径 → 字符串」字典。
* 例:{ a: { b: 1 }, c: [ { d: 'x' } ] } => { 'a.b': '1', 'c.0.d': 'x' }
*/
function walk (prefix, obj, dict) {
if (obj === null || obj === undefined) return
if (typeof obj !== 'object') {
dict[prefix] = tryStringify(obj)
return
}
if (Array.isArray(obj)) {
obj.forEach((v, i) => walk(`${prefix}.${i}`, v, dict))
return
}
for (const [k, v] of Object.entries(obj)) walk(`${prefix}.${k}`, v, dict)
}
/** 构建占位符字典 */
function buildDict ({ method, path, query, headers, body, raw, time, ip }) {
const dict = {}
dict.method = method
dict.path = path
dict.time = time
dict.ip = ip
dict.raw = raw
dict.json = (body !== null && typeof body === 'object') ? JSON.stringify(body, null, 2) : tryStringify(body)
walk('body', body, dict)
walk('query', query, dict)
walk('header', headers, dict)
return dict
}
/** 模板渲染:把 {key} 替换为字典值(未命中的占位符原样保留);模板为空返回默认文本 */
function renderTemplate (tpl, dict, def = '') {
const text = (tpl === undefined || tpl === null || tpl === '') ? def : String(tpl)
let out = text
for (const [k, v] of Object.entries(dict)) {
out = out.split(`{${k}}`).join(v)
}
return out
}
/** 默认消息模板(用户未填 template 时) */
function defaultTemplate () {
return '收到 Webhook 请求\n接口:{path}({method})\n时间:{time}\n来源 IP:{ip}\n{json}'
}
/** 写入 HTTP 响应(兼容 express res 与 node http res) */
function respond (res, status, body) {
if (res.writableEnded || res.headersSent) return
const isJson = typeof body === 'object' && body !== null
const str = isJson ? JSON.stringify(body) : String(body ?? '')
res.statusCode = Number(status) || 200
if (!res.headersSent) {
res.setHeader('Content-Type', isJson ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8')
}
res.end(str)
}
// ==================== 请求体读取 / 解析 ====================
const MAX_BODY = 10 * 1024 * 1024 // 10MB
/** 读取原始请求体(仅独立服务 / express 解析器未命中时使用) */
function readBody (req, limit = MAX_BODY) {
return new Promise((resolve, reject) => {
const chunks = []
let size = 0
req.on('data', (c) => {
size += c.length
if (size > limit) {
reject(new Error('请求体超过 10MB 限制'))
req.destroy()
return
}
chunks.push(c)
})
req.on('end', () => resolve(Buffer.concat(chunks)))
req.on('error', reject)
})
}
/** 按 Content-Type 解析请求体:JSON / 表单 → 对象,其余 → 原始字符串 */
function parseBody (buf, contentType) {
const raw = buf.toString('utf8')
if (!raw) return { body: null, raw: '' }
const ct = String(contentType || '').toLowerCase()
if (ct.includes('application/json')) {
try { return { body: JSON.parse(raw), raw } } catch (e) { return { body: raw, raw } }
}
if (ct.includes('application/x-www-form-urlencoded')) {
try {
const obj = {}
new URLSearchParams(raw).forEach((v, k) => { obj[k] = v })
return { body: obj, raw }
} catch (e) { /* 解析失败按原始文本处理 */ }
}
// 很多客户端漏传 Content-Type,尽量自动识别 JSON
const head = raw.trimStart()
if (head.startsWith('{') || head.startsWith('[')) {
try { return { body: JSON.parse(raw), raw } } catch (e) { /* fallthrough */ }
}
return { body: raw, raw }
}
// ==================== 鉴权 ====================
/** 校验全局 token 与规则级请求头(返回 true = 通过) */
function checkAuth (cfg, rule, req, query) {
if (cfg.token) {
const given = req.headers['x-webhook-token'] || query.token
if (given !== cfg.token) return false
}
const sh = rule.secretHeaders || {}
for (const [name, expect] of Object.entries(sh)) {
const got = req.headers[String(name).toLowerCase()]
if (got !== String(expect)) return false
}
return true
}
// ==================== QQ 消息发送 ====================
/** 获取一个可用的 Bot 实例(带 sendApi,供合并转发等扩展动作使用) */
function getBot () {
const Bot = globalThis.Bot
if (!Bot) return null
const pool = (Bot.bots && typeof Bot.bots === 'object') ? Bot.bots : Bot
for (const k of Object.keys(pool)) {
const b = pool[k]
if (b && typeof b === 'object' && typeof b.sendApi === 'function') return b
}
return null
}
/** 把消息文本转成 OneBot 消息段数组(合并转发 node 的 content 用) */
function textToSegments (msg) {
return [{ type: 'text', data: { text: String(msg ?? '') } }]
}
/**
* 以「合并转发」形式发送(QQ 端显示为聊天记录卡片)。
* 通过 OneBotv11 扩展动作 send_group_forward_msg / send_private_forward_msg(NapCat 支持)。
* @param target { type: 'private'|'group', id: 'QQ号/群号' }
*/
async function sendForwardToQQ (target, msg) {
const Bot = globalThis.Bot
if (!Bot) throw new Error('Bot 未就绪')
const id = String(target.id ?? '').trim()
if (!id) throw new Error('目标 QQ/群号为空')
const bot = getBot()
if (!bot?.sendApi) throw new Error('未找到可用的 Bot.sendApi')
// 转发节点署名:优先取 bot 自身昵称与 QQ;取不到时退回普通发送
const nick = bot.nickname || bot.info?.nickname || '消息转发'
const uin = String(bot.uin ?? bot.info?.user_id ?? bot.self_id ?? '').trim()
if (!uin) {
logger?.info?.('[webhook-plugin] 无法确定转发署名 QQ,改用普通发送')
await sendPlainToQQ(target, msg)
return
}
const action = target.type === 'group' ? 'send_group_forward_msg' : 'send_private_forward_msg'
const key = target.type === 'group' ? 'group_id' : 'user_id'
const nodes = [{
type: 'node',
data: {
name: String(nick),
uin,
content: textToSegments(msg)
}
}]
await bot.sendApi(action, { [key]: id, messages: nodes })
}
/** 普通发送(pickFriend / pickGroup) */
async function sendPlainToQQ (target, msg) {
const Bot = globalThis.Bot
if (!Bot) throw new Error('Bot 未就绪')
const id = String(target.id ?? '').trim()
if (!id) throw new Error('目标 QQ/群号为空')
if (target.type === 'group') {
if (!Bot.pickGroup) throw new Error('Bot.pickGroup 不可用')
await Bot.pickGroup(id).sendMsg(msg)
} else {
if (!Bot.pickFriend) throw new Error('Bot.pickFriend 不可用')
await Bot.pickFriend(id).sendMsg(msg)
}
}
/**
* 向指定目标发送消息;target.forward=true 时优先以合并转发(聊天记录卡片)形式发送,
* 失败(协议端不支持、身份缺失)自动降级为普通文本发送。
*/
async function sendToQQ (target, msg) {
if (target.forward !== true) return sendPlainToQQ(target, msg)
try {
await sendForwardToQQ(target, msg)
logger?.mark?.(`[webhook-plugin] ${target.type}:${target.id} 已按合并转发发送`)
} catch (err) {
logger?.error?.(`[webhook-plugin] 合并转发发送失败(${target.type}:${target.id}),降级普通发送: ${err.message}`)
await sendPlainToQQ(target, msg)
}
}
// ==================== 核心:HTTP 请求处理 ====================
/**
* 统一处理一次 webhook 请求(express 模式与独立服务共用)。
* @param opts.express 是否来自 Bot.express(req.body 可能已被框架解析)
* @param opts.next express 模式未命中规则时调用 next() 放行(避免遮蔽云崽自身路由)
*/
async function handleHttp (req, res, opts = {}) {
const cfg = readConfig()
if (!cfg.enabled) return respond(res, 503, { code: 503, message: 'webhook 服务未启用' })
if (req.method === 'OPTIONS') {
// CORS 预检:直接应答,方便调试工具/浏览器
res.statusCode = 204
if (!res.headersSent) res.setHeader('Allow', 'GET,POST,PUT,DELETE,PATCH,OPTIONS')
return res.end()
}
const method = (req.method || 'GET').toLowerCase()
let pathname = ''
let query = {}
try {
const url = new URL(req.url, 'http://localhost')
pathname = url.pathname
query = Object.fromEntries(url.searchParams.entries())
} catch (e) {
return respond(res, 400, { code: 400, message: 'URL 解析失败' })
}
// 匹配规则:路径 + 请求方式;允许同 path+method 的多条规则,按配置顺序依次执行
const rules = Array.isArray(cfg.rules) ? cfg.rules : []
const matched = rules.filter(r => r && r.enabled !== false &&
normalizePath(r.path) === pathname &&
(String(r.method || 'post').toLowerCase() === method || String(r.method).toLowerCase() === 'any'))
if (!matched.length) {
// express 模式放行给云崽自身路由;独立服务直接 404
if (opts.next) return opts.next()
return respond(res, 404, { code: 404, message: `未找到匹配的接口:${method.toUpperCase()} ${pathname}` })
}
// 获取请求体
let body = null
let raw = ''
if (method !== 'get' && method !== 'head') {
if (opts.express) {
if (req.body !== undefined) {
// 框架已解析(json/urlencoded/text/raw)
body = req.body
raw = tryStringify(body)
} else {
// 解析器未命中(如 application/xml):自行读取流
const buf = await readBody(req).catch(() => null)
if (buf) { const p = parseBody(buf, req.headers['content-type']); body = p.body; raw = p.raw }
}
} else {
const buf = await readBody(req).catch(() => null)
if (buf) { const p = parseBody(buf, req.headers['content-type']); body = p.body; raw = p.raw }
}
}
// 合并 query:express 的 req.query 与手写解析结果取并集
const queryAll = (opts.express && req.query && typeof req.query === 'object')
? { ...query, ...req.query }
: query
// 逐条鉴权(全局 token + 该条 secretHeaders),全部未通过才返回 403
const passRules = []
for (const r of matched) {
if (checkAuth(cfg, r, req, queryAll)) {
passRules.push(r)
} else {
logger?.info?.(`[webhook-plugin] 接口 ${pathname} 的一条规则鉴权失败(来源 ${req.ip || req.socket?.remoteAddress || '未知'}),已跳过`)
}
}
if (!passRules.length) {
logger?.info?.(`[webhook-plugin] 接口 ${pathname} 全部规则鉴权失败(来源 ${req.ip || req.socket?.remoteAddress || '未知'})`)
return respond(res, 403, { code: 403, message: '鉴权失败' })
}
// 构建占位符字典(一次,供各规则模板 / 响应体复用)
const dict = buildDict({
method: method.toUpperCase(),
path: pathname,
query: queryAll,
headers: req.headers || {},
body,
raw,
time: formatTime(new Date()),
ip: req.ip || req.socket?.remoteAddress || ''
})
// 依次执行通过的规则:渲染模板 → 发送各自目标
for (const r of passRules) {
const msg = renderTemplate(r.template, dict, defaultTemplate())
const targets = Array.isArray(r.targets) ? r.targets : []
let ok = 0
for (const t of targets) {
try {
await sendToQQ(t, msg)
ok++
} catch (err) {
logger?.error?.(`[webhook-plugin] 发送失败 ${t.type}:${t.id}: ${err.message}`)
}
}
logger?.mark?.(`[webhook-plugin] ${method.toUpperCase()} ${pathname}(规则 ${String(r.method || 'post').toUpperCase()} ${normalizePath(r.path)})→ ${ok}/${targets.length} 个目标发送成功`)
}
// 响应取第一条通过鉴权规则的配置,其余规则只负责发送
const respRule = passRules[0]
const hasBody = respRule.responseBody !== undefined && respRule.responseBody !== null && respRule.responseBody !== ''
const respBody = hasBody ? renderTemplate(respRule.responseBody, dict) : { code: 0, message: 'ok' }
return respond(res, respRule.responseStatus || 200, respBody)
}
// ==================== 服务挂载 ====================
// 模块级状态:防止热重载后重复挂载 / 重复启动
let standaloneServer = null
/** 挂载到 Bot.express(云崽框架自带 HTTP 服务,与登录页同端口) */
function mountExpress () {
const Bot = globalThis.Bot
if (!Bot?.express?.use) return false
if (Bot.express.__webhookPluginMounted) return true
Bot.express.__webhookPluginMounted = true
Bot.express.use((req, res, next) => {
handleHttp(req, res, { express: true, next }).catch((err) => {
logger?.error?.(`[webhook-plugin] 请求处理异常: ${err.message}`)
if (!res.headersSent) respond(res, 500, { code: 500, message: '处理失败:' + err.message })
})
})
logger?.mark?.('[webhook-plugin] 已挂载至 Bot.express(与云崽 HTTP 服务同端口)')
return true
}
/** 启动独立 HTTP 服务(mode=standalone 或 auto 且无 Bot.express 时) */
function startStandalone (cfg) {
stopStandalone()
const host = cfg.host || '0.0.0.0'
const port = Number(cfg.port) || 5788
const server = http.createServer((req, res) => {
handleHttp(req, res, {}).catch((err) => {
logger?.error?.(`[webhook-plugin] 请求处理异常: ${err.message}`)
if (!res.headersSent) respond(res, 500, { code: 500, message: '处理失败:' + err.message })
})
})
server.on('error', (err) => {
logger?.error?.(`[webhook-plugin] 独立服务启动失败: ${err.message}`)
})
server.listen(port, host, () => {
logger?.mark?.(`[webhook-plugin] 独立 HTTP 服务已启动 http://${host}:${port}`)
})
standaloneServer = server
}
/** 停止独立 HTTP 服务 */
function stopStandalone () {
if (standaloneServer) {
try { standaloneServer.close() } catch (e) { /* 忽略 */ }
standaloneServer = null
}
}
/** 按最新配置(重新)挂载服务:在插件加载 / 锅巴保存后调用 */
function applyService () {
try {
const cfg = readConfig()
stopStandalone()
if (!cfg.enabled) {
logger?.info?.('[webhook-plugin] 服务未启用(enabled=false)')
return
}
if (cfg.mode === 'standalone') return startStandalone(cfg)
if (mountExpress()) return
if (cfg.mode === 'express') {
logger?.error?.('[webhook-plugin] Bot.express 不可用且 mode=express,服务未启动')
return
}
startStandalone(cfg) // auto 且无 Bot.express → 独立服务
} catch (err) {
logger?.error?.(`[webhook-plugin] 服务初始化失败: ${err.message}`)
}
}
// ==================== 插件主体 ====================
export class webhook extends plugin {
constructor () {
super({
name: 'webhook-plugin',
dsc: 'Webhook 插件:自定义 HTTP 接口(路径/请求方式/消息模板),收到请求后转发消息到指定 QQ',
event: 'message',
priority: 100,
rule: [
{
reg: '^#?(webhook|转发)(帮助|状态|测试|help|status|test|\\s|$)',
fnc: 'webhookCmd'
}
]
})
// 暴露实例引用:锅巴保存配置后调用 reloadService() 立即应用挂载方式变更
globalThis.__webhookPluginInstance = this
applyService()
}
/** 按最新配置重新挂载服务(锅巴保存配置后由 guoba.support.js 调用) */
reloadService () {
applyService()
}
// ---------- 命令处理 ----------
async webhookCmd () {
const e = this.e
if (!e?.isMaster) {
await e.reply('该命令仅限主人使用')
return true
}
const raw = (e.msg || '').replace(/^#/, '').trim()
const m = raw.match(/^(webhook|转发)\s*([\s\S]*)$/i)
if (!m) return true
const args = (m[2] || '').trim()
if (/^(帮助|help|)$/i.test(args)) {
await e.reply(helpText())
return true
}
if (/^(状态|status)$/i.test(args)) {
await this.cmdStatus(e)
return true
}
const test = args.match(/^(测试|test)\s*(.*)$/i)
if (test) {
await this.cmdTest(e, test[2].trim())
return true
}
await e.reply(helpText())
return true
}
async cmdStatus (e) {
const cfg = readConfig()
const lines = ['📡 Webhook 插件状态', '━━━━━━━━━━━━']
lines.push(`启用:${cfg.enabled ? '✅ 是' : '❌ 否'}`)
const modeMap = { auto: '自动(优先云崽 HTTP 服务)', express: '云崽 HTTP 服务(Bot.express)', standalone: '独立 HTTP 服务' }
if (cfg.enabled) {
if (cfg.mode !== 'standalone' && globalThis.Bot?.express?.use) {
lines.push(`挂载:${cfg.mode === 'express' ? modeMap.express : '✅ 云崽 HTTP 服务(Bot.express)'}`)
} else {
lines.push(`挂载:${modeMap.standalone}\n地址:http://${cfg.host || '0.0.0.0'}:${cfg.port || 5788}`)
}
}
if (cfg.token) lines.push(`全局 Token 校验:已开启`)
const rules = Array.isArray(cfg.rules) ? cfg.rules.filter(r => r && r.enabled !== false) : []
lines.push('', `已启用接口 ${rules.length} 个:`)
if (!rules.length) {
lines.push('(无,请到锅巴 WebUI → 插件配置 → Webhook 插件 添加)')
} else {
lines.push('')
for (const r of rules) {
const targets = (r.targets || []).map(t => `${t.type === 'group' ? '群' : '私聊'}${t.id}${t.forward ? '·转发' : ''}`).join('、') || '(未配置目标)'
lines.push(`· ${String(r.method || 'post').toUpperCase()} ${normalizePath(r.path)}\n → ${targets}`)
}
}
lines.push('', '发送「#webhook帮助」查看完整说明')
await e.reply(lines.join('\n'))
return true
}
async cmdTest (e, pathArg) {
const cfg = readConfig()
const rules = Array.isArray(cfg.rules) ? cfg.rules.filter(r => r && r.enabled !== false) : []
if (!rules.length) {
await e.reply('当前没有已启用的接口规则,请先到锅巴 WebUI 配置')
return true
}
let rule
if (pathArg) {
const target = normalizePath(pathArg)
rule = rules.find(r => normalizePath(r.path) === target) || rules.find(r => normalizePath(r.path).includes(target))
if (!rule) {
await e.reply(`未找到接口「${pathArg}」,已配置:${rules.map(r => `${r.method}/${r.path}`).join('、')}`)
return true
}
} else {
// 未指定路径:若只有一条规则直接测试,否则列出
if (rules.length > 1) {
await e.reply(`请指定要测试的接口路径,如:\n#webhook测试 /webhook/test\n\n已配置:\n${rules.map(r => `· ${String(r.method || 'post').toUpperCase()} ${normalizePath(r.path)}`).join('\n')}`)
return true
}
rule = rules[0]
}
const targets = Array.isArray(rule.targets) ? rule.targets.filter(t => t && t.id) : []
if (!targets.length) {
await e.reply(`接口 ${normalizePath(rule.path)} 未配置发送目标(targets)`)
return true
}
const dict = {
method: String(rule.method || 'post').toUpperCase(),
path: normalizePath(rule.path),
time: formatTime(new Date()),
ip: '127.0.0.1',
raw: '',
json: '',
'body.test': '这是一条测试消息'
}
const testMsg = renderTemplate(rule.template, dict,
`【测试】收到 Webhook 请求\n接口:{path}({method})\n时间:{time}\n{json}`)
let ok = 0
for (const t of targets) {
try {
await sendToQQ(t, testMsg)
ok++
} catch (err) {
logger?.error?.(`[webhook-plugin] 测试发送失败 ${t.type}:${t.id}: ${err.message}`)
}
}
await e.reply(`✅ 已按模板向 ${ok}/${targets.length} 个目标发送测试消息(接口 ${normalizePath(rule.path)})\n\n${testMsg}`)
return true
}
}
/** 帮助文本 */
function helpText () {
return `📡 Webhook 插件帮助
━━━━━━━━━━━━
🛠️ 命令列表
· #webhook状态 查看服务与接口列表
· #webhook测试 <路径> 向目标发测试消息`
}