@alemonjs/qq-bot 2.1.37 → 2.1.39

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,12 @@ 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
+
16
+ Markdown 图片支持使用 `Media.image(source)` 自动准备 QQ 素材,也可通过媒体 Hook 提前上传、查询与删除,见[图片来源与平台资源](../alemonjs/docs/media.md)。
17
+
12
18
  ## 配置
13
19
 
14
20
  ### 基础配置
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
  /**
@@ -41,7 +44,7 @@ declare const getQQBotBots: () => {
41
44
  bots: Map<string, Options$1>;
42
45
  defaultBot?: string;
43
46
  };
44
- declare const getIdentity: (UserId: string) => readonly [boolean, string];
45
- declare const getMaster: (UserId: string) => readonly [boolean, string];
47
+ declare const getIdentity: (UserId: string) => readonly [any, any];
48
+ declare const getMaster: (UserId: string) => readonly [any, any];
46
49
  //#endregion
47
50
  export { Options, getIdentity, getMaster, getQQBotBots, getQQBotConfig, platform, platformFullName };
@@ -3,66 +3,25 @@ import { OutgoingMessage } from "alemonjs";
3
3
  //#region src/framework-actions.d.ts
4
4
  declare const toQQMessage: (content: OutgoingMessage) => {
5
5
  msg_type: 0 | 2 | 3 | 7;
6
- content: string;
6
+ content: any;
7
7
  markdown: {
8
- content: string;
9
- custom_template_id: string;
10
- template_id: number;
11
- params: {
12
- key: string;
13
- values: string[];
14
- }[];
15
- force_verify_image_resource: boolean;
8
+ content: any;
9
+ custom_template_id: any;
10
+ template_id: any;
11
+ params: any;
12
+ force_verify_image_resource: any;
16
13
  };
17
14
  media: {
18
- file_info: string;
15
+ file_info: any;
19
16
  };
20
17
  ark: {
21
- template_id: number;
22
- kv: {
23
- key: string;
24
- value: string;
25
- obj: {
26
- obj_kv: {
27
- key: string;
28
- value: string;
29
- }[];
30
- }[];
31
- }[];
18
+ template_id: any;
19
+ kv: any;
32
20
  };
33
21
  keyboard: {
34
- id: string;
22
+ id: any;
35
23
  content: {
36
- rows: {
37
- buttons: {
38
- id: string;
39
- group_id: string;
40
- render_data: {
41
- label: string;
42
- visited_label: string;
43
- style: number;
44
- };
45
- action: {
46
- type: number;
47
- data: string;
48
- permission: {
49
- type: number;
50
- specify_user_ids: string[];
51
- specify_role_ids: string[];
52
- };
53
- enter: boolean;
54
- reply: boolean;
55
- unsupport_tips: string;
56
- anchor: number;
57
- click_limit: number;
58
- modal: {
59
- content: string;
60
- confirm_text: string;
61
- cancel_text: string;
62
- };
63
- };
64
- }[];
65
- }[];
24
+ rows: any;
66
25
  };
67
26
  };
68
27
  };
@@ -70,6 +29,6 @@ declare const toQQMessage: (content: OutgoingMessage) => {
70
29
  declare const handleFrameworkAction: (client: QQBotAPI, data: {
71
30
  action: string;
72
31
  payload: any;
73
- }, botId: string) => Promise<import("alemonjs/common").Result<any>[]>;
32
+ }, botId: string) => Promise<ClientAPIMessageResult[]>;
74
33
  //#endregion
75
34
  export { handleFrameworkAction, toQQMessage };
package/lib/hook.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { QQBotAPI } from "./sdk/api.js";
2
1
  import { SUBSCRIBE_MESSAGE_STATUS_TYPE } from "./message/group/SUBSCRIBE_MESSAGE_STATUS.js";
3
2
  import { GROUP_MEMBER_ADD } from "./message/group/GROUP_MEMBER_ADD.js";
4
3
  import { GROUP_MEMBER_REMOVE } from "./message/group/GROUP_MEMBER_REMOVE.js";
@@ -77,7 +76,7 @@ declare const useValue: <T extends EventKeys>(event: Events[T]) => readonly [Eve
77
76
  * @param event
78
77
  * @returns
79
78
  */
80
- declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [QQBotAPI, EventValues[T]];
79
+ declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [any, EventValues[T]];
81
80
  /**
82
81
  * 判断当前模式
83
82
  * @param event
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";
@@ -6,6 +7,6 @@ import { useClient, useMode, useValue } from "./hook.js";
6
7
  import { QQBotGroupEventMap } from "./sdk/message.group.js";
7
8
  import { QQBotPublicEventMap } from "./sdk/message.public.js";
8
9
  //#region src/index.d.ts
9
- declare const _default: () => any;
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 };
@@ -0,0 +1,15 @@
1
+ import { QQBotAPI } from "./sdk/api.js";
2
+ import { MediaResource, MediaResourcePage, MediaSourceInput } from "alemonjs";
3
+ //#region src/materials.d.ts
4
+ /** Bot-scoped Markdown image materials. No access token is forwarded to COS. */
5
+ declare class QQImageMaterials {
6
+ #private;
7
+ private readonly client;
8
+ private readonly botId;
9
+ constructor(client: QQBotAPI, botId: string);
10
+ upload(source: MediaSourceInput): Promise<MediaResource>;
11
+ list(cursor?: string): Promise<MediaResourcePage>;
12
+ delete(resource: MediaResource): Promise<{}>;
13
+ }
14
+ //#endregion
15
+ export { QQImageMaterials };
@@ -0,0 +1,170 @@
1
+ import axios from "axios";
2
+ import { createHash } from "node:crypto";
3
+ import { basename, extname } from "node:path";
4
+ import { readFile, stat } from "node:fs/promises";
5
+ import { fileTypeFromBuffer } from "file-type";
6
+
7
+ //#region src/materials.ts
8
+ const LIMIT = 10485760;
9
+ const supported = {
10
+ "image/png": [".png"],
11
+ "image/jpeg": [".jpg", ".jpeg"],
12
+ "image/gif": [".gif"],
13
+ "image/webp": [".webp"]
14
+ };
15
+ /** Bot-scoped Markdown image materials. No access token is forwarded to COS. */
16
+ var QQImageMaterials = class {
17
+ client;
18
+ botId;
19
+ #cache = /* @__PURE__ */ new Map();
20
+ #pending = /* @__PURE__ */ new Map();
21
+ constructor(client, botId) {
22
+ this.client = client;
23
+ this.botId = botId;
24
+ }
25
+ #resource(raw) {
26
+ if (typeof raw?.image_id !== "string" || typeof raw.url !== "string" || !raw.url.startsWith("qqbot-media://image/v1/")) throw new Error("QQ returned an invalid Markdown image resource");
27
+ return {
28
+ kind: "media-resource",
29
+ type: "image",
30
+ id: raw.image_id,
31
+ owner: {
32
+ platform: "qq-bot",
33
+ botId: this.botId
34
+ },
35
+ usage: "markdown",
36
+ reference: raw.url,
37
+ name: raw.file_name,
38
+ expiration: {
39
+ mode: "sliding",
40
+ ...Number.isSafeInteger(raw.ttl) && raw.ttl > 0 && { windowSeconds: raw.ttl },
41
+ ...Number.isFinite(raw.expires_at) && { expiresAt: raw.expires_at * 1e3 }
42
+ }
43
+ };
44
+ }
45
+ async upload(source) {
46
+ const values = [
47
+ source?.url,
48
+ source?.data,
49
+ source?.filePath
50
+ ].filter((value) => value !== void 0);
51
+ if (values.length !== 1 || values.some((value) => typeof value !== "string" || !value)) throw new Error("Provide exactly one image source");
52
+ let bytes;
53
+ let name = source.name;
54
+ if (source.filePath) {
55
+ const info = await stat(source.filePath);
56
+ if (!info.isFile() || info.size > LIMIT) throw new Error("Markdown image must be a regular file no larger than 10 MiB");
57
+ bytes = await readFile(source.filePath);
58
+ name ??= basename(source.filePath);
59
+ } else if (source.url) {
60
+ const url = new URL(source.url);
61
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("Image URL must use HTTP or HTTPS");
62
+ const response = await axios.get(source.url, {
63
+ responseType: "arraybuffer",
64
+ timeout: 2e4,
65
+ maxContentLength: LIMIT,
66
+ headers: {
67
+ Authorization: null,
68
+ Cookie: null
69
+ }
70
+ });
71
+ bytes = Buffer.from(response.data);
72
+ name ??= basename(url.pathname) || void 0;
73
+ } else {
74
+ const data = source.data.replace(/^base64:\/\//, "");
75
+ if (data.length > Math.ceil(LIMIT / 3) * 4 || !/^[a-z\d+/]*={0,2}$/i.test(data) || data.length % 4 !== 0) throw new Error("Invalid or oversized base64 image");
76
+ bytes = Buffer.from(data, "base64");
77
+ }
78
+ if (!bytes.length || bytes.length > LIMIT) throw new Error("Markdown image must contain at most 10 MiB of image data");
79
+ const detected = await fileTypeFromBuffer(bytes);
80
+ if (!detected || !supported[detected.mime]) throw new Error("QQ Markdown materials support PNG, JPEG, GIF and WebP images");
81
+ if (!name || !source.name && !extname(name)) name = `${name || "image"}.${detected.ext}`;
82
+ if (!supported[detected.mime].includes(extname(name).toLowerCase())) throw new Error("Image filename extension must match its actual MIME type");
83
+ const key = `${createHash("sha256").update(bytes).digest("hex")}:${name}:${detected.mime}`;
84
+ const cached = this.#cache.get(key);
85
+ if (cached && cached.until > Date.now()) return structuredClone(cached.resource);
86
+ const pending = this.#pending.get(key);
87
+ if (pending !== void 0) return structuredClone(await pending);
88
+ if (this.#pending.size >= 100) throw new Error("Too many concurrent material uploads");
89
+ const task = this.#upload(bytes, name, detected.mime).then((resource) => {
90
+ if (this.#cache.size >= 100) this.#cache.delete(this.#cache.keys().next().value);
91
+ const lifetime = resource.expiration?.windowSeconds ?? 0;
92
+ if (lifetime > 0) this.#cache.set(key, {
93
+ resource,
94
+ until: Date.now() + lifetime * 1e3
95
+ });
96
+ return resource;
97
+ });
98
+ this.#pending.set(key, task);
99
+ try {
100
+ return structuredClone(await task);
101
+ } finally {
102
+ this.#pending.delete(key);
103
+ }
104
+ }
105
+ async #upload(bytes, name, mime) {
106
+ const prepared = await this.client.groupService({
107
+ method: "POST",
108
+ url: "/v2/media-images/prepare",
109
+ data: {
110
+ file_name: name,
111
+ file_size: bytes.length,
112
+ content_type: mime,
113
+ md5: createHash("md5").update(bytes).digest("hex"),
114
+ sha1: createHash("sha1").update(bytes).digest("hex")
115
+ }
116
+ });
117
+ const uploadUrl = new URL(prepared.presigned_url);
118
+ if (!["http:", "https:"].includes(uploadUrl.protocol) || !prepared.upload_id) throw new Error("QQ returned an invalid material upload task");
119
+ const uploaded = await axios.put(prepared.presigned_url, bytes, {
120
+ timeout: 2e4,
121
+ maxBodyLength: LIMIT,
122
+ maxRedirects: 0,
123
+ headers: {
124
+ "Content-Type": mime,
125
+ Authorization: null,
126
+ Cookie: null
127
+ }
128
+ }).catch(() => {
129
+ throw new Error("Markdown image binary upload failed");
130
+ });
131
+ const md5 = String(uploaded.headers.etag ?? "").replace(/^"|"$/g, "").toLowerCase();
132
+ if (md5 !== createHash("md5").update(bytes).digest("hex")) throw new Error("Markdown image upload returned an invalid ETag");
133
+ const completed = await this.client.groupService({
134
+ method: "POST",
135
+ url: "/v2/media-images/complete",
136
+ data: {
137
+ upload_id: prepared.upload_id,
138
+ md5
139
+ }
140
+ });
141
+ return {
142
+ ...this.#resource(completed),
143
+ name
144
+ };
145
+ }
146
+ async list(cursor) {
147
+ const raw = await this.client.groupService({
148
+ method: "GET",
149
+ url: "/v2/media-images",
150
+ params: { cursor }
151
+ });
152
+ return {
153
+ Items: raw.images.map((item) => this.#resource(item)),
154
+ NextCursor: raw.next_cursor || void 0,
155
+ Total: raw.total
156
+ };
157
+ }
158
+ async delete(resource) {
159
+ if (resource.owner?.platform !== "qq-bot" || resource.owner.botId !== this.botId || resource.usage !== "markdown" || !resource.id) throw new Error("Image resource does not belong to this bot and usage");
160
+ await this.client.groupService({
161
+ method: "DELETE",
162
+ url: `/v2/media-images/${encodeURIComponent(resource.id)}/delete`
163
+ });
164
+ for (const [key, entry] of this.#cache) if (entry.resource.id === resource.id) this.#cache.delete(key);
165
+ return {};
166
+ }
167
+ };
168
+
169
+ //#endregion
170
+ export { QQImageMaterials };
package/lib/register.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { getIdentity, getMaster, getQQBotConfig, platform } from "./config.js";
2
+ import { QQImageMaterials } from "./materials.js";
3
+ import { sanitizeQQText } from "./text-sanitizer.js";
2
4
  import { AT_MESSAGE_CREATE, C2C_MESSAGE_CREATE, DIRECT_MESSAGE_CREATE, GROUP_AT_MESSAGE_CREATE, MESSAGE_CREATE } from "./sends.js";
3
5
  import { normalizeFrameworkEvent, normalizeMessageUser } from "./framework-events.js";
4
6
  import { handleFrameworkAction } from "./framework-actions.js";
@@ -47,7 +49,14 @@ const register = (client, options) => {
47
49
  const botId = String(options?.botId ?? config?.app_id ?? "");
48
50
  const url = `ws://127.0.0.1:${process.env?.port || config?.port || 17117}`;
49
51
  const cbp = options?.cbp ?? cbpPlatform(url);
50
- const emit = (event, acknowledged = false) => cbp.send(normalizeFrameworkEvent(event, acknowledged));
52
+ const emit = (event, acknowledged = false) => {
53
+ const normalized = normalizeFrameworkEvent(event, acknowledged);
54
+ if (config.textSanitizer && (normalized.name === "message.create" || normalized.name === "private.message.create") && typeof normalized.value?.content === "string") {
55
+ normalized.RawMessageText = normalized.value.content;
56
+ normalized.MessageText = sanitizeQQText(normalized.value.content, botId, config.textSanitizer);
57
+ }
58
+ cbp.send(normalized);
59
+ };
51
60
  /**
52
61
  * group
53
62
  *
@@ -965,6 +974,11 @@ const register = (client, options) => {
965
974
  }
966
975
  }
967
976
  };
977
+ const materials = new QQImageMaterials(client, botId);
978
+ const assertResource = (resource, usage, target) => {
979
+ if (resource.kind !== "media-resource" || resource.type !== "image" || resource.owner?.platform !== "qq-bot" || resource.owner.botId !== botId || resource.usage !== usage || !resource.id || !resource.reference) throw new Error("Image resource does not belong to this bot or usage");
980
+ if (resource.target && (!target || resource.target.scope !== target.scope || resource.target.targetId !== target.targetId)) throw new Error("Image resource belongs to another conversation");
981
+ };
968
982
  const onactions = async (data, consume) => {
969
983
  const event = data.payload.event ?? {};
970
984
  const requestedBot = data.payload.params?.target?.BotId ?? data.payload.target?.BotId ?? data.payload.BotId ?? event.BotId;
@@ -995,6 +1009,88 @@ const register = (client, options) => {
995
1009
  return;
996
1010
  }
997
1011
  }
1012
+ if (data.action.startsWith("media.resource.")) {
1013
+ const params = data.payload.params ?? {};
1014
+ const target = normalizeTarget(params.target ?? data.payload.target);
1015
+ let result;
1016
+ if (data.action === "media.resource.capabilities") result = { usages: {
1017
+ message: {
1018
+ upload: true,
1019
+ list: false,
1020
+ delete: false
1021
+ },
1022
+ markdown: {
1023
+ upload: true,
1024
+ list: true,
1025
+ delete: true,
1026
+ maxBytes: 10485760,
1027
+ maxItems: 100
1028
+ }
1029
+ } };
1030
+ else if (data.action === "media.resource.list") {
1031
+ if (params.usage !== "markdown") throw new Error("QQ resource listing is only available for Markdown images");
1032
+ result = await materials.list(params.cursor);
1033
+ } else if (data.action === "media.resource.delete") {
1034
+ assertResource(params.resource, "markdown");
1035
+ result = await materials.delete(params.resource);
1036
+ } else if (data.action === "media.resource.upload" || data.action === "media.resource.resolve") {
1037
+ if (!["message", "markdown"].includes(params.usage)) throw new Error("Invalid image resource usage");
1038
+ if (data.action === "media.resource.resolve" && params.usage === "markdown" && config.markdownToText) throw new Error("Markdown images cannot be embedded when markdownToText is enabled");
1039
+ const image = params.image;
1040
+ if (image?.kind === "media-resource") {
1041
+ assertResource(image, params.usage, target);
1042
+ result = image;
1043
+ } else {
1044
+ if (image && (image.kind !== "media-source" || image.type !== "image")) throw new Error("Expected an image source");
1045
+ if (!image && params.type !== "image") throw new Error("Expected image upload type");
1046
+ const source = image ? image.source : params.source;
1047
+ if (params.usage === "markdown") result = await materials.upload(source);
1048
+ else {
1049
+ if (!target) throw new Error("A target is required for message image resources");
1050
+ const uploaded = await uploadMedia(target, {
1051
+ ...source,
1052
+ type: "image",
1053
+ send: false
1054
+ });
1055
+ result = {
1056
+ kind: "media-resource",
1057
+ type: "image",
1058
+ id: uploaded.fileId,
1059
+ reference: uploaded.fileId,
1060
+ owner: {
1061
+ platform,
1062
+ botId
1063
+ },
1064
+ usage: "message",
1065
+ target: {
1066
+ ...target,
1067
+ BotId: botId
1068
+ },
1069
+ name: source.name,
1070
+ expiration: {
1071
+ mode: "fixed",
1072
+ expiresAt: "expiresAt" in uploaded ? uploaded.expiresAt : void 0
1073
+ }
1074
+ };
1075
+ }
1076
+ }
1077
+ } else throw new Error("Unsupported media resource operation");
1078
+ consume([createResult(ResultCode.Ok, data.action, result)]);
1079
+ return;
1080
+ }
1081
+ if (data.action === "message.send" && data.payload.params?.format) {
1082
+ const target = normalizeTarget(data.payload.target);
1083
+ const validate = (items) => {
1084
+ for (const item of items) {
1085
+ if (item.media) {
1086
+ if (item.type !== "Image") throw new Error("Structured media must be prepared through useMessage before sending");
1087
+ assertResource(item.media, "message", target);
1088
+ }
1089
+ if ((item.type === "Markdown" || item.type === "MD.blockquote") && Array.isArray(item.value)) validate(item.value);
1090
+ }
1091
+ };
1092
+ validate(data.payload.params.format);
1093
+ }
998
1094
  const handled = await handleFrameworkAction(client, data, botId);
999
1095
  if (handled) {
1000
1096
  consume(handled);
@@ -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
  * 生成签名
package/lib/sends.js CHANGED
@@ -177,13 +177,13 @@ const formatMention = (item, mode) => {
177
177
  const value = item.value;
178
178
  const isEmptyMention = value === "everyone" || value === "all" || value === "" || typeof value !== "string";
179
179
  if (mode === "guild-public") {
180
- if (isEmptyMention) return "@everyone";
181
- if (item.options?.belong === "user") return `<@!${value}>`;
180
+ if (isEmptyMention) return "<qqbot-at-everyone />";
181
+ if (item.options?.belong === "user") return `<qqbot-at-user id="${value}" />`;
182
182
  if (item.options?.belong === "channel") return `<#${value}>`;
183
183
  return "";
184
184
  }
185
185
  if (isEmptyMention) return "";
186
- if (item.options?.belong === "user") return `<@${value}>`;
186
+ if (item.options?.belong === "user") return `<qqbot-at-user id="${value}" />`;
187
187
  return "";
188
188
  };
189
189
  /** 从消息数据中提取文本内容 */
@@ -321,6 +321,7 @@ const resolveFileData = async (item) => {
321
321
  */
322
322
  const resolveMediaUrl = async (media, uploadMedia) => {
323
323
  for (const item of media) {
324
+ if (item.type === "Image" && item.media?.kind === "media-resource") return item.media.reference;
324
325
  const fileData = await resolveFileData(item);
325
326
  if (fileData) {
326
327
  const fileInfo = await uploadMedia({
@@ -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.39",
4
4
  "description": "QQ官方平台",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -12,8 +12,12 @@
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",
19
+ "test:materials": "yarn build && node tests/materials.contract.mjs",
20
+ "test:mention": "yarn build && node tests/everyone.contract.mjs"
17
21
  },
18
22
  "dependencies": {
19
23
  "@noble/curves": "^1.7.0",
@@ -32,9 +36,6 @@
32
36
  "ws": "^8.13.0",
33
37
  "yaml": "^2.5.1"
34
38
  },
35
- "peerDependencies": {
36
- "alemonjs": "^2.1.0"
37
- },
38
39
  "types": "lib",
39
40
  "exports": {
40
41
  ".": {
@@ -100,5 +101,5 @@
100
101
  "type": "git",
101
102
  "url": "https://github.com/lemonade-lab/alemonjs.git"
102
103
  },
103
- "gitHead": "77aa1dad52568d709a460b1cdd32db6c36b6f0c2"
104
+ "gitHead": "114f342c08cb3ebbfee39b1c93fb30607d276083"
104
105
  }