Merge upstream/dev into feat/onebot
This commit is contained in:
commit
0d40a03f28
122 files changed
+7842
-1099
No files matched your search
@@ -3,6 +3,62 @@ import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||
|
||||
// Bounded download for the OneBot `download_file` action. An authenticated
|
||||
// client could otherwise hand us a multi-GB URL (or chunked response with
|
||||
// no Content-Length) and OOM the bot — `await response.arrayBuffer()`
|
||||
// happily allocates the whole payload before any size check fires.
|
||||
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
|
||||
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
|
||||
|
||||
async function fetchDownloadFile(
|
||||
url: string,
|
||||
headers: Record<string, string>,
|
||||
maxBytes: number,
|
||||
timeoutMs: number,
|
||||
): Promise<Buffer> {
|
||||
const response = await fetch(url, {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`);
|
||||
|
||||
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw new Error(`download too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`download too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// Stream so a server that omits / understates Content-Length can't make
|
||||
// us buffer past maxBytes — abort the read as soon as the running total
|
||||
// crosses the cap.
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw new Error(`download too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
return Buffer.concat(chunks, total);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull NapCat-compatible forward preview overrides off a send_*_forward_msg
|
||||
* payload. All four fields are optional — when omitted, the module layer
|
||||
@@ -157,8 +213,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 +221,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 +233,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 +241,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 +255,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 +359,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 +373,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 +538,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,26 +607,55 @@ 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 });
|
||||
|
||||
let filePath: string;
|
||||
// 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 buf: Buffer;
|
||||
if (base64) {
|
||||
const buf = Buffer.from(base64, 'base64');
|
||||
const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex');
|
||||
filePath = pathMod.join(tempDir, fileName);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
// Every 4 base64 chars decode to at most 3 bytes. Reject before
|
||||
// `Buffer.from` allocates anything to avoid OOM on a giant payload
|
||||
// that wouldn't pass the post-decode check anyway.
|
||||
const upperBound = Math.floor((base64.length * 3) / 4);
|
||||
if (upperBound > DOWNLOAD_FILE_MAX_BYTES) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||
}
|
||||
buf = Buffer.from(base64, 'base64');
|
||||
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) {
|
||||
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||
}
|
||||
} else {
|
||||
const response = await fetch(url!, {
|
||||
headers: parseDownloadHeaders(params.headers),
|
||||
});
|
||||
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);
|
||||
fs.writeFileSync(filePath, buf);
|
||||
try {
|
||||
buf = await fetchDownloadFile(
|
||||
url!,
|
||||
parseDownloadHeaders(params.headers),
|
||||
DOWNLOAD_FILE_MAX_BYTES,
|
||||
DOWNLOAD_FILE_TIMEOUT_MS,
|
||||
);
|
||||
} catch (err) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
return okResponse({ file: pathMod.resolve(filePath) });
|
||||
|
||||
const safe = resolveSafePath(name, buf);
|
||||
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
|
||||
// Async write so we don't block the event loop on a GiB-class download
|
||||
// (the prior `writeFileSync` stalled every other bot action while it ran).
|
||||
await fs.promises.writeFile(safe, buf);
|
||||
return okResponse({ file: safe });
|
||||
});
|
||||
|
||||
h.registerAction('set_qq_profile', async (params) => {
|
||||
|
||||
Reference in new issue
Block a user