dsh-message-gateway 0.1.1 → 0.1.3

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,12 +489,23 @@ var DiscordBridge = class {
489
489
  };
490
490
 
491
491
  // src/host/qq-bridge.ts
492
- var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
493
- var REST2 = "https://api.sgroup.qq.com";
494
- var GATEWAY = "wss://api.sgroup.qq.com/?v=1&encoding=json";
495
- var INTENTS2 = 1 << 9 | 1 << 12 | 1 << 30;
496
- var EDIT_INTERVAL_MS3 = 1200;
497
- var MSG_LIMIT3 = 2e3;
492
+ import { createPrivateKey, sign, verify } from "node:crypto";
493
+ var TOKEN_URL = "https://api.bot.qq.com/app/getAppAccessToken";
494
+ var BASE = "https://api.bot.qq.com";
495
+ var INTENTS2 = 1 << 25;
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
+ }
498
509
  var QQBridge = class {
499
510
  constructor(appId, secret, callbacks) {
500
511
  this.appId = appId;
@@ -506,30 +517,35 @@ var QQBridge = class {
506
517
  heartbeat = null;
507
518
  seq = null;
508
519
  accessToken = null;
509
- /** streamId → 已发送消息(用于渐进编辑)。 */
510
- streams = /* @__PURE__ */ new Map();
511
- /** streamId → 最新待推送内容(流式合并,单 worker 消费)。 */
512
- state = /* @__PURE__ */ new Map();
513
- working = /* @__PURE__ */ new Set();
520
+ /** access_token 过期时间戳(官方 ≤7200s;实测可能更短,提前 60s 刷新)。 */
521
+ tokenExpiresAt = 0;
522
+ /** streamId → 已发出(单条定稿消息,防重复发送)。 */
523
+ sent = /* @__PURE__ */ new Set();
524
+ recentMsgIds = /* @__PURE__ */ new Set();
514
525
  status = { state: "idle", detail: "", connectedAt: null };
515
526
  setStatus(state, detail = "") {
516
527
  this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
517
528
  this.callbacks.onStatus(this.status);
518
529
  }
519
- /** 启动:先取 access_token,再连网关。 */
530
+ /** 启动:先取 access_token,再取 WSS 接入点,最后连网关。 */
520
531
  start() {
521
532
  if (!this.stopped && this.ws !== null) return;
522
533
  this.stopped = false;
523
534
  this.setStatus("connecting", "access token");
524
- void this.getAccessToken().then((token) => {
535
+ void this.getAccessToken().then(async (token) => {
525
536
  if (this.stopped) return;
526
537
  if (token === null) {
527
538
  this.setStatus("error", "access token failed");
528
539
  return;
529
540
  }
530
- this.accessToken = token;
531
541
  this.setStatus("connecting", "gateway");
532
- this.connect();
542
+ const url = await this.getGatewayUrl();
543
+ if (this.stopped) return;
544
+ if (url === null) {
545
+ this.setStatus("error", "gateway url failed");
546
+ return;
547
+ }
548
+ this.connect(url);
533
549
  });
534
550
  }
535
551
  async getAccessToken() {
@@ -544,6 +560,8 @@ var QQBridge = class {
544
560
  });
545
561
  const body = await response.json();
546
562
  if (response.ok && body.access_token !== void 0 && body.access_token !== "") {
563
+ this.accessToken = body.access_token;
564
+ this.tokenExpiresAt = Date.now() + (body.expires_in ?? 7200) * 1e3;
547
565
  return body.access_token;
548
566
  }
549
567
  console.warn("[dsh-message-gateway] qq access token failed", response.status, body.message ?? body.code);
@@ -555,18 +573,48 @@ var QQBridge = class {
555
573
  clearTimeout(timer);
556
574
  }
557
575
  }
558
- connect() {
576
+ /** 确保 access_token 未过期(提前 60s 刷新),供 REST/重连使用。 */
577
+ async ensureToken() {
578
+ if (this.accessToken !== null && Date.now() < this.tokenExpiresAt - 6e4) return true;
579
+ const token = await this.getAccessToken();
580
+ return token !== null;
581
+ }
582
+ /** 获取通用 WSS 接入点(官方推荐先调接口拿地址,避免写死)。 */
583
+ async getGatewayUrl() {
584
+ const controller = new AbortController();
585
+ const timer = setTimeout(() => controller.abort(), 15e3);
586
+ try {
587
+ const response = await fetch(`${BASE}/gateway`, {
588
+ headers: { authorization: `QQBot ${this.accessToken ?? ""}` },
589
+ signal: controller.signal
590
+ });
591
+ if (!response.ok) {
592
+ console.warn("[dsh-message-gateway] qq gateway url", response.status);
593
+ return null;
594
+ }
595
+ const body = await response.json();
596
+ if (typeof body.url === "string" && body.url !== "") return body.url;
597
+ console.warn("[dsh-message-gateway] qq gateway url missing", JSON.stringify(body).slice(0, 120));
598
+ return null;
599
+ } catch (error) {
600
+ console.warn("[dsh-message-gateway] qq gateway url error", String(error));
601
+ return null;
602
+ } finally {
603
+ clearTimeout(timer);
604
+ }
605
+ }
606
+ connect(url) {
559
607
  if (this.stopped) return;
560
608
  let ws;
561
609
  try {
562
- ws = new WebSocket(GATEWAY);
610
+ ws = new WebSocket(url);
563
611
  } catch (error) {
564
612
  console.error("[dsh-message-gateway] qq ws create failed", error);
565
613
  this.setStatus("error", "ws create failed");
566
614
  return;
567
615
  }
568
616
  this.ws = ws;
569
- ws.onopen = () => console.log("[dsh-message-gateway] qq gateway open");
617
+ ws.onopen = () => console.log("[dsh-message-gateway] qq gateway open", url);
570
618
  ws.onmessage = (event) => this.onMessage(String(event.data));
571
619
  ws.onerror = () => console.warn("[dsh-message-gateway] qq gateway ws error");
572
620
  ws.onclose = () => {
@@ -574,7 +622,15 @@ var QQBridge = class {
574
622
  this.ws = null;
575
623
  if (!this.stopped) {
576
624
  console.warn("[dsh-message-gateway] qq gateway closed, reconnect in 3s");
577
- setTimeout(() => this.connect(), 3e3);
625
+ setTimeout(() => {
626
+ if (this.stopped) return;
627
+ void this.ensureToken().then(async (ok) => {
628
+ if (this.stopped || !ok) return;
629
+ const u = await this.getGatewayUrl();
630
+ if (this.stopped || u === null) return;
631
+ this.connect(u);
632
+ });
633
+ }, 3e3);
578
634
  }
579
635
  };
580
636
  }
@@ -601,15 +657,24 @@ var QQBridge = class {
601
657
  if (payload.t === "READY") {
602
658
  this.setStatus("connected", "qq");
603
659
  console.log("[dsh-message-gateway] qq READY");
604
- } else if (payload.t === "MESSAGE_CREATE" || payload.t === "DIRECT_MESSAGE_CREATE") {
605
- this.handleMessage(payload.d);
660
+ } else if (payload.t === "C2C_MESSAGE_CREATE") {
661
+ this.handleMessage(payload.d, "c2c");
662
+ } else if (payload.t === "GROUP_AT_MESSAGE_CREATE") {
663
+ this.handleMessage(payload.d, "group");
606
664
  }
607
665
  break;
608
666
  }
667
+ case 9: {
668
+ console.warn("[dsh-message-gateway] qq identify rejected (INVALID_SESSION) \u2014 \u8BF7\u786E\u8BA4\u63A7\u5236\u53F0\u4E8B\u4EF6\u8BA2\u9605\u4E3A WebSocket \u957F\u8FDE\u63A5");
669
+ this.ws?.close();
670
+ break;
671
+ }
609
672
  case 7: {
610
673
  this.ws?.close();
611
674
  break;
612
675
  }
676
+ case 11:
677
+ break;
613
678
  }
614
679
  }
615
680
  sendOp(op, d) {
@@ -618,7 +683,7 @@ var QQBridge = class {
618
683
  }
619
684
  identify() {
620
685
  this.sendOp(2, {
621
- token: this.accessToken,
686
+ token: `QQBot ${this.accessToken ?? ""}`,
622
687
  intents: INTENTS2,
623
688
  shard: [0, 1]
624
689
  });
@@ -635,20 +700,22 @@ var QQBridge = class {
635
700
  }
636
701
  }
637
702
  async rest(method, path, body) {
703
+ if (!await this.ensureToken()) return null;
638
704
  const controller = new AbortController();
639
705
  const timer = setTimeout(() => controller.abort(), 15e3);
640
706
  try {
641
- const response = await fetch(`${REST2}${path}`, {
707
+ const response = await fetch(`${BASE}${path}`, {
642
708
  method,
643
709
  headers: {
644
- authorization: `Bot ${this.accessToken ?? ""}`,
710
+ authorization: `QQBot ${this.accessToken ?? ""}`,
645
711
  "content-type": "application/json"
646
712
  },
647
713
  body: body === void 0 ? void 0 : JSON.stringify(body),
648
714
  signal: controller.signal
649
715
  });
650
716
  if (!response.ok) {
651
- console.warn("[dsh-message-gateway] qq rest", method, path, response.status);
717
+ const text = (await response.text()).slice(0, 200);
718
+ console.warn("[dsh-message-gateway] qq rest", method, path, response.status, text);
652
719
  return null;
653
720
  }
654
721
  return await response.json();
@@ -659,76 +726,182 @@ var QQBridge = class {
659
726
  clearTimeout(timer);
660
727
  }
661
728
  }
662
- handleMessage(d) {
729
+ /** 单聊/群聊消息分发(content 群聊已去 @前缀)。 */
730
+ handleMessage(d, scene) {
663
731
  const author = d.author;
664
732
  if (author?.bot === true) return;
665
733
  const text = typeof d.content === "string" ? d.content.trim() : "";
666
734
  if (text === "") return;
667
- const channelId = String(d.channel_id ?? "");
668
- if (channelId === "") return;
669
- const guildId = String(d.guild_id ?? "");
670
- const frame = { channelId, messageId: String(d.id ?? ""), guildId };
735
+ const msgId = String(d.id ?? "");
736
+ if (msgId === "") return;
737
+ if (this.recentMsgIds.has(msgId)) return;
738
+ this.recentMsgIds.add(msgId);
739
+ if (this.recentMsgIds.size > DEDUP_CAP) {
740
+ const first = this.recentMsgIds.values().next().value;
741
+ if (first !== void 0) this.recentMsgIds.delete(first);
742
+ }
743
+ const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
744
+ if (openid === "") return;
745
+ const frame = { openid, msgId, scene };
671
746
  const sink = {
747
+ // 单聊/群聊回复不支持就地编辑(群聊明确不支持流式),ack 关闭:
748
+ // 只发一条最终消息,避免「正在处理… + 回复」两条。
749
+ ack: false,
672
750
  stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
673
751
  };
674
752
  const identity = {
675
- key: `qq:${channelId}`,
753
+ key: scene === "c2c" ? `qq:c2c:${openid}` : `qq:group:${openid}`,
676
754
  frame,
677
755
  sink,
678
- chatType: guildId === "" ? "single" : "group"
756
+ chatType: scene === "c2c" ? "single" : "group"
679
757
  };
680
- console.log("[dsh-message-gateway] qq text", { channelId, text: text.slice(0, 60) });
758
+ console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
681
759
  this.callbacks.onText(text, identity);
682
760
  }
683
- /** 流式回复:状态合并 + 单 worker——首次被动回复,随后 PATCH 渐进更新(限频)。 */
761
+ /** 回复:finish 时一次发出(带 msg_id 被动回复;幂等防重发)。 */
684
762
  async streamReply(frame, streamId, content, finish) {
685
- const prev = this.state.get(streamId);
686
- this.state.set(streamId, { content, finish: finish || (prev?.finish ?? false) });
687
- if (this.working.has(streamId)) return;
688
- this.working.add(streamId);
689
- try {
690
- for (let guard = 0; guard < 200; guard += 1) {
691
- const current = this.state.get(streamId);
692
- if (current === void 0) break;
693
- const text = (current.content === "" ? " " : current.content).slice(0, MSG_LIMIT3);
694
- const existing = this.streams.get(streamId);
695
- if (existing === void 0) {
696
- if (current.content === "" && !current.finish) break;
697
- const result = await this.rest("POST", `/channels/${frame.channelId}/messages`, {
698
- content: text,
699
- msg_type: 0,
700
- msg_id: frame.messageId
701
- });
702
- if (result?.id === void 0) break;
703
- this.streams.set(streamId, { channelId: frame.channelId, messageId: result.id, lastEdit: Date.now() });
704
- if (current.finish || this.state.get(streamId).content === current.content) break;
705
- continue;
706
- }
707
- const wait = EDIT_INTERVAL_MS3 - (Date.now() - existing.lastEdit);
708
- if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
709
- existing.lastEdit = Date.now();
710
- await this.rest("PATCH", `/channels/${existing.channelId}/messages/${existing.messageId}`, { content: text });
711
- if (current.finish || this.state.get(streamId).content === current.content) break;
712
- }
713
- } catch (error) {
714
- console.error("[dsh-message-gateway] qq reply failed", error);
715
- } finally {
716
- this.working.delete(streamId);
717
- }
763
+ if (!finish) return;
764
+ if (this.sent.has(streamId)) return;
765
+ this.sent.add(streamId);
766
+ const text = content.trim() === "" ? "\uFF08\u7A7A\u56DE\u590D\uFF09" : content.slice(0, 2e3);
767
+ const path = frame.scene === "c2c" ? `/v2/users/${encodeURIComponent(frame.openid)}/messages` : `/v2/groups/${encodeURIComponent(frame.openid)}/messages`;
768
+ const result = await this.rest("POST", path, { content: text, msg_type: 0, msg_id: frame.msgId });
769
+ if (result === null) this.sent.delete(streamId);
718
770
  }
719
771
  /** 停止网关连接。 */
720
772
  stop() {
721
773
  this.stopped = true;
722
774
  this.clearHeartbeat();
723
- this.streams.clear();
724
- this.state.clear();
725
- this.working.clear();
775
+ this.sent.clear();
776
+ this.recentMsgIds.clear();
726
777
  this.ws?.close();
727
778
  this.ws = null;
728
779
  this.accessToken = null;
729
780
  this.setStatus("idle");
730
781
  }
731
782
  };
783
+ var QqWebhookBridge = class {
784
+ constructor(appId, secret, callbackToken, callbacks) {
785
+ this.appId = appId;
786
+ this.secret = secret;
787
+ this.callbackToken = callbackToken;
788
+ this.callbacks = callbacks;
789
+ this.key = qqEd25519Key(callbackToken);
790
+ }
791
+ key;
792
+ accessToken = null;
793
+ tokenExpiresAt = 0;
794
+ recentMsgIds = /* @__PURE__ */ new Set();
795
+ /** op 13 回调地址验证握手 → { plain_token, signature }(供控制台校验通过)。 */
796
+ validate(d) {
797
+ const plainToken = typeof d.plain_token === "string" ? d.plain_token : "";
798
+ const eventTs = typeof d.event_ts === "string" ? d.event_ts : "";
799
+ if (plainToken === "" || eventTs === "") return null;
800
+ const signature = sign(null, Buffer.from(eventTs + plainToken, "utf8"), this.key).toString("hex");
801
+ return { plain_token: plainToken, signature };
802
+ }
803
+ /** 事件签名验证:X-Signature-Timestamp + 原始 body,ed25519 校验。 */
804
+ verifySignature(rawBody, sigHex, timestamp) {
805
+ if (sigHex === "" || timestamp === "") return false;
806
+ let sig;
807
+ try {
808
+ sig = Buffer.from(sigHex, "hex");
809
+ } catch {
810
+ return false;
811
+ }
812
+ if (sig.length !== 64) return false;
813
+ const msg = Buffer.concat([Buffer.from(timestamp, "utf8"), Buffer.from(rawBody, "utf8")]);
814
+ return verify(null, msg, this.key, sig);
815
+ }
816
+ /** 事件分发(payload { t, d });返回是否已消费(非本桥事件返回 false)。 */
817
+ handleEvent(payload) {
818
+ const t = typeof payload.t === "string" ? payload.t : "";
819
+ let scene = null;
820
+ if (t === "C2C_MESSAGE_CREATE") scene = "c2c";
821
+ else if (t === "GROUP_AT_MESSAGE_CREATE") scene = "group";
822
+ if (scene === null) return false;
823
+ const d = payload.d ?? {};
824
+ const author = d.author;
825
+ if (author?.bot === true) return true;
826
+ const text = typeof d.content === "string" ? d.content.trim() : "";
827
+ const msgId = String(d.id ?? "");
828
+ if (text === "" || msgId === "") return true;
829
+ if (this.recentMsgIds.has(msgId)) return true;
830
+ this.recentMsgIds.add(msgId);
831
+ if (this.recentMsgIds.size > DEDUP_CAP) {
832
+ const first = this.recentMsgIds.values().next().value;
833
+ if (first !== void 0) this.recentMsgIds.delete(first);
834
+ }
835
+ const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
836
+ if (openid === "") return true;
837
+ const frame = { openid, msgId, scene };
838
+ const sink = {
839
+ ack: false,
840
+ stream: (_f, _sid, content, finish) => {
841
+ if (finish) void this.reply(frame, content);
842
+ }
843
+ };
844
+ const identity = {
845
+ key: scene === "c2c" ? `qq:c2c:${openid}` : `qq:group:${openid}`,
846
+ frame,
847
+ sink,
848
+ chatType: scene === "c2c" ? "single" : "group"
849
+ };
850
+ console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: text.slice(0, 60) });
851
+ this.callbacks.onText(text, identity);
852
+ return true;
853
+ }
854
+ /** 确保 access_token 未过期(提前 60s 刷新)。 */
855
+ async ensureToken() {
856
+ if (this.accessToken !== null && Date.now() < this.tokenExpiresAt - 6e4) return true;
857
+ const controller = new AbortController();
858
+ const timer = setTimeout(() => controller.abort(), 15e3);
859
+ try {
860
+ const response = await fetch(TOKEN_URL, {
861
+ method: "POST",
862
+ headers: { "content-type": "application/json" },
863
+ body: JSON.stringify({ appId: this.appId, clientSecret: this.secret }),
864
+ signal: controller.signal
865
+ });
866
+ const body = await response.json();
867
+ if (response.ok && body.access_token !== void 0 && body.access_token !== "") {
868
+ this.accessToken = body.access_token;
869
+ this.tokenExpiresAt = Date.now() + (body.expires_in ?? 7200) * 1e3;
870
+ return true;
871
+ }
872
+ console.warn("[dsh-message-gateway] qq webhook token failed", response.status);
873
+ return false;
874
+ } catch (error) {
875
+ console.warn("[dsh-message-gateway] qq webhook token error", String(error));
876
+ return false;
877
+ } finally {
878
+ clearTimeout(timer);
879
+ }
880
+ }
881
+ /** 发送单聊/群聊消息(带 msg_id 被动回复,幂等由调用方保证)。 */
882
+ async reply(frame, content) {
883
+ if (!await this.ensureToken()) return false;
884
+ const text = content.trim() === "" ? "\uFF08\u7A7A\u56DE\u590D\uFF09" : content.slice(0, 2e3);
885
+ const path = frame.scene === "c2c" ? `/v2/users/${encodeURIComponent(frame.openid)}/messages` : `/v2/groups/${encodeURIComponent(frame.openid)}/messages`;
886
+ try {
887
+ const response = await fetch(`${BASE}${path}`, {
888
+ method: "POST",
889
+ headers: { authorization: `QQBot ${this.accessToken ?? ""}`, "content-type": "application/json" },
890
+ body: JSON.stringify({ content: text, msg_type: 0, msg_id: frame.msgId }),
891
+ signal: AbortSignal.timeout(15e3)
892
+ });
893
+ if (!response.ok) {
894
+ const err = (await response.text()).slice(0, 120);
895
+ console.warn("[dsh-message-gateway] qq webhook reply", response.status, err);
896
+ return false;
897
+ }
898
+ return true;
899
+ } catch (error) {
900
+ console.warn("[dsh-message-gateway] qq webhook reply failed", String(error));
901
+ return false;
902
+ }
903
+ }
904
+ };
732
905
 
733
906
  // src/host/email-bridge.ts
734
907
  import { connect } from "node:net";
@@ -1698,7 +1871,7 @@ var BridgeManager = class {
1698
1871
  return { state: "error", detail: live.detail, testedAt: stored?.testedAt ?? null };
1699
1872
  }
1700
1873
  if (live.state === "connecting") {
1701
- return { state: stored?.state ?? "none", detail: "\u8FDE\u63A5\u4E2D\u2026", testedAt: stored?.testedAt ?? null };
1874
+ return { state: "connecting", detail: live.detail || "\u8FDE\u63A5\u4E2D\u2026", testedAt: stored?.testedAt ?? null };
1702
1875
  }
1703
1876
  return stored ?? { state: "none", detail: "", testedAt: null };
1704
1877
  }
@@ -1811,9 +1984,11 @@ var PLATFORMS = [
1811
1984
  nameKey: "platform.qq",
1812
1985
  icon: "\u{1F4AC}",
1813
1986
  testable: true,
1987
+ hintKey: "platform.qq.hint",
1814
1988
  fields: [
1815
1989
  { key: "appId", labelKey: "field.appId", kind: "text" },
1816
- { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" }
1990
+ { key: "secret", labelKey: "field.secret", placeholderKey: "field.secret.ph", kind: "secret" },
1991
+ { key: "callbackToken", labelKey: "field.qqCallbackToken", placeholderKey: "field.secret.ph", kind: "secret" }
1817
1992
  ]
1818
1993
  },
1819
1994
  {
@@ -2295,7 +2470,8 @@ var BODY_CAP_BYTES = 1 << 20;
2295
2470
  var CALLBACK_PATHS = {
2296
2471
  wecom: "/gateway/wecom/callback",
2297
2472
  "wechat-mp": "/gateway/wechat-mp/callback",
2298
- whatsapp: "/gateway/whatsapp/webhook"
2473
+ whatsapp: "/gateway/whatsapp/webhook",
2474
+ qq: "/gateway/qq/callback"
2299
2475
  };
2300
2476
  async function readJsonBody(req) {
2301
2477
  const chunks = [];
@@ -2474,6 +2650,37 @@ async function handleCallbackRoute(req, res, path, query, manager) {
2474
2650
  json(res, { ok: true, value: null });
2475
2651
  return;
2476
2652
  }
2653
+ if (path === "/gateway/qq/callback") {
2654
+ const cred = store.platforms.qq;
2655
+ if (cred === void 0 || cred.callbackToken === "") {
2656
+ json(res, { ok: false, error: { code: "internal", message: "qq callback not configured" } }, 400);
2657
+ return;
2658
+ }
2659
+ const bridge = new QqWebhookBridge(cred.appId ?? "", cred.secret ?? "", cred.callbackToken, {
2660
+ onText: (text, identity) => void manager.handleExternalMessage(identity, text)
2661
+ });
2662
+ const { raw, json: payload } = await readJsonBody(req);
2663
+ const body = payload ?? {};
2664
+ if (body.op === 13) {
2665
+ const validated = bridge.validate(body.d ?? {});
2666
+ if (validated === null) {
2667
+ json(res, { ok: false, error: { code: "internal", message: "bad validation payload" } }, 400);
2668
+ return;
2669
+ }
2670
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
2671
+ res.end(JSON.stringify(validated));
2672
+ return;
2673
+ }
2674
+ const signature = req.headers["x-signature-ed25519"];
2675
+ const timestamp = req.headers["x-signature-timestamp"];
2676
+ if (typeof signature !== "string" || typeof timestamp !== "string" || !bridge.verifySignature(raw, signature, timestamp)) {
2677
+ json(res, { ok: false, error: { code: "internal", message: "signature mismatch" } }, 403);
2678
+ return;
2679
+ }
2680
+ bridge.handleEvent(body);
2681
+ json(res, { ok: true, value: null });
2682
+ return;
2683
+ }
2477
2684
  json(res, { ok: false, error: { code: "internal", message: "unknown callback route" } }, 404);
2478
2685
  } catch (error) {
2479
2686
  const message = error instanceof Error ? error.message : String(error);
@@ -2500,7 +2707,7 @@ function registerGatewayRoutes(ctx, manager) {
2500
2707
  handler: async (req, res) => {
2501
2708
  const url = new URL(req.url ?? "/", "http://dsh");
2502
2709
  const path = url.pathname;
2503
- if (path === "/gateway/wecom/callback" || path === "/gateway/wechat-mp/callback" || path === "/gateway/whatsapp/webhook") {
2710
+ if (path === "/gateway/wecom/callback" || path === "/gateway/wechat-mp/callback" || path === "/gateway/whatsapp/webhook" || path === "/gateway/qq/callback") {
2504
2711
  await handleCallbackRoute(req, res, path, url.searchParams, manager);
2505
2712
  return;
2506
2713
  }
@@ -2747,6 +2954,7 @@ export {
2747
2954
  ImapClient,
2748
2955
  PLATFORMS,
2749
2956
  QQBridge,
2957
+ QqWebhookBridge,
2750
2958
  SmtpClient,
2751
2959
  TelegramBridge,
2752
2960
  WechatMpBridge,