Merge upstream/dev into feat/onebot

This commit is contained in:
H3CoF6 committed 2026-05-19 02:40:14 +08:00
commit 0d40a03f28
122 files changed
+7842 -1099

No files matched your search

@@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise<St
request: {
schema: OidbStrangerStatusReqSchema,
value: { uin, key: [{ key: 27372 }] },
// Same UIN-form flag fetchUserProfile sets — without it newer
// QQ NT rejects with `[oidb] one of uid/openid is invaild`.
isUid: true,
},
response: { schema: OidbStrangerStatusRespSchema },
});
+34 -3
View File
@@ -28,12 +28,23 @@ const forwardResCache = new Map<string, ForwardNodePayload[]>();
async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
userUid?: string,
): Promise<Record<string, unknown>> {
const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin);
if (fromUin <= 0) throw new Error('forward node user uin is invalid');
const nickname = node.nickname.trim() || String(fromUin);
const elems = await buildSendElems(node.elements);
// image/record/video upload inside a forward node must be scoped to the
// forward's recipient: group → groupId, private → recipient uid.
// Without this the OIDB upload (0x11c4/0x11c5) has no scene and the
// element builder throws "private image target uid is missing".
const sendCtx = groupId !== undefined
? { bridge, groupId }
: userUid
? { bridge, userUid }
: { bridge };
const elems = await buildSendElems(node.elements, sendCtx);
const now = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
const seq = Math.floor(Math.random() * 9000000) + 1000000;
@@ -62,12 +73,32 @@ async function buildForwardPushBody(
};
}
export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise<string> {
export async function uploadForwardNodes(
bridge: Bridge,
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<string> {
if (!Array.isArray(nodes) || nodes.length === 0) {
throw new Error('forward nodes are required');
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node)));
// For a private forward to `userId`, any image/record/video inside a node
// needs the recipient's uid as upload scene. Resolve it once up-front,
// and only when at least one node actually contains media (saves an RPC
// for text-only forwards).
let userUid: string | undefined;
if (groupId === undefined && userId !== undefined && userId > 0) {
const hasMedia = nodes.some(node => node.elements.some(
e => e.type === 'image' || e.type === 'record' || e.type === 'video',
));
if (hasMedia) {
const resolved = await bridge.resolveUserUid(userId);
if (resolved) userUid = resolved;
}
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid)));
const longMsgResult = protoEncode({
action: [
{
@@ -9,7 +9,7 @@ import type { Bridge } from '../bridge';
import { protoEncode } from '../../protobuf/decode';
import { runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils';
import {
OidbGroupFileCountViewReqSchema,
OidbGroupFileCountViewRespSchema,
@@ -288,7 +288,9 @@ export async function uploadGroupFile(
folderId = '/',
uploadFile = true,
): Promise<UploadFileResult> {
const loaded = await loadBinarySource(source, 'file');
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
@@ -366,7 +368,9 @@ export async function uploadPrivateFile(
name = '',
uploadFile = true,
): Promise<UploadFileResult> {
const loaded = await loadBinarySource(source, 'file');
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
const targetUid = await bridge.resolveUserUid(userId);
+25 -5
View File
@@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise<FriendInfo[]> {
// ---------------------------------------------------------------------------
export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
// The config flags ask QQ which per-group fields to include in the
// response. Asking for everything looks innocent on small accounts
// but on ~200+ groups it makes the QQ NT process write a payload
// large enough to blow the named-pipe write buffer — we then read
// EPIPE and the whole session dies. See issue #42.
//
// The user-verified safe combination: keep `config1.*` mostly on
// (the response decoder pulls groupOwner / memberMax / memberCount /
// groupName / description / question / announcement from this
// group), but turn off the costly groups of bools that never map
// back to a decoded field:
// - config1.field5002, field5003 (expansive 5xxx-range descriptors)
// - all of config2 (auxiliary per-group blob the decoder ignores)
const allTrue = true;
const body = {
config: {
@@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise<QQGroupInfo[]> {
question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue,
field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue,
field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue,
field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue,
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
},
config2: {
field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue,
field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue,
field1: false, field2: false, field3: false, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
},
@@ -208,16 +221,23 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro
export async function fetchUserProfile(bridge: Bridge, uin: number): Promise<UserProfileInfo> {
const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037];
// Only `uin` and `keys` — see OidbUserInfoRequestSchema for why
// sending field 2 makes the server reject the request.
const body = {
uin,
field2: 0,
keys: keys.map(k => ({ key: k })),
};
// Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the
// name is historical, the wire semantic is "this is the UIN-form
// variant of the call"). Without it newer QQ NT versions take the
// UID-form validation path, find neither uid nor openid in the body
// and bounce the request with `[oidb] one of uid/openid is invaild`.
// Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1).
const resp = await runOidb<any>(bridge, {
cmd: 'OidbSvcTrpcTcp.0xfe1_2',
oidbCmd: 0xFE1, subCmd: 2,
request: { schema: OidbUserInfoRequestSchema, value: body },
request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true },
response: { schema: OidbUserInfoResponseSchema },
});
+1 -1
View File
@@ -100,7 +100,7 @@ export interface BridgeInterface {
likeGroupAlbumMedia(groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean): Promise<any>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───
+10 -4
View File
@@ -20,10 +20,16 @@ export interface OidbCall<TResp = void> {
schema: ProtoSchema;
value: any;
/**
* Sets the OIDB envelope `reserved` field to 1 when true. A handful
* of commands (group/friend list, rkey download) operate on
* UID-keyed data and require this flag — the wire format is
* otherwise identical.
* Sets the OIDB envelope `reserved` field to 1 when true.
*
* The name is historical and misleading: empirically (see Lagrange
* FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own
* highway uploads) the `reserved = 1` flag indicates the UIN-form
* variant of an OIDB call — it tells newer QQ NT to translate the
* UIN in the body to an internal UID rather than running the
* UID-form validator that expects a uid/openid string in the body.
*
* Omit (default false) for genuinely UID-keyed calls.
*/
isUid?: boolean;
};
+1 -1
View File
@@ -461,7 +461,7 @@ export class Bridge implements BridgeInterface {
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }
+28 -4
View File
@@ -37,19 +37,43 @@ function makeFaceElem(faceId: number): ProtoElem {
};
}
function makeMentionElem(element: MessageElement): ProtoElem {
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
if (!ctx || !targetUin) return '';
if (ctx.groupId !== undefined) {
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
return member?.card?.trim() || member?.nickname?.trim() || '';
}
const friend = ctx.bridge.identity.findFriend(targetUin);
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
}
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
const mentionAll = element.uid === 'all' || element.targetUin === 0;
const targetUin = element.targetUin ?? 0;
const extra = protoEncode({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : (element.targetUin ?? 0),
uin: mentionAll ? 0 : targetUin,
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
}, MentionExtraSendSchema);
// Prefer an explicit display string from the caller; otherwise look the
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
// Falls back to the bare uin when the roster doesn't know them yet.
let str = element.text;
if (!str) {
if (mentionAll) {
str = '@全体成员 ';
} else {
const name = resolveMentionDisplay(ctx, targetUin);
str = name ? `@${name} ` : `@${targetUin} `;
}
}
return {
text: {
str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `),
str,
pbReserve: extra,
} as any,
};
@@ -260,7 +284,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'at':
result.push(makeMentionElem(elem));
result.push(makeMentionElem(elem, ctx));
break;
case 'reply':
+18 -1
View File
@@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent {
userUin: number;
}
export interface GroupMsgEmojiLikeEvent extends QQEvent {
kind: 'group_msg_emoji_like';
groupId: number;
operatorUin: number;
operatorUid: string;
/** Sequence of the message that was reacted to (server-assigned msg_seq). */
msgSeq: number;
/** Emoji ID. QQ system faces are short numeric strings; market faces
* are alphanumeric. We keep the wire string verbatim. */
emojiId: string;
/** Multiplicity of the reaction event. Usually 1. */
count: number;
/** True when the reaction is being added; false when removed. */
isAdd: boolean;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -246,4 +262,5 @@ export type QQEventVariant =
| GroupPokeEvent
| GroupEssenceEvent
| GroupFileUploadEvent
| FriendAddEvent;
| FriendAddEvent
| GroupMsgEmojiLikeEvent;
@@ -129,10 +129,31 @@ export function buildHighwayExtend(
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection({ host, port }, () => resolve(socket));
let settled = false;
const onTimeout = () => {
if (settled) return;
settled = true;
socket.destroy();
reject(new Error('TCP connect timeout'));
};
const onError = (err: Error) => {
if (settled) return;
settled = true;
reject(err);
};
const socket = net.createConnection({ host, port }, () => {
if (settled) return;
settled = true;
// Drop the connect-only listeners so subsequent IO errors / idle
// timeouts don't try to reject this already-resolved promise.
socket.setTimeout(0);
socket.removeListener('timeout', onTimeout);
socket.removeListener('error', onError);
resolve(socket);
});
socket.setTimeout(timeoutMs);
socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); });
socket.on('error', reject);
socket.once('timeout', onTimeout);
socket.once('error', onError);
});
}
@@ -148,8 +169,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
let headerEnd = -1;
let contentLength = 0;
let totalNeeded = 0;
let settled = false;
const checkComplete = () => {
const detach = () => {
socket.off('data', onData);
socket.off('error', onError);
socket.off('close', onClose);
};
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
detach();
fn();
};
const onData = (chunk: Buffer) => {
chunks.push(chunk);
const buf = Buffer.concat(chunks);
if (headerEnd < 0) {
const idx = buf.indexOf('\r\n\r\n');
@@ -162,19 +196,19 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
}
}
if (headerEnd >= 0 && buf.length >= totalNeeded) {
socket.removeAllListeners('data');
socket.removeAllListeners('error');
resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)));
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
}
};
socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); });
socket.on('error', reject);
socket.on('close', () => {
const onError = (err: Error) => finish(() => reject(err));
const onClose = () => finish(() => {
const buf = Buffer.concat(chunks);
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
else reject(new Error('connection closed before response'));
});
socket.on('data', onData);
socket.on('error', onError);
socket.on('close', onClose);
});
}
@@ -7,6 +7,7 @@
import type { Bridge } from '../bridge';
import type { MessageElement } from '../events';
import { createLogger } from '../../utils/logger';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client';
import {
finalizeMediaMsgInfo,
@@ -16,6 +17,14 @@ import {
} from './pipeline';
import { computeHashes, detectImageFormat, loadBinarySource } from './utils';
const moduleLog = createLogger('Highway.Image');
function loggerFor(bridge: Bridge) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
interface ImageData {
/** Empty when the caller is forwarding from cached fingerprints. */
bytes: Uint8Array;
@@ -106,7 +115,13 @@ export async function uploadImageMsgInfo(
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const image = await loadImage(element);
log.debug('uploading %d bytes md5=%s... → %s %s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
const uploads: MediaSubFileUpload[] = [{
source: 'top',
@@ -25,6 +25,9 @@ import {
NTV2UploadRichMediaRespSchema,
} from '../proto/highway';
import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client';
import { createLogger } from '../../utils/logger';
const moduleLog = createLogger('Highway');
// ─────────────── public types ───────────────
@@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array {
export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
const label = params.label ?? 'media';
const raw = bridge.identity?.uin;
const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
const log = Number.isFinite(uinNum) && uinNum > 0
? moduleLog.child({ uin: uinNum })
: moduleLog;
// Build the full body once. Pulling this in here means each format file
// only specifies the seven fields that actually vary.
@@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
return session;
};
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
const uKey = target?.uKey ?? '';
@@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<any> {
sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both
sub.subFileIndex ?? 0,
);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source));
const t0 = Date.now();
await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
}
if (!didPut) {
log.debug('%s fast-upload hit (server already had bytes)', label);
}
return upload;
+15 -2
View File
@@ -22,7 +22,13 @@ import {
type MediaSubFileUpload,
} from './pipeline';
const log = createLogger('Ptt');
const moduleLog = createLogger('Highway.Ptt');
function loggerFor(bridge: Bridge) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
export const PRIVATE_PTT_CMD_ID = 1007;
export const GROUP_PTT_CMD_ID = 1008;
@@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise<PttPay
const silk = await encodeSilk(inputPath, tempDir);
if (silk.converted) {
cleanups.push(() => { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } });
log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration);
}
const silkBytes = new Uint8Array(fs.readFileSync(silk.path));
@@ -141,8 +147,15 @@ export async function uploadPttMsgInfo(
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const tempDir = defaultPttTempDir();
const ptt = await loadPtt(element, tempDir);
log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds',
ptt.fileSize,
ptt.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid),
ptt.duration);
try {
const uploads: MediaSubFileUpload[] = [{
source: 'top',
+74 -5
View File
@@ -11,6 +11,20 @@ export interface LoadedBinary {
fileName: string;
}
/**
* Default cap on a single binary load issued through this helper. Callers
* that route here (image / voice via base64+HTTP, group/private file
* uploads, avatar) get bounded reads. Not all callers route through here
* — in particular `video-upload.stageVideoSource` reads local-video files
* directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private
* file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's
* file protocol legitimately supports up to 4 GiB.
*/
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
const FETCH_TIMEOUT_MS = 60_000;
export interface ImageHashes {
md5: Uint8Array;
sha1: Uint8Array;
@@ -54,24 +68,74 @@ export function resolveLocalFilePath(source: string): string | null {
return filePath;
}
export async function loadBinarySource(source: string, resourceName: string): Promise<LoadedBinary> {
export async function loadBinarySource(
source: string,
resourceName: string,
maxBytes: number = DEFAULT_MAX_BINARY_SIZE,
): Promise<LoadedBinary> {
if (!source) throw new Error(`${resourceName} source is empty`);
if (/^base64:\/\//i.test(source)) {
return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' };
const bytes = Buffer.from(source.slice(9), 'base64');
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
return { bytes, fileName: '' };
}
if (/^https?:\/\//i.test(source)) {
const resp = await fetch(source);
const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
const bytes = new Uint8Array(await resp.arrayBuffer());
const declared = Number(resp.headers.get('content-length') ?? '0');
if (Number.isFinite(declared) && declared > maxBytes) {
throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`);
}
const fileName = guessFileNameFromUrl(source);
// Stream the body incrementally so a server that omits or
// understates Content-Length can't make us buffer a chunked response
// past maxBytes — `await resp.arrayBuffer()` would happily allocate
// the entire payload before we get a chance to length-check it.
const reader = resp.body?.getReader();
if (!reader) {
const bytes = new Uint8Array(await resp.arrayBuffer());
if (bytes.length > maxBytes) {
throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
}
return { bytes, fileName };
}
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(`${resourceName} too large: > ${maxBytes}`);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return { bytes, fileName };
}
const filePath = resolveLocalFilePath(source);
if (!filePath) throw new Error(`${resourceName} source is not a local file`);
const stat = fs.statSync(filePath);
if (stat.size > maxBytes) {
throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`);
}
const bytes = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
return { bytes, fileName };
@@ -183,7 +247,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat {
if (offset + 4 > bytes.length) break;
const segLen = readBE16(bytes, offset + 2);
if (segLen < 2 || offset + 2 + segLen > bytes.length) break;
if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) {
// Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC
// (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT
// and friends, then misread Huffman table bytes as image dimensions.
const isSof = marker >= 0xC0 && marker <= 0xCF
&& marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC;
if (isSof && segLen >= 7 && offset + 9 <= bytes.length) {
height = readBE16(bytes, offset + 5);
width = readBE16(bytes, offset + 7);
return { format: 1000, width, height };
@@ -29,7 +29,13 @@ import {
type MediaSubFileUpload,
} from './pipeline';
const log = createLogger('Video');
const moduleLog = createLogger('Highway.Video');
function loggerFor(bridge: Bridge) {
const raw = bridge.identity?.uin;
const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0;
return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
}
export const PRIVATE_VIDEO_CMD_ID = 1001;
export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002;
@@ -280,6 +286,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
const local = resolveLocalFilePath(source);
if (local && fs.existsSync(local)) {
// Pre-check on disk size BEFORE reading bytes into memory. The later
// `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only
// run after we'd already allocated the entire file (so a 10 GiB
// local path still OOMs us before the check fires).
const stat = fs.statSync(local);
if (stat.size > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
}
return {
bytes: new Uint8Array(fs.readFileSync(local)),
filePath: local,
@@ -287,7 +301,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu
};
}
const loaded = await loadBinarySource(source, 'video');
const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE);
const fileName = element.fileName || loaded.fileName || '';
const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`);
fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes));
@@ -315,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
try {
thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes;
} catch (err) {
log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err));
}
}
@@ -329,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{
thumbBytes = new Uint8Array(info.image);
}
} catch (err) {
log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err));
}
}
@@ -375,7 +389,7 @@ async function loadVideo(element: MessageElement): Promise<VideoPayload> {
const staged = await stageVideoSource(element, tempDir, cleanups);
if (staged.bytes.length === 0) throw new Error('video file is empty');
if (staged.bytes.length > MAX_VIDEO_SIZE) {
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`);
throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`);
}
const hashes = computeHashes(staged.bytes);
@@ -422,7 +436,13 @@ export async function uploadVideoMsgInfo(
targetIdOrUid: string | number,
element: MessageElement,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const video = await loadVideo(element);
log.debug('uploading %d bytes md5=%s... → %s %s',
video.fileSize,
video.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
try {
const uploads: MediaSubFileUpload[] = [
{
@@ -487,11 +507,17 @@ export async function uploadVideoMsgInfo(
subFileType: 100,
},
],
// Scene tag the NTV2 upload registers under. image-upload and
// ptt-upload both differentiate (group=2, c2c=1); video was
// hardcoded to the group value, which contributed to the c2c
// send-back rejection (PbSendMsg result=79).
compatQmsgSceneType: isGroup ? 2 : 1,
// Hardcoded 2 even on c2c (matches NapCat). Image/PTT use
// `isGroup ? 2 : 1` because their legacy compat elements differ
// per scene (notOnlineImage vs customFace; ptt c2c vs group),
// but the legacy `videoFile` element has no scene split — its
// fromChatType/toChatType live inside the element itself — so
// the server generates a single group-shaped compat payload
// regardless. Setting 1 here makes the server emit a c2c-scene
// shaped compat blob that old QQ clients fail to resolve,
// showing the message as "视频已过期" on those receivers while
// new clients (which only read the commonElem) display fine.
compatQmsgSceneType: 2,
extBizInfo: {
pic: { bizType: 0, textSummary: 'Nya~' },
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
+15 -3
View File
@@ -6,9 +6,9 @@ import type {
FriendInfo, GroupMemberInfo, QQGroupInfo,
UserProfileInfo, GroupRequestInfo,
} from './qq-info';
import { createLogger } from '../utils/logger';
import { createLogger, type Logger } from '../utils/logger';
const log = createLogger('Identity');
const moduleLogger = createLogger('Identity');
/**
* Hooks Identity uses when its read methods miss every cache layer. Wired in
@@ -112,9 +112,14 @@ export class IdentityService {
private readonly db: DatabaseSync | null;
private inTransaction = false;
private fetcher: IdentityFetcher | null = null;
private readonly log: Logger;
constructor(uin: string, dbPath: string | null) {
this.uin_ = uin;
const uinNum = Number.parseInt(uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0
? moduleLogger.child({ uin: uinNum })
: moduleLogger;
if (!dbPath) {
this.db = null;
@@ -440,6 +445,13 @@ export class IdentityService {
const normalizedUid = normalizeUid(uid);
const normalizedUin = normalizeUin(uin);
if (!normalizedUid || normalizedUin === null) return;
// Drop any stale mapping for the old partner first; otherwise the two
// maps disagree (`findUinByUid(oldUid) -> uin` while
// `findUidByUin(uin) -> newUid`) after a uid/uin re-binding.
const oldUid = this.uidByUin.get(normalizedUin);
if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid);
const oldUin = this.uinByUid.get(normalizedUid);
if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin);
this.uinByUid.set(normalizedUid, normalizedUin);
this.uidByUin.set(normalizedUin, normalizedUid);
}
@@ -833,7 +845,7 @@ export class IdentityService {
try {
fn();
} catch (err) {
log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err));
}
}
}
@@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums';
import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
} from '../helpers';
import { createLogger } from '../../../utils/logger';
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
@@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
}
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
return [];
};
@@ -1,12 +1,14 @@
// Handles Event0x2DC wrapper (732). Internal switch on subType dispatches
// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21).
// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) /
// GroupGreyTip (20) / GroupEssence (21).
import { protoDecode } from '../../../protobuf/decode';
import {
GroupMuteSchema, NotifyMessageBodySchema,
GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema,
} from '../../proto/notify';
import type {
GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
QQEventVariant,
} from '../../events';
import type { MsgPushDecoder } from '../registry';
@@ -16,14 +18,19 @@ import {
resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue,
unwrapGroupNotifyPayload,
} from '../helpers';
import { createLogger } from '../../../utils/logger';
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
}
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
return [];
};
@@ -104,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
};
return [ev];
}
// Magic prefix QQ prepends to the GroupReactNotify payload inside
// body.msgContent for Event0x2DC subType=16. Same value NapCat strips
// (see api/group.ts: `msgContent?.slice(7)`).
const GROUP_REACT_PREFIX_BYTES = 7;
// Discriminator on GroupReactNotify.field13 — same subType is reused
// for other notify variants, only 35 means "emoji react". Anything
// else falls through to MsgPush.Unknown for protocol-drift visibility.
const GROUP_REACT_DISCRIMINATOR = 35;
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protoDecode(payload, GroupReactNotifySchema);
if (!notify) return [];
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
return [];
}
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
if (!content) return [];
const groupId = Number(notify.groupUin ?? 0n);
const operatorUid = content.operatorUid ?? '';
const emojiId = content.code ?? '';
const count = content.count ?? 1;
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
// removed. Older payloads occasionally omit it; default to "add"
// since most clients can only generate add events.
const isAdd = (content.type ?? 1) === 1;
const msgSeq = Number(target?.seq ?? 0n);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
}
@@ -21,6 +21,7 @@ export enum PkgType {
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
@@ -9,6 +9,7 @@ import type { MsgPushContext } from './context';
import type { PkgType } from './enums';
const log = createLogger('MsgPush');
const unknownLog = createLogger('MsgPush.Unknown');
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
@@ -27,7 +28,13 @@ export class MsgPushRegistry {
decode(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) return [];
if (!decoder) {
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
return [];
}
try {
return decoder(ctx);
} catch (e) {
+48 -56
View File
@@ -20,10 +20,23 @@ import type { PacketInfo } from '../protocol/types';
import type { QQEventVariant } from './events';
import type { IdentityService } from './identity-service';
import type { BridgeEventBus } from './event-bus';
import { createLogger } from '../utils/logger';
import { createLogger, type Logger } from '../utils/logger';
import { formatEvent } from '../utils/event-format';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
const moduleLog = createLogger('Bridge');
const moduleEventLog = createLogger('Event');
// Notice kinds that get logged as a warning (operationally important
// state changes that an operator probably wants to see at default
// info level). Everything else falls through to info.
const WARN_EVENT_KINDS = new Set([
'group_recall',
'friend_recall',
'group_member_leave',
'group_mute',
'friend_request',
'group_invite',
]);
type GroupMemberIdentityEvent = Extract<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
@@ -43,8 +56,18 @@ export interface PacketPipelineDeps {
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
private readonly log: Logger;
private readonly eventLog: Logger;
constructor(private readonly deps: PacketPipelineDeps) {}
constructor(private readonly deps: PacketPipelineDeps) {
// Tag every line we emit with this Bridge's UIN so per-account file
// routing works. Unparseable uin (shouldn't happen) falls back to
// the module-level logger so we still log, just without the slot.
const uinNum = Number.parseInt(deps.identity.uin, 10);
const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null;
this.log = bind ? moduleLog.child(bind) : moduleLog;
this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog;
}
registerCmd(cmd: string, parser: CmdParser): void {
const arr = this.cmdHandlers_.get(cmd) ?? [];
@@ -65,15 +88,18 @@ export class IncomingPacketPipeline {
const events = handler(pkt, this.deps.identity);
for (const event of events) {
if (this.needsPreDispatchIdentityRefresh(event)) {
void this.dispatchAfterIdentityRefresh(event);
void this.dispatchAfterIdentityRefresh(event).catch((err) => {
this.log.warn('dispatchAfterIdentityRefresh failed: %s',
err instanceof Error ? (err.stack ?? err.message) : String(err));
});
} else {
this.handleSideEffects(event);
printEvent(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
}
} catch (e) {
log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e));
}
}
}
@@ -93,12 +119,12 @@ export class IncomingPacketPipeline {
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s',
event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e));
}
this.handleSideEffects(event, refreshed);
printEvent(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
@@ -166,9 +192,9 @@ export class IncomingPacketPipeline {
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
groupId, reason, e instanceof Error ? e.message : String(e));
} finally {
this.memberRefreshTasks_.delete(groupId);
@@ -226,50 +252,16 @@ export class IncomingPacketPipeline {
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId);
break;
case 'group_member_leave':
eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId);
break;
case 'group_mute':
eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration);
break;
case 'group_admin':
eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-');
break;
function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void {
// Message-class events (group/friend/temp message) get rendered by the
// OneBot layer's logReceivedMessage — its output already includes the
// assigned message ID, which the raw packet doesn't have. Returning
// null here is the formatter's signal to skip.
const message = formatEvent(identity, event);
if (!message) return;
if (WARN_EVENT_KINDS.has(event.kind)) {
log.warn('%s', message);
} else {
log.info('%s', message);
}
}
+38
View File
@@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = {
msgSequence: { field: 37, type: 'uint32' as const },
field39: { field: 39, type: 'uint32' as const },
} satisfies ProtoSchema;
// ─── Event0x2DC subType=16: GroupMsgEmojiLike ──────────────────────────────
//
// QQ pushes a Group message emoji reaction (someone tapped an emoji on a
// message in a group). The payload nesting matches NapCat's transformer
// (packet/transformer/proto/message/message.ts → GroupReactNotify); the
// outermost message is preceded by a 7-byte prefix that must be stripped
// before decoding (see the call site).
export const GroupReactionDataInnerDataTargetSchema = {
seq: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
export const GroupReactionDataContentSchema = {
code: { field: 1, type: 'string' as const },
count: { field: 3, type: 'uint32' as const },
operatorUid: { field: 4, type: 'string' as const },
type: { field: 5, type: 'uint32' as const },
} satisfies ProtoSchema;
export const GroupReactionDataInnerDataSchema = {
groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema },
groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema },
} satisfies ProtoSchema;
export const GroupReactionDataInnerSchema = {
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema },
} satisfies ProtoSchema;
export const GroupReactionDataSchema = {
data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema },
} satisfies ProtoSchema;
export const GroupReactNotifySchema = {
groupUin: { field: 4, type: 'uint64' as const },
field13: { field: 13, type: 'uint32' as const },
groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema },
} satisfies ProtoSchema;
@@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = {
key: { field: 1, type: 'uint32' as const },
} satisfies ProtoSchema;
// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions
// reinterpret field 2 as `uid: string` / `openid: string` and reject
// the request with "one of uid/openid is invaild" when a varint 0
// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin`
// and `key[]`, so we match that exactly.
export const OidbUserInfoRequestSchema = {
uin: { field: 1, type: 'uint32' as const },
field2: { field: 2, type: 'uint32' as const },
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
uin: { field: 1, type: 'uint32' as const },
keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema },
} satisfies ProtoSchema;
export const OidbTwoNumberSchema = {
@@ -1,4 +1,7 @@
import { RequestUtil, cookieToString, getBknFromCookie } from './request-util';
import { createLogger } from '../../utils/logger';
const log = createLogger('Bridge.Web');
// 定义接口返回类型
export interface GroupEssenceMsgRet {
@@ -39,6 +42,8 @@ export async function getGroupEssenceMsg(
);
return ret.retcode === 0 ? ret : undefined;
} catch (e) {
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
+5 -1
View File
@@ -1,4 +1,7 @@
import { RequestUtil, cookieToString } from './request-util';
import { createLogger } from '../../utils/logger';
const log = createLogger('Bridge.Web');
export enum WebHonorType {
TALKATIVE = 'talkative',
@@ -43,7 +46,8 @@ export async function getHonorListWebAPI(cookieObject: Record<string, string>, g
description: item?.desc,
}));
} catch (e) {
// console.error(e);
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
}
}
+14 -6
View File
@@ -1,7 +1,8 @@
import { RequestUtil, cookieToString } from './request-util';
import https from 'node:https';
// import { readFileSync } from 'node:fs';
// import * as console from "node:console";
import { createLogger } from '../../utils/logger';
const log = createLogger('Bridge.Web');
export interface SetNoticeRetSuccess {
ec?: number;
@@ -112,6 +113,7 @@ export async function setGroupNoticeWebAPI(
);
return ret;
} catch (e) {
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
@@ -158,7 +160,8 @@ export async function getGroupNoticeWebAPI(
);
// console.log(JSON.stringify(ret, null, 2));
return ret?.ec === 0 ? ret : undefined;
} catch {
} catch (e) {
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
@@ -215,11 +218,15 @@ export async function uploadGroupNoticeImage(
}
});
});
req.on('error', () => resolve(undefined));
req.on('error', (err) => {
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
resolve(undefined);
});
req.write(body);
req.end();
});
} catch {
} catch (e) {
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
}
@@ -260,7 +267,8 @@ export async function deleteGroupNotice(
false
);
return ret?.ec === 0;
} catch {
} catch (e) {
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
return false;
}
}
+30 -11
View File
@@ -21,26 +21,45 @@ export function loadRuntimeConfig(): RuntimeConfig {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
const loaded = tryLoadRuntimeConfig();
let normalized: RuntimeConfig;
if (!loaded) {
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
return { ...DEFAULT_RUNTIME_CONFIG };
normalized = { ...DEFAULT_RUNTIME_CONFIG };
} else {
normalized = {
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
};
if (
normalized.webuiPort !== loaded.webuiPort
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
) {
saveRuntimeConfig(normalized);
}
}
const normalized: RuntimeConfig = {
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
};
if (
normalized.webuiPort !== loaded.webuiPort
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
) {
saveRuntimeConfig(normalized);
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
// pick a free port per-launch while CLI/Docker users continue to drive
// it from runtime.json.
const envPort = envPortOverride();
if (envPort !== undefined) {
normalized = { ...normalized, webuiPort: envPort };
}
return normalized;
}
function envPortOverride(): number | undefined {
const raw = process.env.SNOWLUMA_WEBUI_PORT;
if (!raw || typeof raw !== 'string') return undefined;
const n = Number(raw.trim());
if (!Number.isFinite(n)) return undefined;
const port = Math.trunc(n);
if (port <= 0 || port > 65535) return undefined;
return port;
}
function tryLoadRuntimeConfig(): RuntimeConfig | null {
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
+12 -3
View File
@@ -14,8 +14,13 @@ export type HookSessionDeps = {
};
makeClient: (pid: number) => QqHookClient;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. */
pipeWatcher: { isPipeLive: (pid: number) => boolean };
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
* staleness that would otherwise false-flag a successful unload. */
pipeWatcher: {
isPipeLive: (pid: number) => boolean;
tickNow?: () => Promise<void>;
};
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
@@ -254,7 +259,11 @@ export class HookSession extends EventEmitter {
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. Drop back to 'connecting' and let the watcher reconnect.
// resident. The cached snapshot is up to 1500ms stale and we just
// changed the world, so force a fresh poll first — otherwise even
// a successful unload reads as "pipe still live" until the next
// background tick runs and we'd report a spurious failure.
await this.pipeWatcher.tickNow?.();
if (this.pipeWatcher.isPipeLive(this.pid)) {
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
this.setStatus('connecting', this._error);
+12 -1
View File
@@ -444,7 +444,18 @@ export class QqHookClient extends EventEmitter {
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
const requestId = this.nextRequestId++ >>> 0;
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
// postfix increment loses precision before the shift), letting two
// distinct requests collide on the same id. Skip 0 because zero is
// used as a sentinel by the wire protocol.
let requestId = this.nextRequestId;
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
requestId = (requestId + 1) >>> 0;
if (requestId === 0) requestId = 1;
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
const payload = encodeFrame({
op: PipeOp.sendRequest,
requestId,
+11 -6
View File
@@ -1,7 +1,7 @@
import { BridgeManager } from './bridge/manager';
import { OneBotManager } from './onebot/manager';
import { loadRuntimeConfig } from './common/runtime';
import { createLogger } from './utils/logger';
import { closeLogger, createLogger } from './utils/logger';
import { HookManager } from './hook/hook-manager';
const runtimeConfig = loadRuntimeConfig();
@@ -38,13 +38,17 @@ async function main() {
}
}
// Graceful shutdown
process.on('SIGINT', () => {
log.warn('Shutting down...');
// Graceful shutdown: dispose managers, await log flush, then exit.
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
const shutdown = (signal: string) => async () => {
log.warn(`Shutting down (${signal})...`);
oneBotManager.dispose();
hookManager.dispose();
await closeLogger();
process.exit(0);
});
};
process.on('SIGINT', shutdown('SIGINT'));
process.on('SIGTERM', shutdown('SIGTERM'));
}
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
@@ -57,7 +61,8 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
return fromConfig === true;
}
main().catch((error) => {
main().catch(async (error) => {
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
await closeLogger();
process.exit(1);
});
+123 -32
View File
@@ -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) => {
+21 -2
View File
@@ -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);
}
+26 -23
View File
@@ -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> {
+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),
+63 -47
View File
@@ -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}`);
}
}
+2 -2
View File
@@ -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;
+36 -16
View File
@@ -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: `&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 +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));
}
}
+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');
@@ -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') {
+209
View File
@@ -0,0 +1,209 @@
// Identity-aware, one-line readable rendering for log output.
//
// Two layers consume this:
// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …)
// - onebot/instance.ts → received-message log
//
// All formatters are defensive: any field lookup that throws falls
// back to the raw numeric form, so a malformed event or stale
// Identity cache never crashes the logger. Cache misses simply
// degrade to the previous "just print the uin / groupId" output.
import type { IdentityService } from '../bridge/identity-service';
import type { QQEventVariant } from '../bridge/events';
import type { MessageStore } from '../onebot/message-store';
import type { JsonObject, JsonValue } from '../onebot/types';
const MAX_TEXT_PREVIEW = 50;
const MAX_REPLY_BODY_PREVIEW = 30;
/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */
export function formatGroup(identity: IdentityService, groupId: number): string {
if (!groupId || groupId <= 0) return String(groupId || 0);
try {
const g = identity.findGroup(groupId);
const name = g?.groupName?.trim();
return name ? `[${name}(${groupId})]` : String(groupId);
} catch {
return String(groupId);
}
}
/**
* "[card-or-nick(uin)]" when the uin is in the group-member or friend
* roster; falls back to the bare uin string. When only a uid is known
* (no uin yet) the uid is returned as-is so the line still references
* someone — better than logging "0".
*/
export function formatUser(
identity: IdentityService,
groupId: number | undefined,
uin: number,
uid?: string,
): string {
try {
if (!uin || uin <= 0) return uid ? uid : '0';
if (groupId !== undefined && groupId > 0) {
const member = identity.findGroupMember(groupId, uin);
const name = member?.card?.trim() || member?.nickname?.trim();
if (name) return `[${name}(${uin})]`;
}
const friend = identity.findFriend(uin);
const fname = friend?.remark?.trim() || friend?.nickname?.trim();
if (fname) return `[${fname}(${uin})]`;
return String(uin);
} catch {
return String(uin);
}
}
/**
* One-line preview of an OneBot-shape message (array of segments or
* raw string). Element rendering matches the existing logReceivedMessage
* vocabulary so this is a drop-in replacement, with a few additions
* (json / xml / markdown / forward / poke / file).
*/
export function formatMessageSegments(message: JsonValue): string {
try {
if (typeof message === 'string') {
return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]';
}
if (!Array.isArray(message)) return '[空消息]';
const parts: string[] = [];
for (const seg of message) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const obj = seg as JsonObject;
const type = String(obj.type ?? '');
const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data))
? obj.data as Record<string, unknown>
: {};
parts.push(renderSegment(type, data));
}
return parts.join(' ').trim() || '[空消息]';
} catch {
return '[消息渲染异常]';
}
}
function renderSegment(type: string, data: Record<string, unknown>): string {
switch (type) {
case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW);
case 'image': return '[图片]';
case 'face': return '[表情]';
case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]';
case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`;
case 'reply': return `[回复:${data.id ?? ''}]`;
case 'record': return '[语音]';
case 'video': return '[视频]';
case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]';
case 'json': return '[JSON]';
case 'xml': return '[XML]';
case 'markdown': return '[Markdown]';
case 'forward': return '[聊天记录]';
case 'poke': return '[戳一戳]';
default: return `[${type}]`;
}
}
function truncate(s: string, max: number): string {
return s.length > max ? `${s.slice(0, max)}...` : s;
}
/**
* Resolve a `reply` segment's referenced message and return a short
* "[回复 user: body...]" string. On miss (older than store retention,
* never seen, lookup throws) falls back to "[回复:<id>]" so the chain
* reference is at least preserved.
*
* Deliberately one level deep — we don't recurse into the reply's own
* reply. Long chains aren't worth the runtime cost in the hot path,
* and a 1-level peek catches 90% of real-world "what's this referring
* to" questions.
*/
export function formatReply(
messageStore: MessageStore,
identity: IdentityService,
replyId: number,
): string {
try {
if (!replyId) return '[回复:0]';
const event = messageStore.findEvent(replyId);
if (!event) return `[回复:${replyId}]`;
const isGroup = event.message_type === 'group';
const uin = toIntOrZero(event.user_id);
const groupId = isGroup ? toIntOrZero(event.group_id) : undefined;
// Prefer cache; if cache miss, use the sender fields baked into the
// stored event itself (those came from the original receive path
// when the roster was warm).
let userPart = formatUser(identity, groupId, uin);
if (userPart === String(uin) && uin > 0) {
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
? event.sender as JsonObject
: {};
const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim();
if (fallback) userPart = `[${fallback}(${uin})]`;
}
const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW);
return `[回复 ${userPart}: ${body}]`;
} catch {
return `[回复:${replyId}]`;
}
}
function toIntOrZero(v: unknown): number {
if (typeof v === 'number' && Number.isFinite(v)) return v;
if (typeof v === 'string') {
const n = Number.parseInt(v, 10);
return Number.isFinite(n) ? n : 0;
}
return 0;
}
/**
* Readable one-line rendering of a notice-class QQEventVariant. Returns
* null for kinds the OneBot layer's message log already renders
* (group_message / friend_message / temp_message / group_file_upload /
* friend_add — those have richer dedicated paths).
*/
export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null {
try {
switch (event.kind) {
case 'group_message':
case 'friend_message':
case 'temp_message':
case 'group_file_upload':
case 'friend_add':
return null;
case 'group_recall':
return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`;
case 'friend_recall':
return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`;
case 'group_member_join':
return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`;
case 'group_member_leave':
return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`;
case 'group_mute':
return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`;
case 'group_admin':
return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`;
case 'friend_poke':
return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`;
case 'group_poke':
return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`;
case 'friend_request':
return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`;
case 'group_invite':
return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`;
case 'group_essence':
return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`;
case 'group_msg_emoji_like':
return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`;
default:
return null;
}
} catch {
return null;
}
}
@@ -0,0 +1,295 @@
// File transport for the SnowLuma logger.
//
// Writes plain text (ANSI stripped) to:
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
// <SNOWLUMA_LOG_DIR>/<uin>/snowluma-YYYY-MM-DD.log (per-account)
//
// Both pathways use the same daily rotation + per-file size cap. When the
// cap is hit the in-flight file is closed and writes continue in
// snowluma-YYYY-MM-DD.1.log, .2.log, ...
// at the same date. Files older than the retain window are unlinked on
// startup and on each day rollover.
//
// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally
// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O
// failure during init or write degrades silently to console-only — we
// deliberately do NOT use the logger from inside this module to avoid
// recursion.
import fs from 'node:fs';
import path from 'node:path';
const DEFAULT_DIR = 'logs';
const DEFAULT_MAX_MB = 50;
const DEFAULT_RETAIN_DAYS = 7;
const FILE_PREFIX = 'snowluma-';
const FILE_SUFFIX = '.log';
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
// eslint-disable-next-line no-control-regex
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
// eslint-disable-next-line no-control-regex
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
function parsePositiveInt(v: string | undefined, dflt: number): number {
if (!v) return dflt;
const n = Number.parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : dflt;
}
function todayString(d: Date = new Date()): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function dateOf(s: string): Date {
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
return new Date(y!, m! - 1, d!);
}
function stripAnsi(line: string): string {
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
}
interface OpenFile {
stream: fs.WriteStream;
bytes: number;
date: string;
splitIndex: number;
path: string;
}
/**
* Owns one output directory: keeps at most one open WriteStream, handles
* daily rollover, per-file size cap, and retention cleanup. The shared
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
*/
class FileWriter {
private disabled = false;
private file: OpenFile | null = null;
constructor(
private readonly dir: string,
private readonly maxBytes: number,
private readonly retainDays: number,
) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
// eslint-disable-next-line no-console
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
return;
}
this.cleanup();
}
get isDisabled(): boolean {
return this.disabled;
}
get currentPath(): string | null {
return this.file?.path ?? null;
}
write(data: string, bytes: number): void {
if (this.disabled) return;
const today = todayString();
this.ensureForToday(today);
if (!this.file) return;
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return;
}
this.file.stream.write(data);
this.file.bytes += bytes;
}
close(): Promise<void> {
const f = this.file;
this.file = null;
if (!f) return Promise.resolve();
return new Promise((resolve) => {
try {
f.stream.end(() => resolve());
} catch {
resolve();
}
});
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file) {
try {
this.file.stream.end();
} catch {
/* ignore */
}
this.file = null;
this.cleanup();
}
// Resume from the highest existing split index for today (so two
// process starts on the same day share files / don't clobber).
let idx = 0;
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
this.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
const date = this.file.date;
try {
this.file.stream.end();
} catch {
/* ignore */
}
let next = this.file.splitIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
this.file = this.openFile(date, next);
}
private openFile(date: string, splitIndex: number): OpenFile | null {
const p = this.pathFor(date, splitIndex);
try {
let bytes = 0;
try {
bytes = fs.statSync(p).size;
} catch {
/* file doesn't exist yet */
}
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
// eslint-disable-next-line no-console
console.error(`[logger] file write error on ${p}: ${err.message}`);
});
return { stream, bytes, date, splitIndex, path: p };
} catch (err) {
// eslint-disable-next-line no-console
console.error(
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
);
return null;
}
}
private pathFor(date: string, splitIndex: number): string {
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
}
private cleanup(): void {
let entries: string[];
try {
entries = fs.readdirSync(this.dir);
} catch {
return;
}
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - retainMs;
for (const name of entries) {
const m = FILE_RE.exec(name);
if (!m) continue;
const dateStr = m[1]!;
if (dateOf(dateStr).getTime() < cutoff) {
try {
fs.unlinkSync(path.join(this.dir, name));
} catch {
/* ignore */
}
}
}
}
}
export class FileTransport {
private readonly dir: string;
private readonly maxBytes: number;
private readonly retainDays: number;
private readonly enabled: boolean;
private readonly perUinEnabled: boolean;
private shared: FileWriter | null = null;
private perUin = new Map<number, FileWriter>();
constructor() {
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
this.maxBytes =
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
this.retainDays = parsePositiveInt(
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
DEFAULT_RETAIN_DAYS,
);
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
if (this.enabled) {
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
this.shared = w.isDisabled ? null : w;
}
}
/** True when no file output will happen (env disable or init failure). */
get isDisabled(): boolean {
return !this.shared;
}
/** Current shared-file path (or null if disabled / not yet opened). */
get currentPath(): string | null {
return this.shared?.currentPath ?? null;
}
/** Path of the per-UIN file for the given UIN, if open. */
perUinPath(uin: number): string | null {
return this.perUin.get(uin)?.currentPath ?? null;
}
write(line: string, uin?: number): void {
if (!this.shared) return;
const data = stripAnsi(line) + '\n';
const bytes = Buffer.byteLength(data, 'utf8');
this.shared.write(data, bytes);
if (uin !== undefined && this.perUinEnabled) {
let w = this.perUin.get(uin);
if (!w) {
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
if (w.isDisabled) return;
this.perUin.set(uin, w);
}
w.write(data, bytes);
}
}
async close(): Promise<void> {
const closes: Promise<void>[] = [];
if (this.shared) closes.push(this.shared.close());
for (const w of this.perUin.values()) closes.push(w.close());
this.shared = null;
this.perUin.clear();
await Promise.all(closes);
}
}
let singleton: FileTransport | null = null;
export function getFileTransport(): FileTransport {
if (!singleton) singleton = new FileTransport();
return singleton;
}
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
singleton = null;
}
+60
View File
@@ -0,0 +1,60 @@
// Compact one-line param summary for log output.
//
// OneBot action params can include large message arrays / nested
// payloads that would blow the line width to multiple kilobytes if we
// JSON.stringify them naively. This helper produces a flat
// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard
// total cap, designed to be grep-friendly without flooding the log
// file.
const MAX_FIELD = 40;
const MAX_TOTAL = 200;
function valueRepr(v: unknown): string {
if (v === null) return 'null';
if (v === undefined) return 'undefined';
switch (typeof v) {
case 'string':
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
case 'number':
case 'boolean':
case 'bigint':
return String(v);
case 'object':
if (Array.isArray(v)) return `[len=${v.length}]`;
return '{...}';
default:
return typeof v;
}
}
/**
* Render a params object as a single line for logging. Skips deep
* traversal: nested objects collapse to `{...}`, arrays to `[len=N]`.
* Strings are quoted; long ones are truncated with an ellipsis.
*
* Output is capped at MAX_TOTAL chars; on overflow the tail is
* replaced with `...` so the next field doesn't get half-rendered.
*/
export function summarizeParams(params: unknown): string {
if (params === null || params === undefined) return '{}';
if (typeof params !== 'object') {
const s = String(params);
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s;
}
if (Array.isArray(params)) return `[len=${params.length}]`;
const out: string[] = [];
let total = 0;
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
const entry = `${k}=${valueRepr(v)}`;
// +1 accounts for the separating space we'd insert when joining.
if (total > 0 && total + entry.length + 1 > MAX_TOTAL) {
out.push('...');
break;
}
out.push(entry);
total += entry.length + (out.length > 1 ? 1 : 0);
}
return out.join(' ');
}
+108 -26
View File
@@ -1,4 +1,5 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
@@ -7,14 +8,26 @@ export interface LogEntry {
time: string;
level: LogLevel;
scope: string;
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
uin?: number;
message: string;
line: string;
}
interface LogOptions {
scope: string;
uin?: number;
/** Free-form meta carried across `.child(...)` calls. Currently only
* `uin` is rendered, but the bag is preserved for future fields
* (requestId / traceId / etc.). */
meta?: Record<string, unknown>;
}
// Fixed-width slot for the UIN tag in rendered output so the [Scope]
// column stays vertically aligned across lines with and without a UIN.
// Width covers `[1234567890]` (12 chars); anything longer just won't pad.
const UIN_SLOT_WIDTH = 12;
const LEVEL_WEIGHT: Record<LogLevel, number> = {
debug: 10,
info: 20,
@@ -55,10 +68,32 @@ function resolveMinLevel(): LogLevel {
return 'info';
}
const MIN_LEVEL = resolveMinLevel();
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
// setLogLevel() lets WebUI / SDK callers flip it without a restart.
// Only governs console + ring buffer + subscribers; the file
// transport always sees debug-and-up regardless.
let currentLevel: LogLevel = resolveMinLevel();
function shouldLog(level: LogLevel): boolean {
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL];
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
}
export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error'];
export function getLogLevel(): LogLevel {
return currentLevel;
}
/**
* Change the console / subscriber level at runtime. Invalid input is
* a no-op (returns false). File transport is unaffected — it always
* sees every level so post-mortems remain useful.
*/
export function setLogLevel(level: string): boolean {
const lower = String(level).toLowerCase();
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
currentLevel = lower as LogLevel;
return true;
}
function useColor(): boolean {
@@ -78,43 +113,72 @@ function currentTime(): string {
return `${hh}:${mm}:${ss}`;
}
function render(level: LogLevel, scope: string, args: unknown[]): string {
function render(level: LogLevel, options: LogOptions, args: unknown[]): string {
const message = format(...args);
const ts = currentTime();
const label = LEVEL_LABEL[level].padEnd(5, ' ');
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
if (!useColor()) {
return `${ts} ${label} [${scope}] ${message}`;
return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`;
}
const cTs = ansi(COLOR_DIM, ts);
const cLabel = ansi(COLOR_CODE[level], label);
const cScope = ansi(COLOR_SCOPE, `[${scope}]`);
return `${cTs} ${cLabel} ${cScope} ${message}`;
// Pad first, then color only the visible tag so escape codes don't eat
// into the alignment width.
const cUin = uinTag
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
: ' '.repeat(UIN_SLOT_WIDTH);
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`;
}
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
if (!shouldLog(level)) return;
// Console / subscriber level filter. File output is debug-and-up always;
// see log-file-transport.ts.
const passesConsole = shouldLog(level);
const message = format(...args);
const line = render(level, options.scope, args);
const line = render(level, options, args);
const entry: LogEntry = {
id: nextLogId++,
time: new Date().toISOString(),
level,
scope: options.scope,
...(options.uin !== undefined ? { uin: options.uin } : {}),
message,
line,
};
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
// BEL (0x07) in user-provided strings (e.g. group member names) from
// triggering Windows system beep sounds. ESC (0x1B) is preserved so the
// ANSI color sequences emitted by render() actually reach the terminal.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
if (passesConsole) {
logEntries.push(entry);
if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift();
for (const subscriber of logSubscribers) subscriber(entry);
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
// Strip ASCII control characters before writing to terminal to prevent
// BEL (0x07) in user-provided strings (e.g. group member names) from
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
// sequences emitted by render() pass through intact.
// eslint-disable-next-line no-control-regex
stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// File transport always sees every level (debug-and-up) for post-mortem
// value; ANSI stripping happens inside the transport. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
}
/**
* Flush and close the underlying log file. Call from shutdown hooks
* (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal
* buffer makes it to disk. Returns a promise that resolves once the OS
* has finalized the write.
*/
export function closeLogger(): Promise<void> {
return getFileTransport().close();
}
export function getRecentLogs(limit = 300): LogEntry[] {
@@ -135,15 +199,33 @@ export interface Logger {
success: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
/**
* Derive a new logger that inherits this one's scope and carries
* additional metadata. Currently `uin` is the only key with rendering
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
* other keys are preserved on the options bag for forward compat.
*/
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
}
function makeLogger(opts: LogOptions): Logger {
return {
debug: (...args: unknown[]) => emit('debug', opts, args),
info: (...args: unknown[]) => emit('info', opts, args),
success: (...args: unknown[]) => emit('success', opts, args),
warn: (...args: unknown[]) => emit('warn', opts, args),
error: (...args: unknown[]) => emit('error', opts, args),
child: (meta) => {
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
return makeLogger({
scope: opts.scope,
uin: nextUin,
meta: { ...(opts.meta ?? {}), ...meta },
});
},
};
}
export function createLogger(scope: string): Logger {
const options: LogOptions = { scope };
return {
debug: (...args: unknown[]) => emit('debug', options, args),
info: (...args: unknown[]) => emit('info', options, args),
success: (...args: unknown[]) => emit('success', options, args),
warn: (...args: unknown[]) => emit('warn', options, args),
error: (...args: unknown[]) => emit('error', options, args),
};
return makeLogger({ scope });
}
+63 -2
View File
@@ -1,6 +1,9 @@
import fs from 'fs';
import path from 'path';
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
import { createLogger } from '../utils/logger';
const log = createLogger('WebUI.Auth');
const CONFIG_DIR = 'config';
const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json');
@@ -21,6 +24,16 @@ export function isDevAuthMode(): boolean {
return process.env.SNOWLUMA_DEV_MODE === '1';
}
function envBootstrapPassword(): string | null {
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
if (!raw || typeof raw !== 'string') return null;
// Minimum sanity: avoid accidental empty / 1-char seeds. Strength
// rules still don't apply because we want trusted launchers to be
// able to pick a high-entropy random secret (e.g. base64(16)).
if (raw.length < 8) return null;
return raw;
}
export interface WebuiAuthState {
passwordHash: string; // hex
passwordSalt: string; // hex
@@ -84,6 +97,16 @@ function generateInitialState(initialPassword: string): WebuiAuthState {
};
}
function backupCorruptConfig(): void {
try {
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
fs.renameSync(WEBUI_CONFIG_PATH, dest);
log.warn('previous webui.json moved to %s', dest);
} catch (err) {
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
}
}
function atomicWrite(state: WebuiAuthState): void {
ensureConfigDir();
const tmp = WEBUI_CONFIG_PATH + '.tmp';
@@ -128,12 +151,50 @@ export class WebuiAuth {
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
if (isValidState(parsed)) {
if (parsed.mustChangePassword) {
// Previous start generated a bootstrap password but the operator
// never completed the forced-change flow. The plaintext is gone
// (only the hash is on disk, and the log line from last run may
// be lost), so rotate to a fresh CSPRNG password they can see.
const initialPassword = randomBytes(8).toString('hex');
const state = generateInitialState(initialPassword);
atomicWrite(state);
log.warn('previous bootstrap password was never rotated; regenerated a new one');
return new WebuiAuth(state, initialPassword, false);
}
return new WebuiAuth(parsed, null, false);
}
} catch {
/* fallthrough — regenerate */
log.error('webui.json schema invalid; backing up and regenerating credentials');
backupCorruptConfig();
} catch (err) {
log.error(
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
err instanceof Error ? err.message : String(err),
);
backupCorruptConfig();
}
}
// SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the
// password on first run instead of having to scrape it from logs.
// Effect: write webui.json with the env-provided password, hashed,
// and mustChangePassword=false. Only honoured when there is NO existing
// webui.json — once persisted, password changes happen via the UI.
const envPassword = envBootstrapPassword();
if (envPassword !== null) {
const salt = randomBytes(16);
const hash = hashPassword(envPassword, salt);
const now = new Date().toISOString();
const state: WebuiAuthState = {
passwordHash: hash.toString('hex'),
passwordSalt: salt.toString('hex'),
mustChangePassword: false,
generatedAt: now,
updatedAt: now,
};
atomicWrite(state);
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
return new WebuiAuth(state, null, false);
}
const initialPassword = randomBytes(8).toString('hex');
const state = generateInitialState(initialPassword);
atomicWrite(state);
+106
View File
@@ -0,0 +1,106 @@
// Resolve the request's "real" client IP for per-IP rate limiting.
//
// Threat model:
// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and
// `X-Real-IP` are client-controllable, so honoring them lets any
// client rotate the header to escape the 5-attempts/15-min login
// lockout.
// - Operators who actually run behind a reverse proxy (nginx, Caddy,
// a SaaS CDN) need a way to opt back into the real client IP. The
// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the
// immediate TCP peer is THIS, treat the headers as authoritative".
//
// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY:
// - unset / empty — default; ignore headers, use socket peer
// - "loopback" — trust headers when the socket peer is 127.0.0.1
// or ::1 (typical for nginx/Caddy on the same host)
// - "1" / "true" / — trust headers from any peer (only safe behind a
// "all" trusted SaaS CDN that strips client-set headers)
// - comma-separated — trust headers when the socket peer matches one
// IP list of these IPs (reverse proxy on another machine)
//
// When trusted, we prefer X-Real-IP (a single value the reverse proxy
// overwrites unconditionally) and fall back to the first hop of
// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy
// chain isn't fully trusted, the leftmost value can still be spoofed
// by the original client, and a single-tier proxy is the only setup
// this app realistically sees.
import type { Context } from 'hono';
import { getConnInfo } from '@hono/node-server/conninfo';
export type TrustProxyMode =
| { kind: 'none' }
| { kind: 'loopback' }
| { kind: 'all' }
| { kind: 'ip-list'; ips: Set<string> };
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
const value = raw?.trim().toLowerCase() ?? '';
if (!value) return { kind: 'none' };
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
if (value === 'loopback') return { kind: 'loopback' };
const ips = new Set(
value.split(',').map((s) => s.trim()).filter(Boolean),
);
if (ips.size === 0) return { kind: 'none' };
return { kind: 'ip-list', ips };
}
export function describeTrustProxy(mode: TrustProxyMode): string {
switch (mode.kind) {
case 'none': return 'socket peer (default)';
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
/**
* Pick the right "client IP" for rate-limit keying.
*
* Exposed as a pure function over a small dependency surface so the
* unit tests can fabricate request shapes without spinning up a server.
*/
export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
const realIp = c.req.header('x-real-ip')?.trim();
if (realIp) return realIp;
const xff = c.req.header('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0].trim();
if (first) return first;
}
return socketIp;
}
/** Convenience binding for the live server: read socket via getConnInfo. */
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
return (c) => pickClientIp(c, mode, () => {
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
catch { return '127.0.0.1'; }
});
}
+138 -85
View File
@@ -1,12 +1,13 @@
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono } from 'hono';
import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger';
import { Hono, type Context } from 'hono';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger';
import { randomBytes } from 'crypto';
import type { OneBotManager } from '../onebot/manager';
import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config';
import type { OneBotConfig } from '../onebot/types';
import type { HookManager } from '../hook/hook-manager';
import type { HookManager, HookProcessInfo } from '../hook/hook-manager';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { fileURLToPath } from 'url';
@@ -40,6 +41,14 @@ const MUST_CHANGE_ALLOWLIST = new Set([
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Only the
// SSE log stream is here because EventSource cannot set custom headers; all
// other endpoints MUST use the Authorization header so tokens never leak
// into access logs / Referer / browser history.
const TOKEN_QUERY_ALLOWLIST = new Set([
'/api/logs/stream',
]);
// uin = QQ number; 5–12 digits. Used to construct config file paths,
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
const UIN_REGEX = /^\d{5,12}$/;
@@ -51,11 +60,19 @@ function purgeExpiredTokens() {
for (const [token, info] of sessionTokens) {
if (now > info.expiresAt) sessionTokens.delete(token);
}
for (const [ip, attempt] of loginAttempts) {
if (now > attempt.resetAt) loginAttempts.delete(ip);
}
}
function getClientIp(req: Request): string {
return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1';
}
/**
* Resolve the client IP for per-IP rate limiting. Default is the TCP
* socket peer (cannot be spoofed by the client). Operators behind a
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
* var; see `./client-ip.ts` for the accepted values.
*/
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
const getClientIp = makeClientIpResolver(trustProxyMode);
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
@@ -81,14 +98,44 @@ export async function initWebUI(
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('════════════════════════════════════════════════════════════════');
log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★');
log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。');
log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。');
log.info(' Log in and change the password now; it will not be shown again.');
log.info('────────────────────────────────────────────────────────────────');
log.info('initial credentials: user=admin password=%s', initialPassword);
log.info('password change required after first login');
log.info('════════════════════════════════════════════════════════════════');
} else if (auth.mustChangePassword()) {
log.warn('password change is still required');
}
log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode));
if (trustProxyMode.kind === 'all') {
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
}
const app = new Hono();
// ─── Anti-indexing ───────────────────────────────────────────────────────
// The WebUI is an admin surface that has no business showing up in
// search results — even the login page leaks the existence of a
// SnowLuma instance to anyone scanning the IP. Three overlapping
// signals: a hard X-Robots-Tag on every response, a robots.txt for
// crawlers that read it before pages, and a <meta robots> in the
// SPA shell for the case where a proxy strips headers.
app.use('*', async (c, next) => {
await next();
c.res.headers.set(
'X-Robots-Tag',
'noindex, nofollow, noarchive, nosnippet, noimageindex',
);
});
app.get('/robots.txt', (c) => {
c.res.headers.set('Content-Type', 'text/plain; charset=utf-8');
return c.body('User-agent: *\nDisallow: /\n');
});
// ─── Auth middleware ─────────────────────────────────────────────────────
app.use('/api/*', async (c, next) => {
const reqPath = c.req.path;
@@ -96,11 +143,10 @@ export async function initWebUI(
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = c.req.query('token') ?? '';
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
const token = bearerToken || queryToken;
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
purgeExpiredTokens();
const info = sessionTokens.get(token);
if (!info || Date.now() > info.expiresAt) {
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
@@ -114,9 +160,14 @@ export async function initWebUI(
await next();
});
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
const ip = getClientIp(c.req.raw);
const ip = getClientIp(c);
const now = Date.now();
const attempt = loginAttempts.get(ip);
if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) {
@@ -140,7 +191,6 @@ export async function initWebUI(
}
loginAttempts.delete(ip);
purgeExpiredTokens();
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
@@ -196,20 +246,15 @@ export async function initWebUI(
try {
auth.setPassword(newPassword);
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400);
log.warn('change password failed: %s', err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '密码修改失败' }, 400);
}
// Invalidate all other sessions; current keeps but loses must-change flag.
const currentToken = c.get('sessionToken' as never) as string | undefined;
for (const [tok, info] of sessionTokens) {
if (tok === currentToken) {
info.mustChangePassword = false;
sessionTokens.set(tok, info);
} else {
sessionTokens.delete(tok);
}
}
log.info('password updated');
return c.json({ success: true });
// Invalidate every session, including the current one. If the old
// password was compromised, the attacker may already hold the current
// token; rotating credentials must rotate sessions too.
sessionTokens.clear();
log.info('password updated; all sessions invalidated');
return c.json({ success: true, requireRelogin: true });
});
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
@@ -315,27 +360,53 @@ export async function initWebUI(
return c.json({ list: getRecentLogs(limit) });
});
app.get('/api/logs/level', (c) => {
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.post('/api/logs/level', async (c) => {
const body = await c.req.json().catch(() => null) as { level?: unknown } | null;
const next = typeof body?.level === 'string' ? body.level : '';
if (!setLogLevel(next)) {
return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400);
}
log.info('console log level set to %s via WebUI', getLogLevel());
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
});
app.get('/api/logs/stream', (c) => {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let unsubscribe: (() => void) | undefined;
let heartbeat: NodeJS.Timeout | undefined;
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
unsubscribe?.();
try { controller.close(); } catch { /* ignore */ }
};
const safeEnqueue = (chunk: Uint8Array) => {
if (closed) return;
try {
controller.enqueue(chunk);
} catch {
// The peer dropped between abort and the next enqueue —
// treat as end-of-stream so we don't leak listeners.
teardown();
}
};
const send = (event: unknown) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
};
send({ type: 'ready' });
const unsubscribe = subscribeLogs((entry) => send(entry));
const heartbeat = setInterval(() => {
controller.enqueue(encoder.encode(': heartbeat\n\n'));
unsubscribe = subscribeLogs((entry) => send(entry));
heartbeat = setInterval(() => {
safeEnqueue(encoder.encode(': heartbeat\n\n'));
}, 15000);
c.req.raw.signal.addEventListener('abort', () => {
clearInterval(heartbeat);
unsubscribe();
try {
controller.close();
} catch {
/* ignore */
}
});
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
@@ -356,62 +427,43 @@ export async function initWebUI(
}
});
app.post('/api/processes/:pid/load', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.loadProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.post('/api/processes/:pid/unload', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.unloadProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
app.post('/api/processes/:pid/refresh', async (c) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await hookManager.refreshProcess(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500);
}
});
// Per-process action handler. The three routes below differ only in
// which HookManager method they call.
const MAX_PID = 4_194_304;
function processAction(label: string, action: (pid: number) => Promise<HookProcessInfo>) {
return async (c: Context) => {
if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503);
const pid = Number(c.req.param('pid'));
if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) {
return c.json({ success: false, message: 'invalid pid' }, 400);
}
try {
const processInfo = await action(pid);
return c.json({ success: processInfo.status !== 'error', process: processInfo });
} catch (err) {
log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500);
}
};
}
app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid)));
app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid)));
app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid)));
app.get('/api/config/:uin', (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
// Read-only: never write defaults to disk on a GET. The persisted
// file is created when manager.onSessionStarted boots an instance
// or when the operator POSTs from this very endpoint.
const config = loadOneBotConfig(uin);
return c.json({
...config,
config,
});
return c.json({ config });
});
app.post('/api/config/:uin', async (c) => {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
try {
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400);
const body = (await c.req.json()) as OneBotConfig;
saveOneBotConfig(uin, body);
const reloaded = oneBotManager.reloadConfig(uin);
@@ -422,7 +474,8 @@ export async function initWebUI(
message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。',
});
} catch (err) {
return c.json({ success: false, message: String(err) }, 400);
log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err));
return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400);
}
});