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

@@ -30,7 +30,7 @@ export interface NetworkTabDescriptor<K extends NetworkKind> {
defaultEntry: (suffix: number) => OneBotNetworks[K][number];
}
function genToken(): string {
export function generateAccessToken(): string {
const bytes = new Uint8Array(32);
globalThis.crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
@@ -48,11 +48,11 @@ const httpServersTab: NetworkTabDescriptor<'httpServers'> = {
},
defaultEntry: (suffix): HttpServerNetwork => ({
name: `http-${suffix}`,
host: '0.0.0.0',
host: '127.0.0.1',
port: 3000,
path: '/',
enableWebSocket: false,
accessToken: genToken(),
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}),
@@ -85,11 +85,11 @@ const wsServersTab: NetworkTabDescriptor<'wsServers'> = {
},
defaultEntry: (suffix): WsServerNetwork => ({
name: `ws-${suffix}`,
host: '0.0.0.0',
host: '127.0.0.1',
port: 3001,
path: '/',
role: 'Universal' as WsRole,
accessToken: genToken(),
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}),
@@ -7,7 +7,7 @@
// captioned sections, soft rounded cards, settings rows with a label on the
// left and a control (toggle / custom dropdown) on the right.
import { useRef, useState, type ReactNode } from 'react';
import { useId, useMemo, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import {
ArrowLeftRight,
@@ -17,6 +17,7 @@ import {
Eye,
EyeOff,
Radio,
RefreshCw,
Server,
type LucideIcon,
} from 'lucide-react';
@@ -27,6 +28,11 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { cn } from '@/lib/utils';
import {
accessTokenFeedback,
type AccessTokenFeedback,
} from '@/lib/access-token-feedback';
import { isLoopbackHostname } from '@/lib/transport-security';
import type {
HttpClientNetwork,
HttpServerNetwork,
@@ -37,7 +43,7 @@ import type {
WsRole,
WsServerNetwork,
} from '@/types';
import { NETWORK_TABS } from './defaults';
import { generateAccessToken, NETWORK_TABS } from './defaults';
type AnyAdapter<K extends NetworkKind> = OneBotNetworks[K][number];
@@ -59,11 +65,13 @@ interface NodeEditDialogProps<K extends NetworkKind> {
isEdit: boolean;
/** Names of every other adapter in the same list, for duplicate check. */
otherNames: string[];
/** Account context used when evaluating user-chosen access tokens. */
uin: string;
onSubmit: (item: AnyAdapter<K>) => void;
}
export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps<K>) {
const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props;
const { open, onOpenChange, kind, initial, isEdit, otherNames, uin, onSubmit } = props;
const tab = NETWORK_TABS[kind];
const Icon: LucideIcon = KIND_ICON[kind];
@@ -76,7 +84,24 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
const blankName = trimmedName.length === 0;
const duplicateName = !blankName && otherNames.includes(trimmedName);
const canSave = !blankName && !duplicateName;
const isInboundServer = kind === 'httpServers' || kind === 'wsServers';
const tokenChanged = (draft.accessToken ?? '') !== (initial.accessToken ?? '');
const enforceTokenPolicy = isInboundServer && (!isEdit || tokenChanged);
const allowEmptyToken = typeof window !== 'undefined'
&& isLoopbackHostname(window.location.hostname);
const inbound = isInboundServer ? draft as HttpServerNetwork | WsServerNetwork : null;
const tokenFeedback = useMemo(
() => enforceTokenPolicy
? accessTokenFeedback(
draft.accessToken ?? '',
[uin, draft.name ?? '', kind, inbound?.host ?? '', inbound?.port ?? 0],
allowEmptyToken,
)
: undefined,
[allowEmptyToken, draft.accessToken, draft.name, enforceTokenPolicy, inbound?.host, inbound?.port, kind, uin],
);
const canSave = !blankName && !duplicateName && (tokenFeedback?.valid ?? true);
const patch = (changes: Partial<AnyAdapter<K>>) => setDraft({ ...draft, ...changes } as AnyAdapter<K>);
@@ -155,9 +180,11 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
<div className="p-4">
<TokenField
label="授权 Token"
placeholder="不填则无密码"
placeholder={isInboundServer ? '留空则关闭鉴权(仅允许本机保存)' : '按对端要求填写'}
value={draft.accessToken}
onChange={(v) => patch({ accessToken: v || undefined } as Partial<AnyAdapter<K>>)}
onGenerate={() => patch({ accessToken: generateAccessToken() } as Partial<AnyAdapter<K>>)}
feedback={tokenFeedback}
/>
</div>
</Section>
@@ -259,7 +286,7 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
@@ -307,7 +334,7 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
@@ -381,7 +408,9 @@ interface TokenFieldProps {
label: string;
value: string | undefined;
onChange: (v: string) => void;
onGenerate: () => void;
placeholder?: string;
feedback?: AccessTokenFeedback;
}
/** Insecure-context clipboard fallback. Returns true on success.
@@ -411,10 +440,11 @@ function legacyCopyToClipboard(value: string): boolean {
* unmasks it and a copy button shoves the current value to the system
* clipboard with a short "已复制" confirmation flash.
*/
function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
function TokenField({ label, value, onChange, onGenerate, placeholder, feedback }: TokenFieldProps) {
const [visible, setVisible] = useState(false);
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<number | null>(null);
const feedbackId = useId();
const handleCopy = async () => {
if (!value) return;
@@ -449,8 +479,20 @@ function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
placeholder={placeholder}
autoComplete="off"
spellCheck={false}
aria-invalid={feedback?.tone === 'error' || undefined}
aria-describedby={feedback ? feedbackId : undefined}
className="flex-1 font-mono"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={onGenerate}
aria-label="生成新的随机令牌"
title="生成新的随机令牌"
>
<RefreshCw className="size-4" />
</Button>
<Button
type="button"
variant="outline"
@@ -473,6 +515,22 @@ function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
{visible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{feedback && (
<p
id={feedbackId}
aria-live="polite"
className={cn(
'text-xs',
feedback.tone === 'error'
? 'text-destructive'
: feedback.tone === 'warning'
? 'text-warning'
: 'text-success',
)}
>
{feedback.message}
</p>
)}
</div>
);
}
@@ -269,7 +269,7 @@ export function ConfigPage() {
</div>
{/* Single dialog covers create + edit across all 4 kinds. */}
{dialog.open && config && (
{dialog.open && config && selectedUin && (
<NodeEditDialog
open={dialog.open}
onOpenChange={(open) => !open && setDialog({ open: false })}
@@ -277,6 +277,7 @@ export function ConfigPage() {
initial={dialog.seed}
isEdit={dialog.index != null}
otherNames={otherNames(config.networks, dialog.kind, dialog.index)}
uin={selectedUin}
onSubmit={(item) => {
if (dialog.index == null) handleCreate(dialog.kind, item);
else handleEdit(dialog.kind, dialog.index, item);
@@ -0,0 +1,48 @@
import { assessAccessToken } from '@snowluma/common/access-token';
export interface AccessTokenFeedback {
valid: boolean;
tone: 'success' | 'warning' | 'error';
message: string;
}
export function accessTokenFeedback(
token: string,
userInputs: readonly (string | number)[],
allowEmpty: boolean,
): AccessTokenFeedback {
if (!token) {
return allowEmpty
? {
valid: true,
tone: 'warning',
message: '留空将关闭该服务端的鉴权,仅建议在本机使用。',
}
: {
valid: false,
tone: 'error',
message: '当前为远程访问,请使用右侧按钮生成令牌后保存。',
};
}
const assessment = assessAccessToken(token, userInputs);
if (assessment.reason === 'too-short') {
return {
valid: false,
tone: 'error',
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
};
}
if (!assessment.acceptable) {
return {
valid: false,
tone: 'error',
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
};
}
return {
valid: true,
tone: 'success',
message: '令牌强度符合要求。',
};
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import { accessTokenFeedback } from '../src/lib/access-token-feedback';
import { NETWORK_TABS, generateAccessToken } from '../src/components/config/defaults';
describe('OneBot access token editor policy', () => {
it('creates inbound endpoints on loopback with generated tokens', () => {
const http = NETWORK_TABS.httpServers.defaultEntry(1);
const ws = NETWORK_TABS.wsServers.defaultEntry(1);
expect(http.host).toBe('127.0.0.1');
expect(ws.host).toBe('127.0.0.1');
expect(http.accessToken).not.toBe(ws.accessToken);
expect(accessTokenFeedback(http.accessToken ?? '', [], false).valid).toBe(true);
expect(accessTokenFeedback(ws.accessToken ?? '', [], false).valid).toBe(true);
});
it('generates a fresh strong token on demand', () => {
const first = generateAccessToken();
const second = generateAccessToken();
expect(first).not.toBe(second);
expect(accessTokenFeedback(first, ['SnowLuma', 'OneBot'], false).valid).toBe(true);
});
it('gives one actionable message for short and guessable values', () => {
expect(accessTokenFeedback('short', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌至少需要 16 个字符,请继续补充或重新生成。',
});
expect(accessTokenFeedback('SnowLumaSnowLuma', ['SnowLuma'], false)).toEqual({
valid: false,
tone: 'error',
message: '令牌容易被猜中,请使用右侧按钮生成新的随机令牌。',
});
});
it('only permits an empty inbound token on loopback', () => {
expect(accessTokenFeedback('', [], false)).toMatchObject({ valid: false, tone: 'error' });
expect(accessTokenFeedback('', [], true)).toMatchObject({ valid: true, tone: 'warning' });
});
});