Merge pull request #44 from SnowLuma/dev

chore: promote dev → main (90884df)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-05-17 11:29:18 +00:00
commit 71b0bda8f4
87 files changed
+4850 -786

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.8.1",
"version": "1.8.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+6 -2
View File
@@ -28,12 +28,16 @@ const forwardResCache = new Map<string, ForwardNodePayload[]>();
async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
): 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);
const sendCtx = groupId !== undefined
? { bridge, groupId }
: { 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;
@@ -67,7 +71,7 @@ export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePaylo
throw new Error('forward nodes are required');
}
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node)));
const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId)));
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);
+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':
@@ -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);
});
}
+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 };
@@ -280,6 +280,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 +295,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));
@@ -375,7 +383,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);
@@ -487,11 +495,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]) },
@@ -440,6 +440,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);
}
+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 -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,
+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) => {
+1 -4
View File
@@ -12,9 +12,6 @@ import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { WebHonorType } from '@/bridge/web/group-honor';
// import {ClientKeyInfo} from "@/bridge/bridge";
export interface MessageSendResult {
messageId: number;
meta?: MessageMeta;
@@ -91,7 +88,7 @@ export interface ApiActionContext {
getDownloadRKeys: () => Promise<JsonObject[]>;
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>;
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
+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);
}
+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),
+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;
+32 -15
View File
@@ -16,6 +16,19 @@ export interface ParseMessageOptions {
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
/**
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
* when the input can't be parsed as a finite integer — `parseInt('abc')`
* is `NaN`, which silently turns into `0`/`null` further down the wire
* pipeline and produces undebuggable protocol-level failures.
*/
function intOr(value: unknown, fallback = 0): number {
if (value === undefined || value === null) return fallback;
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
@@ -33,9 +46,12 @@ function parseCQParams(raw: string): Record<string, string> {
}
function cqUnescape(text: string): string {
// Order matters: `&amp;` MUST be last so that, e.g., `&amp;#91;` keeps
// the literal `&#91;` instead of decoding twice into `[`.
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
@@ -88,7 +104,8 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return text ? { type: 'text', text } : null;
}
case 'face': {
const id = parseInt(String(data.id ?? '0'), 10);
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
}
case 'at': {
@@ -96,7 +113,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = parseInt(qq, 10);
const uin = intOr(qq, 0);
if (uin <= 0) return null;
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
@@ -105,16 +122,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 +165,7 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
type: 'image',
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
flash: data.type === 'flash',
subType: parseInt(String(data.subType ?? '0'), 10),
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
}
@@ -178,13 +196,13 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
return {
type: 'xml',
text: String(data.data ?? ''),
subType: parseInt(String(data.id ?? '0'), 10),
subType: intOr(data.id, 0),
};
}
case 'poke': {
return {
type: 'poke',
faceId: parseInt(String(data.type ?? data.id ?? '0'), 10),
faceId: intOr(data.type ?? data.id, 0),
};
}
case 'forward': {
@@ -196,11 +214,10 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
const uin = String(data.user_id ?? data.uin ?? '0');
const name = String(data.nickname ?? data.name ?? '');
return {
type: 'node',
targetUin: parseInt(uin, 10) || 0,
targetUin: intOr(data.user_id ?? data.uin, 0),
text: name,
// Raw content is stored as JSON string in resId for later processing
resId: JSON.stringify(data.content ?? ''),
@@ -99,10 +99,32 @@ export async function sendPrivateMessage(
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
// Prefer the cached event (it carries the REAL sender). When only
// meta exists — typically because the message we're replying to was
// sent by the bot itself and never round-tripped through dispatch
// (reportSelfMessage off / no message_sent event) — fall back to
// selfId. The previous code used `meta.targetId` here, which is the
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
// self-reply.
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
const senderUin = typeof event.user_id === 'number'
? event.user_id
: parseInt(String(event.user_id || '0'), 10);
const time = typeof event.time === 'number'
? event.time
: parseInt(String(event.time || '0'), 10);
const meta = ref.messageStore.findMeta(replyMessageId);
return {
senderUin,
time,
random: meta?.random ?? 0,
};
}
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId,
senderUin: ref.selfId,
time: meta.timestamp,
random: meta.random,
};
@@ -240,9 +262,12 @@ export async function sendPrivateForwardMessage(
export async function uploadForwardMessage(
ref: OneBotInstanceContext,
messages: JsonValue,
groupId?: number,
): Promise<{ forwardId: string }> {
const nodes = await parseForwardNodes(ref, messages);
const forwardId = await ref.bridge.uploadForwardNodes(nodes);
// groupId controls the resId namespace (group vs private). Without it,
// a resId minted here is unusable when later sent into a group.
const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId);
return { forwardId };
}
+1 -2
View File
@@ -6,8 +6,7 @@ import type { WebSocket } from '@snowluma/websocket';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const rawAuth = request.headers.authorization;
const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? '';
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
+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'; }
});
}
+103 -84
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 { Hono, type Context } from 'hono';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import { createLogger, getRecentLogs, 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,11 +98,21 @@ 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();
@@ -96,11 +123,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 +140,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 +171,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 +226,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) ────────────────────────────────────────
@@ -319,23 +344,35 @@ export async function initWebUI(
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 +393,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 +440,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);
}
});
@@ -16,6 +16,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({
})),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
}));
import * as oidb from '../../src/bridge/bridge-oidb';
+30 -2
View File
@@ -45,7 +45,7 @@ describe('loadOneBotConfig', () => {
it('creates and persists default config when none exists', () => {
const uin = '10001';
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
@@ -74,7 +74,7 @@ describe('loadOneBotConfig', () => {
};
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
expect(config.networks.httpServers[0].port).toBe(3100);
expect(config.networks.httpServers[0].accessToken).toBe('tok');
@@ -128,6 +128,34 @@ describe('loadOneBotConfig', () => {
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('does not write to disk by default (read-only contract)', () => {
const uin = '10006';
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);
// Default call must not materialize the file or mint a fresh access token.
const config = loadOneBotConfig(uin);
expect(config.networks.httpServers).toHaveLength(1);
expect(fs.existsSync(cfgPath)).toBe(false);
// Explicit opt-in still writes.
loadOneBotConfig(uin, { persistDefaults: true });
expect(fs.existsSync(cfgPath)).toBe(true);
});
it('respects an operator-emptied adapter list instead of seeding defaults back', () => {
const uin = '10007';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
musicSignUrl: '',
}), 'utf8');
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toEqual([]);
expect(config.networks.wsServers).toEqual([]);
});
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
const uin = '10005';
const dir = path.join(tempDir, 'config');
+74 -1
View File
@@ -2,7 +2,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { pathToFileURL } from 'url';
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils';
describe('highway source paths', () => {
@@ -26,3 +26,76 @@ describe('highway source paths', () => {
}
});
});
describe('loadBinarySource maxBytes enforcement', () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => {
// Streamed chunk-encoded response: no Content-Length, totals > cap.
const chunkSize = 4 * 1024;
const totalChunks = 16;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize));
controller.close();
},
});
globalThis.fetch = vi.fn(async () => new Response(stream, {
status: 200,
headers: { /* no content-length */ },
})) as typeof fetch;
// Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream.
await expect(
loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024),
).rejects.toThrow(/too large/);
});
it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => {
globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), {
status: 200,
headers: { 'content-length': String(10 * 1024 * 1024) },
})) as typeof fetch;
await expect(
loadBinarySource('https://example.test/big.bin', 'test', 1024),
).rejects.toThrow(/too large: 10485760/);
});
it('accepts a streamed download that fits inside maxBytes', async () => {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.enqueue(new Uint8Array([4, 5]));
controller.close();
},
});
globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;
const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024);
expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]);
});
it('rejects oversized local files via fs.stat before reading them', async () => {
const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`);
fs.writeFileSync(filePath, Buffer.alloc(128));
try {
await expect(
loadBinarySource(filePath, 'test', 64),
).rejects.toThrow(/too large: 128 > 64/);
} finally {
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
}
});
it('rejects oversized base64 payloads', async () => {
const big = Buffer.alloc(128).toString('base64');
await expect(
loadBinarySource(`base64://${big}`, 'test', 64),
).rejects.toThrow(/too large: 128 > 64/);
});
});
@@ -0,0 +1,92 @@
import { describe, expect, it } from 'vitest';
import {
describeTrustProxy,
parseTrustProxy,
pickClientIp,
type TrustProxyMode,
} from '../src/webui/client-ip';
function mockCtx(headers: Record<string, string> = {}) {
return {
req: {
header: (name: string) => headers[name.toLowerCase()],
},
} as unknown as Parameters<typeof pickClientIp>[0];
}
describe('parseTrustProxy', () => {
it('treats empty / unset as none (safe default)', () => {
expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' });
expect(parseTrustProxy('')).toEqual({ kind: 'none' });
expect(parseTrustProxy(' ')).toEqual({ kind: 'none' });
});
it('recognises "1" / "true" / "all" as full trust', () => {
expect(parseTrustProxy('1')).toEqual({ kind: 'all' });
expect(parseTrustProxy('true')).toEqual({ kind: 'all' });
expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' });
});
it('recognises "loopback" case-insensitively', () => {
expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' });
});
it('parses a comma-separated IP list', () => {
const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, ');
expect(mode.kind).toBe('ip-list');
if (mode.kind !== 'ip-list') throw new Error('unreachable');
expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']);
});
});
describe('pickClientIp', () => {
const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' };
const realIp = { 'x-real-ip': '203.0.113.42' };
const both = { ...xff, ...realIp };
it('returns socket peer and IGNORES headers when trust=none (default)', () => {
const mode: TrustProxyMode = { kind: 'none' };
expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9');
});
it('honors X-Real-IP first, then XFF first hop, when trust=all', () => {
const mode: TrustProxyMode = { kind: 'all' };
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42');
expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7');
});
it('falls back to socket peer when trust=all but no headers present', () => {
const mode: TrustProxyMode = { kind: 'all' };
expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1');
});
it('trust=loopback honors headers only when socket is loopback', () => {
const mode: TrustProxyMode = { kind: 'loopback' };
expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42');
expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42');
expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42');
// Non-loopback peer → headers ignored, socket wins.
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1');
});
it('trust=ip-list honors headers only when socket is in the list', () => {
const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) };
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42');
expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9');
});
it('survives a socket resolver that throws', () => {
const mode: TrustProxyMode = { kind: 'none' };
expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1');
});
});
describe('describeTrustProxy', () => {
it('renders each mode in a recognisable form for the boot log', () => {
expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer');
expect(describeTrustProxy({ kind: 'all' })).toContain('any peer');
expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback');
expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) }))
.toContain('10.0.0.1');
});
});