qq-bot-roost 1.1.18 → 1.2.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/src/web/server.js CHANGED
@@ -4,6 +4,7 @@ import fsSync from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import crypto from 'node:crypto';
6
6
  import { ROOT } from '../config.js';
7
+ import { RESET_CONFIRM, resetFrameworkConfigs } from '../config-reset.js';
7
8
  import { redactText } from '../runtime.js';
8
9
  import { DIRS, botPaths, listBotIds, rel } from '../paths.js';
9
10
  import { createLogger, recentLogs, onLog, getLevel, setLevel } from '../logger.js';
@@ -37,6 +38,13 @@ import { toImportRow } from '../ledger.js';
37
38
  import { ledgerTextOf } from '../ledger-text.js';
38
39
  import { createMediaStore } from '../media-store.js';
39
40
  import { runRoute } from '../plugin/routes.js';
41
+ import {
42
+ MIN_KEY_LENGTH,
43
+ MIN_LOGIN_PASSWORD_LENGTH,
44
+ checkKeyStrength,
45
+ checkLoginPasswordStrength,
46
+ warnWeakKey,
47
+ } from './key-strength.js';
40
48
  import { toggleGroupPlugin } from '../plugin/groupscope.js';
41
49
  import { suspendPluginWatch } from '../services/plugin-watch.js';
42
50
  import { syncNickname } from '../services/nickname.js';
@@ -537,24 +545,74 @@ async function startWebServerInstance({
537
545
 
538
546
  const host = wc.host || '127.0.0.1';
539
547
  const port = Number(wc.port) || 15207;
540
- const accessKey = wc.accessKey || wc.token || '';
548
+ /**
549
+ * 两把钥匙(2026-11-28):
550
+ * - `accessKey` 给**机器**用(dsh-roost / roost-mcp 的 X-Access-Key / ?key=),16+;
551
+ * - `loginPassword` 给**人**用(登录页输入),8+。
552
+ *
553
+ * 必须是 `let` 而不是 const:面板改凭证后要即时生效并吊销旧凭证(旧版是
554
+ * const 固化,实测改完 key 旧 key 仍能进、新 key 反而 401——换了等于没换)。
555
+ * `loginPassword` 留空时登录页退回收 `accessKey`,老用户升级不断档。
556
+ */
557
+ let accessKey = wc.accessKey || wc.token || '';
558
+ let loginPassword = wc.loginPassword || '';
541
559
 
542
560
  /**
543
- * 硬阻断:监听非 loopback 却没设 accessKey。
561
+ * 硬阻断:监听非 loopback 却没设/设了弱 accessKey。
544
562
  *
545
563
  * 以前只在 doctor 里软告警。`authorized()` 在 accessKey 为空时无条件放行,
546
564
  * 于是 `webui.host=0.0.0.0` 且忘设 key 的面板在全部网卡零认证开放——
547
565
  * 远程可建/删机器人、改配置、装任意插件(插件代码在子进程执行 = RCE)。
548
- * 这种误配不该靠人记得去看 doctor,直接在启动期拒绝。
566
+ * 2026-11-28 起再加一道:外部暴露时弱 key 也拒绝(20 次/分钟的限流挡不住
567
+ * 短口令被穷举)。本机 loopback 完全不拦,只给弱 key 打 warn——升级不锁死
568
+ * 老用户(历史短 key 仍能用,但会被提醒去换)。
549
569
  */
550
570
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '']);
551
- if (!LOOPBACK_HOSTS.has(String(host)) && !accessKey) {
571
+ const exposed = !LOOPBACK_HOSTS.has(String(host));
572
+ const keyStrength = checkKeyStrength(accessKey);
573
+ if (exposed && !accessKey) {
552
574
  throw new Error(
553
575
  `面板监听 ${host} 但未设置 webui.accessKey。\n` +
554
576
  `这样任何人访问该端口都能无认证接管面板(含安装插件=执行任意代码)。\n` +
555
577
  `请在 config/bot.json 里设置 webui.accessKey,或把 webui.host 改回 127.0.0.1。`,
556
578
  );
557
579
  }
580
+ if (exposed && !keyStrength.ok) {
581
+ throw new Error(
582
+ `面板监听 ${host} 但 webui.accessKey 强度不足:${keyStrength.message}。\n` +
583
+ `这把钥匙给机器调用 API 用(dsh-roost / 脚本),外部暴露时弱密钥可被穷举。\n` +
584
+ `请换成至少 ${MIN_KEY_LENGTH} 位的随机字符串(如 node -e "console.log(require('crypto').randomBytes(24).toString('hex'))"),` +
585
+ `或把 webui.host 改回 127.0.0.1。`,
586
+ );
587
+ }
588
+ /**
589
+ * 外网暴露 = 给人登录:必须设独立的 loginPassword(8+),不能只靠机器 key。
590
+ * 两把钥匙分开后,人不用记 16 位的机器令牌;机器也不用把人密码写在脚本里。
591
+ */
592
+ const loginStrength = checkLoginPasswordStrength(loginPassword);
593
+ if (exposed && !loginPassword) {
594
+ throw new Error(
595
+ `面板监听 ${host} 但未设置 webui.loginPassword。\n` +
596
+ `外网访问是给人在登录页输密码的:请单独设一个至少 ${MIN_LOGIN_PASSWORD_LENGTH} 位的登录密码,` +
597
+ `它和给机器用的 accessKey 分开,改完重启生效。\n` +
598
+ `或把 webui.host 改回 127.0.0.1(本机不需要独立登录密码)。`,
599
+ );
600
+ }
601
+ if (exposed && !loginStrength.ok) {
602
+ throw new Error(
603
+ `面板监听 ${host} 但 webui.loginPassword 强度不足:${loginStrength.message}。\n` +
604
+ `请换成至少 ${MIN_LOGIN_PASSWORD_LENGTH} 位、且不是常见口令的登录密码。`,
605
+ );
606
+ }
607
+ if (!exposed) {
608
+ if (accessKey) {
609
+ const hint = warnWeakKey(accessKey);
610
+ if (hint) log.warn(`面板机器密钥强度不足:${hint}`);
611
+ }
612
+ if (loginPassword && !loginStrength.ok) {
613
+ log.warn(`面板登录密码强度不足:${loginStrength.message};建议更换`);
614
+ }
615
+ }
558
616
 
559
617
  /**
560
618
  * 反向代理设置。
@@ -747,6 +805,11 @@ async function startWebServerInstance({
747
805
  * 暂停是个紧急操作,等用户点进某个页签才发现「原来还暂停着」就太晚了。
748
806
  */
749
807
  snap.gate = rt?.gate?.peek?.() ?? null;
808
+ /**
809
+ * 外接协议状态:概览页的卡片和「外接」页的实时行共用这一份快照。
810
+ * snapshot() 不含 token,跟着 5 秒一次的 status 走,不必再开轮询接口。
811
+ */
812
+ snap.host = rt?.host?.snapshot?.() ?? null;
750
813
  return snap;
751
814
  };
752
815
 
@@ -1209,16 +1272,38 @@ async function startWebServerInstance({
1209
1272
  const sid0 = /(?:^|;\s*)roost_sid=([a-f0-9]{64})/.exec(ck)?.[1];
1210
1273
  const exp0 = sid0 ? sessions.get(sid0) : 0;
1211
1274
  if (!exp0 || exp0 <= Date.now()) {
1275
+ /**
1276
+ * 登录表单(2026-11-28):密钥只在 POST body 里交给 /api/login,不再让用户
1277
+ * 把密钥贴进网址。URL 会进历史 / 书签同步 / Referer / 反代 access_log,
1278
+ * 每一条都是明文泄露面;表单 + HttpOnly Cookie 把这条路径堵上。
1279
+ *
1280
+ * 脚本仍是 `script-src 'self'`(见 CSP_MAIN),所以不能内联:
1281
+ * 用同源的 /login.js,它在下面的鉴权闸门里显式放行——用户还没会话时
1282
+ * 必须加载得到,否则表单就是个按不动的空壳。
1283
+ *
1284
+ * 保留兼容:`?key=` 首跳(1186 行)和 `authorized()` 的 query 分支都还在,
1285
+ * dsh-roost / roost-mcp 那条路一行没动。这里只多一条给人走的入口。
1286
+ */
1212
1287
  res.writeHead(401, { 'Content-Type': 'text/html; charset=utf-8' });
1213
1288
  return res.end(
1214
- '<!doctype html><meta charset="utf-8"><title>需要访问密钥</title>' +
1289
+ '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' +
1290
+ '<title>面板登录</title>' +
1215
1291
  '<body style="font:15px/1.6 system-ui;max-width:34em;margin:14vh auto;padding:0 1.2em">' +
1216
- '<h1 style="font-size:18px">需要访问密钥</h1>' +
1217
- '<p>面板已开启访问密钥,但当前浏览器还没有会话(进程重启后会话会全部失效)。</p>' +
1218
- '<p>请用带密钥的地址打开一次,之后会在浏览器里记住 7 天:</p>' +
1219
- '<pre style="background:rgba(128,128,128,.14);padding:10px 12px;border-radius:6px;overflow:auto">' +
1220
- `http://${shownHost}:${actualPort}/?key=你的密钥</pre>` +
1221
- '<p style="opacity:.65;font-size:13px">密钥在 config/bot.json 的 webui.accessKey,或启动时设置的环境变量里。</p>',
1292
+ '<h1 style="font-size:18px">面板登录</h1>' +
1293
+ '<p>请输入面板登录密码(<code>webui.loginPassword</code>;没设过时仍可用旧的访问密钥)。' +
1294
+ '登录状态在浏览器里保留 7 天,程序重启后需要重新登录。</p>' +
1295
+ '<form id="loginForm">' +
1296
+ '<label for="panelKey">访问密钥</label><br>' +
1297
+ '<input id="panelKey" type="password" autocomplete="current-password" required ' +
1298
+ 'style="box-sizing:border-box;width:100%;max-width:28em;padding:8px 10px;margin:6px 0 10px">' +
1299
+ '<button type="submit" style="padding:8px 18px">登录</button>' +
1300
+ '</form>' +
1301
+ '<p id="loginError" role="alert" style="color:#e5484d;min-height:1.6em"></p>' +
1302
+ '<p style="opacity:.65;font-size:13px">登录密码在 <code>config/bot.json</code> 的 ' +
1303
+ '<code>webui.loginPassword</code>,或环境变量里。<br>' +
1304
+ '程序化调用(dsh-roost / 脚本)用的是另一把 <code>webui.accessKey</code>,' +
1305
+ '通过 <code>X-Access-Key</code> 头或 <code>?key=</code> 参数传递,照常工作。</p>' +
1306
+ '<script src="/login.js" defer></script>',
1222
1307
  );
1223
1308
  }
1224
1309
  }
@@ -1338,6 +1423,83 @@ async function startWebServerInstance({
1338
1423
  return res.end();
1339
1424
  }
1340
1425
 
1426
+ /**
1427
+ * 面板登录 / 登出(2026-11-28,**必须在 authorized() 之前**)。
1428
+ *
1429
+ * 登录是「拿密钥换会话」的入口,调用方此时还没有会话,走统一鉴权会
1430
+ * 直接 401——自己和自己死锁。所以这两个端点在鉴权闸门前面处理,但
1431
+ * 安全要求一条不少:
1432
+ * · 写操作必须 application/json(复用 isJsonRequest)
1433
+ * · 必须同源(复用 isSameOrigin,Referer 兜底)
1434
+ * · 失败走 authFails 同一份 per-IP 计数——不能让攻击者拿这个端点
1435
+ * 把「20 次/分钟」的限流翻倍
1436
+ * · 成功新建 sid(crypto.randomBytes(32)),与 ?key= 首跳完全同构,
1437
+ * 天然防 session fixation
1438
+ *
1439
+ * 登出删的是服务端 session + 清 Cookie。只清浏览器 Cookie 不删服务端
1440
+ * 记录等于没登出——偷到 sid 的人还能继续用。
1441
+ */
1442
+ if ((pathname === '/api/login' || pathname === '/api/logout') && req.method === 'POST') {
1443
+ if (!isJsonRequest(req)) {
1444
+ return json(res, 415, { error: '写操作需要 Content-Type: application/json' });
1445
+ }
1446
+ if (!isSameOrigin(req)) {
1447
+ return json(res, 403, { error: '跨站请求被拒绝' });
1448
+ }
1449
+ const ip = clientIp(req);
1450
+ const now = Date.now();
1451
+ const rec = authFails.get(ip);
1452
+ if (rec && now - rec.start < AUTH_WINDOW && rec.count >= AUTH_MAX_FAILS) {
1453
+ log.error(
1454
+ `面板登录失败次数过多,已临时封禁 ${ip}(${Math.ceil((AUTH_WINDOW - (now - rec.start)) / 1000)} 秒后解除)`,
1455
+ );
1456
+ return json(res, 429, { error: '尝试次数过多,请稍后再试' });
1457
+ }
1458
+ let body;
1459
+ try {
1460
+ body = await readBody(req);
1461
+ } catch (e) {
1462
+ return json(res, 400, { error: `请求体不合法:${e?.message || e}` });
1463
+ }
1464
+ if (pathname === '/api/login') {
1465
+ const given = body?.key;
1466
+ /**
1467
+ * 两把钥匙:设了 loginPassword 就只认它(人密码),没设才退回
1468
+ * accessKey(老用户升级不断档)。机器令牌不能当登录密码用——
1469
+ * 否则把它贴进登录页又回到「密钥进表单」的老路。
1470
+ */
1471
+ const expected = loginPassword || accessKey;
1472
+ /** 没设任何凭证时本机本就无需鉴权,别开一道「空密码也能登」的门 */
1473
+ if (!expected || !safeEqual(given, expected)) {
1474
+ const cur = rec && now - rec.start < AUTH_WINDOW ? rec : { count: 0, start: now };
1475
+ cur.count += 1;
1476
+ authFails.set(ip, cur);
1477
+ log.warn(`面板登录失败:来源 ${ip},本窗口第 ${cur.count} 次`);
1478
+ if (authFails.size > 5000) authFails.clear();
1479
+ return json(res, 401, { error: '访问密钥无效' });
1480
+ }
1481
+ authFails.delete(ip);
1482
+ const sid = crypto.randomBytes(32).toString('hex');
1483
+ sessions.set(sid, Date.now() + SESSION_TTL_MS);
1484
+ res.writeHead(200, {
1485
+ 'Content-Type': 'application/json; charset=utf-8',
1486
+ 'Cache-Control': 'no-store',
1487
+ 'Set-Cookie': `roost_sid=${sid}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${Math.floor(
1488
+ SESSION_TTL_MS / 1000,
1489
+ )}`,
1490
+ });
1491
+ return res.end(JSON.stringify({ ok: true }));
1492
+ }
1493
+ const cookieSid = /(?:^|;\s*)roost_sid=([a-f0-9]{64})/.exec(String(req.headers.cookie || ''))?.[1];
1494
+ if (cookieSid) sessions.delete(cookieSid);
1495
+ res.writeHead(200, {
1496
+ 'Content-Type': 'application/json; charset=utf-8',
1497
+ 'Cache-Control': 'no-store',
1498
+ 'Set-Cookie': 'roost_sid=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0',
1499
+ });
1500
+ return res.end(JSON.stringify({ ok: true }));
1501
+ }
1502
+
1341
1503
  if (!authorized(req, url, ptPage)) return json(res, 401, { error: '访问密钥无效' });
1342
1504
 
1343
1505
  /**
@@ -1981,6 +2143,9 @@ async function startWebServerInstance({
1981
2143
  ...(globalCfg.webui ?? {}),
1982
2144
  accessKey: '',
1983
2145
  accessKeySet: Boolean(globalCfg.webui?.accessKey),
2146
+ // 登录密码与机器密钥一样不回显(本机任意进程一条 GET 就能抄走)
2147
+ loginPassword: '',
2148
+ loginPasswordSet: Boolean(globalCfg.webui?.loginPassword),
1984
2149
  },
1985
2150
  logLevel: globalCfg.logLevel ?? 'info',
1986
2151
  /**
@@ -2126,15 +2291,51 @@ async function startWebServerInstance({
2126
2291
  : [],
2127
2292
  };
2128
2293
  }
2294
+ /** 凭证是否变更——变更后要即时生效 + 吊销所有会话 */
2295
+ let credentialsChanged = false;
2129
2296
  if (body.webui && typeof body.webui === 'object') {
2130
2297
  // webui 是全局设置,不能写进机器人 cfg:
2131
2298
  // 写进去 saveBotConfig 也不保存它(白名单式保存),
2132
2299
  // 结果是面板提示「已保存」但什么都没变。
2133
2300
  const patch = { ...body.webui };
2134
2301
  // 面板不回显密钥,所以空值代表「不修改」,不是「清空」
2135
- if (!patch.accessKey) delete patch.accessKey;
2302
+ const newAccessKey = patch.accessKey ? String(patch.accessKey).trim() : '';
2303
+ const newLoginPassword = patch.loginPassword ? String(patch.loginPassword).trim() : '';
2304
+ delete patch.accessKey;
2305
+ delete patch.loginPassword;
2136
2306
  delete patch.accessKeySet;
2307
+ delete patch.loginPasswordSet;
2308
+
2309
+ if (newAccessKey) {
2310
+ // 只校验「本次真的改了」的值——历史弱 key 用户不填这栏照样能保存别的设置。
2311
+ const strength = checkKeyStrength(newAccessKey);
2312
+ if (!strength.ok) return json(res, 400, { ok: false, error: strength.message });
2313
+ if (newAccessKey !== accessKey) {
2314
+ accessKey = newAccessKey;
2315
+ credentialsChanged = true;
2316
+ }
2317
+ }
2318
+ if (newLoginPassword) {
2319
+ const strength = checkLoginPasswordStrength(newLoginPassword);
2320
+ if (!strength.ok) return json(res, 400, { ok: false, error: strength.message });
2321
+ if (newLoginPassword !== loginPassword) {
2322
+ loginPassword = newLoginPassword;
2323
+ credentialsChanged = true;
2324
+ }
2325
+ }
2326
+
2137
2327
  globalCfg.webui = { ...globalCfg.webui, ...patch };
2328
+ if (newAccessKey) globalCfg.webui.accessKey = newAccessKey;
2329
+ if (newLoginPassword) globalCfg.webui.loginPassword = newLoginPassword;
2330
+ if (credentialsChanged) {
2331
+ /**
2332
+ * 吊销必须**紧跟凭证赋值**,不能挪到本请求末尾的 await 之后:
2333
+ * 后面还有 syncBotName() 这类要几百毫秒甚至几秒的异步操作,
2334
+ * 那段时间旧 cookie 仍有效——攻击者拿着旧会话就能继续操作。
2335
+ */
2336
+ sessions.clear();
2337
+ log.warn('面板凭证已更新:旧密钥/密码立即失效,所有会话已吊销,请用新凭证重新登录');
2338
+ }
2138
2339
  await saveGlobalConfig?.(globalCfg).catch(() => {});
2139
2340
  configureMirror(globalCfg);
2140
2341
  configureProxy(globalCfg);
@@ -2239,9 +2440,21 @@ async function startWebServerInstance({
2239
2440
 
2240
2441
  // 填完 AppID / AppSecret 顺手把「默认机器人」换成官方昵称
2241
2442
  const name = await syncBotName(rt);
2443
+ if (credentialsChanged) {
2444
+ /**
2445
+ * 凭证换了必须即时吊销旧凭证换来的会话——只清浏览器 Cookie 不够,
2446
+ * 偷到 sid 的人还能继续用。sessions 只存内存,清掉即全部失效。
2447
+ * 前端收到 credentialsChanged 后跳登录页,用户用新密码重登。
2448
+ */
2449
+ sessions.clear();
2450
+ log.warn('面板凭证已更新:旧密钥/密码立即失效,所有会话已吊销,请用新凭证重新登录');
2451
+ }
2242
2452
  return json(res, 200, {
2243
2453
  ok: true,
2244
2454
  name: name ?? rt.name,
2455
+ ...(credentialsChanged
2456
+ ? { credentialsChanged: true, message: '凭证已更新,旧凭证立即失效,请用新凭证重新登录' }
2457
+ : {}),
2245
2458
  // 换了连接方式必须重启才生效,明确告诉前端,别让用户以为已经切了
2246
2459
  ...(connectionChanged
2247
2460
  ? {
@@ -2256,6 +2469,27 @@ async function startWebServerInstance({
2256
2469
  });
2257
2470
  }
2258
2471
 
2472
+ /**
2473
+ * 恢复默认设置(只设置,不动 data/)。给 dsh-roost 面板的支持弹窗用:
2474
+ * 它自己不写框架配置,而是带面板密钥调这里,避免跨进程抢同一份状态。
2475
+ *
2476
+ * 二次确认放在服务端也做一遍——前端按钮只是一层 UI,裸调接口不该生效。
2477
+ * 成功后的配置由 config-watch 在 ~3s 内热加载;端口不会重新 bind,
2478
+ * 所以 webui.host/port 是保留项(见 config-reset.js)。
2479
+ */
2480
+ if (pathname === '/api/config/reset' && req.method === 'POST') {
2481
+ const body = await readBody(req);
2482
+ if (body?.confirm !== RESET_CONFIRM) {
2483
+ return json(res, 400, { ok: false, error: `需要 confirm: "${RESET_CONFIRM}"` });
2484
+ }
2485
+ try {
2486
+ const r = await resetFrameworkConfigs({ confirm: body.confirm });
2487
+ return json(res, r.ok ? 200 : 500, r);
2488
+ } catch (e) {
2489
+ return json(res, 500, { ok: false, error: `恢复默认失败:${e?.message || e}` });
2490
+ }
2491
+ }
2492
+
2259
2493
  // 插件
2260
2494
  if (pathname === '/api/plugins' && req.method === 'GET') {
2261
2495
  /**
@@ -5093,7 +5327,7 @@ async function startWebServerInstance({
5093
5327
 
5094
5328
  log.info(`可视化面板: ${baseUrl}`);
5095
5329
  if (accessKey) {
5096
- log.info('面板已开启访问密钥:浏览器会自动带上;手动访问时在地址后加 ?key=<你的密钥>(日志里不打印)');
5330
+ log.info('面板已开启访问密钥:打开面板后在登录页输入密钥即可(密钥只在 POST body 里传,不进网址/日志);程序化调用仍可用 X-Access-Key 头或 ?key=');
5097
5331
  }
5098
5332
 
5099
5333
  let closed = false;
package/start.bat ADDED
@@ -0,0 +1,61 @@
1
+ @echo off
2
+ chcp 65001 >nul
3
+ setlocal
4
+ cd /d "%~dp0"
5
+ title 栖 Roost
6
+
7
+ rem ============================================================
8
+ rem 找 node,按优先级:
9
+ rem 1. 系统 PATH
10
+ rem 2. 环境变量 NODE_EXE
11
+ rem 3. 同目录 node-path.txt(本机临时指定,删掉即恢复默认)
12
+ rem 4. 同目录 node\node.exe(便携版)
13
+ rem ============================================================
14
+ set "NODE_CMD="
15
+ for %%p in (node.exe) do if not defined NODE_CMD if not "%%~$PATH:p"=="" set "NODE_CMD=%%~$PATH:p"
16
+ if not defined NODE_CMD if defined NODE_EXE if exist "%NODE_EXE%" set "NODE_CMD=%NODE_EXE%"
17
+ if not defined NODE_CMD if exist "%~dp0node-path.txt" for /f "usebackq delims=" %%p in ("%~dp0node-path.txt") do if not defined NODE_CMD set "NODE_CMD=%%p"
18
+ if not defined NODE_CMD if exist "%~dp0node\node.exe" set "NODE_CMD=%~dp0node\node.exe"
19
+ if not defined NODE_CMD goto :no_node
20
+
21
+ rem ---- 版本检查交给 node 自己算,避免在批处理里解析版本号 ----
22
+ "%NODE_CMD%" -e "process.exit(Number(process.versions.node.split('.')[0]) >= 22 ? 0 : 1)"
23
+ if errorlevel 1 goto :old_node
24
+
25
+ rem ---- 启动 ----
26
+ "%NODE_CMD%" src/main.js %*
27
+ set "CODE=%ERRORLEVEL%"
28
+
29
+ if not "%CODE%"=="0" (
30
+ echo.
31
+ echo 程序异常退出,代码 %CODE%
32
+ echo 排查日志: logs\bot.log
33
+ )
34
+
35
+ pause
36
+ exit /b %CODE%
37
+
38
+ :no_node
39
+ echo.
40
+ echo [错误] 没有找到 Node.js
41
+ echo.
42
+ echo 本项目需要 Node.js 22 或更高版本,它不是能免安装运行的独立程序。
43
+ echo 请去 https://nodejs.org/ 下载 LTS 版本安装,安装时勾选 Add to PATH,
44
+ echo 装完关掉这个窗口重新双击 start.bat。
45
+ echo.
46
+ echo 如果已经装了但不在 PATH 里,可以在本目录建一个 node-path.txt,
47
+ echo 里面写一行 node.exe 的完整路径,例如:
48
+ echo C:\Program Files\nodejs\node.exe
49
+ echo.
50
+ pause
51
+ exit /b 1
52
+
53
+ :old_node
54
+ echo.
55
+ echo [错误] Node.js 版本太低
56
+ echo 当前使用的 node: %NODE_CMD%
57
+ "%NODE_CMD%" -v
58
+ echo 需要 22 或更高,请去 https://nodejs.org/ 装一个 LTS 版本。
59
+ echo.
60
+ pause
61
+ exit /b 1
package/web/app.js CHANGED
@@ -43,6 +43,17 @@ async function api(path, opts = {}) {
43
43
  err.status = res.status;
44
44
  throw err;
45
45
  }
46
+ /**
47
+ * 凭证(accessKey / loginPassword)刚被改过:服务端已即时吊销旧凭证和所有
48
+ * 会话,当前页面接下来每个请求都会 401。在这里直接跳登录页,别让用户对着
49
+ * 一片「访问密钥无效」猜发生了什么。
50
+ */
51
+ if (data?.credentialsChanged) {
52
+ const msg = data.message || '凭证已更新,请用新凭证重新登录';
53
+ try { sessionStorage.setItem('roostLoginNotice', msg); } catch { /* 隐私模式下忽略 */ }
54
+ location.reload();
55
+ return data;
56
+ }
46
57
  return data;
47
58
  }
48
59
 
@@ -1543,6 +1554,64 @@ window.addEventListener('hashchange', () => {
1543
1554
 
1544
1555
  /* ---------------- 概览 ---------------- */
1545
1556
 
1557
+ /** 宿主协议状态:概览卡与「外接」页的实时行共用同一份 status 快照 */
1558
+ const HOST_STATE_TEXT = {
1559
+ running: '运行中',
1560
+ disabled: '未开启',
1561
+ stopped: '已停止',
1562
+ 'missing-deps': '缺依赖',
1563
+ error: '启动失败',
1564
+ };
1565
+
1566
+ function hostStatusTone(state) {
1567
+ if (state === 'running') return 'var(--ok)';
1568
+ if (state === 'error' || state === 'missing-deps') return 'var(--err)';
1569
+ return 'var(--warn)';
1570
+ }
1571
+
1572
+ function hostDot(color) {
1573
+ return '<span style="display:inline-block;width:8px;height:8px;border-radius:50%;'
1574
+ + `background:${color};margin-right:6px;vertical-align:middle"></span>`;
1575
+ }
1576
+
1577
+ function renderHostOverview(host) {
1578
+ const el = $('#c-host');
1579
+ if (!el) return;
1580
+ const state = host?.state ?? 'disabled';
1581
+ const label = HOST_STATE_TEXT[state] ?? state;
1582
+ const detail = state === 'running'
1583
+ ? `${label} · ${Number(host?.connections ?? 0)} 连接`
1584
+ : label;
1585
+ el.innerHTML = hostDot(hostStatusTone(state)) + escapeHtml(detail);
1586
+ el.title = state === 'running'
1587
+ ? `实际监听 ${host?.host ?? '127.0.0.1'}:${host?.port ?? 0}` +
1588
+ ` · seq ${host?.seq ?? 0} · 点击查看`
1589
+ : escapeHtml(host?.error || '点击查看外接协议');
1590
+ el.onclick = () => { location.hash = 'onebot'; };
1591
+ }
1592
+
1593
+ function renderHostLive(host) {
1594
+ const el = $('#hostLiveStatus');
1595
+ if (!el || !host) return;
1596
+ const state = host.state ?? 'disabled';
1597
+ const label = HOST_STATE_TEXT[state] ?? state;
1598
+ const tr = host.transports ?? {};
1599
+ const channels = [tr.ws ? 'WS' : null, tr.sse ? 'SSE' : null, tr.http ? 'HTTP' : null]
1600
+ .filter(Boolean).join('/') || '—';
1601
+ const text = state === 'running'
1602
+ ? `${label} · ${host.host ?? '127.0.0.1'}:${host.port ?? 0}` +
1603
+ ` · ${Number(host.connections ?? 0)} 个连接 · ${channels} · seq ${host.seq ?? 0}`
1604
+ : label;
1605
+ el.innerHTML = hostDot(hostStatusTone(state)) + escapeHtml(text)
1606
+ + (host.error ? `<div style="color:var(--err);margin-top:4px">${escapeHtml(host.error)}</div>` : '');
1607
+ const hint = $('#hostStateHint');
1608
+ if (hint) {
1609
+ hint.textContent = state === 'running'
1610
+ ? `实时:${label} · ${host.port ?? 0} · ${Number(host.connections ?? 0)} 连接`
1611
+ : `实时:${label}`;
1612
+ }
1613
+ }
1614
+
1546
1615
  function renderStatus(s) {
1547
1616
  // 迟到的别的机器人的状态包,直接丢掉
1548
1617
  if (s && s.botId && CURRENT_BOT && s.botId !== CURRENT_BOT) return;
@@ -1573,6 +1642,9 @@ function renderStatus(s) {
1573
1642
  $('#botName').textContent = online ? s.botName || '已连接' : '未连接';
1574
1643
 
1575
1644
  $('#c-conn').textContent = online ? '在线' : state === 'error' ? '连接失败' : '离线';
1645
+ /** 外接协议状态跟着同一份 5 秒 status 走,概览卡和外接页实时行一起刷 */
1646
+ renderHostOverview(s.host);
1647
+ renderHostLive(s.host);
1576
1648
  $('#c-uptime').textContent = fmtDuration(s.uptimeMs);
1577
1649
  $('#c-cred').textContent = s.credentialExpiresIn
1578
1650
  ? `${Math.floor(s.credentialExpiresIn / 60)} 分`
@@ -1980,9 +2052,13 @@ function fillForm(c) {
1980
2052
 
1981
2053
  f.webuiHost.value = c.webui?.host || '127.0.0.1';
1982
2054
  f.webuiPort.value = c.webui?.port ?? 15207;
1983
- // 密钥不回显(后端只返回 accessKeySet):留空 = 不修改
2055
+ // 两把钥匙都不回显(后端只返回 *Set):留空 = 不修改
1984
2056
  f.webuiAccessKey.value = '';
1985
2057
  f.webuiAccessKey.placeholder = c.webui?.accessKeySet ? '已设置(留空则保持不变)' : '未设置';
2058
+ if (f.webuiLoginPassword) {
2059
+ f.webuiLoginPassword.value = '';
2060
+ f.webuiLoginPassword.placeholder = c.webui?.loginPasswordSet ? '已设置(留空则保持不变)' : '未设置';
2061
+ }
1986
2062
  f.logLevel.value = c.logLevel || 'info';
1987
2063
 
1988
2064
  f.groupInvited.checked = Boolean(c.groupManage?.invited);
@@ -2457,6 +2533,7 @@ function collectAutoPayload(f) {
2457
2533
  host: f.webuiHost.value.trim() || '127.0.0.1',
2458
2534
  port: Number(f.webuiPort.value) || 15207,
2459
2535
  accessKey: f.webuiAccessKey.value.trim(),
2536
+ ...(f.webuiLoginPassword?.value.trim() ? { loginPassword: f.webuiLoginPassword.value.trim() } : {}),
2460
2537
  },
2461
2538
  groupManage: { invited: f.groupInvited.checked },
2462
2539
  media: { placeholderSpace: f.mediaPlaceholderSpace.checked },
@@ -2558,6 +2635,7 @@ async function saveCfgForm({ fromQr = false } = {}) {
2558
2635
  host: f.webuiHost.value.trim() || '127.0.0.1',
2559
2636
  port: Number(f.webuiPort.value) || 15207,
2560
2637
  accessKey: f.webuiAccessKey.value.trim(),
2638
+ ...(f.webuiLoginPassword?.value.trim() ? { loginPassword: f.webuiLoginPassword.value.trim() } : {}),
2561
2639
  },
2562
2640
  groupManage: {
2563
2641
  invited: f.groupInvited.checked,
@@ -2789,11 +2867,15 @@ function bindSetup() {
2789
2867
  // 保存访问方式(webui 全局配置,增量提交;重启才生效)
2790
2868
  $('#setupNetSave')?.addEventListener('click', async () => {
2791
2869
  const key = $('#setupAccessKey')?.value.trim() || '';
2870
+ const loginPass = $('#setupLoginPassword')?.value.trim() || '';
2792
2871
  const host = $('#setupHost')?.value.trim() || '0.0.0.0';
2793
2872
  const port = Number($('#setupPort')?.value) || 15207;
2794
2873
  const err = $('#setupErr');
2795
- if (!key) {
2796
- if (err) { err.textContent = '对外服务必须设置访问密钥'; err.hidden = false; }
2874
+ if (!key || !loginPass) {
2875
+ if (err) {
2876
+ err.textContent = '对外服务要设两把钥匙:登录密码(给人用)和机器密钥(给脚本用),缺一不可';
2877
+ err.hidden = false;
2878
+ }
2797
2879
  return;
2798
2880
  }
2799
2881
  const btn = $('#setupNetSave');
@@ -2802,15 +2884,17 @@ function bindSetup() {
2802
2884
  try {
2803
2885
  await api('/api/config', {
2804
2886
  method: 'PUT',
2805
- body: JSON.stringify({ webui: { host, port, accessKey: key } }),
2887
+ body: JSON.stringify({ webui: { host, port, accessKey: key, loginPassword: loginPass } }),
2806
2888
  });
2807
2889
  if (err) {
2808
- err.textContent = '已保存。重启框架后生效:用局域网 / 公网地址加 ?key=你的密钥 访问面板。';
2890
+ err.textContent = '已保存。重启框架后生效:用局域网 / 公网地址打开面板,在登录页输入登录密码。';
2809
2891
  err.hidden = false;
2810
2892
  err.classList.add('setup-ok');
2811
2893
  }
2812
2894
  const access = $('#setupAccessKey');
2813
2895
  if (access) access.value = '';
2896
+ const passInput = $('#setupLoginPassword');
2897
+ if (passInput) passInput.value = '';
2814
2898
  } catch (e) {
2815
2899
  if (err) { err.textContent = '保存失败:' + errText(e); err.hidden = false; }
2816
2900
  } finally {
@@ -6584,14 +6668,6 @@ async function loadOnebot() {
6584
6668
  }
6585
6669
  }
6586
6670
 
6587
- const HOST_STATE_TEXT = {
6588
- running: '运行中',
6589
- disabled: '未开启',
6590
- stopped: '已停止',
6591
- 'missing-deps': '缺依赖',
6592
- error: '启动失败',
6593
- };
6594
-
6595
6671
  /** 宿主协议那半边:配置表单 + 运行状态 + 方法表 */
6596
6672
  function renderHost(d) {
6597
6673
  const cfg = d?.cfg ?? {};
@@ -6670,9 +6746,12 @@ function renderHost(d) {
6670
6746
  ? '<div class="hint" style="margin-top:6px;color:var(--err)"><b>机器人本体没上线</b>:' +
6671
6747
  '客户端能连上,但发消息、调官方接口会失败——先到「运行」页让它上线</div>'
6672
6748
  : '');
6673
- } else if (st.state === 'missing-deps' || st.state === 'error') {
6674
- hint.innerHTML = `<b>${escapeHtml(st.error || '没起来')}</b>` +
6675
- '。缺依赖就到下面「依赖」卡装,装完会自动重连。';
6749
+ } else if (st.state === 'missing-deps') {
6750
+ hint.innerHTML = `<b>${escapeHtml(st.error || '缺依赖')}</b>` +
6751
+ '。到下面「依赖」卡装,装完会自动重连。';
6752
+ } else if (st.state === 'error') {
6753
+ /** 端口被系统保留 / 被占都不是缺依赖,别再一律让用户去装依赖 */
6754
+ hint.innerHTML = `<b>${escapeHtml(st.error || '没起来')}</b>`;
6676
6755
  } else {
6677
6756
  hint.textContent = '开启后这里会显示连接串和运行状态。';
6678
6757
  }