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) => {
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import type { ForwardPreviewMeta } from './modules/message-actions';
|
||||
import type { BridgeInterface } from '../bridge/bridge-interface';
|
||||
import { RETCODE, failedResponse } from './types';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { summarizeParams } from '../utils/log-summary';
|
||||
|
||||
const moduleLog = createLogger('Bridge.Action');
|
||||
|
||||
import { register as registerInfo } from './actions/info';
|
||||
import { register as registerMessage } from './actions/message';
|
||||
@@ -92,7 +96,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 }>;
|
||||
// Extended NapCat-compatible
|
||||
@@ -131,8 +135,10 @@ type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiRespon
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(context: ApiActionContext) {
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
registerInfo(this, context);
|
||||
registerMessage(this, context);
|
||||
registerFriend(this, context);
|
||||
@@ -151,12 +157,25 @@ export class ApiHandler {
|
||||
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
|
||||
const handler = this.handlers.get(action);
|
||||
if (!handler) {
|
||||
this.log.debug('unknown action %s', action);
|
||||
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
|
||||
}
|
||||
|
||||
// Entry log goes to file always (debug); console only when level is
|
||||
// dialed down to debug. Caller-perspective summary lets the operator
|
||||
// grep "what did the bot get asked to do" without scraping wire logs.
|
||||
this.log.debug('%s params=%s', action, summarizeParams(params));
|
||||
|
||||
try {
|
||||
return await handler(params);
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
// the log file stays a useful signal of real internal faults.
|
||||
this.log.warn('%s failed: %s\n%s',
|
||||
action,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
HttpServerNetwork,
|
||||
@@ -13,6 +14,8 @@ import type {
|
||||
WsServerNetwork,
|
||||
} from './types';
|
||||
|
||||
const log = createLogger('OneBot.Config');
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
@@ -50,7 +53,18 @@ function generateAccessToken(): string {
|
||||
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
export interface LoadOneBotConfigOptions {
|
||||
/**
|
||||
* Persist the normalized config to disk when the file is missing or was
|
||||
* in legacy format. Default `false` so accidental call sites (read-only
|
||||
* GETs in particular) don't generate fresh access tokens, race on
|
||||
* concurrent writes, or surprise the operator with materialized files.
|
||||
* Pass `true` from boot / explicit POST handlers.
|
||||
*/
|
||||
persistDefaults?: boolean;
|
||||
}
|
||||
|
||||
export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig {
|
||||
ensureConfigDir();
|
||||
|
||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||
@@ -65,12 +79,11 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||
if (globalRaw) sources.push(globalRaw);
|
||||
if (perUinRaw) sources.push(perUinRaw);
|
||||
|
||||
const config = fromJson(sources);
|
||||
const config = fromJson(sources, !perUinRaw && !globalRaw);
|
||||
|
||||
// Persist normalized form whenever the file is missing OR was in legacy
|
||||
// format, so downstream code can rely on the unified shape on disk.
|
||||
const shouldSave = !perUinRaw || legacy;
|
||||
if (shouldSave) saveOneBotConfig(uin, config);
|
||||
if (options.persistDefaults && (!perUinRaw || legacy)) {
|
||||
saveOneBotConfig(uin, config);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
@@ -148,7 +161,7 @@ function wsClientToJson(n: WsClientNetwork): JsonObject {
|
||||
return out;
|
||||
}
|
||||
|
||||
function fromJson(sources: JsonObject[]): OneBotConfig {
|
||||
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
// Legacy top-level scalars are pulled DOWN into each adapter on the first
|
||||
// load: the on-disk schema has no globals anymore, every adapter is
|
||||
// self-describing. We compute the legacy fallbacks here so that adapters
|
||||
@@ -175,8 +188,11 @@ function fromJson(sources: JsonObject[]): OneBotConfig {
|
||||
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
|
||||
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
|
||||
|
||||
// Seed defaults if all four arrays are empty (brand-new install).
|
||||
// Seed defaults ONLY for a brand-new install (no source files at all).
|
||||
// If the operator deliberately emptied every adapter, respect that and
|
||||
// do NOT silently revive default 0.0.0.0 listeners.
|
||||
if (
|
||||
freshInstall &&
|
||||
httpServers.length === 0 &&
|
||||
httpClients.length === 0 &&
|
||||
wsServers.length === 0 &&
|
||||
@@ -354,7 +370,8 @@ function tryLoadJson(filePath: string): JsonObject | null {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -364,20 +381,6 @@ function saveJson(filePath: string, json: JsonObject): void {
|
||||
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
function deepClone(obj: JsonObject): JsonObject {
|
||||
return JSON.parse(JSON.stringify(obj)) as JsonObject;
|
||||
}
|
||||
|
||||
function deepMerge(base: JsonObject, override: JsonObject): void {
|
||||
for (const [key, value] of Object.entries(override)) {
|
||||
if (isObject(base[key]) && isObject(value)) {
|
||||
deepMerge(base[key] as JsonObject, value);
|
||||
} else {
|
||||
base[key] = value as never;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
convertGroupFileUpload,
|
||||
convertGroupMemberJoin,
|
||||
convertGroupMemberLeave,
|
||||
convertGroupMsgEmojiLike,
|
||||
convertGroupMute,
|
||||
convertGroupPoke,
|
||||
convertGroupRecall,
|
||||
@@ -98,6 +99,7 @@ export async function convertEvent(
|
||||
case 'group_essence': return convertGroupEssence(ctx, event);
|
||||
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
|
||||
case 'friend_add': return convertFriendAdd(ctx, event);
|
||||
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
|
||||
|
||||
// Requests.
|
||||
case 'friend_request': return convertFriendRequest(ctx, event);
|
||||
|
||||
@@ -21,6 +21,7 @@ type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
|
||||
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
|
||||
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
|
||||
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
|
||||
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
|
||||
|
||||
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
|
||||
return {
|
||||
@@ -187,3 +188,32 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO
|
||||
user_id: event.userUin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
|
||||
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
|
||||
* v11 standard has no slot for reactions and that's what every
|
||||
* downstream framework keys off.
|
||||
*/
|
||||
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
|
||||
// Reconstruct the OneBot message_id we originally minted for the
|
||||
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
|
||||
// matches whatever the client received at receive-time, even when
|
||||
// the message has fallen out of our store.
|
||||
const messageId = applyMessageIdResolver(
|
||||
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
|
||||
);
|
||||
return {
|
||||
time: event.time,
|
||||
self_id: ctx.selfId,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_msg_emoji_like',
|
||||
sub_type: event.isAdd ? 'add' : 'remove',
|
||||
group_id: event.groupId,
|
||||
user_id: event.operatorUin,
|
||||
operator_id: event.operatorUin,
|
||||
message_id: messageId,
|
||||
message_seq: event.msgSeq,
|
||||
likes: [{ emoji_id: event.emojiId, count: event.count }],
|
||||
};
|
||||
}
|
||||
@@ -73,6 +73,7 @@ const NOTICE_KINDS = [
|
||||
'group_essence',
|
||||
'group_file_upload',
|
||||
'friend_add',
|
||||
'group_msg_emoji_like',
|
||||
] as const satisfies readonly QQEventVariant['kind'][];
|
||||
|
||||
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -10,7 +10,7 @@ import { RKeyCache } from './instance-rkey';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
|
||||
import {
|
||||
OneBotNetworkManager,
|
||||
WsServerAdapter,
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
HttpPostAdapter,
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { createLogger, type Logger } from '../utils/logger';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format';
|
||||
|
||||
const log = createLogger('Event');
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
@@ -40,12 +41,17 @@ export class OneBotInstance {
|
||||
private online = true;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private static readonly HEARTBEAT_INTERVAL = 30000;
|
||||
private readonly log: Logger;
|
||||
|
||||
get nickname(): string { return this.bridge.identity.nickname; }
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
const uinNum = Number.parseInt(uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0
|
||||
? moduleLog.child({ uin: uinNum })
|
||||
: moduleLog;
|
||||
|
||||
this.rkeyCache = new RKeyCache();
|
||||
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
|
||||
@@ -85,10 +91,12 @@ export class OneBotInstance {
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx));
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
this.installAdaptersFromConfig(config);
|
||||
void this.networkManager.openAll();
|
||||
void this.networkManager.openAll().catch((err) => {
|
||||
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
|
||||
this.startHeartbeat();
|
||||
this.rkeyCache.warmUp(this.bridge, this.uin);
|
||||
@@ -99,7 +107,9 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
void this.applyConfigDiff(config);
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -107,7 +117,9 @@ export class OneBotInstance {
|
||||
this.stopHeartbeat();
|
||||
this.disposeEventPipeline?.();
|
||||
this.disposeEventPipeline = null;
|
||||
void this.networkManager.closeAll();
|
||||
void this.networkManager.closeAll().catch((err) => {
|
||||
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
this.messageStore.close();
|
||||
this.mediaStore.close();
|
||||
}
|
||||
@@ -136,8 +148,12 @@ export class OneBotInstance {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// NetworkManager builds the dispatch payload once and fans out to every
|
||||
// active adapter in parallel via Promise.allSettled.
|
||||
void this.networkManager.emitEvent(event);
|
||||
// active adapter in parallel via Promise.allSettled — per-adapter errors
|
||||
// are already isolated, so the outer promise should never reject. The
|
||||
// .catch is a belt-and-suspenders guard against future refactors.
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
@@ -206,7 +222,7 @@ export class OneBotInstance {
|
||||
try {
|
||||
await existing.reload(net as never);
|
||||
} catch (err) {
|
||||
log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else if (net.enabled !== false) {
|
||||
const factory = factories.get(name);
|
||||
@@ -224,56 +240,56 @@ export class OneBotInstance {
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const isGroup = event.message_type === 'group';
|
||||
|
||||
// Build message preview
|
||||
const parts: string[] = [];
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
const identity = this.bridge.identity;
|
||||
|
||||
// Walk the segment array once: render via the shared formatter for
|
||||
// non-reply segments, and resolve `reply` segments through the
|
||||
// message store so the chain reference becomes legible
|
||||
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
|
||||
const renderedParts: string[] = [];
|
||||
const message = event.message;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String(seg.type ?? '');
|
||||
const data: Record<string, unknown> = (
|
||||
typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data)
|
||||
) ? seg.data : {};
|
||||
|
||||
if (type === 'text' && data.text) {
|
||||
const text = String(data.text);
|
||||
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
parts.push(preview);
|
||||
} else if (type === 'image') {
|
||||
parts.push('[图片]');
|
||||
} else if (type === 'face') {
|
||||
parts.push('[表情]');
|
||||
} else if (type === 'at') {
|
||||
parts.push(`@${data.qq || ''}`);
|
||||
} else if (type === 'reply') {
|
||||
parts.push(`[回复:${data.id || ''}]`);
|
||||
} else if (type === 'record') {
|
||||
parts.push('[语音]');
|
||||
} else if (type === 'video') {
|
||||
parts.push('[视频]');
|
||||
const type = String((seg as JsonObject).type ?? '');
|
||||
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
|
||||
? (seg as JsonObject).data as Record<string, unknown>
|
||||
: {};
|
||||
if (type === 'reply') {
|
||||
const replyId = toInt(data.id);
|
||||
renderedParts.push(formatReply(this.messageStore, identity, replyId));
|
||||
} else {
|
||||
parts.push(`[${type}]`);
|
||||
renderedParts.push(formatMessageSegments([seg as JsonValue]));
|
||||
}
|
||||
}
|
||||
} else if (typeof message === 'string') {
|
||||
renderedParts.push(formatMessageSegments(message));
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
const idStr = `ID:${messageId}`;
|
||||
const selfTag = isSelf ? '[自身] ' : '';
|
||||
|
||||
const content = renderedParts.join(' ').trim() || '[空消息]';
|
||||
|
||||
if (isGroup) {
|
||||
const groupId = toInt(event.group_id);
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.card || sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, groupId, userId);
|
||||
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
|
||||
} else {
|
||||
const userId = toInt(event.user_id);
|
||||
const sender = event.sender as any;
|
||||
const nickname = sender?.nickname || String(userId);
|
||||
log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`);
|
||||
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
|
||||
? event.sender as JsonObject
|
||||
: {};
|
||||
const nicknameFromEvent = (sender.nickname as string) || '';
|
||||
const userPart = nicknameFromEvent
|
||||
? `[${nicknameFromEvent}(${userId})]`
|
||||
: formatUser(identity, undefined, userId);
|
||||
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export class OneBotManager {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return false;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
instance.reloadConfig(config);
|
||||
log.info('configuration reloaded: UIN=%s', uin);
|
||||
return true;
|
||||
@@ -51,7 +51,7 @@ export class OneBotManager {
|
||||
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
|
||||
if (this.instances.has(uin)) return;
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
const config = loadOneBotConfig(uin, { persistDefaults: true });
|
||||
const instance = new OneBotInstance(uin, bridge, config);
|
||||
|
||||
const activePid = bridge.activePid;
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
import type { MessageElement } from '../bridge/events';
|
||||
import type { JsonValue, JsonObject } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
@@ -16,6 +19,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 +49,12 @@ function parseCQParams(raw: string): Record<string, string> {
|
||||
}
|
||||
|
||||
function cqUnescape(text: string): string {
|
||||
// Order matters: `&` MUST be last so that, e.g., `&#91;` keeps
|
||||
// the literal `[` instead of decoding twice into `[`.
|
||||
return text
|
||||
.replace(/[/g, '[')
|
||||
.replace(/]/g, ']')
|
||||
.replace(/,/g, ',')
|
||||
.replace(/&/g, '&');
|
||||
}
|
||||
|
||||
@@ -88,7 +107,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 +116,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();
|
||||
@@ -105,16 +125,17 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'at',
|
||||
targetUin: uin,
|
||||
uid: uid || undefined,
|
||||
text: name ? `@${name} ` : `@${uin} `,
|
||||
};
|
||||
// Leave `text` undefined when the caller didn't supply a display
|
||||
// name. The element-builder then resolves it from the group roster
|
||||
// (so QQ renders `@昵称` instead of `@QQ号`).
|
||||
const element: MessageElement = { type: 'at', targetUin: uin };
|
||||
if (uid) element.uid = uid;
|
||||
if (name) element.text = `@${name} `;
|
||||
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);
|
||||
@@ -147,7 +168,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,
|
||||
};
|
||||
}
|
||||
@@ -178,13 +199,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': {
|
||||
@@ -196,11 +217,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 ?? ''),
|
||||
@@ -254,7 +274,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
const musicJson = await resp.text();
|
||||
return { type: 'json', text: musicJson };
|
||||
} catch (e) {
|
||||
console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`);
|
||||
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
|
||||
// Fallback: build a basic card locally
|
||||
const title = String(data.title ?? 'Music');
|
||||
const jsonData = JSON.stringify({
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -219,7 +241,10 @@ export async function sendPrivateForwardMessage(
|
||||
meta?: ForwardPreviewMeta,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages);
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
|
||||
// userId is plumbed through so inner image/record/video can be uploaded
|
||||
// under the recipient's scene (otherwise the OIDB private-image upload
|
||||
// has no target uid and the element builder bails).
|
||||
const forwardId = await ref.bridge.uploadForwardNodes(nodes, undefined, userId);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, [previewElement]);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
@@ -240,9 +265,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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,20 @@ export async function handleGroupAddRequest(
|
||||
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
|
||||
const parts = flag.split(':');
|
||||
if (parts.length < 3) throw new Error('invalid group request flag');
|
||||
const requestType = parts[0];
|
||||
const groupId = parseInt(parts[1], 10);
|
||||
const targetUid = parts.slice(2).join(':');
|
||||
if (!groupId) throw new Error('invalid group_id in flag');
|
||||
if (!targetUid) throw new Error('invalid request target in flag');
|
||||
|
||||
const requests = await bridge.fetchGroupRequests();
|
||||
const matching = requests.find(r => r.groupId === groupId);
|
||||
const matching = requests.find((r) => {
|
||||
if (r.groupId !== groupId) return false;
|
||||
if (requestType === 'add') return r.targetUid === targetUid;
|
||||
if (requestType === 'invite') return r.invitorUid === targetUid;
|
||||
return false;
|
||||
}) || requests.find(r => r.groupId === groupId);
|
||||
|
||||
if (!matching) {
|
||||
throw new Error('matching group request not found');
|
||||
}
|
||||
|
||||
@@ -10,21 +10,24 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { executeQuickOperation } from './quick-operation';
|
||||
|
||||
const log = createLogger('OneBot.POST');
|
||||
const moduleLog = createLogger('OneBot.POST');
|
||||
const DEFAULT_TIMEOUT_MS = 5000;
|
||||
|
||||
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private signature_: string;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.signature_ = bindingSignature(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -74,7 +77,9 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!this.isEnabled) return;
|
||||
const json = pickDispatchJson(payload, this.options);
|
||||
if (json === null) return;
|
||||
void this.postEvent(json, event);
|
||||
void this.postEvent(json, event).catch((err) => {
|
||||
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private async postEvent(payload: string, event: JsonObject): Promise<void> {
|
||||
@@ -106,11 +111,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isEnabled) {
|
||||
log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,7 +126,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
if (!operation || typeof operation !== 'object') return;
|
||||
await executeQuickOperation(event, operation, this.ctx.api);
|
||||
} catch (error) {
|
||||
log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,21 @@ import {
|
||||
} from 'http';
|
||||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.HTTP');
|
||||
const moduleLog = createLogger('OneBot.HTTP');
|
||||
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
// HTTP server never receives events — `isActive` purely tracks the
|
||||
@@ -81,7 +88,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
this.server = server;
|
||||
|
||||
server.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -90,7 +97,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
);
|
||||
});
|
||||
server.on('error', (err) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||||
@@ -136,19 +143,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
} else if (req.method === 'POST') {
|
||||
const bodyContent = await readRequestBody(req);
|
||||
if (bodyContent.trim()) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||
params = parsedBody.params as Record<string, unknown>;
|
||||
} else {
|
||||
params = parsedBody as Record<string, unknown>;
|
||||
const contentType = req.headers['content-type'] ?? '';
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
echo = parsedBody.echo;
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
} catch {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
} else if (contentType.includes('application/json') || !contentType) {
|
||||
try {
|
||||
const parsedBody = JSON.parse(bodyContent);
|
||||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||||
params = parsedBody.params as Record<string, unknown>;
|
||||
} else {
|
||||
params = parsedBody as Record<string, unknown>;
|
||||
}
|
||||
echo = parsedBody.echo;
|
||||
}
|
||||
} catch {
|
||||
if (contentType.includes('application/json')) {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||||
return;
|
||||
}
|
||||
// 无 content-type,JSON 失败则 fallback 到 urlencoded
|
||||
const parsed = new URLSearchParams(bodyContent);
|
||||
parsed.forEach((value, key) => {
|
||||
try {
|
||||
params[key] = JSON.parse(value);
|
||||
} catch {
|
||||
params[key] = value;
|
||||
}
|
||||
});
|
||||
if (params.action && !action) {
|
||||
action = String(params.action);
|
||||
delete params.action;
|
||||
}
|
||||
if (params.echo !== undefined) {
|
||||
echo = params.echo;
|
||||
delete params.echo;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -200,4 +249,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void
|
||||
res.statusCode = statusCode;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { rawDataToString, safeClose, safeSend } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Client');
|
||||
const moduleLog = createLogger('OneBot.WS-Client');
|
||||
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
|
||||
|
||||
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
@@ -26,11 +26,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
this.role = config.role ?? 'Universal';
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -111,12 +114,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = socket;
|
||||
|
||||
socket.on('open', () => {
|
||||
log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.log.info('[%s] connected %s', this.name, this.config.url);
|
||||
this.sendBootstrapMetaEvents(socket);
|
||||
});
|
||||
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, raw);
|
||||
void this.handleApiMessage(socket, raw).catch((err) => {
|
||||
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
@@ -126,7 +131,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@ import {
|
||||
type DispatchPayload,
|
||||
type EventReportOptions,
|
||||
} from '../event-filter';
|
||||
import { createLogger } from '../../utils/logger';
|
||||
import { createLogger, type Logger } from '../../utils/logger';
|
||||
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
|
||||
import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils';
|
||||
|
||||
const log = createLogger('OneBot.WS-Server');
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
interface ForwardConn {
|
||||
socket: WebSocket;
|
||||
@@ -30,10 +30,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
private readonly log: Logger;
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx);
|
||||
this.options = resolveReportOptions(config);
|
||||
const uinNum = Number.parseInt(ctx.uin, 10);
|
||||
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
|
||||
}
|
||||
|
||||
override get isActive(): boolean {
|
||||
@@ -114,7 +117,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.wss = wss;
|
||||
|
||||
wss.on('listening', () => {
|
||||
log.success(
|
||||
this.log.success(
|
||||
'[%s] listening %s:%d%s',
|
||||
this.name,
|
||||
this.config.host ?? '0.0.0.0',
|
||||
@@ -124,7 +127,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
|
||||
wss.on('error', (err: Error) => {
|
||||
log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
|
||||
@@ -145,7 +148,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
});
|
||||
socket.on('close', () => this.connections.delete(socket));
|
||||
socket.on('error', (err: Error) => {
|
||||
log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
|
||||
if (role === 'Event' || role === 'Universal') {
|
||||
|
||||
Reference in new issue
Block a user