koishi-plugin-bns-rate 1.2.8 → 1.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.
Files changed (3) hide show
  1. package/README.md +24 -1
  2. package/index.js +203 -19
  3. package/package.json +16 -5
package/README.md CHANGED
@@ -2,7 +2,26 @@
2
2
 
3
3
  从 [dd373.com](https://www.dd373.com/s-d5gqt8.html) 获取剑灵怀旧服**神石**实时汇率,输出当前时段最低比例前 N 条。
4
4
 
5
- 支持**官方 QQ 机器人 Markdown 卡片**回复:标题 + 横幅图 + 灰框报价 + 跳转按钮,全部可在插件设置页配置。
5
+ 支持**官方 QQ 机器人 Markdown 卡片**回复:标题 + 横幅图 + 报价区 + 跳转按钮,全部可在插件设置页配置。
6
+
7
+ > ⚠️ **dd373 已启用阿里云 WAF**:纯 HTTP 请求会返回滑块验证页。插件必须借助真实浏览器拿到 `acw_tc` / `cdn_sec_tc` 信任 Cookie 才能取数,详见下方「取数方式」。
8
+
9
+ ## 取数方式(重要)
10
+
11
+ dd373 的风控会拦截"不像浏览器"的请求。插件提供 4 种方式,用设置页的 `fetchMode` 切换:
12
+
13
+ | fetchMode | 说明 | 适用环境 |
14
+ | --- | --- | --- |
15
+ | **`auto`(默认)** | 先试 HTTP;被 WAF 拦则自动用本机浏览器取一次 | 推荐。装了 puppeteer 或 Chrome/Edge 即可 |
16
+ | `browser` | 始终用浏览器取 | 同上 |
17
+ | `cookie` | 只用 HTTP,带上你手填的 Cookie | 服务器不能装浏览器的场景 |
18
+ | `http` | 纯 HTTP,不做兜底 | 仅调试 |
19
+
20
+ **浏览器模式**优先使用 `puppeteer`(服务器上常见,自带 Chromium),找不到再回退系统 Chrome/Edge。流程是:同一浏览器会话先访问 dd373 首页(WAF 在此下发信任 Cookie),再访问目标列表页。
21
+
22
+ **Cookie 模式**:在浏览器打开 dd373 → F12 → 网络/Network → 刷新 → 点任意请求 → 复制请求头里的完整 `Cookie`(需含 `acw_tc` 与 `cdn_sec_tc`),粘到设置页的 `cookie`。⚠️ Cookie 会过期,失效后重新复制即可;也可能与原 IP 绑定,跨机器使用需自行验证。
23
+
24
+ 用 `bnsrate.diag` 可以一眼看到当前是否检测到 puppeteer / 浏览器,以及真实抓取结果。
6
25
 
7
26
  ## 命令
8
27
 
@@ -12,6 +31,7 @@
12
31
  | `bnsrate -f` | 忽略缓存,强制刷新 |
13
32
  | `bnsrate.box` | **报价区排版对照**:一条消息里给出 code / table / quote / list / none 五种样式,在手机上挑一个填进 `ratesBox` |
14
33
  | `bnsrate.preview` | 只输出卡片 Markdown 源码(不发送卡片),调试用 |
34
+ | `bnsrate.diag` | 自检:报告插件版本、fetchMode、是否找到 puppeteer/浏览器、真实抓取结果 |
15
35
 
16
36
  ## 卡片效果
17
37
 
@@ -80,6 +100,9 @@
80
100
  | --- | --- | --- |
81
101
  | `url` | dd373 剑灵怀旧服页面 | 目标区服页面 URL |
82
102
  | `cacheSeconds` | `60` | 缓存时间(秒),缓存期内重复查询不再请求页面 |
103
+ | `fetchMode` | `auto` | 取数方式:`auto` / `browser` / `cookie` / `http`,见上文「取数方式」 |
104
+ | `cookie` | 空 | 浏览器 Cookie(`fetchMode=cookie` 时用),需含 `acw_tc` 与 `cdn_sec_tc` |
105
+ | `chromePath` | 空 | 浏览器可执行文件路径,留空自动查找(优先 puppeteer) |
83
106
  | `count` | `5` | 显示的条目数量(1–10) |
84
107
  | `markdown` | `true` | 用 QQ 官方 Markdown 卡片回复 |
85
108
  | `title` | `神石比例实时播报` | 卡片标题 |
package/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { Schema } = require('koishi')
2
+ const path = require('path')
2
3
 
3
4
  // 当前加载的插件版本(用于 bnsrate.diag 自检:一眼看出 Koishi 到底在跑哪个版本)
4
5
  let PLUGIN_VERSION = '未知'
@@ -34,6 +35,19 @@ const Config = Schema.object({
34
35
  .min(10)
35
36
  .max(300)
36
37
  .description('缓存时间(秒),缓存内重复查询不再请求页面'),
38
+
39
+ // ===== 反爬 / 取数方式 =====
40
+ fetchMode: Schema.union(['auto', 'http', 'cookie', 'browser'])
41
+ .default('auto')
42
+ .description('🔧 取数方式(dd373 已启用 WAF,纯 HTTP 请求会被拦):<br>auto = 自动:先试 HTTP,被拦则用本机浏览器取一次(推荐)<br>browser = 始终用本机 Chrome/Edge 取(需该机器装了浏览器)<br>cookie = 只用 HTTP + 下面填的 Cookie(服务器没浏览器时用这个)<br>http = 纯 HTTP,不做任何兜底(调试用)'),
43
+ cookie: Schema.string()
44
+ .role('textarea', { rows: [3, 6] })
45
+ .default('')
46
+ .description('🍪 浏览器 Cookie(仅 fetchMode=cookie 时使用):在浏览器打开 dd373,按 F12 → 网络/Network → 刷新 → 点任意请求 → 复制请求头里的完整 Cookie。需包含 acw_tc 与 cdn_sec_tc。⚠️ 可能过期;若提示仍被拦截,重新复制一次'),
47
+ chromePath: Schema.string()
48
+ .default('')
49
+ .description('🌐 浏览器可执行文件路径(fetchMode=auto/browser 时用)。留空自动查找 Chrome / Edge。Windows 示例:C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe;Linux 示例:/usr/bin/chromium'),
50
+
37
51
  count: Schema.number()
38
52
  .default(5)
39
53
  .min(1)
@@ -106,22 +120,185 @@ function looksLikeWafChallenge(html) {
106
120
  return /aliyun-captcha|_waf_is_mobile|slideStyle|captcha-element/.test(s)
107
121
  }
108
122
 
109
- // 抓页面原始 HTML(含对抗 dd373 WAF 所需的请求头)
110
- async function fetchHtml(ctx, url) {
111
- const response = await ctx.http.get(url, {
112
- responseType: 'text',
113
- headers: {
114
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
115
- 'Accept': 'text/html,application/xhtml+xml',
116
- 'Accept-Language': 'zh-CN,zh;q=0.9',
117
- // ⚠️ dd373 的阿里云 WAF 会拦截「没有 Referer」的请求,直接返回滑块验证页(约 12KB,无任何商品数据)
118
- // 实测结论:只有 Referer 是必需项,Cookie 无关(连伪造的 acw_tc 都能过)。缺了它整站必然解析失败
119
- 'Referer': DEFAULT_BUTTON_URL,
120
- },
121
- })
123
+ const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
124
+
125
+ // —— 方式一:纯 HTTP(可附带 Cookie) ——
126
+ async function fetchHtmlHttp(ctx, url, cookie) {
127
+ const headers = {
128
+ 'User-Agent': UA,
129
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
130
+ 'Accept-Language': 'zh-CN,zh;q=0.9',
131
+ 'Referer': DEFAULT_BUTTON_URL,
132
+ }
133
+ if (cookie) headers.Cookie = cookie
134
+ const response = await ctx.http.get(url, { responseType: 'text', headers })
122
135
  return typeof response === 'string' ? response : response.data
123
136
  }
124
137
 
138
+ // —— 方式二:本机浏览器(Chrome / Edge 无头模式 --dump-dom) ——
139
+ // dd373 要求 acw_tc / cdn_sec_tc 信任 Cookie,纯 HTTP 无法自举,必须借真实浏览器过一次挑战。
140
+ // 做法:用一个持久化 profile,先访问首页拿到信任 Cookie,再访问目标页(同一 profile 复用 Cookie)。
141
+ let browserChain = Promise.resolve() // 串行化,避免多个请求抢同一个 profile
142
+
143
+ function findBrowser(explicit) {
144
+ const fs = require('fs')
145
+ const cands = explicit ? [explicit] : [
146
+ process.env.CHROME_PATH,
147
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
148
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
149
+ path.join(process.env.LOCALAPPDATA || '', 'Google\\Chrome\\Application\\chrome.exe'),
150
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
151
+ 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
152
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser',
153
+ '/snap/bin/chromium', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
154
+ ].filter(Boolean)
155
+ return cands.find(p => { try { return fs.existsSync(p) } catch { return false } }) || null
156
+ }
157
+
158
+ function dumpDom(browser, profileDir, url, timeoutMs = 40000) {
159
+ return new Promise((resolve, reject) => {
160
+ const { spawn } = require('child_process')
161
+ const child = spawn(browser, [
162
+ '--headless=new', '--disable-gpu', '--no-sandbox', '--disable-dev-shm-usage',
163
+ '--no-first-run', '--no-default-browser-check', '--disable-extensions',
164
+ '--disable-background-networking', '--mute-audio',
165
+ `--user-data-dir=${profileDir}`,
166
+ '--virtual-time-budget=20000', '--dump-dom', url,
167
+ ], { stdio: ['ignore', 'pipe', 'ignore'] })
168
+
169
+ let out = ''
170
+ let done = false
171
+ const finish = (err) => {
172
+ if (done) return
173
+ done = true
174
+ clearTimeout(timer)
175
+ try { child.kill() } catch {}
176
+ err ? reject(err) : resolve(out)
177
+ }
178
+ child.stdout.on('data', (d) => { out += d.toString('utf8') })
179
+ child.on('error', (e) => finish(e))
180
+ child.on('close', () => finish(null))
181
+ const timer = setTimeout(() => finish(new Error('浏览器取数超时')), timeoutMs)
182
+ })
183
+ }
184
+
185
+ function loadPuppeteer() {
186
+ for (const m of ['puppeteer', 'puppeteer-core']) {
187
+ try { return require(m) } catch {}
188
+ }
189
+ return null
190
+ }
191
+
192
+ // 用 puppeteer 取页面(服务器上通常装的是 puppeteer,自带 Chromium)
193
+ // 关键:在同一次浏览器会话里先访问首页(拿 WAF 信任 Cookie),再访问目标页。
194
+ // 不共用持久化 profile,避免多进程争抢同一个 profile 目录导致拿到空内容。
195
+ async function fetchHtmlViaPuppeteer(puppeteer, url, config) {
196
+ const launchOpts = {
197
+ headless: true,
198
+ args: [
199
+ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage',
200
+ '--disable-gpu', '--no-first-run', '--no-default-browser-check',
201
+ ],
202
+ }
203
+ // 仅在能自动找到浏览器时才指定路径;否则交给 puppeteer 用它自带的 Chromium
204
+ const exe = String(config.chromePath || '').trim() || findBrowser('')
205
+ if (exe) launchOpts.executablePath = exe
206
+
207
+ const browser = await puppeteer.launch(launchOpts)
208
+ try {
209
+ const page = await browser.newPage()
210
+ try { await page.setUserAgent(UA) } catch {}
211
+
212
+ const grab = async (u) => {
213
+ await page.goto(u, { waitUntil: 'domcontentloaded', timeout: 35000 })
214
+ await new Promise(r => setTimeout(r, 1200))
215
+ return await page.content()
216
+ }
217
+
218
+ // ① 预热首页:WAF 在此下发 acw_tc / cdn_sec_tc 信任 Cookie
219
+ await grab(DEFAULT_BUTTON_URL).catch(() => {})
220
+ // ② 再取目标页
221
+ let html = await grab(url)
222
+ if (looksLikeWafChallenge(html) || parseRates(html, 1).length === 0) {
223
+ await grab(DEFAULT_BUTTON_URL).catch(() => {})
224
+ html = await grab(url)
225
+ }
226
+ return html
227
+ } finally {
228
+ try { await browser.close() } catch {}
229
+ }
230
+ }
231
+
232
+ async function fetchHtmlBrowser(ctx, url, config) {
233
+ const fs = require('fs')
234
+ const os = require('os')
235
+ const logger = getLogger(ctx)
236
+ const profileDir = path.join(os.tmpdir(), 'bns-rate-profile')
237
+ try { fs.mkdirSync(profileDir, { recursive: true }) } catch {}
238
+
239
+ const puppeteer = loadPuppeteer()
240
+
241
+ // 串行执行,避免并发争抢同一个 profile 目录
242
+ const run = async () => {
243
+ // 首选 puppeteer(服务器上一般用它,且自带 Chromium)
244
+ if (puppeteer) {
245
+ try {
246
+ return await fetchHtmlViaPuppeteer(puppeteer, url, config)
247
+ } catch (e) {
248
+ logger.debug('puppeteer 取数失败,回退系统浏览器: ' + ((e && e.message) || e))
249
+ }
250
+ }
251
+ const browser = findBrowser(config.chromePath)
252
+ if (!browser) {
253
+ throw new Error('没有可用的浏览器:既找不到 Chrome/Edge,也未检测到 puppeteer。请 npm i puppeteer,或安装 Chrome,或在设置页填写 chromePath')
254
+ }
255
+ let html = await dumpDom(browser, profileDir, url)
256
+ if (looksLikeWafChallenge(html) || parseRates(html, 1).length === 0) {
257
+ // 用同一 profile 访问首页刷新信任 Cookie,再重试
258
+ await dumpDom(browser, profileDir, DEFAULT_BUTTON_URL).catch(() => {})
259
+ html = await dumpDom(browser, profileDir, url)
260
+ }
261
+ return html
262
+ }
263
+ const task = browserChain.then(run, run)
264
+ browserChain = task.then(() => {}, () => {})
265
+ return task
266
+ }
267
+
268
+ function getLogger(ctx) {
269
+ try {
270
+ const l = ctx.logger('bns-rate')
271
+ if (l) return l
272
+ } catch {}
273
+ return { debug() {}, info() {}, warn() {}, error() {} }
274
+ }
275
+
276
+ // —— 统一入口:按 fetchMode 选择,并做兜底 ——
277
+ async function fetchHtml(ctx, url, config = {}) {
278
+ const mode = String(config.fetchMode || 'auto')
279
+ const cookie = String(config.cookie || '').trim()
280
+ const logger = getLogger(ctx)
281
+
282
+ const tryHttp = async () => fetchHtmlHttp(ctx, url, cookie)
283
+
284
+ if (mode === 'http') return tryHttp()
285
+ if (mode === 'cookie') {
286
+ if (!cookie) throw new Error('fetchMode=cookie 但没填 Cookie,请到设置页填写(F12→网络→复制请求头 Cookie)')
287
+ return tryHttp()
288
+ }
289
+ if (mode === 'browser') return fetchHtmlBrowser(ctx, url, config)
290
+
291
+ // auto:先 HTTP(有 Cookie 直接带),被拦再用浏览器
292
+ try {
293
+ const html = await tryHttp()
294
+ if (!looksLikeWafChallenge(html) && parseRates(html, 1).length > 0) return html
295
+ logger.debug('HTTP 取数被 WAF 拦截,改用浏览器')
296
+ } catch (e) {
297
+ logger.debug('HTTP 取数失败,改用浏览器: ' + (e && e.message))
298
+ }
299
+ return fetchHtmlBrowser(ctx, url, config)
300
+ }
301
+
125
302
  // 从 HTML 里解析汇率(可能返回空数组,交给调用方判断原因)
126
303
  function parseRates(html, count) {
127
304
  const limit = Math.max(1, Math.min(10, Number(count) || 5))
@@ -144,16 +321,16 @@ function parseRates(html, count) {
144
321
  return rates
145
322
  }
146
323
 
147
- async function fetchRates(ctx, url, count) {
148
- const html = await fetchHtml(ctx, url)
324
+ async function fetchRates(ctx, url, count, config = {}) {
325
+ const html = await fetchHtml(ctx, url, config)
149
326
  const rates = parseRates(html, count)
150
327
 
151
328
  if (rates.length === 0) {
152
329
  // 区分「被反爬拦截」和「页面真的改版了」——两者的排查方向完全不同
153
330
  if (looksLikeWafChallenge(html)) {
154
- throw new Error('请求被 dd373 的反爬验证页拦截(阿里云 WAF,返回了滑块验证页)。通常是请求过于频繁或缺少 Referer')
331
+ throw new Error('请求被 dd373 的反爬验证页拦截(阿里云 WAF)。该站已要求浏览器信任 Cookie:请把 fetchMode 设为 auto/browser 并装好浏览器,或改成 cookie 模式并在设置页填入 Cookie')
155
332
  }
156
- throw new Error('无法解析页面汇率数据,页面结构可能已变更')
333
+ throw new Error(`无法解析页面汇率数据(响应 ${html.length} 字节),页面结构可能已变更`)
157
334
  }
158
335
 
159
336
  return rates
@@ -398,7 +575,7 @@ function apply(ctx, config) {
398
575
  return { rates: cache.rates, timestamp: cache.timestamp, stale: false }
399
576
  }
400
577
  try {
401
- const rates = await fetchRates(ctx, config.url, config.count)
578
+ const rates = await fetchRates(ctx, config.url, config.count, config)
402
579
  cache = { rates, timestamp: Date.now() }
403
580
  return { rates, timestamp: cache.timestamp, stale: false }
404
581
  } catch (e) {
@@ -459,6 +636,10 @@ function apply(ctx, config) {
459
636
  .action(async ({ session }) => {
460
637
  const lines = [`bnsrate 自检 · 插件 v${PLUGIN_VERSION}`]
461
638
  lines.push(`配置: count=${config.count} cache=${config.cacheSeconds}s ratesBox=${config.ratesBox} markdown=${config.markdown}`)
639
+ lines.push(`取数: fetchMode=${config.fetchMode || 'auto'} cookie=${config.cookie ? '已填(' + config.cookie.length + '字)' : '空'}`)
640
+ const browser = findBrowser(config.chromePath)
641
+ const pup = loadPuppeteer()
642
+ lines.push(`浏览器: puppeteer=${pup ? '✅ 已安装' : '❌ 未安装'} · 系统浏览器=${browser ? '✅ ' + browser : '❌ 未找到'}`)
462
643
  lines.push(`URL: ${config.url}`)
463
644
  if (session) {
464
645
  lines.push(`平台: session=${session.platform || '(无)'} bot=${(session.bot && session.bot.platform) || '(无)'} 支持卡片=${supportsCard(session)}`)
@@ -468,7 +649,7 @@ function apply(ctx, config) {
468
649
 
469
650
  const started = Date.now()
470
651
  try {
471
- const html = await fetchHtml(ctx, config.url)
652
+ const html = await fetchHtml(ctx, config.url, config)
472
653
  const rates = parseRates(html, config.count)
473
654
  lines.push(`抓取: ✅ 成功 · ${html.length} 字节 · ${Date.now() - started}ms`)
474
655
  lines.push(`反爬: ${looksLikeWafChallenge(html) ? '❌ 收到阿里云 WAF 验证页' : '✅ 未检测到验证页'}`)
@@ -534,6 +715,9 @@ module.exports = {
534
715
  _test: {
535
716
  fetchRates,
536
717
  fetchHtml,
718
+ fetchHtmlHttp,
719
+ fetchHtmlBrowser,
720
+ findBrowser,
537
721
  parseRates,
538
722
  looksLikeWafChallenge,
539
723
  PLUGIN_VERSION,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-bns-rate",
3
- "version": "1.2.8",
3
+ "version": "1.3.0",
4
4
  "description": "Fetch BNS Classic Divine Stone exchange rate from dd373.com, with QQ official Markdown card support",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -8,7 +8,16 @@
8
8
  "README.md"
9
9
  ],
10
10
  "license": "MIT",
11
- "keywords": ["koishi", "koishi-plugin", "bns", "dd373", "exchange-rate", "神石", "剑灵", "markdown"],
11
+ "keywords": [
12
+ "koishi",
13
+ "koishi-plugin",
14
+ "bns",
15
+ "dd373",
16
+ "exchange-rate",
17
+ "神石",
18
+ "剑灵",
19
+ "markdown"
20
+ ],
12
21
  "peerDependencies": {
13
22
  "koishi": "^4.18.0"
14
23
  },
@@ -17,11 +26,13 @@
17
26
  },
18
27
  "koishi": {
19
28
  "description": {
20
- "zh": "从 dd373.com 获取剑灵怀旧服神石实时汇率,输入 神石/bnsrate/shenshi 即可查询最低比例。支持官方QQ机器人 Markdown 卡片:标题 + 横幅图 + 报价区支持代码块灰框/表格/引用/列表四种排版+ 跳转按钮,正文与按钮同一条消息;横幅图片、外框样式、配色、小数位均可在插件设置页配置。",
21
- "en": "Fetch BNS Classic Divine Stone exchange rate from dd373.com. QQ official bot Markdown card: title, banner image, gray code-box rate table, jump button — all in a single message and fully configurable."
29
+ "zh": "从 dd373.com 获取剑灵怀旧服神石实时汇率,输入 神石/bnsrate/shenshi 即可查询最低比例。dd373 已启用 WAF,插件支持「puppeteer / 本机浏览器」或「浏览器 Cookie」两种取数方式(设置页可切换)。支持官方QQ机器人 Markdown 卡片:标题 + 横幅图 + 报价区(代码块/表格/引用/列表/纯文本)+ 跳转按钮,正文与按钮同一条消息。",
30
+ "en": "Fetch BNS Classic Divine Stone exchange rate from dd373.com. Handles dd373's WAF via puppeteer / local browser or a pasted cookie. Renders a QQ official Markdown card with title, banner, rate block and jump button in a single message."
22
31
  },
23
32
  "service": {
24
- "required": ["http"]
33
+ "required": [
34
+ "http"
35
+ ]
25
36
  }
26
37
  }
27
38
  }