fix(onebot): strengthen endpoint defaults

Use safer defaults for newly created service endpoints and guide operators toward suitable access credentials without disrupting existing deployments.

Apply the same policy at the save boundary, retain deliberate local-only setups and external client compatibility, and add regression coverage for editing, recovery, and trusted access paths.
This commit is contained in:
DrSmoothl committed 2026-08-01 18:12:04 +08:00
1 parent abe4ea80c8
commit 3c97e71650
16 files changed
+601 -33

No files matched your search

+29 -12
View File
@@ -28,15 +28,23 @@ export function describeTrustProxy(mode: TrustProxyMode): string {
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
export function isLoopbackClientIp(ip: string): boolean {
const normalized = ip.trim().toLowerCase();
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
if (normalized.startsWith('::ffff:')) {
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
}
const octets = normalized.split('.');
return octets.length === 4
&& octets[0] === '127'
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'loopback': return isLoopbackClientIp(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
@@ -45,11 +53,15 @@ export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
fallbackIp = '127.0.0.1',
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
let socketIp: string;
try {
socketIp = getSocketIp();
} catch {
return fallbackIp;
}
if (!socketIp) return fallbackIp;
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
@@ -64,9 +76,14 @@ export function pickClientIp(
}
/** 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'; }
});
export function makeClientIpResolver(
mode: TrustProxyMode,
fallbackIp = '127.0.0.1',
): (c: Context) => string {
return (c) => pickClientIp(
c,
mode,
() => getConnInfo(c).remote.address ?? fallbackIp,
fallbackIp,
);
}
@@ -0,0 +1,81 @@
import { assessAccessToken } from '@snowluma/common/access-token';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { isLoopbackClientIp } from './client-ip';
export class OneBotAccessTokenPolicyError extends Error {
constructor(message: string) {
super(message);
this.name = 'OneBotAccessTokenPolicyError';
}
}
export interface OneBotAccessTokenPolicyOptions {
clientIp: string;
uin: string;
}
type InboundKind = 'httpServers' | 'wsServers';
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
function sameTokenAtPreviousIdentity(
previous: OneBotConfig['networks'][InboundKind],
next: OneBotConfig['networks'][InboundKind],
nextName: string,
nextToken: string,
index: number,
): boolean {
const named = previous.find((adapter) => adapter.name === nextName);
if (named && (named.accessToken ?? '') === nextToken) return true;
// Preserve a legacy token when the operator only renames the same list item.
// Reordering keeps names stable and is covered by the lookup above.
const sameIndex = previous[index];
return sameIndex !== undefined
&& !next.some((adapter) => adapter.name === sameIndex.name)
&& (sameIndex.accessToken ?? '') === nextToken;
}
export function validateOneBotAccessTokenChanges(
previous: OneBotConfig | null,
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
): void {
const allowEmpty = isLoopbackClientIp(options.clientIp);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
for (let index = 0; index < nextList.length; index += 1) {
const adapter = nextList[index];
const token = adapter.accessToken ?? '';
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
if (!token) {
if (!allowEmpty) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”仅能从本机页面保存无令牌配置;请生成令牌后重试。`,
);
}
continue;
}
const host = adapter.host ?? '0.0.0.0';
const assessment = assessAccessToken(token, [
options.uin,
adapter.name,
kind,
host,
adapter.port,
]);
if (assessment.reason === 'too-short') {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
);
}
if (!assessment.acceptable) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
);
}
}
}
}
+37 -3
View File
@@ -17,6 +17,7 @@ import {
subscribeLogs,
} from '@snowluma/common/logger';
import {
assertValidOneBotConfig,
loadOneBotConfig,
OneBotConfigValidationError,
saveOneBotConfig,
@@ -61,6 +62,10 @@ import { startConnectionDiffLoop } from './connection-diff-loop';
import { comparableConnectionSnapshot } from './connection-snapshot';
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import {
OneBotAccessTokenPolicyError,
validateOneBotAccessTokenChanges,
} from './onebot-token-policy';
import { findAvailablePort } from './port';
import {
clearBackgroundImage,
@@ -442,6 +447,10 @@ export async function initWebUI(
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
const trustProxyMode = parseTrustProxy(listener.trustProxy);
const getClientIp = makeClientIpResolver(trustProxyMode);
// Security decisions must not silently turn an unreadable socket peer into
// localhost. The regular resolver keeps its compatibility fallback for
// rate-limit bucketing; this resolver fails closed with an empty address.
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
@@ -1295,11 +1304,36 @@ export async function initWebUI(
return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400);
}
let nextConfig: OneBotConfig;
try {
saveOneBotConfig(uin, body as OneBotConfig);
assertValidOneBotConfig(body);
nextConfig = body;
let previousConfig: OneBotConfig | null = null;
try {
previousConfig = loadOneBotConfig(uin);
} catch (err) {
// A damaged existing file must not strand the recovery UI. Treat the
// submitted endpoints as new, apply the full policy, and let the
// subsequent atomic save either repair the file or fail visibly.
log.warn(
'could not read prior OneBot config for uin=%s before save: %s',
uin,
err instanceof Error ? err.message : String(err),
);
}
validateOneBotAccessTokenChanges(previousConfig, nextConfig, {
clientIp: getSecurityClientIp(c),
uin,
});
saveOneBotConfig(uin, nextConfig);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (err instanceof OneBotConfigValidationError) {
if (
err instanceof OneBotConfigValidationError
|| err instanceof OneBotAccessTokenPolicyError
) {
log.warn('reject invalid config for uin=%s: %s', uin, message);
return c.json({ success: false, saved: false, applied: false, message }, 400);
}
@@ -1311,7 +1345,7 @@ export async function initWebUI(
// Apply the exact validated value that was persisted above. Re-reading
// the path here would race concurrent POSTs (request A could load B and
// falsely report that A was applied).
const apply = await oneBotManager.reloadConfig(uin, body as OneBotConfig);
const apply = await oneBotManager.reloadConfig(uin, nextConfig);
const message = !apply.online
? '配置保存成功,当前会话未在线,将在下次连接时生效。'
: apply.applied