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:
16 files changed
+601
-33
No files matched your search
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<string | number> {
|
||||
const unique = new Set<string | number>(['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 };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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}”的令牌容易被猜中;请重新生成随机令牌。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<typeof makeDefaultOneBotConfig> | null,
|
||||
next: ReturnType<typeof makeDefaultOneBotConfig>,
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> = {}) {
|
||||
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', () => {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
Generated
+42
@@ -78,6 +78,16 @@ importers:
|
||||
version: 4.1.4(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
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/[email protected]':
|
||||
resolution: {integrity: sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==}
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
resolution: {integrity: sha512-RQmxWB3AMI+HGQErQdUv6Aq32aQhp6xOxrfgCP0+T9MsLZoP3xtLHuT8O8VojsUxdmQVZfJlYkYb1A0wOwIS+Q==}
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
resolution: {integrity: sha512-p3KyPzxGc3vWSap5hHA6SllbUCmh7s+NtpGyC3qEWrxYJT9t9TUAzjPm48Okipo+UUyPQfDlIvTcs9JRShBFiQ==}
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
resolution: {integrity: sha512-g2bg4skmlJG9aJqC/nWziZzgYpSe/f3rKeGobrkdFiOrfZVFqqzUgC6BUQWuX54Sua9j0Jxxt+1bf4f/Mal1Kg==}
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
resolution: {integrity: sha512-6UdzuBd3Uex8TKubohcn+uXRVAH34Zjs2eCfT4hQVo9zeTy7AkQRQfdV4OnHR5hQfW/XBrK/AGTZk7VBWh7wwQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
|
||||
engines: {node: '>= 0.6'}
|
||||
@@ -2382,6 +2404,10 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==}
|
||||
engines: {node: '>= 4.9.1'}
|
||||
|
||||
[email protected]:
|
||||
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/[email protected]':
|
||||
dependencies:
|
||||
fastest-levenshtein: 1.0.16
|
||||
|
||||
'@zxcvbn-ts/[email protected]': {}
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
dependencies:
|
||||
'@zxcvbn-ts/dictionary-compression': 3.0.1
|
||||
|
||||
'@zxcvbn-ts/[email protected]':
|
||||
dependencies:
|
||||
'@zxcvbn-ts/dictionary-compression': 3.0.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
mime-types: 3.0.2
|
||||
@@ -5173,6 +5213,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]([email protected]):
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.4
|
||||
|
||||
Reference in new issue
Block a user