dsh-message-gateway 0.1.2 → 0.1.4

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/lib/index.js CHANGED
@@ -489,23 +489,98 @@ var DiscordBridge = class {
489
489
  };
490
490
 
491
491
  // src/host/qq-bridge.ts
492
- var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
492
+ import { createPrivateKey, sign, verify } from "node:crypto";
493
+ var TOKEN_URL = "https://api.bot.qq.com/app/getAppAccessToken";
493
494
  var BASE = "https://api.bot.qq.com";
494
495
  var INTENTS2 = 1 << 25;
495
496
  var DEDUP_CAP = 64;
497
+ function qqEd25519Key(secret) {
498
+ let seed = secret;
499
+ while (Buffer.byteLength(seed) < 32) seed += seed;
500
+ const seedBuf = Buffer.from(seed, "utf8").subarray(0, 32);
501
+ const inner = Buffer.concat([Buffer.from([4, 32]), seedBuf]);
502
+ const wrapped = Buffer.concat([Buffer.from([4, inner.length]), inner]);
503
+ const alg = Buffer.from([48, 5, 6, 3, 43, 101, 112]);
504
+ const ver = Buffer.from([2, 1, 0]);
505
+ const body = Buffer.concat([ver, alg, wrapped]);
506
+ const der = Buffer.concat([Buffer.from([48, body.length]), body]);
507
+ return createPrivateKey({ key: der, format: "der", type: "pkcs8" });
508
+ }
509
+ var QqMessageSender = class {
510
+ constructor(rest) {
511
+ this.rest = rest;
512
+ }
513
+ c2cStreams = /* @__PURE__ */ new Map();
514
+ sent = /* @__PURE__ */ new Set();
515
+ /** 发送一帧;finish=false 为中间帧(单聊流式推进,群聊忽略),finish=true 定稿。 */
516
+ async send(frame, streamId, content, finish) {
517
+ if (frame.scene === "c2c") {
518
+ await this.streamC2c(frame, streamId, content, finish);
519
+ } else if (finish) {
520
+ await this.sendGroupOnce(frame, streamId, content);
521
+ }
522
+ }
523
+ async streamC2c(frame, streamId, content, finish) {
524
+ if (this.sent.has(streamId)) return;
525
+ const state = this.c2cStreams.get(streamId) ?? { index: 0, streamMsgId: "" };
526
+ const text = content.trim() === "" ? "\u2026" : content.slice(0, 2e3);
527
+ const body = {
528
+ input_mode: "replace",
529
+ input_state: finish ? 10 : 1,
530
+ index: state.index,
531
+ content_type: "markdown",
532
+ content_raw: text,
533
+ msg_id: frame.msgId,
534
+ msg_seq: 1
535
+ };
536
+ if (state.streamMsgId !== "") body.stream_msg_id = state.streamMsgId;
537
+ const result = await this.rest(
538
+ "POST",
539
+ `/v2/users/${encodeURIComponent(frame.openid)}/stream_messages`,
540
+ body
541
+ );
542
+ if (result?.id !== void 0) {
543
+ state.streamMsgId = result.id;
544
+ state.index += 1;
545
+ this.c2cStreams.set(streamId, state);
546
+ if (finish) this.sent.add(streamId);
547
+ } else {
548
+ this.c2cStreams.delete(streamId);
549
+ if (finish) this.sent.add(streamId);
550
+ }
551
+ }
552
+ async sendGroupOnce(frame, streamId, content) {
553
+ if (this.sent.has(streamId)) return;
554
+ this.sent.add(streamId);
555
+ const text = content.trim() === "" ? "\uFF08\u7A7A\u56DE\u590D\uFF09" : content.slice(0, 2e3);
556
+ const result = await this.rest(
557
+ "POST",
558
+ `/v2/groups/${encodeURIComponent(frame.openid)}/messages`,
559
+ { content: text, msg_type: 0, msg_id: frame.msgId }
560
+ );
561
+ if (result === null) this.sent.delete(streamId);
562
+ }
563
+ clear() {
564
+ this.c2cStreams.clear();
565
+ this.sent.clear();
566
+ }
567
+ };
496
568
  var QQBridge = class {
497
569
  constructor(appId, secret, callbacks) {
498
570
  this.appId = appId;
499
571
  this.secret = secret;
500
572
  this.callbacks = callbacks;
573
+ this.sender = new QqMessageSender((method, path, body) => this.rest(method, path, body));
501
574
  }
502
575
  ws = null;
503
576
  stopped = false;
504
577
  heartbeat = null;
505
578
  seq = null;
506
579
  accessToken = null;
507
- /** streamId → 已发出(单条定稿消息,防重复发送)。 */
508
- sent = /* @__PURE__ */ new Set();
580
+ /** access_token 过期时间戳(官方 ≤7200s;实测可能更短,提前 60s 刷新)。 */
581
+ tokenExpiresAt = 0;
582
+ /** 单聊流式/群聊定稿发送器。 */
583
+ sender;
509
584
  recentMsgIds = /* @__PURE__ */ new Set();
510
585
  status = { state: "idle", detail: "", connectedAt: null };
511
586
  setStatus(state, detail = "") {
@@ -523,7 +598,6 @@ var QQBridge = class {
523
598
  this.setStatus("error", "access token failed");
524
599
  return;
525
600
  }
526
- this.accessToken = token;
527
601
  this.setStatus("connecting", "gateway");
528
602
  const url = await this.getGatewayUrl();
529
603
  if (this.stopped) return;
@@ -546,6 +620,8 @@ var QQBridge = class {
546
620
  });
547
621
  const body = await response.json();
548
622
  if (response.ok && body.access_token !== void 0 && body.access_token !== "") {
623
+ this.accessToken = body.access_token;
624
+ this.tokenExpiresAt = Date.now() + (body.expires_in ?? 7200) * 1e3;
549
625
  return body.access_token;
550
626
  }
551
627
  console.warn("[dsh-message-gateway] qq access token failed", response.status, body.message ?? body.code);
@@ -557,6 +633,12 @@ var QQBridge = class {
557
633
  clearTimeout(timer);
558
634
  }
559
635
  }
636
+ /** 确保 access_token 未过期(提前 60s 刷新),供 REST/重连使用。 */
637
+ async ensureToken() {
638
+ if (this.accessToken !== null && Date.now() < this.tokenExpiresAt - 6e4) return true;
639
+ const token = await this.getAccessToken();
640
+ return token !== null;
641
+ }
560
642
  /** 获取通用 WSS 接入点(官方推荐先调接口拿地址,避免写死)。 */
561
643
  async getGatewayUrl() {
562
644
  const controller = new AbortController();
@@ -602,7 +684,9 @@ var QQBridge = class {
602
684
  console.warn("[dsh-message-gateway] qq gateway closed, reconnect in 3s");
603
685
  setTimeout(() => {
604
686
  if (this.stopped) return;
605
- void this.getGatewayUrl().then((u) => {
687
+ void this.ensureToken().then(async (ok) => {
688
+ if (this.stopped || !ok) return;
689
+ const u = await this.getGatewayUrl();
606
690
  if (this.stopped || u === null) return;
607
691
  this.connect(u);
608
692
  });
@@ -676,6 +760,7 @@ var QQBridge = class {
676
760
  }
677
761
  }
678
762
  async rest(method, path, body) {
763
+ if (!await this.ensureToken()) return null;
679
764
  const controller = new AbortController();
680
765
  const timer = setTimeout(() => controller.abort(), 15e3);
681
766
  try {
@@ -719,10 +804,10 @@ var QQBridge = class {
719
804
  if (openid === "") return;
720
805
  const frame = { openid, msgId, scene };
721
806
  const sink = {
722
- // 单聊/群聊回复不支持就地编辑(群聊明确不支持流式),ack 关闭:
723
- // 只发一条最终消息,避免「正在处理… + 回复」两条。
807
+ // 单聊:流式(ack 开启,「正在处理…」就地增长);群聊:不支持流式,关闭 ack 只发定稿。
724
808
  ack: false,
725
- stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
809
+ // 单聊流式用 replace 全量正文,不能先发独立回执(前缀不一致会 40007);群聊本就不支持流式。
810
+ stream: (f, sid, content, finish) => void this.sender.send(f, sid, content, finish)
726
811
  };
727
812
  const identity = {
728
813
  key: scene === "c2c" ? `qq:c2c:${openid}` : `qq:group:${openid}`,
@@ -733,21 +818,11 @@ var QQBridge = class {
733
818
  console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
734
819
  this.callbacks.onText(text, identity);
735
820
  }
736
- /** 回复:finish 时一次发出(带 msg_id 被动回复;幂等防重发)。 */
737
- async streamReply(frame, streamId, content, finish) {
738
- if (!finish) return;
739
- if (this.sent.has(streamId)) return;
740
- this.sent.add(streamId);
741
- const text = content.trim() === "" ? "\uFF08\u7A7A\u56DE\u590D\uFF09" : content.slice(0, 2e3);
742
- const path = frame.scene === "c2c" ? `/v2/users/${encodeURIComponent(frame.openid)}/messages` : `/v2/groups/${encodeURIComponent(frame.openid)}/messages`;
743
- const result = await this.rest("POST", path, { content: text, msg_type: 0, msg_id: frame.msgId });
744
- if (result === null) this.sent.delete(streamId);
745
- }
746
821
  /** 停止网关连接。 */
747
822
  stop() {
748
823
  this.stopped = true;
749
824
  this.clearHeartbeat();
750
- this.sent.clear();
825
+ this.sender.clear();
751
826
  this.recentMsgIds.clear();
752
827
  this.ws?.close();
753
828
  this.ws = null;
@@ -755,6 +830,128 @@ var QQBridge = class {
755
830
  this.setStatus("idle");
756
831
  }
757
832
  };
833
+ var QqWebhookBridge = class {
834
+ constructor(appId, secret, callbackToken, callbacks) {
835
+ this.appId = appId;
836
+ this.secret = secret;
837
+ this.callbackToken = callbackToken;
838
+ this.callbacks = callbacks;
839
+ this.key = qqEd25519Key(callbackToken);
840
+ this.sender = new QqMessageSender((method, path, body) => this.rest(method, path, body));
841
+ }
842
+ key;
843
+ sender;
844
+ accessToken = null;
845
+ tokenExpiresAt = 0;
846
+ recentMsgIds = /* @__PURE__ */ new Set();
847
+ /** op 13 回调地址验证握手 → { plain_token, signature }(供控制台校验通过)。 */
848
+ validate(d) {
849
+ const plainToken = typeof d.plain_token === "string" ? d.plain_token : "";
850
+ const eventTs = typeof d.event_ts === "string" ? d.event_ts : "";
851
+ if (plainToken === "" || eventTs === "") return null;
852
+ const signature = sign(null, Buffer.from(eventTs + plainToken, "utf8"), this.key).toString("hex");
853
+ return { plain_token: plainToken, signature };
854
+ }
855
+ /** 事件签名验证:X-Signature-Timestamp + 原始 body,ed25519 校验。 */
856
+ verifySignature(rawBody, sigHex, timestamp) {
857
+ if (sigHex === "" || timestamp === "") return false;
858
+ let sig;
859
+ try {
860
+ sig = Buffer.from(sigHex, "hex");
861
+ } catch {
862
+ return false;
863
+ }
864
+ if (sig.length !== 64) return false;
865
+ const msg = Buffer.concat([Buffer.from(timestamp, "utf8"), Buffer.from(rawBody, "utf8")]);
866
+ return verify(null, msg, this.key, sig);
867
+ }
868
+ /** 事件分发(payload { t, d });返回是否已消费(非本桥事件返回 false)。 */
869
+ handleEvent(payload) {
870
+ const t = typeof payload.t === "string" ? payload.t : "";
871
+ let scene = null;
872
+ if (t === "C2C_MESSAGE_CREATE") scene = "c2c";
873
+ else if (t === "GROUP_AT_MESSAGE_CREATE") scene = "group";
874
+ if (scene === null) return false;
875
+ const d = payload.d ?? {};
876
+ const author = d.author;
877
+ if (author?.bot === true) return true;
878
+ const text = typeof d.content === "string" ? d.content.trim() : "";
879
+ const msgId = String(d.id ?? "");
880
+ if (text === "" || msgId === "") return true;
881
+ if (this.recentMsgIds.has(msgId)) return true;
882
+ this.recentMsgIds.add(msgId);
883
+ if (this.recentMsgIds.size > DEDUP_CAP) {
884
+ const first = this.recentMsgIds.values().next().value;
885
+ if (first !== void 0) this.recentMsgIds.delete(first);
886
+ }
887
+ const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
888
+ if (openid === "") return true;
889
+ const frame = { openid, msgId, scene };
890
+ const sink = {
891
+ // 单聊:流式(ack 开启);群聊:只发定稿。
892
+ ack: false,
893
+ // 单聊流式用 replace 全量正文,不能先发独立回执(前缀不一致会 40007);群聊本就不支持流式。
894
+ stream: (f, sid, content, finish) => void this.sender.send(f, sid, content, finish)
895
+ };
896
+ const identity = {
897
+ key: scene === "c2c" ? `qq:c2c:${openid}` : `qq:group:${openid}`,
898
+ frame,
899
+ sink,
900
+ chatType: scene === "c2c" ? "single" : "group"
901
+ };
902
+ console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: text.slice(0, 60) });
903
+ this.callbacks.onText(text, identity);
904
+ return true;
905
+ }
906
+ /** 确保 access_token 未过期(提前 60s 刷新)。 */
907
+ async ensureToken() {
908
+ if (this.accessToken !== null && Date.now() < this.tokenExpiresAt - 6e4) return true;
909
+ const controller = new AbortController();
910
+ const timer = setTimeout(() => controller.abort(), 15e3);
911
+ try {
912
+ const response = await fetch(TOKEN_URL, {
913
+ method: "POST",
914
+ headers: { "content-type": "application/json" },
915
+ body: JSON.stringify({ appId: this.appId, clientSecret: this.secret }),
916
+ signal: controller.signal
917
+ });
918
+ const body = await response.json();
919
+ if (response.ok && body.access_token !== void 0 && body.access_token !== "") {
920
+ this.accessToken = body.access_token;
921
+ this.tokenExpiresAt = Date.now() + (body.expires_in ?? 7200) * 1e3;
922
+ return true;
923
+ }
924
+ console.warn("[dsh-message-gateway] qq webhook token failed", response.status);
925
+ return false;
926
+ } catch (error) {
927
+ console.warn("[dsh-message-gateway] qq webhook token error", String(error));
928
+ return false;
929
+ } finally {
930
+ clearTimeout(timer);
931
+ }
932
+ }
933
+ /** 发送器用的 rest:先确保 token,再打 /v2 接口。 */
934
+ async rest(method, path, body) {
935
+ if (!await this.ensureToken()) return null;
936
+ try {
937
+ const response = await fetch(`${BASE}${path}`, {
938
+ method,
939
+ headers: { authorization: `QQBot ${this.accessToken ?? ""}`, "content-type": "application/json" },
940
+ body: body === void 0 ? void 0 : JSON.stringify(body),
941
+ signal: AbortSignal.timeout(15e3)
942
+ });
943
+ if (!response.ok) {
944
+ const err = (await response.text()).slice(0, 120);
945
+ console.warn("[dsh-message-gateway] qq webhook rest", method, path, response.status, err);
946
+ return null;
947
+ }
948
+ return await response.json();
949
+ } catch (error) {
950
+ console.warn("[dsh-message-gateway] qq webhook rest failed", method, path, String(error));
951
+ return null;
952
+ }
953
+ }
954
+ };
758
955
 
759
956
  // src/host/email-bridge.ts
760
957
  import { connect } from "node:net";
@@ -1837,9 +2034,11 @@ var PLATFORMS = [
1837
2034
  nameKey: "platform.qq",
1838
2035
  icon: "\u{1F4AC}",
1839
2036
  testable: true,
2037
+ hintKey: "platform.qq.hint",
1840
2038
  fields: [
1841
2039
  { key: "appId", labelKey: "field.appId", kind: "text" },
1842
- { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" }
2040
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" },
2041
+ { key: "callbackToken", labelKey: "field.qqCallbackToken", placeholderKey: "field.secret.ph", kind: "secret" }
1843
2042
  ]
1844
2043
  },
1845
2044
  {
@@ -2321,7 +2520,8 @@ var BODY_CAP_BYTES = 1 << 20;
2321
2520
  var CALLBACK_PATHS = {
2322
2521
  wecom: "/gateway/wecom/callback",
2323
2522
  "wechat-mp": "/gateway/wechat-mp/callback",
2324
- whatsapp: "/gateway/whatsapp/webhook"
2523
+ whatsapp: "/gateway/whatsapp/webhook",
2524
+ qq: "/gateway/qq/callback"
2325
2525
  };
2326
2526
  async function readJsonBody(req) {
2327
2527
  const chunks = [];
@@ -2500,6 +2700,37 @@ async function handleCallbackRoute(req, res, path, query, manager) {
2500
2700
  json(res, { ok: true, value: null });
2501
2701
  return;
2502
2702
  }
2703
+ if (path === "/gateway/qq/callback") {
2704
+ const cred = store.platforms.qq;
2705
+ if (cred === void 0 || cred.callbackToken === "") {
2706
+ json(res, { ok: false, error: { code: "internal", message: "qq callback not configured" } }, 400);
2707
+ return;
2708
+ }
2709
+ const bridge = new QqWebhookBridge(cred.appId ?? "", cred.secret ?? "", cred.callbackToken, {
2710
+ onText: (text, identity) => void manager.handleExternalMessage(identity, text)
2711
+ });
2712
+ const { raw, json: payload } = await readJsonBody(req);
2713
+ const body = payload ?? {};
2714
+ if (body.op === 13) {
2715
+ const validated = bridge.validate(body.d ?? {});
2716
+ if (validated === null) {
2717
+ json(res, { ok: false, error: { code: "internal", message: "bad validation payload" } }, 400);
2718
+ return;
2719
+ }
2720
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
2721
+ res.end(JSON.stringify(validated));
2722
+ return;
2723
+ }
2724
+ const signature = req.headers["x-signature-ed25519"];
2725
+ const timestamp = req.headers["x-signature-timestamp"];
2726
+ if (typeof signature !== "string" || typeof timestamp !== "string" || !bridge.verifySignature(raw, signature, timestamp)) {
2727
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2728
+ return;
2729
+ }
2730
+ bridge.handleEvent(body);
2731
+ json(res, { ok: true, value: null });
2732
+ return;
2733
+ }
2503
2734
  json(res, { ok: false, error: { code: "internal", message: "unknown callback route" } }, 404);
2504
2735
  } catch (error) {
2505
2736
  const message = error instanceof Error ? error.message : String(error);
@@ -2526,7 +2757,7 @@ function registerGatewayRoutes(ctx, manager) {
2526
2757
  handler: async (req, res) => {
2527
2758
  const url = new URL(req.url ?? "/", "http://dsh");
2528
2759
  const path = url.pathname;
2529
- if (path === "/gateway/wecom/callback" || path === "/gateway/wechat-mp/callback" || path === "/gateway/whatsapp/webhook") {
2760
+ if (path === "/gateway/wecom/callback" || path === "/gateway/wechat-mp/callback" || path === "/gateway/whatsapp/webhook" || path === "/gateway/qq/callback") {
2530
2761
  await handleCallbackRoute(req, res, path, url.searchParams, manager);
2531
2762
  return;
2532
2763
  }
@@ -2773,6 +3004,7 @@ export {
2773
3004
  ImapClient,
2774
3005
  PLATFORMS,
2775
3006
  QQBridge,
3007
+ QqWebhookBridge,
2776
3008
  SmtpClient,
2777
3009
  TelegramBridge,
2778
3010
  WechatMpBridge,