diff --git a/packages/common/package.json b/packages/common/package.json index c30e9810..0bc5d959 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -63,6 +63,10 @@ "./uin": { "types": "./src/uin.ts", "default": "./src/uin.ts" + }, + "./access-token": { + "types": "./src/access-token.ts", + "default": "./src/access-token.ts" } }, "scripts": { @@ -73,5 +77,10 @@ "@types/node": "catalog:", "typescript": "catalog:", "vitest": "^4.1.4" + }, + "dependencies": { + "@zxcvbn-ts/core": "^4.1.2", + "@zxcvbn-ts/language-common": "^4.1.3", + "@zxcvbn-ts/language-en": "^4.1.1" } } diff --git a/packages/common/src/access-token.ts b/packages/common/src/access-token.ts new file mode 100644 index 00000000..903a8616 --- /dev/null +++ b/packages/common/src/access-token.ts @@ -0,0 +1,58 @@ +import { ZxcvbnFactory } from '@zxcvbn-ts/core'; +import { adjacencyGraphs, dictionary } from '@zxcvbn-ts/language-common'; +import { translations } from '@zxcvbn-ts/language-en'; + +export const ACCESS_TOKEN_MIN_LENGTH = 16; +export const ACCESS_TOKEN_MIN_SCORE = 3; + +export type AccessTokenAssessmentReason = + | 'empty' + | 'too-short' + | 'guessable' + | 'acceptable'; + +export interface AccessTokenAssessment { + acceptable: boolean; + reason: AccessTokenAssessmentReason; + score: number; +} + +const checker = new ZxcvbnFactory({ + translations, + graphs: adjacencyGraphs, + dictionary, +}); + +function normalizeUserInputs(values: readonly (string | number)[]): Array { + const unique = new Set(['SnowLuma', 'OneBot']); + for (const value of values) { + if (typeof value === 'number') { + if (Number.isFinite(value)) unique.add(value); + continue; + } + const trimmed = value.trim(); + if (trimmed) unique.add(trimmed.slice(0, 256)); + } + return [...unique].slice(0, 24); +} + +/** + * Evaluate a newly chosen OneBot access token against the shared product + * policy. Callers decide whether an empty token is permitted in their own + * trust context; an empty value is never considered strong here. + */ +export function assessAccessToken( + token: string, + userInputs: readonly (string | number)[] = [], +): AccessTokenAssessment { + if (!token) return { acceptable: false, reason: 'empty', score: 0 }; + if (token.length < ACCESS_TOKEN_MIN_LENGTH) { + return { acceptable: false, reason: 'too-short', score: 0 }; + } + + const score = checker.check(token, normalizeUserInputs(userInputs)).score; + if (score < ACCESS_TOKEN_MIN_SCORE) { + return { acceptable: false, reason: 'guessable', score }; + } + return { acceptable: true, reason: 'acceptable', score }; +} diff --git a/packages/common/tests/access-token.test.ts b/packages/common/tests/access-token.test.ts new file mode 100644 index 00000000..5363483f --- /dev/null +++ b/packages/common/tests/access-token.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; +import { + ACCESS_TOKEN_MIN_LENGTH, + ACCESS_TOKEN_MIN_SCORE, + assessAccessToken, +} from '../src/access-token'; + +describe('access token strength', () => { + it('requires the configured minimum length', () => { + expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({ + acceptable: false, + reason: 'too-short', + }); + }); + + it('scores system and user-specific words as guessable', () => { + expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001'])) + .toMatchObject({ acceptable: false, reason: 'guessable' }); + }); + + it('accepts a sufficiently long, hard-to-guess token', () => { + const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']); + + expect(result.acceptable).toBe(true); + expect(result.reason).toBe('acceptable'); + expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE); + }); +}); diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts index 4251bc92..ead56398 100644 --- a/packages/core/src/webui/client-ip.ts +++ b/packages/core/src/webui/client-ip.ts @@ -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, 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, + ); } diff --git a/packages/core/src/webui/onebot-token-policy.ts b/packages/core/src/webui/onebot-token-policy.ts new file mode 100644 index 00000000..7d883f6b --- /dev/null +++ b/packages/core/src/webui/onebot-token-policy.ts @@ -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}”的令牌容易被猜中;请重新生成随机令牌。`, + ); + } + } + } +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 08f97b41..58611be3 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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 diff --git a/packages/core/tests/onebot-token-policy.test.ts b/packages/core/tests/onebot-token-policy.test.ts new file mode 100644 index 00000000..26a4ed19 --- /dev/null +++ b/packages/core/tests/onebot-token-policy.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest'; +import { makeDefaultOneBotConfig } from '@snowluma/onebot/config'; +import { + OneBotAccessTokenPolicyError, + validateOneBotAccessTokenChanges, +} from '../src/webui/onebot-token-policy'; + +function validate( + previous: ReturnType | null, + next: ReturnType, + clientIp: string, +): void { + validateOneBotAccessTokenChanges(previous, next, { clientIp, uin: '10001' }); +} + +describe('OneBot access token save policy', () => { + it('rejects clearing an inbound token from a non-loopback client', () => { + const previous = makeDefaultOneBotConfig(); + const next = structuredClone(previous); + next.networks.httpServers[0].accessToken = undefined; + + expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError); + expect(() => validate(previous, next, '192.0.2.10')).toThrow(/本机/); + }); + + it('treats every inbound token as new when no readable prior config exists', () => { + const next = makeDefaultOneBotConfig(); + next.networks.httpServers[0].accessToken = undefined; + + expect(() => validate(null, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError); + }); + + it('allows a loopback client to deliberately clear an inbound token', () => { + const previous = makeDefaultOneBotConfig(); + const next = structuredClone(previous); + next.networks.wsServers[0].accessToken = undefined; + + expect(() => validate(previous, next, '127.0.0.2')).not.toThrow(); + }); + + it('rejects a newly changed weak inbound token', () => { + const previous = makeDefaultOneBotConfig(); + const next = structuredClone(previous); + next.networks.httpServers[0].accessToken = 'SnowLumaSnowLuma'; + + expect(() => validate(previous, next, '127.0.0.1')).toThrow(/容易被猜中/); + }); + + it('does not strand installations whose legacy token is unchanged', () => { + const previous = makeDefaultOneBotConfig(); + previous.networks.httpServers[0].accessToken = 'legacy'; + const next = structuredClone(previous); + next.networks.httpServers[0].name = 'renamed-http'; + next.networks.httpServers[0].port = 3100; + + expect(() => validate(previous, next, '192.0.2.10')).not.toThrow(); + }); + + it('allows remote edits that leave an existing empty inbound token unchanged', () => { + const previous = makeDefaultOneBotConfig(); + previous.networks.httpServers[0].accessToken = undefined; + const next = structuredClone(previous); + next.networks.httpServers[0].port = 3100; + + expect(() => validate(previous, next, '192.0.2.10')).not.toThrow(); + }); + + it('preserves legacy tokens when existing endpoints are reordered by name', () => { + const previous = makeDefaultOneBotConfig(); + previous.networks.httpServers[0].accessToken = 'legacy'; + previous.networks.httpServers.push({ + ...previous.networks.httpServers[0], + name: 'second-http', + port: 3100, + }); + const next = structuredClone(previous); + next.networks.httpServers.reverse(); + + expect(() => validate(previous, next, '192.0.2.10')).not.toThrow(); + }); + + it('does not mistake an inserted endpoint for a renamed legacy endpoint', () => { + const previous = makeDefaultOneBotConfig(); + previous.networks.httpServers[0].accessToken = 'legacy'; + const next = structuredClone(previous); + next.networks.httpServers.unshift({ + ...next.networks.httpServers[0], + name: 'new-http', + port: 3100, + }); + + expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError); + }); + + it('does not impose local inbound-token policy on outbound adapters', () => { + const previous = makeDefaultOneBotConfig(); + const next = structuredClone(previous); + next.networks.httpClients.push({ + name: 'remote-service', + url: 'https://example.com/events', + accessToken: 'remote-chosen-token', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => validate(previous, next, '192.0.2.10')).not.toThrow(); + }); + + it('accepts a newly changed strong inbound token', () => { + const previous = makeDefaultOneBotConfig(); + const next = structuredClone(previous); + next.networks.wsServers[0].accessToken = 'E5xqVb7_9pLt2QwR4M8kZ1nY'; + + expect(() => validate(previous, next, '192.0.2.10')).not.toThrow(); + }); +}); diff --git a/packages/core/tests/webui-client-ip.test.ts b/packages/core/tests/webui-client-ip.test.ts index 0a8159f3..8883c243 100644 --- a/packages/core/tests/webui-client-ip.test.ts +++ b/packages/core/tests/webui-client-ip.test.ts @@ -1,11 +1,24 @@ import { describe, expect, it } from 'vitest'; import { describeTrustProxy, + isLoopbackClientIp, parseTrustProxy, pickClientIp, type TrustProxyMode, } from '../src/webui/client-ip'; +describe('isLoopbackClientIp', () => { + it.each(['127.0.0.1', '127.0.0.2', '::1', '0:0:0:0:0:0:0:1', '::ffff:127.0.0.9'])( + 'accepts loopback address %s', + (address) => expect(isLoopbackClientIp(address)).toBe(true), + ); + + it.each(['', 'localhost', '0.0.0.0', '192.168.1.2', '::ffff:192.168.1.2'])( + 'rejects non-loopback or unverified address %s', + (address) => expect(isLoopbackClientIp(address)).toBe(false), + ); +}); + function mockCtx(headers: Record = {}) { return { req: { @@ -79,6 +92,23 @@ describe('pickClientIp', () => { const mode: TrustProxyMode = { kind: 'none' }; expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1'); }); + + it('can fail closed when a security decision cannot resolve the socket peer', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); }, '')).toBe(''); + }); + + it('does not trust forwarded headers when the socket peer is unknown', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect( + pickClientIp( + mockCtx({ 'x-real-ip': '127.0.0.1' }), + mode, + () => { throw new Error('boom'); }, + '', + ), + ).toBe(''); + }); }); describe('describeTrustProxy', () => { diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 536679ce..4598dcd4 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -45,7 +45,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig { networks: { httpServers: [{ name: 'http-default', - host: '0.0.0.0', + host: '127.0.0.1', port: 3000, path: '/', enableWebSocket: false, @@ -56,7 +56,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig { httpClients: [], wsServers: [{ name: 'ws-default', - host: '0.0.0.0', + host: '127.0.0.1', port: 3001, path: '/', role: 'Universal', diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index 2142ad4e..26ca11dd 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -18,13 +18,14 @@ describe('makeDefaultOneBotConfig', () => { const config = makeDefaultOneBotConfig(); expect(config.networks.httpServers).toHaveLength(1); expect(config.networks.httpServers[0].name).toBe('http-default'); - expect(config.networks.httpServers[0].host).toBe('0.0.0.0'); + expect(config.networks.httpServers[0].host).toBe('127.0.0.1'); expect(config.networks.httpServers[0].port).toBe(3000); expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN); expect(config.networks.httpServers[0].messageFormat).toBe('array'); expect(config.networks.httpServers[0].reportSelfMessage).toBe(false); expect(config.networks.httpClients).toEqual([]); expect(config.networks.wsServers).toHaveLength(1); + expect(config.networks.wsServers[0].host).toBe('127.0.0.1'); expect(config.networks.wsServers[0].port).toBe(3001); expect(config.networks.wsServers[0].role).toBe('Universal'); expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN); @@ -87,6 +88,7 @@ describe('assertValidOneBotConfig', () => { it('rejects enabled servers with the same normalized host and port', () => { const config = makeDefaultOneBotConfig(); + config.networks.httpServers[0].host = '0.0.0.0'; config.networks.wsServers.push({ name: 'conflicting-ws', host: '0.0.0.0', @@ -107,6 +109,7 @@ describe('assertValidOneBotConfig', () => { expect(() => assertValidOneBotConfig(blank)).toThrow(/\.host/); const wildcard = makeDefaultOneBotConfig(); + wildcard.networks.httpServers[0].host = '0.0.0.0'; wildcard.networks.wsServers.push({ name: 'specific-ws', host: '127.0.0.1', @@ -182,13 +185,14 @@ describe('saveOneBotConfig validation boundary', () => { const config = makeDefaultOneBotConfig(); config.networks.wsServers.push({ name: 'same-bind', + host: '127.0.0.1', port: 3000, path: '/ws', messageFormat: 'array', reportSelfMessage: false, }); - expect(() => saveOneBotConfig('10001', config)).toThrow(/server binding 0\.0\.0\.0:3000/); + expect(() => saveOneBotConfig('10001', config)).toThrow(/server binding 127\.0\.0\.1:3000/); expect(fs.existsSync(path.join(tempDir, 'config', 'onebot_10001.json'))).toBe(false); } finally { process.chdir(previous); diff --git a/packages/webui/src/components/config/defaults.ts b/packages/webui/src/components/config/defaults.ts index bcd80c94..ec9aac29 100644 --- a/packages/webui/src/components/config/defaults.ts +++ b/packages/webui/src/components/config/defaults.ts @@ -30,7 +30,7 @@ export interface NetworkTabDescriptor { 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, }), diff --git a/packages/webui/src/components/config/node-edit-dialog.tsx b/packages/webui/src/components/config/node-edit-dialog.tsx index 29bc3f2f..460f1d5b 100644 --- a/packages/webui/src/components/config/node-edit-dialog.tsx +++ b/packages/webui/src/components/config/node-edit-dialog.tsx @@ -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 = OneBotNetworks[K][number]; @@ -59,11 +65,13 @@ interface NodeEditDialogProps { 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) => void; } export function NodeEditDialog(props: NodeEditDialogProps) { - 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(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>) => setDraft({ ...draft, ...changes } as AnyAdapter); @@ -155,9 +180,11 @@ export function NodeEditDialog(props: NodeEditDialogProps
patch({ accessToken: v || undefined } as Partial>)} + onGenerate={() => patch({ accessToken: generateAccessToken() } as Partial>)} + feedback={tokenFeedback} />
@@ -259,7 +286,7 @@ function KindFields({ kind, draft, patch }: KindFieldsPro
set({ host: v || undefined })} /> @@ -307,7 +334,7 @@ function KindFields({ kind, draft, patch }: KindFieldsPro
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(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" /> +
+ {feedback && ( +

+ {feedback.message} +

+ )}
); } diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index 1965af42..35d360f2 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -269,7 +269,7 @@ export function ConfigPage() { {/* Single dialog covers create + edit across all 4 kinds. */} - {dialog.open && config && ( + {dialog.open && config && selectedUin && ( !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); diff --git a/packages/webui/src/lib/access-token-feedback.ts b/packages/webui/src/lib/access-token-feedback.ts new file mode 100644 index 00000000..5866c13f --- /dev/null +++ b/packages/webui/src/lib/access-token-feedback.ts @@ -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: '令牌强度符合要求。', + }; +} diff --git a/packages/webui/tests/onebot-access-token.test.ts b/packages/webui/tests/onebot-access-token.test.ts new file mode 100644 index 00000000..6972ae45 --- /dev/null +++ b/packages/webui/tests/onebot-access-token.test.ts @@ -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' }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 46fe1743..eeb66545 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -78,6 +78,16 @@ importers: version: 4.1.4(@types/node@22.13.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.1.0(@types/node@22.13.0)(esbuild@0.28.1)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) packages/common: + dependencies: + '@zxcvbn-ts/core': + specifier: ^4.1.2 + version: 4.1.2 + '@zxcvbn-ts/language-common': + specifier: ^4.1.3 + version: 4.1.3 + '@zxcvbn-ts/language-en': + specifier: ^4.1.1 + version: 4.1.1 devDependencies: '@types/node': specifier: 'catalog:' @@ -2036,6 +2046,18 @@ packages: '@vitest/utils@4.1.4': resolution: {integrity: sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==} + '@zxcvbn-ts/core@4.1.2': + resolution: {integrity: sha512-RQmxWB3AMI+HGQErQdUv6Aq32aQhp6xOxrfgCP0+T9MsLZoP3xtLHuT8O8VojsUxdmQVZfJlYkYb1A0wOwIS+Q==} + + '@zxcvbn-ts/dictionary-compression@3.0.1': + resolution: {integrity: sha512-p3KyPzxGc3vWSap5hHA6SllbUCmh7s+NtpGyC3qEWrxYJT9t9TUAzjPm48Okipo+UUyPQfDlIvTcs9JRShBFiQ==} + + '@zxcvbn-ts/language-common@4.1.3': + resolution: {integrity: sha512-g2bg4skmlJG9aJqC/nWziZzgYpSe/f3rKeGobrkdFiOrfZVFqqzUgC6BUQWuX54Sua9j0Jxxt+1bf4f/Mal1Kg==} + + '@zxcvbn-ts/language-en@4.1.1': + resolution: {integrity: sha512-6UdzuBd3Uex8TKubohcn+uXRVAH34Zjs2eCfT4hQVo9zeTy7AkQRQfdV4OnHR5hQfW/XBrK/AGTZk7VBWh7wwQ==} + accepts@2.0.0: resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} engines: {node: '>= 0.6'} @@ -2382,6 +2404,10 @@ packages: fast-uri@3.1.2: resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -4786,6 +4812,20 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.0 + '@zxcvbn-ts/core@4.1.2': + dependencies: + fastest-levenshtein: 1.0.16 + + '@zxcvbn-ts/dictionary-compression@3.0.1': {} + + '@zxcvbn-ts/language-common@4.1.3': + dependencies: + '@zxcvbn-ts/dictionary-compression': 3.0.1 + + '@zxcvbn-ts/language-en@4.1.1': + dependencies: + '@zxcvbn-ts/dictionary-compression': 3.0.1 + accepts@2.0.0: dependencies: mime-types: 3.0.2 @@ -5173,6 +5213,8 @@ snapshots: fast-uri@3.1.2: {} + fastest-levenshtein@1.0.16: {} + fdir@6.5.0(picomatch@4.0.4): optionalDependencies: picomatch: 4.0.4