fix(onebot): correctness pass on actions and message parser

Action-layer fixes, all cross-checked against NapCat's reference
implementation in packages/napcat-onebot:

* download_file (extended.ts:539) now sanitizes `name` via
  path.basename + resolve/relative containment check. Previously an
  authenticated client could write `../../config/onebot_<uin>.json`
  and replace access tokens / webhook URLs.
* mark_group_msg_as_read / mark_private_msg_as_read / mark_msg_as_read
  fall back to meta.targetId when the optional group_id/user_id arg
  is missing. The old code passed 0 to the Bridge. NapCat resolves the
  peer from message_id alone in MarkMsgAsRead.ts; we now match that.
* set_friend_remark / set_group_remark refuse a missing `remark` field.
  The previous `asString(...) ?? ''` silently CLEARED the remark for
  any client that forgot the parameter. NapCat's typebox schema makes
  `remark` required; we now do the same.
* upload_forward_msg threads `group_id` down to uploadForwardNodes so
  the resulting resId lives in the correct namespace (type:3 + groupUin
  vs type:1 + selfUid — see bridge/actions/forward.ts). NapCat passes
  `peer.chatType === GROUP ? +peerUid : 0` for the same reason.
  ApiActionContext.sendForwardMsg + uploadForwardMessage signatures
  pick up an optional groupId.
* Private-message reply meta now resolves senderUin from the cached
  event (real sender), with a self-id fallback when only meta exists
  (bot's own outbound message — `cacheMessageMeta` does not populate
  the event row). The old code used meta.targetId, which is the
  conversation peer — wrong when the bot replies to its own message.
* message-parser:
    - intOr(value, fallback) helper replaces parseInt(String(...)) at
      face/at/reply/image/xml/poke/node sites so non-numeric input no
      longer produces NaN downstream. Invalid face ids skip the
      element rather than emit NaN.
    - cqUnescape decodes `&#44;` (escaped comma) — the OneBot 11 spec
      requires it and clients in the wild emit it.
* Drop the dead Array.isArray(rawAuth) branch in onebot/network/utils
  (Node's headers.authorization is `string | undefined`, never an
  array) and the unused WebHonorType import in api-handler.
This commit is contained in:
时瑾 authored and DrSmoothl committed 2026-05-16 21:31:34 +08:00
1 parent 917f08ce4d
commit b2c53b56f7
6 files changed
+113 -41

No files matched your search

+58 -23
View File
@@ -2,6 +2,19 @@ import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import { RETCODE, failedResponse, okResponse } from '../types';
import { createLogger } from '../../utils/logger';
const log = createLogger('OneBot.Action');
/**
* Standard error wrapper. Logs the full error (so operators can debug) but
* surfaces only `Error.message` (or the supplied fallback) to the caller.
*/
function actionFailed(action: string, err: unknown, fallback = 'action failed') {
const detail = err instanceof Error ? err.message : String(err);
log.warn('%s failed: %s', action, detail);
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : fallback);
}
/**
* Pull NapCat-compatible forward preview overrides off a send_*_forward_msg
@@ -157,8 +170,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
if (!meta || !meta.isGroup) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message');
}
@@ -167,8 +178,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence);
return okResponse();
});
@@ -180,8 +190,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
if (!meta || meta.isGroup) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message');
}
@@ -190,8 +198,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session');
}
await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence);
return okResponse();
});
@@ -205,15 +212,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const meta = ctx.getMessageMeta(messageId);
if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
if (targetId && targetId !== meta.targetId) {
return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session');
}
if (meta.isGroup) {
await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence);
} else {
await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence);
await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence);
}
return okResponse();
});
@@ -310,7 +316,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const groupId = asNumber(params.group_id);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendForwardMsg(messages);
// Group and private forwards live in different resId namespaces
// (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid).
// Passing groupId through is what makes the resulting resId usable
// when the caller later sends it into the same group.
const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined);
const data: Record<string, unknown> = {
res_id: result.forwardId,
forward_id: result.forwardId,
@@ -320,10 +330,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
return okResponse(data as any);
});
// Kept for backward compat with clients that follow the historical
// gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg.
h.registerAction('upload_foward_msg', async (params) => {
const messages = asMessage(params.messages ?? params.message);
const groupId = asNumber(params.group_id);
if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required');
const result = await ctx.sendForwardMsg(messages);
const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined);
return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 });
});
@@ -482,17 +495,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_friend_remark', async (params) => {
const userId = asNumber(params.user_id);
const remark = asString(params.remark) ?? '';
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.bridge.setFriendRemark(userId, remark);
// remark must be explicitly provided. Falling back to '' on a missing
// field would silently CLEAR the operator's existing remark.
if (params.remark === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)');
}
await ctx.bridge.setFriendRemark(userId, asString(params.remark));
return okResponse();
});
h.registerAction('set_group_remark', async (params) => {
const groupId = asNumber(params.group_id);
const remark = asString(params.remark) ?? '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.setGroupRemark(groupId, remark);
if (params.remark === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)');
}
await ctx.bridge.setGroupRemark(groupId, asString(params.remark));
return okResponse();
});
@@ -545,14 +564,29 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
const fs = await import('fs');
const pathMod = await import('path');
const cryptoMod = await import('crypto');
const tempDir = pathMod.join('data', 'downloads');
const tempDir = pathMod.resolve('data', 'downloads');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
// Sanitize file name: strip any path components, reject anything that
// resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"`
// would let an authenticated OneBot client overwrite arbitrary files
// (config / dist / node_modules) under the working directory.
const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => {
const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex');
const safeName = pathMod.basename(raw);
if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null;
const resolved = pathMod.resolve(tempDir, safeName);
const rel = pathMod.relative(tempDir, resolved);
if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null;
return resolved;
};
let filePath: string;
if (base64) {
const buf = Buffer.from(base64, 'base64');
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
filePath = pathMod.join(tempDir, fileName);
const safe = resolveSafePath(name, buf);
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
filePath = safe;
fs.writeFileSync(filePath, buf);
} else {
const response = await fetch(url!, {
@@ -560,11 +594,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
});
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
const buf = Buffer.from(await response.arrayBuffer());
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
filePath = pathMod.join(tempDir, fileName);
const safe = resolveSafePath(name, buf);
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
filePath = safe;
fs.writeFileSync(filePath, buf);
}
return okResponse({ file: pathMod.resolve(filePath) });
return okResponse({ file: filePath });
});
h.registerAction('set_qq_profile', async (params) => {
+1 -4
View File
@@ -12,9 +12,6 @@ import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { WebHonorType } from '@/bridge/web/group-honor';
// import {ClientKeyInfo} from "@/bridge/bridge";
export interface MessageSendResult {
messageId: number;
meta?: MessageMeta;
@@ -91,7 +88,7 @@ export interface ApiActionContext {
getDownloadRKeys: () => Promise<JsonObject[]>;
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
+1 -1
View File
@@ -158,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
sendForwardMsg: (messages) => uploadForwardMessage(ref, messages),
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block),
+25 -9
View File
@@ -16,6 +16,19 @@ export interface ParseMessageOptions {
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
/**
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
* when the input can't be parsed as a finite integer — `parseInt('abc')`
* is `NaN`, which silently turns into `0`/`null` further down the wire
* pipeline and produces undebuggable protocol-level failures.
*/
function intOr(value: unknown, fallback = 0): number {
if (value === undefined || value === null) return fallback;
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
@@ -33,9 +46,12 @@ function parseCQParams(raw: string): Record<string, string> {
}
function cqUnescape(text: string): string {
// Order matters: `&amp;` MUST be last so that, e.g., `&amp;#91;` keeps
// the literal `&#91;` instead of decoding twice into `[`.
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
@@ -88,7 +104,8 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return text ? { type: 'text', text } : null;
}
case 'face': {
const id = parseInt(String(data.id ?? '0'), 10);
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
}
case 'at': {
@@ -96,7 +113,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = parseInt(qq, 10);
const uin = intOr(qq, 0);
if (uin <= 0) return null;
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
@@ -114,8 +131,8 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return element;
}
case 'reply': {
const id = parseInt(String(data.id ?? '0'), 10);
if (!Number.isInteger(id) || id === 0) return null;
const id = intOr(data.id, 0);
if (id === 0) return null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
@@ -148,7 +165,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
type: 'image',
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
flash: data.type === 'flash',
subType: parseInt(String(data.subType ?? '0'), 10),
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
}
@@ -179,13 +196,13 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return {
type: 'xml',
text: String(data.data ?? ''),
subType: parseInt(String(data.id ?? '0'), 10),
subType: intOr(data.id, 0),
};
}
case 'poke': {
return {
type: 'poke',
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
faceId: intOr(data.type ?? data.id, 0),
};
}
case 'forward': {
@@ -197,11 +214,10 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
const uin = String(data.user_id ?? data.uin ?? '0');
const name = String(data.nickname ?? data.name ?? '');
return {
type: 'node',
targetUin: parseInt(uin, 10) || 0,
targetUin: intOr(data.user_id ?? data.uin, 0),
text: name,
// Raw content is stored as JSON string in resId for later processing
resId: JSON.stringify(data.content ?? ''),
@@ -99,10 +99,32 @@ export async function sendPrivateMessage(
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
// Prefer the cached event (it carries the REAL sender). When only
// meta exists — typically because the message we're replying to was
// sent by the bot itself and never round-tripped through dispatch
// (reportSelfMessage off / no message_sent event) — fall back to
// selfId. The previous code used `meta.targetId` here, which is the
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
// self-reply.
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
const senderUin = typeof event.user_id === 'number'
? event.user_id
: parseInt(String(event.user_id || '0'), 10);
const time = typeof event.time === 'number'
? event.time
: parseInt(String(event.time || '0'), 10);
const meta = ref.messageStore.findMeta(replyMessageId);
return {
senderUin,
time,
random: meta?.random ?? 0,
};
}
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId,
senderUin: ref.selfId,
time: meta.timestamp,
random: meta.random,
};
@@ -240,9 +262,12 @@ export async function sendPrivateForwardMessage(
export async function uploadForwardMessage(
ref: OneBotInstanceContext,
messages: JsonValue,
groupId?: number,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
// groupId controls the resId namespace (group vs private). Without it,
// a resId minted here is unusable when later sent into a group.
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
return { forwardId };
}
+1 -2
View File
@@ -6,8 +6,7 @@ import type { WebSocket } from '@snowluma/websocket';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');