@alemonjs/qq-bot 2.1.37 → 2.1.38

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/README.md CHANGED
@@ -9,6 +9,10 @@ AlemonJS 的 QQ 开放平台适配器,用于连接官方机器人接口,将
9
9
  - 提供群管理、媒体上传和单聊流式消息能力;具体能力以平台权限为准。
10
10
  - 支持 WebSocket、Webhook 连接,以及 WebSocket 多机器人配置。
11
11
 
12
+ 官方 Node SDK 的对照结果、已落实修复和后续框架改进见 [SDK 对照与改进](./SDK_REVIEW.md)。
13
+
14
+ 三层限流、QQ 文本清洗、引用索引、群历史、LLM 上下文和 C2C 自动 typing 的配置与用法见 [消息处理与会话上下文](../alemonjs/docs/message-context.md)。
15
+
12
16
  ## 配置
13
17
 
14
18
  ### 基础配置
package/lib/config.d.ts CHANGED
@@ -1,8 +1,11 @@
1
+ import { QQTextSanitizerOptions } from "./text-sanitizer.js";
1
2
  import { Options as Options$1 } from "./sdk/typing.js";
2
3
  //#region src/config.d.ts
3
4
  declare const platform = "qq-bot";
4
5
  declare const platformFullName = "@alemonjs/qq-bot";
5
6
  type Options = {
7
+ /** Opt-in QQ markup normalization; raw content remains available. */
8
+ textSanitizer?: QQTextSanitizerOptions;
6
9
  /** 按钮/快捷菜单自动 ACK。设为 false 后由应用 useInteraction().ack() 回应。 */
7
10
  autoInteractionAck?: boolean;
8
11
  /**
package/lib/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { QQTextSanitizerOptions, sanitizeQQText } from "./text-sanitizer.js";
1
2
  import { ApiRequestData, ButtonType, FileType, GlobalMuteRule, GroupAction, JoinApprovalStrategy, JoinRequest, KeyboardType, MarkdownType, MemberMuteState, MessageType, Options, SetMemberMuteState, StreamMessageData, StreamMessageResult, UploadConfig, UploadPart, UploadPartFinishData, UploadPrepareData, UploadPrepareResult, VerifyInfo } from "./sdk/typing.js";
2
3
  import { platform } from "./config.js";
3
4
  import { QQBotArkData, QQBotAttachment, QQBotBlacklistUser, QQBotGroupMember, QQBotInteractionResolved, QQBotMenu, QQBotMenuItem, QQBotMessageContent, QQBotMessageElement, QQBotMessageResult, QQBotMessageUser, QQBotPage, QQBotPanel, QQBotPanelCreate, QQBotPanelRecord, QQBotPanelScope } from "./sdk/non-channel-types.js";
@@ -8,4 +9,4 @@ import { QQBotPublicEventMap } from "./sdk/message.public.js";
8
9
  //#region src/index.d.ts
9
10
  declare const _default: () => any;
10
11
  //#endregion
11
- export { QQBotAPI as API, type ApiRequestData, type ButtonType, type FileType, type GlobalMuteRule, type GroupAction, type JoinApprovalStrategy, type JoinRequest, type KeyboardType, type MarkdownType, type MemberMuteState, type MessageType, type Options, type QQBotArkData, type QQBotAttachment, type QQBotBlacklistUser, type QQBotGroupEventMap, type QQBotGroupMember, type QQBotInteractionResolved, type QQBotMenu, type QQBotMenuItem, type QQBotMessageContent, type QQBotMessageElement, type QQBotMessageResult, type QQBotMessageUser, type QQBotPage, type QQBotPanel, type QQBotPanelCreate, type QQBotPanelRecord, type QQBotPanelScope, type QQBotPublicEventMap, type SetMemberMuteState, type StreamMessageData, type StreamMessageResult, type UploadConfig, type UploadPart, type UploadPartFinishData, type UploadPrepareData, type UploadPrepareResult, type VerifyInfo, _default as default, platform, useClient, useMode, useValue };
12
+ export { QQBotAPI as API, type ApiRequestData, type ButtonType, type FileType, type GlobalMuteRule, type GroupAction, type JoinApprovalStrategy, type JoinRequest, type KeyboardType, type MarkdownType, type MemberMuteState, type MessageType, type Options, type QQBotArkData, type QQBotAttachment, type QQBotBlacklistUser, type QQBotGroupEventMap, type QQBotGroupMember, type QQBotInteractionResolved, type QQBotMenu, type QQBotMenuItem, type QQBotMessageContent, type QQBotMessageElement, type QQBotMessageResult, type QQBotMessageUser, type QQBotPage, type QQBotPanel, type QQBotPanelCreate, type QQBotPanelRecord, type QQBotPanelScope, type QQBotPublicEventMap, type QQTextSanitizerOptions, type SetMemberMuteState, type StreamMessageData, type StreamMessageResult, type UploadConfig, type UploadPart, type UploadPartFinishData, type UploadPrepareData, type UploadPrepareResult, type VerifyInfo, _default as default, platform, sanitizeQQText, useClient, useMode, useValue };
package/lib/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getQQBotConfig, platform } from "./config.js";
2
+ import { sanitizeQQText } from "./text-sanitizer.js";
2
3
  import { QQBotAPI } from "./sdk/api.js";
3
4
  import { start } from "./index.websoket.js";
4
5
  import { useClient, useMode, useValue } from "./hook.js";
@@ -14,4 +15,4 @@ const main = () => {
14
15
  var src_default = definePlatform({ main });
15
16
 
16
17
  //#endregion
17
- export { QQBotAPI as API, src_default as default, platform, useClient, useMode, useValue };
18
+ export { QQBotAPI as API, src_default as default, platform, sanitizeQQText, useClient, useMode, useValue };
package/lib/register.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getIdentity, getMaster, getQQBotConfig, platform } from "./config.js";
2
+ import { sanitizeQQText } from "./text-sanitizer.js";
2
3
  import { AT_MESSAGE_CREATE, C2C_MESSAGE_CREATE, DIRECT_MESSAGE_CREATE, GROUP_AT_MESSAGE_CREATE, MESSAGE_CREATE } from "./sends.js";
3
4
  import { normalizeFrameworkEvent, normalizeMessageUser } from "./framework-events.js";
4
5
  import { handleFrameworkAction } from "./framework-actions.js";
@@ -47,7 +48,14 @@ const register = (client, options) => {
47
48
  const botId = String(options?.botId ?? config?.app_id ?? "");
48
49
  const url = `ws://127.0.0.1:${process.env?.port || config?.port || 17117}`;
49
50
  const cbp = options?.cbp ?? cbpPlatform(url);
50
- const emit = (event, acknowledged = false) => cbp.send(normalizeFrameworkEvent(event, acknowledged));
51
+ const emit = (event, acknowledged = false) => {
52
+ const normalized = normalizeFrameworkEvent(event, acknowledged);
53
+ if (config.textSanitizer && (normalized.name === "message.create" || normalized.name === "private.message.create") && typeof normalized.value?.content === "string") {
54
+ normalized.RawMessageText = normalized.value.content;
55
+ normalized.MessageText = sanitizeQQText(normalized.value.content, botId, config.textSanitizer);
56
+ }
57
+ cbp.send(normalized);
58
+ };
51
59
  /**
52
60
  * group
53
61
  *
@@ -68,7 +68,13 @@ var QQBotClient = class extends QQBotAPI {
68
68
  if (!ws) {
69
69
  this.#setTimeoutBotConfig();
70
70
  this.#app = new Koa();
71
- this.#app.use(bodyParser());
71
+ this.#app.use(bodyParser({
72
+ enableTypes: ["json"],
73
+ onerror: (_error, ctx) => {
74
+ ctx.status = 400;
75
+ ctx.body = { msg: "invalid json" };
76
+ }
77
+ }));
72
78
  const router = new Router();
73
79
  const port = this.config.get("port");
74
80
  const secret = this.config.get("secret");
@@ -78,31 +84,39 @@ var QQBotClient = class extends QQBotAPI {
78
84
  port: port ? Number(port) : 17157
79
85
  };
80
86
  const ntqqWebhook = new WebhookAPI({ secret: cfg.secret });
81
- this.#app.use(async (ctx, next) => {
82
- let rawData = "";
83
- ctx.req.on("data", (chunk) => rawData += chunk);
84
- ctx.req.on("end", () => ctx.request.rawBody = rawData);
85
- await next();
86
- });
87
87
  router.post(route, (ctx) => {
88
- const sign = ctx.req.headers["x-signature-ed25519"];
89
- const timestamp = ctx.req.headers["x-signature-timestamp"];
90
- const rawBody = ctx.request.rawBody;
91
- if (!ntqqWebhook.validSign(timestamp, rawBody, String(sign))) {
88
+ const request = ctx.request;
89
+ const body = request.body;
90
+ if (!body || typeof body !== "object" || Array.isArray(body) || !Number.isInteger(body.op)) {
91
+ ctx.status = 400;
92
+ ctx.body = { msg: "invalid payload" };
93
+ return;
94
+ }
95
+ if (body.op !== 13 && !ntqqWebhook.validSign(ctx.get("x-signature-timestamp"), request.rawBody, ctx.get("x-signature-ed25519"))) {
92
96
  ctx.status = 400;
93
97
  ctx.body = { msg: "invalid signature" };
94
98
  return;
95
99
  }
96
- const body = normalizeGatewayMessage(ctx.request.body);
97
- if (+body.op === 13) {
100
+ if (body.op === 13) {
101
+ if (typeof body.d?.plain_token !== "string" || !body.d.plain_token || typeof body.d?.event_ts !== "string" || !body.d.event_ts) {
102
+ ctx.status = 400;
103
+ ctx.body = { msg: "invalid validation" };
104
+ return;
105
+ }
98
106
  ctx.status = 200;
99
107
  ctx.body = {
100
108
  plain_token: body.d.plain_token,
101
109
  signature: ntqqWebhook.getSign(body.d.event_ts, body.d.plain_token)
102
110
  };
103
- } else if (+body.op === 0) {
111
+ } else if (body.op === 0) {
112
+ if (typeof body.t !== "string" || !body.t || !body.d || typeof body.d !== "object" || Array.isArray(body.d)) {
113
+ ctx.status = 400;
114
+ ctx.body = { msg: "invalid dispatch" };
115
+ return;
116
+ }
117
+ normalizeGatewayMessage(body);
104
118
  ctx.status = 204;
105
- for (const event of this.#events[body.t] || []) event(body.d);
119
+ this.#dispatch(body);
106
120
  const accessToken = this.config.get("access_token");
107
121
  for (const client of this.#client) try {
108
122
  if (accessToken) body["access_token"] = accessToken;
@@ -131,7 +145,7 @@ var QQBotClient = class extends QQBotAPI {
131
145
  ws.on("message", (message) => {
132
146
  try {
133
147
  const body = normalizeGatewayMessage(JSON.parse(message.toString()));
134
- for (const event of this.#events[body.t] || []) event(body.d);
148
+ this.#dispatch(body);
135
149
  } catch (e) {
136
150
  this.#error(e);
137
151
  }
@@ -154,7 +168,7 @@ var QQBotClient = class extends QQBotAPI {
154
168
  const body = normalizeGatewayMessage(JSON.parse(data.toString()));
155
169
  const accessToken = body["access_token"];
156
170
  if (accessToken) this.config.set("access_token", accessToken);
157
- for (const event of this.#events[body.t] || []) event(body.d);
171
+ this.#dispatch(body);
158
172
  } catch (e) {
159
173
  this.#error(e);
160
174
  }
@@ -177,12 +191,17 @@ var QQBotClient = class extends QQBotAPI {
177
191
  this.#error(e);
178
192
  }
179
193
  }
194
+ /** Acknowledge receipt without waiting for application work. Each listener
195
+ * owns its failure path so a rejection cannot escape the transport. */
196
+ #dispatch(body) {
197
+ for (const event of this.#events[body.t] || []) Promise.resolve().then(() => event(body.d)).catch((error) => this.#error(error));
198
+ }
180
199
  /**
181
200
  *
182
201
  * @param error
183
202
  */
184
203
  #error(error) {
185
- if (this.#events["ERROR"]) for (const event of this.#events["ERROR"] || []) event(error);
204
+ for (const event of this.#events["ERROR"] || []) Promise.resolve().then(() => event(error)).catch((failure) => console.error("[qq-bot] ERROR listener failed", failure instanceof Error ? failure.name : "UnknownError"));
186
205
  }
187
206
  };
188
207
 
@@ -1,11 +1,6 @@
1
1
  import { AxiosInstance, AxiosRequestConfig } from "axios";
2
2
  //#region src/sdk/instance.d.ts
3
- /**
4
- * 基础请求
5
- * @param service
6
- * @param options
7
- * @returns
8
- */
3
+ /** Preserve native platform failure payloads for existing SDK and Action callers. */
9
4
  declare const createAxiosInstance: (service: AxiosInstance, options: AxiosRequestConfig) => Promise<any>;
10
5
  //#endregion
11
6
  export { createAxiosInstance };
@@ -1,75 +1,29 @@
1
1
  import { logger } from "alemonjs";
2
2
 
3
3
  //#region src/sdk/instance.ts
4
- const filterHeaders = (headers = {}) => {
5
- if (!headers) return headers;
6
- const filtered = {};
7
- const sensitiveKeys = [
8
- /^authorization$/i,
9
- /^cookie$/i,
10
- /^set-cookie$/i,
11
- /token/i,
12
- /key/i,
13
- /jwt/i,
14
- /^session[-_]id$/i,
15
- /^uid$/i,
16
- /^user[-_]id$/i
17
- ];
18
- for (const key in headers) {
19
- if (/^_/.test(key)) continue;
20
- if (typeof key === "symbol") continue;
21
- if (typeof headers[key] === "function") continue;
22
- if (sensitiveKeys.some((re) => re.test(key))) filtered[key] = "******";
23
- else filtered[key] = headers[key];
24
- }
25
- return filtered;
26
- };
27
- const filterConfig = (config = {}) => {
28
- if (!config) return config;
29
- const filtered = {};
30
- for (const key in config) {
31
- if (/^_/.test(key)) continue;
32
- if (typeof key === "symbol") continue;
33
- if (typeof config[key] === "function") continue;
34
- filtered[key] = config[key];
35
- }
36
- return filtered;
37
- };
38
- const filterRequest = (request = {}) => {
39
- if (!request) return request;
40
- const filtered = {};
41
- for (const key in request) {
42
- if (/^_/.test(key)) continue;
43
- if (typeof key === "symbol") continue;
44
- if (typeof request[key] === "function") continue;
45
- filtered[key] = request[key];
46
- }
47
- return filtered;
48
- };
4
+ /** Log an allowlist of diagnostics. Axios config/request objects may contain
5
+ * credentials, signed URLs, message bodies, buffers and circular references. */
49
6
  const loggerError = (err) => {
50
- logger.error("[axios] error", {
51
- config: {
52
- headers: filterHeaders(err?.config?.headers),
53
- params: err?.config?.params,
54
- data: err?.config?.data
55
- },
56
- response: {
57
- status: err?.response?.status,
58
- statusText: err?.response?.statusText,
59
- headers: filterHeaders(err?.response?.headers),
60
- config: filterConfig(err?.response?.config),
61
- request: filterRequest(err?.response?.request),
62
- data: err?.response?.data
63
- },
64
- message: err?.message
7
+ const config = err?.config;
8
+ let path;
9
+ try {
10
+ path = new URL(config?.url ?? "", config?.baseURL || "http://localhost").pathname;
11
+ } catch {
12
+ path = void 0;
13
+ }
14
+ const headers = err?.response?.headers;
15
+ const data = err?.response?.data;
16
+ const scalarCode = (value) => typeof value === "number" || typeof value === "string" && /^[\w-]{1,64}$/.test(value) ? value : void 0;
17
+ logger.error("[qq-bot] HTTP request failed", {
18
+ method: typeof config?.method === "string" ? config.method.toUpperCase() : void 0,
19
+ path,
20
+ status: err?.response?.status,
21
+ code: scalarCode(data?.code ?? data?.err_code),
22
+ transportCode: scalarCode(err?.code),
23
+ traceId: headers?.["x-tps-trace-id"] ?? headers?.["x-trace-id"]
65
24
  });
66
25
  };
67
- /**
68
- * 基础请求
69
- * @param service
70
- * @param options
71
- * @returns
72
- */
26
+ /** Preserve native platform failure payloads for existing SDK and Action callers. */
73
27
  const createAxiosInstance = async (service, options) => {
74
28
  try {
75
29
  return (await service(options))?.data ?? {};
@@ -13,7 +13,7 @@ declare class WebhookAPI {
13
13
  * @param sign
14
14
  * @returns
15
15
  */
16
- validSign(ts: any, body: any, sign: any): boolean;
16
+ validSign(ts: unknown, body: unknown, sign: unknown): boolean;
17
17
  /**
18
18
  * 生成签名
19
19
  * @param eventTs
@@ -14,11 +14,16 @@ var WebhookAPI = class {
14
14
  * @returns
15
15
  */
16
16
  validSign(ts, body, sign) {
17
- const { publicKey } = this.getKey();
18
- const sig = Buffer.isBuffer(sign) ? sign : Buffer.from(sign, "hex");
19
- const httpBody = Buffer.from(body);
20
- const msg = Buffer.from(ts + httpBody);
21
- return ed25519.verify(sig, msg, publicKey);
17
+ if (typeof ts !== "string" || !ts || typeof body !== "string" && !Buffer.isBuffer(body)) return false;
18
+ if (!Buffer.isBuffer(sign) && (typeof sign !== "string" || !/^[a-f\d]{128}$/i.test(sign))) return false;
19
+ try {
20
+ const { publicKey } = this.getKey();
21
+ const sig = Buffer.isBuffer(sign) ? sign : Buffer.from(sign, "hex");
22
+ const msg = Buffer.concat([Buffer.from(ts), Buffer.isBuffer(body) ? body : Buffer.from(body)]);
23
+ return ed25519.verify(sig, msg, publicKey);
24
+ } catch {
25
+ return false;
26
+ }
22
27
  }
23
28
  /**
24
29
  * 生成签名
@@ -0,0 +1,13 @@
1
+ //#region src/text-sanitizer.d.ts
2
+ type QQTextSanitizerOptions = {
3
+ /** Strip only this bot by default. Other users' mentions retain meaning. */
4
+ botMention?: 'remove' | 'preserve';
5
+ otherMentions?: 'remove' | 'preserve';
6
+ faces?: 'preserve' | 'remove' | 'label';
7
+ /** Disabled by default to preserve paragraphs and code indentation. */
8
+ collapseWhitespace?: boolean;
9
+ };
10
+ /** Converts QQ protocol markup, never HTML. Raw event content is preserved. */
11
+ declare const sanitizeQQText: (text: string, botId: string, options?: QQTextSanitizerOptions) => string;
12
+ //#endregion
13
+ export { QQTextSanitizerOptions, sanitizeQQText };
@@ -0,0 +1,26 @@
1
+ //#region src/text-sanitizer.ts
2
+ /** Converts QQ protocol markup, never HTML. Raw event content is preserved. */
3
+ const sanitizeQQText = (text, botId, options = {}) => {
4
+ let result = text.replace(/<@!?([^>\s]+)>/g, (marker, id) => {
5
+ return (id === botId ? options.botMention !== "preserve" : options.otherMentions === "remove") ? "" : marker;
6
+ });
7
+ const faces = options.faces ?? "preserve";
8
+ if (faces !== "preserve") {
9
+ result = result.replace(/\[<face,id=(\d+)\/?>\]/g, (_marker, id) => faces === "label" ? `[表情:${id}]` : "");
10
+ result = result.replace(/<faceType=\d+,faceId="([^"]*)",ext="([^"]*)">/g, (_marker, id, ext) => {
11
+ if (faces === "remove") return "";
12
+ try {
13
+ if (ext.length <= 1e4) {
14
+ const data = JSON.parse(Buffer.from(ext, "base64").toString("utf8"));
15
+ if (typeof data?.text === "string" && data.text) return `[表情:${data.text.slice(0, 100)}]`;
16
+ }
17
+ } catch {}
18
+ return `[表情:${id}]`;
19
+ });
20
+ }
21
+ if (options.collapseWhitespace) result = result.replace(/\s+/g, " ");
22
+ return result.trim();
23
+ };
24
+
25
+ //#endregion
26
+ export { sanitizeQQText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alemonjs/qq-bot",
3
- "version": "2.1.37",
3
+ "version": "2.1.38",
4
4
  "description": "QQ官方平台",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -12,8 +12,10 @@
12
12
  "test:send": "yarn build && node tests/use-send.notice.mjs",
13
13
  "test:channel": "yarn --cwd ../alemonjs build && yarn build && node tests/channel.contract.mjs",
14
14
  "test:qr": "yarn build && node tests/qr-auth.mjs",
15
- "test:non-channel": "yarn build && node tests/non-channel.contract.mjs && node tests/framework.contract.mjs && node tests/non-channel.transport.mjs && node tests/media-upload.contract.mjs && node tests/routing.contract.mjs && node tests/lifecycle.contract.mjs && tsc -p tests/tsconfig.non-channel.json",
16
- "docs:snapshot": "python3 scripts/snapshot-official.py"
15
+ "test:non-channel": "yarn build && node tests/non-channel.contract.mjs && node tests/framework.contract.mjs && node tests/non-channel.transport.mjs && node tests/media-upload.contract.mjs && node tests/routing.contract.mjs && node tests/lifecycle.contract.mjs && node tests/http-diagnostics.contract.mjs && node tests/webhook-ingress.contract.mjs && node tests/text-sanitizer.contract.mjs && tsc -p tests/tsconfig.non-channel.json",
16
+ "docs:snapshot": "python3 scripts/snapshot-official.py",
17
+ "test:http": "yarn build && node tests/http-diagnostics.contract.mjs && node tests/webhook-ingress.contract.mjs",
18
+ "test:text": "yarn build && node tests/text-sanitizer.contract.mjs"
17
19
  },
18
20
  "dependencies": {
19
21
  "@noble/curves": "^1.7.0",
@@ -32,9 +34,6 @@
32
34
  "ws": "^8.13.0",
33
35
  "yaml": "^2.5.1"
34
36
  },
35
- "peerDependencies": {
36
- "alemonjs": "^2.1.0"
37
- },
38
37
  "types": "lib",
39
38
  "exports": {
40
39
  ".": {
@@ -100,5 +99,5 @@
100
99
  "type": "git",
101
100
  "url": "https://github.com/lemonade-lab/alemonjs.git"
102
101
  },
103
- "gitHead": "77aa1dad52568d709a460b1cdd32db6c36b6f0c2"
102
+ "gitHead": "e736f4e180a8694f8c9eb1796a23fdfadcc48f3e"
104
103
  }