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

+103
View File
@@ -0,0 +1,103 @@
name: Publish UI to npm
on:
push:
branches: [main]
paths:
- 'packages/ui/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: ui-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build and publish UI
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check UI
run: pnpm --filter @snowluma/ui typecheck
- name: Build UI
run: pnpm --filter @snowluma/ui build
- name: Check npm package version
id: npm
working-directory: packages/ui
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish UI to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## UI npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"
+19
View File
@@ -0,0 +1,19 @@
{
"$schema": "./qq.schema.json",
"version": 1,
"updatedAt": "2026-05-16T00:00:00Z",
"policy": {
"allowUnknown": true,
"warnUnknown": true
},
"knownGoodVersions": [],
"knownBadVersions": [],
"minVersion": null,
"notes": [
"QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本",
"policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)",
"knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本",
"minVersion: 设为 SemVer 字符串则更早的版本会被拒",
"知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明"
]
}
+56
View File
@@ -0,0 +1,56 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SnowLuma QQ compatibility manifest",
"type": "object",
"required": ["version", "policy", "knownGoodVersions", "knownBadVersions"],
"properties": {
"$schema": { "type": "string" },
"version": { "type": "integer", "const": 1 },
"updatedAt": { "type": "string", "format": "date-time" },
"policy": {
"type": "object",
"required": ["allowUnknown"],
"properties": {
"allowUnknown": {
"type": "boolean",
"description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions"
},
"warnUnknown": {
"type": "boolean",
"description": "未列出的版本启动时是否弹警告"
}
}
},
"knownGoodVersions": {
"type": "array",
"items": {
"type": "object",
"required": ["version"],
"properties": {
"version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" },
"note": { "type": "string" }
}
}
},
"knownBadVersions": {
"type": "array",
"items": {
"type": "object",
"required": ["version"],
"properties": {
"version": { "type": "string" },
"reason": { "type": "string" },
"fixedInDesktopVersion": { "type": "string" }
}
}
},
"minVersion": {
"type": ["string", "null"],
"description": "最低支持版本(SemVer),null = 不限"
},
"notes": {
"type": "array",
"items": { "type": "string" }
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.8.1",
"version": "1.8.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+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');
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/runtime",
"version": "1.8.1",
"version": "1.8.2",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "[email protected]"
},
"version": "1.8.1",
"version": "1.8.2",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+18
View File
@@ -122,6 +122,24 @@ export const SNOWLUMA_ACTIONS = [
'rename_group_file',
'get_file',
'.send_packet',
// napcat-parity extensions (Tier 1 + Tier 2)
'send_packet',
'bot_exit',
'nc_get_packet_status',
'nc_get_rkey',
'nc_get_user_status',
'get_group_ignore_add_request',
'delete_group_folder',
'set_group_todo',
'complete_group_todo',
'cancel_group_todo',
// Tier 3: DIY status
'set_diy_online_status',
// AI voice trio
'get_ai_characters',
'get_ai_record',
'send_group_ai_record',
] as const satisfies readonly (keyof SnowLumaActionMap)[];
export type SnowLumaKnownAction = typeof SNOWLUMA_ACTIONS[number];
+31 -1
View File
@@ -60,6 +60,13 @@ import type {
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
SetDiyOnlineStatusParams,
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
} from './params';
import type {
CapabilityInfo,
@@ -84,6 +91,9 @@ import type {
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
} from './results';
export type ActionData = JsonValue;
@@ -209,7 +219,27 @@ export interface SnowLumaActionMap {
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: JsonObject; data: JsonValue };
'.send_packet': { params: SendPacketParams; data: string };
// — napcat-parity extensions (Tier 1 + Tier 2) —
send_packet: { params: SendPacketParams; data: string };
bot_exit: { params: JsonObject; data: EmptyData };
nc_get_packet_status: { params: JsonObject; data: JsonValue };
nc_get_rkey: { params: JsonObject; data: JsonObject[] };
nc_get_user_status: { params: NcGetUserStatusParams; data: UserOnlineStatus };
get_group_ignore_add_request: { params: JsonObject; data: JsonArray };
delete_group_folder: { params: DeleteGroupFolderParams; data: EmptyData };
set_group_todo: { params: GroupTodoParams; data: EmptyData };
complete_group_todo: { params: GroupTodoParams; data: EmptyData };
cancel_group_todo: { params: GroupTodoParams; data: EmptyData };
// — Tier 3: DIY status —
set_diy_online_status: { params: SetDiyOnlineStatusParams; data: EmptyData };
// — AI voice trio —
get_ai_characters: { params: GetAiCharactersParams; data: AiCharacterCategory[] };
get_ai_record: { params: AiVoiceParams; data: string };
send_group_ai_record: { params: AiVoiceParams; data: SendGroupAiRecordResult };
}
export type SnowLumaAction = keyof SnowLumaActionMap | (string & {});
+44
View File
@@ -316,3 +316,47 @@ export interface SetOnlineStatusParams extends JsonObject {
ext_status?: number;
battery_status?: number;
}
// DIY online status — status/extStatus are forced to 10/2000 server-side,
// and these three fields land in the customExt sub-message.
export interface SetDiyOnlineStatusParams extends JsonObject {
face_id: number | string;
wording?: string;
face_type?: number | string;
}
// nc_get_user_status — read the QQ-side online/ext-status word for a uin.
export interface NcGetUserStatusParams extends UserIdParams {}
// set_/complete_/cancel_group_todo all share this shape; the action verb
// lives in the route, not the body.
export interface GroupTodoParams extends GroupIdParams {
message_id: number | string;
}
// AI voice — fetch the in-group AI character list.
export interface GetAiCharactersParams extends GroupIdParams {
chat_type?: number | string;
}
// AI voice — `get_ai_record` and `send_group_ai_record` share params.
// The action's verb (read vs send) is the route, not the body.
export interface AiVoiceParams extends GroupIdParams {
character: string;
text: string;
chat_type?: number | string;
}
// delete_group_folder — napcat's alias for delete_group_file_folder.
// Same body, different action name.
export interface DeleteGroupFolderParams extends GroupIdParams {
folder_id: string;
}
// send_packet — debug endpoint, sends a hex-encoded raw packet.
// `rsp=false` skips waiting for a response.
export interface SendPacketParams extends JsonObject {
cmd: string;
data?: string;
rsp?: boolean;
}
+23
View File
@@ -101,3 +101,26 @@ export interface GroupAtAllRemainInfo {
}
export type EmptyData = null;
// — AI 语音角色:get_ai_characters 返回的分类数组 —
export interface AiCharacter {
character_id: string;
character_name: string;
preview_url: string;
}
export interface AiCharacterCategory {
type: string;
characters: AiCharacter[];
}
// — nc_get_user_status 返回的状态字 —
export interface UserOnlineStatus {
status: number;
ext_status: number;
}
// — send_group_ai_record 返回(合成是异步副作用,message_id 总为 0) —
export interface SendGroupAiRecordResult {
message_id: number;
}
+89
View File
@@ -0,0 +1,89 @@
{
"name": "@snowluma/ui",
"author": {
"name": "MotricSeven",
"email": "[email protected]"
},
"version": "1.8.2",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
"ui",
"shadcn",
"tailwind",
"react"
],
"homepage": "https://github.com/SnowLuma/SnowLuma#readme",
"bugs": {
"url": "https://github.com/SnowLuma/SnowLuma/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SnowLuma/SnowLuma.git",
"directory": "packages/ui"
},
"license": "UNLICENSED",
"type": "module",
"sideEffects": [
"**/*.css"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./styles/theme.css": "./src/styles/theme.css",
"./package.json": "./package.json"
},
"files": [
"dist",
"src/styles"
],
"scripts": {
"clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"",
"prebuild": "pnpm run clean",
"build": "tsup",
"dev": "tsup --watch",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit"
},
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=22"
},
"peerDependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.7",
"@radix-ui/react-checkbox": "^1.1.5",
"@radix-ui/react-dialog": "^1.1.7",
"@radix-ui/react-label": "^2.1.3",
"@radix-ui/react-popover": "^1.1.7",
"@radix-ui/react-scroll-area": "^1.2.4",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.3",
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.1.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.469.0",
"sonner": "^2.0.6",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"tsup": "^8.5.0",
"typescript": "catalog:"
}
}
@@ -0,0 +1,98 @@
import * as React from 'react';
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
import { cn } from '../lib/cn';
import { buttonVariants } from './button';
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-background/60 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
));
AlertDialogOverlay.displayName = 'AlertDialogOverlay';
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg grid-cols-[minmax(0,1fr)] -translate-x-1/2 -translate-y-1/2 gap-5 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-xl ring-1 ring-foreground/5',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = 'AlertDialogContent';
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
);
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
);
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn('text-base font-semibold leading-tight tracking-tight', className)} {...props} />
));
AlertDialogTitle.displayName = 'AlertDialogTitle';
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn('text-sm leading-relaxed text-muted-foreground', className)} {...props} />
));
AlertDialogDescription.displayName = 'AlertDialogDescription';
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = 'AlertDialogAction';
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel ref={ref} className={cn(buttonVariants({ variant: 'outline' }), 'mt-0', className)} {...props} />
));
AlertDialogCancel.displayName = 'AlertDialogCancel';
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
+44
View File
@@ -0,0 +1,44 @@
import * as React from 'react';
import { cn } from '../lib/cn';
interface AvatarProps extends React.HTMLAttributes<HTMLDivElement> {
size?: number;
}
const Avatar = React.forwardRef<HTMLDivElement, AvatarProps>(
({ className, size = 36, style, ...props }, ref) => (
<div
ref={ref}
className={cn('relative inline-flex shrink-0 overflow-hidden rounded-full bg-muted', className)}
style={{ width: size, height: size, ...style }}
{...props}
/>
)
);
Avatar.displayName = 'Avatar';
const AvatarImage = React.forwardRef<HTMLImageElement, React.ImgHTMLAttributes<HTMLImageElement>>(
({ className, alt = '', ...props }, ref) => (
<img
ref={ref}
alt={alt}
className={cn('aspect-square size-full object-cover', className)}
referrerPolicy="no-referrer"
{...props}
/>
)
);
AvatarImage.displayName = 'AvatarImage';
const AvatarFallback = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>(
({ className, ...props }, ref) => (
<span
ref={ref}
className={cn('flex size-full items-center justify-center bg-muted text-xs font-medium text-muted-foreground', className)}
{...props}
/>
)
);
AvatarFallback.displayName = 'AvatarFallback';
export { Avatar, AvatarImage, AvatarFallback };
+35
View File
@@ -0,0 +1,35 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../lib/cn';
export const badgeVariants = cva(
'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium leading-none transition-colors',
{
variants: {
variant: {
default: 'border-transparent bg-primary/15 text-primary',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive/15 text-destructive',
success: 'border-transparent bg-success/15 text-success',
warning: 'border-transparent bg-warning/15 text-warning',
info: 'border-transparent bg-info/15 text-info',
outline: 'border-border bg-card text-foreground',
soft: 'border-transparent bg-muted text-muted-foreground',
},
size: {
default: 'px-2 py-0.5 text-[11px]',
sm: 'px-1.5 py-px text-[10px]',
lg: 'px-2.5 py-1 text-xs',
},
},
defaultVariants: { variant: 'default', size: 'default' },
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLSpanElement>,
VariantProps<typeof badgeVariants> {}
export function Badge({ className, variant, size, ...props }: BadgeProps) {
return <span className={cn(badgeVariants({ variant, size }), className)} {...props} />;
}
+54
View File
@@ -0,0 +1,54 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../lib/cn';
export const buttonVariants = cva(
[
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium",
"transition-[color,background-color,border-color,box-shadow,transform] duration-150 ease-out",
"disabled:pointer-events-none disabled:opacity-50",
"[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0",
"outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring",
"active:translate-y-px cursor-pointer",
].join(' '),
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95',
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 active:bg-destructive/95',
outline:
'border border-border bg-card text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground hover:border-border/80',
secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
ghost: 'text-foreground hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline shadow-none',
success: 'bg-success text-success-foreground shadow-sm hover:bg-success/90',
warning: 'bg-warning text-warning-foreground shadow-sm hover:bg-warning/90',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-lg px-6',
icon: 'size-9 rounded-lg',
'icon-sm': 'size-8 rounded-md',
'icon-xs': 'size-7 rounded-md',
},
},
defaultVariants: { variant: 'default', size: 'default' },
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return <Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />;
},
);
Button.displayName = 'Button';
+50
View File
@@ -0,0 +1,50 @@
import * as React from 'react';
import { cn } from '../lib/cn';
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('rounded-xl border border-border bg-card text-card-foreground shadow-sm', className)}
{...props}
/>
),
);
Card.displayName = 'Card';
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex flex-col gap-1.5 p-5', className)} {...props} />
),
);
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('text-base font-semibold leading-tight tracking-tight', className)} {...props} />
),
);
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('text-sm leading-relaxed text-muted-foreground', className)} {...props} />
),
);
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-5 pt-0', className)} {...props} />
),
);
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center gap-2 p-5 pt-0', className)} {...props} />
),
);
CardFooter.displayName = 'CardFooter';
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter };
+30
View File
@@ -0,0 +1,30 @@
import * as React from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check, Minus } from 'lucide-react';
import { cn } from '../lib/cn';
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
'peer size-4 shrink-0 rounded-[5px] border border-border bg-card shadow-xs transition-colors',
'hover:border-border/80',
'focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground data-[state=checked]:border-primary',
'data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
{props.checked === 'indeterminate' ? <Minus className="size-3" /> : <Check className="size-3" />}
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = 'Checkbox';
export { Checkbox };
+102
View File
@@ -0,0 +1,102 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '../lib/cn';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-background/60 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
));
DialogOverlay.displayName = 'DialogOverlay';
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { showClose?: boolean }
>(({ className, children, showClose = true, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
// grid-cols-[minmax(0,1fr)] keeps wide children (long select text,
// file paths, etc.) from blowing past the dialog's max-w-lg by
// forcing the implicit grid track's `min-width: auto` to 0.
'fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg grid-cols-[minmax(0,1fr)] -translate-x-1/2 -translate-y-1/2 gap-5 rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-xl ring-1 ring-foreground/5',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[state=open]:slide-in-from-top-2',
className,
)}
{...props}
>
{children}
{showClose && (
<DialogPrimitive.Close className="absolute right-4 top-4 inline-flex size-7 items-center justify-center rounded-md text-muted-foreground opacity-80 transition hover:bg-muted hover:opacity-100 focus:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40">
<X className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = 'DialogContent';
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
);
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
);
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn('text-base font-semibold leading-tight tracking-tight', className)}
{...props}
/>
));
DialogTitle.displayName = 'DialogTitle';
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm leading-relaxed text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = 'DialogDescription';
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
@@ -0,0 +1,36 @@
import * as React from 'react';
import { cn } from '../lib/cn';
interface EmptyStateProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
icon?: React.ReactNode;
title: React.ReactNode;
description?: React.ReactNode;
action?: React.ReactNode;
}
/**
* Generic "nothing here yet" placeholder. Used by Bot list, search-with-no-
* results, log filters that filtered everything out, etc.
*/
export function EmptyState({ icon, title, description, action, className, ...props }: EmptyStateProps) {
return (
<div
className={cn(
'flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-border bg-card/40 px-6 py-12 text-center',
className,
)}
{...props}
>
{icon && (
<div className="flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
{icon}
</div>
)}
<div className="space-y-1">
<h3 className="text-sm font-medium text-foreground">{title}</h3>
{description && <p className="text-xs leading-relaxed text-muted-foreground">{description}</p>}
</div>
{action && <div className="pt-1">{action}</div>}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import * as React from 'react';
import { cn } from '../lib/cn';
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, type, ...props }, ref) => (
<input
type={type}
ref={ref}
className={cn(
'flex h-9 w-full min-w-0 rounded-lg border border-border bg-card px-3 py-1 text-sm text-foreground shadow-xs transition-[color,box-shadow,border-color,background-color] outline-none',
'file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium',
'placeholder:text-muted-foreground',
'hover:border-border/80',
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
'disabled:cursor-not-allowed disabled:opacity-50',
'aria-invalid:border-destructive aria-invalid:ring-destructive/20',
className,
)}
{...props}
/>
),
);
Input.displayName = 'Input';
export { Input };
+17
View File
@@ -0,0 +1,17 @@
import * as React from 'react';
import { cn } from '../lib/cn';
/** Small inline keyboard-key label, e.g. `<Kbd>⌘K</Kbd>`. */
export const Kbd = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElement>>(
({ className, ...props }, ref) => (
<kbd
ref={ref}
className={cn(
'inline-flex h-5 min-w-[1.25rem] items-center justify-center rounded border border-border bg-muted px-1 font-mono text-[10px] font-medium text-muted-foreground',
className,
)}
{...props}
/>
),
);
Kbd.displayName = 'Kbd';
+17
View File
@@ -0,0 +1,17 @@
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cn } from '../lib/cn';
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn('text-xs font-medium leading-none text-muted-foreground select-none', className)}
{...props}
/>
));
Label.displayName = 'Label';
export { Label };
+31
View File
@@ -0,0 +1,31 @@
import * as React from 'react';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { cn } from '../lib/cn';
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = 'center', sideOffset = 6, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-xl ring-1 ring-foreground/5 outline-none',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = 'PopoverContent';
export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent };
+54
View File
@@ -0,0 +1,54 @@
import * as React from 'react';
import { cn } from '../lib/cn';
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
value?: number;
indicatorClassName?: string;
/**
* When true, the bar shows an animated marquee instead of a fixed
* width — useful when we know a job is running but don't yet know
* the total size (e.g. a download whose Content-Length is unknown).
*/
indeterminate?: boolean;
}
const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
({ className, value = 0, indicatorClassName, indeterminate = false, ...props }, ref) => {
const clamped = Math.max(0, Math.min(100, value));
return (
<div
ref={ref}
role="progressbar"
aria-valuenow={indeterminate ? undefined : clamped}
aria-valuemin={0}
aria-valuemax={100}
className={cn(
'relative h-2 w-full overflow-hidden rounded-full bg-muted',
className,
)}
{...props}
>
{indeterminate ? (
<div
className={cn(
'absolute inset-y-0 left-0 w-1/3 rounded-full bg-primary',
'animate-[progress-marquee_1.4s_ease-in-out_infinite]',
indicatorClassName,
)}
/>
) : (
<div
className={cn(
'h-full rounded-full bg-primary transition-[width] duration-200 ease-out',
indicatorClassName,
)}
style={{ width: `${clamped}%` }}
/>
)}
</div>
);
},
);
Progress.displayName = 'Progress';
export { Progress };
@@ -0,0 +1,50 @@
import * as React from 'react';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import { cn } from '../lib/cn';
interface ScrollAreaProps extends React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> {
viewportClassName?: string;
}
const ScrollArea = React.forwardRef<React.ElementRef<typeof ScrollAreaPrimitive.Root>, ScrollAreaProps>(
({ className, children, viewportClassName, type = 'hover', ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
type={type}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
className={cn('size-full rounded-[inherit] [&>div]:!block', viewportClassName)}
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollBar orientation="horizontal" />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
),
);
ScrollArea.displayName = 'ScrollArea';
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = 'vertical', ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
'flex touch-none select-none p-0.5 transition-colors',
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
orientation === 'horizontal' && 'h-2.5 w-full flex-col border-t border-t-transparent',
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border transition-colors hover:bg-muted-foreground/50" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = 'ScrollBar';
export { ScrollArea, ScrollBar };
+158
View File
@@ -0,0 +1,158 @@
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '../lib/cn';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'group flex h-9 w-full min-w-0 items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-1 text-sm shadow-xs outline-none transition-[color,box-shadow,background-color,border-color]',
'hover:border-border/80 hover:bg-card/70',
'placeholder:text-muted-foreground',
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
'data-[state=open]:border-ring data-[state=open]:ring-[3px] data-[state=open]:ring-ring/40',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[placeholder]:text-muted-foreground',
// Selected text mustn't push the chevron out of the trigger.
'[&>span:not([data-radix-select-icon])]:flex-1 [&>span:not([data-radix-select-icon])]:min-w-0 [&>span:not([data-radix-select-icon])]:truncate [&>span:not([data-radix-select-icon])]:text-left',
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild data-radix-select-icon>
<ChevronDown className="size-4 shrink-0 opacity-60 transition-transform group-data-[state=open]:rotate-180" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = 'SelectTrigger';
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1 text-muted-foreground', className)}
{...props}
>
<ChevronUp className="size-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = 'SelectScrollUpButton';
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn('flex cursor-default items-center justify-center py-1 text-muted-foreground', className)}
{...props}
>
<ChevronDown className="size-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = 'SelectScrollDownButton';
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
position={position}
sideOffset={4}
className={cn(
// Solid popover surface — explicit bg + ring for visibility against any background.
'relative z-50 max-h-(--radix-select-content-available-height) min-w-(--radix-select-trigger-width) overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-xl ring-1 ring-foreground/5',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=top]:-translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1',
className,
)}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width)',
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = 'SelectContent';
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground', className)}
{...props}
/>
));
SelectLabel.displayName = 'SelectLabel';
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center gap-2 rounded-md py-1.5 pl-2 pr-8 text-sm outline-none transition-colors',
'focus:bg-accent focus:text-accent-foreground',
'data-[state=checked]:font-medium',
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center text-primary">
<SelectPrimitive.ItemIndicator>
<Check className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = 'SelectItem';
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator ref={ref} className={cn('-mx-1 my-1 h-px bg-border', className)} {...props} />
));
SelectSeparator.displayName = 'SelectSeparator';
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+23
View File
@@ -0,0 +1,23 @@
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '../lib/cn';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
className
)}
{...props}
/>
));
Separator.displayName = 'Separator';
export { Separator };
+66
View File
@@ -0,0 +1,66 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../lib/cn';
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
const SheetClose = DialogPrimitive.Close;
const SheetPortal = DialogPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
SheetOverlay.displayName = 'SheetOverlay';
const sheetVariants = cva(
'fixed z-50 gap-4 bg-card p-0 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 outline-none',
{
variants: {
side: {
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
left: 'inset-y-0 left-0 h-full w-3/4 max-w-xs border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
right: 'inset-y-0 right-0 h-full w-3/4 max-w-xs border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',
},
},
defaultVariants: { side: 'right' },
}
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
VariantProps<typeof sheetVariants> {
showClose?: boolean;
}
const SheetContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>, SheetContentProps>(
({ side = 'right', className, children, showClose = true, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<DialogPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
{showClose && (
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none cursor-pointer">
<X className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</SheetPortal>
)
);
SheetContent.displayName = 'SheetContent';
export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay };
+6
View File
@@ -0,0 +1,6 @@
import * as React from 'react';
import { cn } from '../lib/cn';
export function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn('animate-pulse rounded-md bg-muted', className)} {...props} />;
}
+49
View File
@@ -0,0 +1,49 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../lib/cn';
/**
* A semantic colored status dot — drop-in replacement for ad-hoc emoji
* (🟢 / 🟡 / 🔴) so we keep visual rhythm with the rest of the Lucide
* iconography. `pulse` adds a soft halo for the "active" state.
*/
const dotVariants = cva('inline-block shrink-0 rounded-full', {
variants: {
tone: {
success: 'bg-success',
warning: 'bg-warning',
destructive: 'bg-destructive',
info: 'bg-info',
muted: 'bg-muted-foreground/50',
primary: 'bg-primary',
},
size: {
xs: 'size-1.5',
sm: 'size-2',
md: 'size-2.5',
lg: 'size-3',
},
},
defaultVariants: { tone: 'muted', size: 'sm' },
});
export interface StatusDotProps
extends React.HTMLAttributes<HTMLSpanElement>,
VariantProps<typeof dotVariants> {
pulse?: boolean;
}
export function StatusDot({ className, tone, size, pulse, ...props }: StatusDotProps) {
return (
<span
className={cn(
'relative inline-flex items-center justify-center',
pulse && 'before:absolute before:inset-0 before:rounded-full before:bg-current before:opacity-30 before:animate-ping',
className,
)}
{...props}
>
<span className={cn(dotVariants({ tone, size }), 'relative')} aria-hidden />
</span>
);
}
+35
View File
@@ -0,0 +1,35 @@
import * as React from 'react';
import * as SwitchPrimitive from '@radix-ui/react-switch';
import { cn } from '../lib/cn';
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitive.Root
ref={ref}
className={cn(
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-border shadow-inner transition-colors',
'focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
'disabled:cursor-not-allowed disabled:opacity-50',
// Checked: filled with primary
'data-[state=checked]:bg-primary data-[state=checked]:border-primary',
// Unchecked: visible track that contrasts with both surface modes
'data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-muted-foreground/25',
className,
)}
{...props}
>
<SwitchPrimitive.Thumb
className={cn(
'pointer-events-none block size-4 rounded-full shadow-md ring-0 transition-transform',
// Thumb always uses card surface so it pops against the track in both states.
'bg-card dark:bg-foreground/95',
'data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
)}
/>
</SwitchPrimitive.Root>
));
Switch.displayName = 'Switch';
export { Switch };
+52
View File
@@ -0,0 +1,52 @@
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '../lib/cn';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-9 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
className
)}
{...props}
/>
));
TabsList.displayName = 'TabsList';
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1 text-sm font-medium transition-all',
'focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40',
'disabled:pointer-events-none disabled:opacity-50',
'data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm',
className
)}
{...props}
/>
));
TabsTrigger.displayName = 'TabsTrigger';
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn('mt-2 outline-none', className)}
{...props}
/>
));
TabsContent.displayName = 'TabsContent';
export { Tabs, TabsList, TabsTrigger, TabsContent };
+29
View File
@@ -0,0 +1,29 @@
import { Toaster as Sonner, toast, type ToasterProps } from 'sonner';
/**
* SnowLuma-themed toaster. Uses the Tailwind `--*-foreground / --background`
* tokens defined in `@snowluma/ui/styles/theme.css` so toasts match the
* surrounding chrome in both light and dark mode.
*/
export function Toaster(props: ToasterProps) {
return (
<Sonner
position="bottom-right"
richColors
closeButton
theme="system"
toastOptions={{
classNames: {
toast: 'group toast group-[.toaster]:bg-card group-[.toaster]:text-card-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg',
description: 'group-[.toast]:text-muted-foreground',
actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
},
}}
{...props}
/>
);
}
export { toast };
export type { ToasterProps };
+29
View File
@@ -0,0 +1,29 @@
import * as React from 'react';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { cn } from '../lib/cn';
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 6, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 max-w-xs overflow-hidden rounded-md border border-border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-lg ring-1 ring-foreground/5',
'data-[state=delayed-open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=delayed-open]:fade-in-0',
'data-[state=delayed-open]:zoom-in-95 data-[state=closed]:zoom-out-95',
className,
)}
{...props}
/>
</TooltipPrimitive.Portal>
));
TooltipContent.displayName = 'TooltipContent';
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
+72
View File
@@ -0,0 +1,72 @@
export { cn } from './lib/cn';
export { Button, buttonVariants, type ButtonProps } from './components/button';
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
} from './components/alert-dialog';
export { Avatar, AvatarImage, AvatarFallback } from './components/avatar';
export { Badge, badgeVariants, type BadgeProps } from './components/badge';
export {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from './components/card';
export { Checkbox } from './components/checkbox';
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
} from './components/dialog';
export { Input } from './components/input';
export { Label } from './components/label';
export { Progress } from './components/progress';
export { ScrollArea, ScrollBar } from './components/scroll-area';
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
} from './components/select';
export { Separator } from './components/separator';
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetPortal,
SheetOverlay,
} from './components/sheet';
export { Skeleton } from './components/skeleton';
export { Switch } from './components/switch';
export { Tabs, TabsList, TabsTrigger, TabsContent } from './components/tabs';
export { Toaster, toast, type ToasterProps } from './components/toaster';
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from './components/tooltip';
export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent } from './components/popover';
export { Kbd } from './components/kbd';
export { StatusDot, type StatusDotProps } from './components/status-dot';
export { EmptyState } from './components/empty-state';
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
+259
View File
@@ -0,0 +1,259 @@
/**
* @snowluma/ui — Tailwind 4 theme tokens.
*
* Consumer setup:
* @import "tailwindcss";
* @import "tw-animate-css";
* @import "@snowluma/ui/styles/theme.css";
* @source "../node_modules/@snowluma/ui/dist/**\/*.js";
*/
@custom-variant dark (&:where(.dark, .dark *));
:root {
/* Surface ramp — light mode: near-white surfaces over a faint blue base. */
--radius: 0.625rem;
--background: oklch(99% 0.004 240);
--foreground: oklch(20% 0.03 250);
--card: oklch(100% 0 0);
--card-foreground: oklch(20% 0.03 250);
--popover: oklch(100% 0 0);
--popover-foreground: oklch(20% 0.03 250);
/* sky accent ramp */
--primary: oklch(64% 0.16 230);
--primary-foreground: oklch(99% 0.005 240);
--secondary: oklch(96.5% 0.012 240);
--secondary-foreground: oklch(22% 0.03 250);
--muted: oklch(96.5% 0.012 240);
--muted-foreground: oklch(48% 0.02 250);
--accent: oklch(94% 0.04 230);
--accent-foreground: oklch(28% 0.08 230);
--destructive: oklch(58% 0.22 27);
--destructive-foreground: oklch(99% 0.005 240);
--success: oklch(64% 0.16 155);
--success-foreground: oklch(99% 0.005 240);
--warning: oklch(76% 0.16 75);
--warning-foreground: oklch(20% 0.05 75);
--info: oklch(64% 0.16 230);
--info-foreground: oklch(99% 0.005 240);
--border: oklch(91% 0.012 240);
--input: oklch(94% 0.012 240);
--ring: oklch(64% 0.16 230);
--sidebar: oklch(98% 0.006 240);
--sidebar-foreground: oklch(25% 0.03 250);
--sidebar-primary: oklch(64% 0.16 230);
--sidebar-primary-foreground: oklch(99% 0.005 240);
--sidebar-accent: oklch(94% 0.03 230);
--sidebar-accent-foreground: oklch(28% 0.08 230);
--sidebar-border: oklch(91% 0.012 240);
--sidebar-ring: oklch(64% 0.16 230);
--chrome-height: 3.25rem; /* 52px — uniform top-bar height */
--titlebar-height: 2rem; /* 32px — Windows native titlebar height */
--shadow-color: 240 6% 10%;
--shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.05);
--shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.08), 0 1px 2px -1px hsl(var(--shadow-color) / 0.06);
--shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.08), 0 2px 4px -2px hsl(var(--shadow-color) / 0.04);
--shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.10), 0 4px 6px -4px hsl(var(--shadow-color) / 0.05);
--shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.14);
}
.dark {
--background: oklch(13% 0.02 250);
--foreground: oklch(96% 0.012 240);
--card: oklch(17% 0.022 250);
--card-foreground: oklch(96% 0.012 240);
--popover: oklch(20% 0.025 250);
--popover-foreground: oklch(96% 0.012 240);
--primary: oklch(72% 0.16 230);
--primary-foreground: oklch(12% 0.025 250);
--secondary: oklch(22% 0.025 250);
--secondary-foreground: oklch(94% 0.012 240);
--muted: oklch(20% 0.022 250);
--muted-foreground: oklch(72% 0.02 240);
--accent: oklch(30% 0.06 230);
--accent-foreground: oklch(88% 0.12 230);
--destructive: oklch(66% 0.22 27);
--destructive-foreground: oklch(98% 0.005 240);
--success: oklch(70% 0.16 155);
--success-foreground: oklch(12% 0.025 250);
--warning: oklch(80% 0.16 75);
--warning-foreground: oklch(20% 0.05 75);
--info: oklch(72% 0.16 230);
--info-foreground: oklch(12% 0.025 250);
--border: oklch(28% 0.025 250);
--input: oklch(26% 0.025 250);
--ring: oklch(72% 0.16 230);
--sidebar: oklch(15% 0.022 250);
--sidebar-foreground: oklch(92% 0.012 240);
--sidebar-primary: oklch(72% 0.16 230);
--sidebar-primary-foreground: oklch(12% 0.025 250);
--sidebar-accent: oklch(28% 0.06 230);
--sidebar-accent-foreground: oklch(88% 0.12 230);
--sidebar-border: oklch(24% 0.025 250);
--sidebar-ring: oklch(72% 0.16 230);
--shadow-color: 240 14% 4%;
--shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.30);
--shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.36), 0 1px 2px -1px hsl(var(--shadow-color) / 0.28);
--shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.40), 0 2px 4px -2px hsl(var(--shadow-color) / 0.28);
--shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.50), 0 4px 6px -4px hsl(var(--shadow-color) / 0.32);
--shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.55);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-success: var(--success);
--color-success-foreground: var(--success-foreground);
--color-warning: var(--warning);
--color-warning-foreground: var(--warning-foreground);
--color-info: var(--info);
--color-info-foreground: var(--info-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-xs: calc(var(--radius) - 6px);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 16px);
--shadow-xs: var(--shadow-xs);
--shadow-sm: var(--shadow-sm);
--shadow-md: var(--shadow-md);
--shadow-lg: var(--shadow-lg);
--shadow-xl: var(--shadow-xl);
--font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
}
@layer base {
* {
border-color: var(--border);
}
html, body, #root {
height: 100%;
}
body {
margin: 0;
background-color: var(--background);
color: var(--foreground);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
line-height: 1.5;
overflow: hidden; /* desktop chrome: no body scroll, panels manage their own */
}
::selection {
background-color: color-mix(in oklab, var(--primary) 28%, transparent);
color: var(--foreground);
}
*::-webkit-scrollbar {
width: 10px;
height: 10px;
}
*::-webkit-scrollbar-track {
background: transparent;
}
*::-webkit-scrollbar-thumb {
background-color: color-mix(in oklab, var(--muted-foreground) 35%, transparent);
border-radius: 9999px;
border: 2px solid transparent;
background-clip: content-box;
}
*::-webkit-scrollbar-thumb:hover {
background-color: color-mix(in oklab, var(--muted-foreground) 55%, transparent);
background-clip: content-box;
}
html[data-density="compact"] body {
font-size: 13.5px;
line-height: 1.45;
}
}
@layer utilities {
.hover-lift {
transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1),
box-shadow 220ms cubic-bezier(0.22, 1, 0.36, 1);
}
.hover-lift:hover {
transform: translateY(-1px);
box-shadow: var(--shadow-md);
}
.surface-gloss {
background-image: linear-gradient(
180deg,
color-mix(in oklab, var(--foreground) 3%, transparent) 0%,
transparent 80%
);
}
.surface-glass {
background-color: color-mix(in oklab, var(--popover) 92%, transparent);
backdrop-filter: saturate(180%) blur(12px);
-webkit-backdrop-filter: saturate(180%) blur(12px);
}
}
@keyframes progress-marquee {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(400%);
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"jsx": "react-jsx",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["react", "react-dom"],
"ignoreDeprecations": "6.0"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm'],
dts: true,
sourcemap: true,
clean: true,
external: ['react', 'react-dom'],
target: 'es2022',
treeshake: true,
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@snowluma/websocket",
"version": "1.8.1",
"version": "1.8.2",
"private": true,
"type": "module",
"main": "./src/index.ts",
+2 -1
View File
@@ -1,7 +1,7 @@
{
"name": "webui",
"private": true,
"version": "1.8.1",
"version": "1.8.2",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,6 +18,7 @@
"@radix-ui/react-separator": "^1.1.3",
"@radix-ui/react-slot": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.9",
"@tanstack/react-router": "^1.169.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.469.0",
+80 -393
View File
@@ -1,421 +1,108 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { RouterProvider } from '@tanstack/react-router';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ThemeProvider, useTheme } from '@/contexts/ThemeContext';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { SessionProvider } from '@/contexts/SessionContext';
import { LoginPage } from '@/components/pages/login-page';
import { MainLayout } from '@/components/layout/main-layout';
import { OverviewPage } from '@/components/pages/overview-page';
import { ConfigPage } from '@/components/pages/config-page';
import { LogsPage } from '@/components/pages/logs-page';
import { SettingsPage } from '@/components/pages/settings-page';
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
const TOKEN_KEY = 'snowluma_token';
function readToken() {
return localStorage.getItem(TOKEN_KEY) || '';
}
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { ApiProvider, createApiClient, useApi, type ApiClient } from '@/lib/api';
import { appRouter } from '@/router';
export default function App() {
return (
<ThemeProvider>
<AppInner />
<AuthBoundary />
</ThemeProvider>
);
}
function AppInner() {
const { pollInterval } = useTheme();
function AuthBoundary() {
const [authChecked, setAuthChecked] = useState(false);
const [authed, setAuthed] = useState(false);
const [mustChange, setMustChange] = useState(false);
const [status, setStatus] = useState('未连接');
const [active, setActive] = useState<Page>('overview');
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [processLoadingPid, setProcessLoadingPid] = useState<number | null>(null);
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
const [processActionStatus, setProcessActionStatus] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
// collapse spam-clicks instead of firing a second concurrent request.
const inflightProcessOps = useRef(new Set<number>());
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const [config, setConfig] = useState<OneBotConfig | null>(null);
const [saveStatus, setSaveStatus] = useState('');
const tokenRef = useRef(readToken());
// ---------- API helpers ----------
const fetchApi = useCallback(async (url: string, options: RequestInit = {}) => {
const headers: Record<string, string> = {
...(options.headers as Record<string, string> | undefined),
};
if (tokenRef.current) headers['Authorization'] = `Bearer ${tokenRef.current}`;
if (options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...options, headers });
if (res.status === 401) {
tokenRef.current = '';
localStorage.removeItem(TOKEN_KEY);
setAuthed(false);
setStatus('未授权');
}
return res;
}, []);
// ---------- Polling ----------
const refreshQqList = useCallback(async () => {
try {
const res = await fetchApi('/api/qq-list');
if (!res.ok) return;
const data = await res.json();
setQqList(data.list || []);
} catch (e) {
console.error('qq-list', e);
}
}, [fetchApi]);
const refreshProcesses = useCallback(async () => {
try {
const res = await fetchApi('/api/processes');
if (!res.ok) return;
const data = await res.json();
setProcessList(data.list || []);
} catch (e) {
console.error('processes', e);
}
}, [fetchApi]);
const refreshSystem = useCallback(async () => {
try {
const res = await fetchApi('/api/system');
if (!res.ok) return;
const data = (await res.json()) as SystemInfo;
setSystemInfo(data);
} catch (e) {
console.error('system', e);
}
}, [fetchApi]);
const checkStatus = useCallback(async () => {
try {
const res = await fetchApi('/api/status');
if (res.ok) {
setAuthed(true);
setStatus('已连接');
return true;
}
setStatus('未连接');
return false;
} catch {
setStatus('未连接');
return false;
}
}, [fetchApi]);
const client = useMemo<ApiClient>(
() =>
createApiClient({
onUnauthorized: () => {
setAuthed(false);
setStatus('未授权');
},
}),
[],
);
useEffect(() => {
(async () => {
if (tokenRef.current) {
const ok = await checkStatus();
if (ok) {
// Existing session may still need to change password.
try {
const r = await fetchApi('/api/auth/state');
if (r.ok) {
const d = await r.json();
setMustChange(!!d.mustChangePassword);
}
} catch { /* ignore */ }
}
const ok = await client.status();
if (ok) {
setAuthed(true);
setStatus('已连接');
setMustChange(await client.mustChangePassword());
}
setAuthChecked(true);
})();
}, [checkStatus, fetchApi]);
}, [client]);
useEffect(() => {
if (!authed || mustChange) return;
if (pollInterval <= 0) return;
let cancelled = false;
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
};
tick();
const interval = setInterval(tick, pollInterval);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [authed, mustChange, pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
// Auto-select first uin when navigating to config
useEffect(() => {
if (active !== 'config') return;
if (!selectedUin && qqList.length > 0) setSelectedUin(qqList[0].uin);
}, [active, qqList, selectedUin]);
// Load config when selectedUin changes
useEffect(() => {
if (!selectedUin) {
setConfig(null);
return;
}
let cancelled = false;
(async () => {
try {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
if (!res.ok) return;
const data = await res.json();
const loaded = data?.config ?? data;
if (cancelled) return;
const nets = loaded?.networks ?? {};
const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array';
const legacyReport = !!loaded?.reportSelfMessage;
const normalizeNetwork = <T extends Record<string, unknown>>(item: T) => ({
...item,
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
reportSelfMessage:
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
});
setConfig({
networks: {
httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [],
httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [],
wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [],
wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [],
},
musicSignUrl: loaded?.musicSignUrl,
});
} catch (e) {
console.error('load-config', e);
}
})();
return () => {
cancelled = true;
};
}, [selectedUin, fetchApi]);
// ---------- Actions ----------
const handleLogin = useCallback(async (password: string) => {
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { success: false, error: data.message || data.error || '令牌错误' };
}
const data = await res.json();
const token = data.token as string;
localStorage.setItem(TOKEN_KEY, token);
tokenRef.current = token;
setMustChange(!!data.mustChangePassword);
const ok = await checkStatus();
return ok ? { success: true } : { success: false, error: '校验失败' };
} catch (e) {
return { success: false, error: (e as Error).message || '网络错误' };
}
}, [checkStatus]);
const handleLogout = useCallback(async () => {
try { await fetchApi('/api/logout', { method: 'POST' }); } catch { /* ignore */ }
localStorage.removeItem(TOKEN_KEY);
tokenRef.current = '';
const handleLogoutComplete = useCallback(() => {
// Reset the URL so the next login lands on the overview page, matching
// the pre-router behaviour.
window.history.replaceState({}, '', '/');
setAuthed(false);
setMustChange(false);
setStatus('未连接');
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setSelectedUin(null);
setConfig(null);
}, [fetchApi]);
const handleLoadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessLoadingPid(pid);
setProcessActionStatus(`正在向进程 ${pid} 加载 SnowLuma…`);
try {
const res = await fetchApi(`/api/processes/${pid}/load`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '加载失败');
setProcessActionStatus(`已向进程 ${pid} 注入 SnowLuma,等待管道连接…`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`加载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessLoadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleUnloadProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessUnloadingPid(pid);
setProcessActionStatus(`正在从进程 ${pid} 卸载…`);
try {
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
// Check if unload actually failed (pipe still exists)
if (data.process?.status === 'connecting' && data.process?.error) {
setUnloadFailedAlert({ pid, error: data.process.error });
setProcessActionStatus(`进程 ${pid} 卸载失败`);
} else {
setProcessActionStatus(`已从进程 ${pid} 卸载`);
}
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessUnloadingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleRefreshProcess = useCallback(async (pid: number) => {
if (inflightProcessOps.current.has(pid)) return;
inflightProcessOps.current.add(pid);
setProcessRefreshingPid(pid);
setProcessActionStatus(`正在刷新进程 ${pid} 的管道状态…`);
try {
const res = await fetchApi(`/api/processes/${pid}/refresh`, { method: 'POST' });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.message || data.error || '刷新失败');
setProcessActionStatus(`已刷新进程 ${pid} 的管道状态`);
await refreshProcesses();
} catch (e) {
setProcessActionStatus(`刷新失败:${(e as Error).message}`);
} finally {
inflightProcessOps.current.delete(pid);
setProcessRefreshingPid(null);
setTimeout(() => setProcessActionStatus(''), 4000);
}
}, [fetchApi, refreshProcesses]);
const handleSaveConfig = useCallback(async () => {
if (!selectedUin || !config) return;
setSaveStatus('保存中...');
try {
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`, {
method: 'POST',
body: JSON.stringify(config),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || '保存失败');
setSaveStatus('保存成功');
} catch (e) {
setSaveStatus(`保存失败:${(e as Error).message}`);
} finally {
setTimeout(() => setSaveStatus(''), 3000);
}
}, [selectedUin, config, fetchApi]);
// ---------- Render ----------
if (!authChecked) {
return (
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
初始化中…
</div>
);
}
const checkStrength = async (password: string) => {
const res = await fetchApi('/api/auth/check-strength', {
method: 'POST',
body: JSON.stringify({ password }),
});
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
return { rules: data.rules ?? [], valid: !!data.valid };
};
const submitPwd = async (oldPassword: string, newPassword: string) => {
const res = await fetchApi('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ oldPassword, newPassword }),
});
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
return { success: !!data.success, message: data.message };
};
setMustChange(false);
}, []);
return (
<TooltipProvider delayDuration={150}>
{!authed ? (
<LoginPage onLogin={handleLogin} />
) : mustChange ? (
<ChangePasswordPage
forced
checkStrength={checkStrength}
submit={submitPwd}
onSuccess={() => setMustChange(false)}
/>
) : (
<MainLayout active={active} onNavigate={setActive} status={status} onLogout={handleLogout}>
{active === 'overview' && (
<OverviewPage
qqList={qqList}
status={status}
processList={processList}
processLoadingPid={processLoadingPid}
processUnloadingPid={processUnloadingPid}
processRefreshingPid={processRefreshingPid}
processActionStatus={processActionStatus}
systemInfo={systemInfo}
onRefreshProcesses={refreshProcesses}
onRefreshSystem={refreshSystem}
onLoadProcess={handleLoadProcess}
onUnloadProcess={handleUnloadProcess}
onRefreshProcess={handleRefreshProcess}
/>
)}
{active === 'config' && (
<ConfigPage
qqList={qqList}
selectedUin={selectedUin}
config={config}
saveStatus={saveStatus}
onSelectAccount={setSelectedUin}
onSave={handleSaveConfig}
onConfigChange={setConfig}
/>
)}
{active === 'logs' && <LogsPage fetchApi={fetchApi} />}
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
</MainLayout>
)}
<ConfirmDialog
open={!!unloadFailedAlert}
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
title="卸载失败"
description={
unloadFailedAlert ? (
<>
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
<p className="mt-2 text-sm text-muted-foreground">
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
</p>
</>
) : null
}
confirmText="知道了"
onConfirm={() => setUnloadFailedAlert(null)}
/>
</TooltipProvider>
<ApiProvider client={client}>
<TooltipProvider delayDuration={150}>
{!authChecked ? (
<div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted-foreground">
初始化中…
</div>
) : !authed ? (
<LoginGate
onAuthed={(needsChange) => {
setAuthed(true);
setStatus('已连接');
setMustChange(needsChange);
}}
/>
) : mustChange ? (
<ForcedChangePasswordGate onSuccess={() => setMustChange(false)} />
) : (
<SessionProvider value={{ status, onLogoutComplete: handleLogoutComplete }}>
<RouterProvider router={appRouter} />
</SessionProvider>
)}
</TooltipProvider>
</ApiProvider>
);
}
function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) {
const api = useApi();
const handleLogin = useCallback(
async (password: string) => {
const result = await api.login(password);
if (!result.ok) return { success: false, error: result.message };
onAuthed(result.mustChangePassword);
return { success: true };
},
[api, onAuthed],
);
return <LoginPage onLogin={handleLogin} />;
}
function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) {
const api = useApi();
return (
<ChangePasswordPage
forced
checkStrength={(p) => api.checkPasswordStrength(p)}
submit={(o, n) => api.changePassword(o, n)}
onSuccess={onSuccess}
/>
);
}
@@ -1,26 +1,26 @@
import { useEffect, useState, type ReactNode } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { useRouterState } from '@tanstack/react-router';
import { Sheet, SheetContent } from '@/components/ui/sheet';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Sidebar, type Page } from '@/components/layout/sidebar';
import { Sidebar } from '@/components/layout/sidebar';
import { TopBar } from '@/components/layout/top-bar';
import { useMediaQuery } from '@/hooks/use-media-query';
import { cn } from '@/lib/utils';
interface MainLayoutProps {
active: Page;
onNavigate: (page: Page) => void;
status: string;
onLogout: () => void;
children: ReactNode;
}
export function MainLayout({ active, onNavigate, status, onLogout, children }: MainLayoutProps) {
export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
const isMobile = !useMediaQuery('(min-width: 768px)');
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('snowluma_sidebar_collapsed') === '1';
});
const [mobileOpen, setMobileOpen] = useState(false);
const pathname = useRouterState({ select: (s) => s.location.pathname });
useEffect(() => {
localStorage.setItem('snowluma_sidebar_collapsed', collapsed ? '1' : '0');
@@ -36,7 +36,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
transition={{ type: 'spring', stiffness: 280, damping: 32 }}
className="relative h-full shrink-0 border-r overflow-hidden"
>
<Sidebar active={active} onNavigate={onNavigate} collapsed={collapsed} />
<Sidebar collapsed={collapsed} />
</motion.aside>
)}
@@ -44,11 +44,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
{isMobile && (
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetContent side="left" className="w-64 max-w-[80vw] p-0">
<Sidebar
active={active}
onNavigate={onNavigate}
onItemClick={() => setMobileOpen(false)}
/>
<Sidebar onItemClick={() => setMobileOpen(false)} />
</SheetContent>
</Sheet>
)}
@@ -56,7 +52,6 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
{/* Main column */}
<div className="flex min-w-0 flex-1 flex-col">
<TopBar
active={active}
status={status}
collapsed={collapsed}
onToggleCollapse={() => setCollapsed((v) => !v)}
@@ -70,7 +65,7 @@ export function MainLayout({ active, onNavigate, status, onLogout, children }: M
<div className="mx-auto w-full max-w-7xl px-4 py-5 sm:px-6 sm:py-6 lg:px-8">
<AnimatePresence mode="wait">
<motion.div
key={active}
key={pathname}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
@@ -1,27 +1,34 @@
import { LayoutDashboard, Settings, SlidersHorizontal, Terminal } from 'lucide-react';
import { motion } from 'motion/react';
import { Link, useRouterState } from '@tanstack/react-router';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';
import { APP_NAME, APP_VERSION } from '@/types';
import type { AppPath } from '@/router';
export type Page = 'overview' | 'config' | 'logs' | 'settings';
export interface NavItem {
to: AppPath;
label: string;
icon: typeof LayoutDashboard;
description: string;
}
export const NAV_ITEMS: { page: Page; label: string; icon: typeof LayoutDashboard; description: string }[] = [
{ page: 'overview', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
{ page: 'config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
{ page: 'logs', label: '日志', icon: Terminal, description: '实时事件流' },
{ page: 'settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
export const NAV_ITEMS: NavItem[] = [
{ to: '/', label: '总览', icon: LayoutDashboard, description: '主机与服务状态' },
{ to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
{ to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' },
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
];
interface SidebarProps {
active: Page;
onNavigate: (page: Page) => void;
collapsed?: boolean;
onItemClick?: () => void;
}
export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }: SidebarProps) {
export function Sidebar({ collapsed = false, onItemClick }: SidebarProps) {
const pathname = useRouterState({ select: (s) => s.location.pathname });
return (
<div className="flex h-full w-full flex-col bg-sidebar text-sidebar-foreground">
{/* Brand */}
@@ -43,23 +50,21 @@ export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }:
{/* Nav */}
<ScrollArea className="flex-1 min-h-0" viewportClassName="[&>div]:!block">
<nav className={cn('flex flex-col gap-1 p-2', collapsed && 'items-center')}>
{NAV_ITEMS.map(({ page, label, icon: Icon, description }) => {
const isActive = active === page;
{NAV_ITEMS.map(({ to, label, icon: Icon, description }) => {
const isActive = pathname === to;
return (
<button
key={page}
type="button"
<Link
key={to}
to={to}
title={collapsed ? label : undefined}
onClick={() => {
onNavigate(page);
onItemClick?.();
}}
onClick={onItemClick}
aria-current={isActive ? 'page' : undefined}
className={cn(
'group relative flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors cursor-pointer outline-none',
collapsed && 'w-10 justify-center px-0',
isActive
? 'text-sidebar-accent-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground'
: 'text-muted-foreground hover:bg-sidebar-accent/40 hover:text-foreground',
)}
>
{isActive && (
@@ -76,7 +81,7 @@ export function Sidebar({ active, onNavigate, collapsed = false, onItemClick }:
<span className="text-[10px] font-normal text-muted-foreground truncate">{description}</span>
</span>
)}
</button>
</Link>
);
})}
</nav>
@@ -1,15 +1,14 @@
import { useState } from 'react';
import { LogOut, Menu, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { useRouterState } from '@tanstack/react-router';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ThemeToggle } from '@/components/theme-toggle';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { Page } from '@/components/layout/sidebar';
import { NAV_ITEMS } from '@/components/layout/sidebar';
interface TopBarProps {
active: Page;
status: string;
collapsed: boolean;
onToggleCollapse: () => void;
@@ -19,7 +18,6 @@ interface TopBarProps {
}
export function TopBar({
active,
status,
collapsed,
onToggleCollapse,
@@ -28,7 +26,8 @@ export function TopBar({
isMobile,
}: TopBarProps) {
const [confirmLogout, setConfirmLogout] = useState(false);
const meta = NAV_ITEMS.find((n) => n.page === active);
const pathname = useRouterState({ select: (s) => s.location.pathname });
const meta = NAV_ITEMS.find((n) => n.to === pathname);
const PageIcon = meta?.icon;
const online = status === '已连接';
@@ -56,7 +55,7 @@ export function TopBar({
{/* Page title */}
<AnimatePresence mode="wait">
<motion.div
key={active}
key={pathname}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 8 }}
@@ -16,19 +16,10 @@ import type {
NetworkKind,
OneBotConfig,
OneBotNetworks,
QQInfo,
WsRole,
} from '@/types';
interface ConfigPageProps {
qqList: QQInfo[];
selectedUin: string | null;
config: OneBotConfig | null;
saveStatus: string;
onSelectAccount: (uin: string) => void;
onSave: () => Promise<void> | void;
onConfigChange: (config: OneBotConfig) => void;
}
import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config';
import { useAppState } from '@/contexts/AppStateContext';
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
@@ -98,18 +89,28 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
);
}
export function ConfigPage({
qqList,
selectedUin,
config,
saveStatus,
onSelectAccount,
onSave,
onConfigChange,
}: ConfigPageProps) {
export function ConfigPage() {
const { qqList, selectedUin, setSelectedUin } = useAppState();
const {
config,
setConfig,
dirty,
requestSwitchUin,
pendingSwitchUin,
confirmSwitch,
cancelSwitch,
save,
saveStatus,
} = useOneBotInstanceConfig(qqList, {
selectedUin,
onSelectedUinChange: setSelectedUin,
});
const [confirmSave, setConfirmSave] = useState(false);
const update = (next: OneBotConfig) => onConfigChange(next);
const update = (next: OneBotConfig) => setConfig(next);
const pendingSwitchAccount = pendingSwitchUin
? qqList.find((q) => q.uin === pendingSwitchUin) ?? null
: null;
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_minmax(0,1fr)]">
@@ -132,7 +133,7 @@ export function ConfigPage({
type="button"
whileHover={{ scale: 1.01 }}
whileTap={{ scale: 0.98 }}
onClick={() => onSelectAccount(q.uin)}
onClick={() => requestSwitchUin(q.uin)}
className={cn(
'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer',
isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40'
@@ -193,7 +194,12 @@ export function ConfigPage({
{saveStatus}
</span>
)}
<Button onClick={() => setConfirmSave(true)} size="sm">
{dirty && !saveStatus && (
<span className="rounded-full border border-warning/30 bg-warning/10 px-2.5 py-1 text-[11px] font-medium text-warning">
未保存
</span>
)}
<Button onClick={() => setConfirmSave(true)} size="sm" disabled={!dirty}>
<Save className="size-3.5" /> 保存设定
</Button>
</div>
@@ -421,7 +427,27 @@ export function ConfigPage({
title="保存配置变更?"
description={`即将把当前修改保存到 UIN ${selectedUin ?? ''} 的配置文件,并尝试热重载该会话。`}
confirmText="保存"
onConfirm={onSave}
onConfirm={save}
/>
<ConfirmDialog
open={pendingSwitchUin != null}
onOpenChange={(open) => !open && cancelSwitch()}
title="放弃未保存的修改?"
description={
<>
<p>
当前会话 <code className="font-mono">{selectedUin}</code> 还有未保存的修改。
</p>
<p className="mt-2">
切换到 <code className="font-mono">{pendingSwitchAccount?.uin ?? pendingSwitchUin}</code>
{pendingSwitchAccount?.nickname ? `(${pendingSwitchAccount.nickname})` : ''} 会丢弃这些修改。
</p>
</>
}
confirmText="放弃并切换"
destructive
onConfirm={confirmSwitch}
/>
</div>
);
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { motion } from 'motion/react';
import { Pause, Play, RefreshCw, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -9,10 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn } from '@/lib/utils';
import type { LogEntry } from '@/types';
interface LogsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
}
import { useApi } from '@/lib/api';
const levelClass: Record<LogEntry['level'], string> = {
debug: 'text-muted-foreground',
@@ -24,7 +21,8 @@ const levelClass: Record<LogEntry['level'], string> = {
const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error'];
export function LogsPage({ fetchApi }: LogsPageProps) {
export function LogsPage() {
const api = useApi();
const [logs, setLogs] = useState<LogEntry[]>([]);
const [streamStatus, setStreamStatus] = useState('连接中');
const [paused, setPaused] = useState(false);
@@ -34,36 +32,30 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const token = useMemo(() => localStorage.getItem('snowluma_token') || '', []);
async function loadLogs() {
const res = await fetchApi('/api/logs?limit=500');
if (!res.ok) return;
const data = await res.json();
setLogs(data.list || []);
}
const loadLogs = useCallback(async () => {
try {
setLogs(await api.logs.list(500));
} catch (e) {
console.error('logs', e);
}
}, [api]);
useEffect(() => {
loadLogs().catch(console.error);
}, []);
void loadLogs();
}, [loadLogs]);
useEffect(() => {
if (!token) return;
const url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
const source = new EventSource(url);
source.onopen = () => setStreamStatus('实时');
source.onerror = () => setStreamStatus('重连中');
source.onmessage = (event) => {
try {
const entry = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in entry) return;
return api.logs.stream({
onLine: (entry) => {
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-1000));
} catch {
// ignore
}
};
return () => source.close();
}, [token]);
},
onStatus: (s) => {
if (s === 'open') setStreamStatus('实时');
else if (s === 'reconnecting') setStreamStatus('重连中');
else setStreamStatus('已断开');
},
});
}, [api]);
useEffect(() => {
if (paused) return;
@@ -115,7 +107,7 @@ export function LogsPage({ fetchApi }: LogsPageProps) {
{paused ? <Play className="size-3.5" /> : <Pause className="size-3.5" />}
{paused ? '继续' : '暂停'}
</Button>
<Button variant="outline" size="sm" onClick={() => loadLogs().catch(console.error)}>
<Button variant="outline" size="sm" onClick={() => void loadLogs()}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
<Button
@@ -22,23 +22,9 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { cn, formatBytes, formatUptime } from '@/lib/utils';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
interface OverviewPageProps {
qqList: QQInfo[];
status: string;
processList: HookProcessInfo[];
processLoadingPid: number | null;
processUnloadingPid: number | null;
processRefreshingPid: number | null;
processActionStatus: string;
systemInfo: SystemInfo | null;
onRefreshProcesses: () => void;
onRefreshSystem: () => void;
onLoadProcess: (pid: number) => Promise<void> | void;
onUnloadProcess: (pid: number) => Promise<void> | void;
onRefreshProcess: (pid: number) => Promise<void> | void;
}
import type { HookProcessInfo } from '@/types';
import { useAppState } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
const processStatusLabel: Record<HookProcessInfo['status'], string> = {
available: '可加载',
@@ -96,21 +82,11 @@ function StatTile({
);
}
export function OverviewPage({
qqList,
status,
processList,
processLoadingPid,
processUnloadingPid,
processRefreshingPid,
processActionStatus,
systemInfo,
onRefreshProcesses,
onRefreshSystem,
onLoadProcess,
onUnloadProcess,
onRefreshProcess,
}: OverviewPageProps) {
export function OverviewPage() {
const { qqList, processList, systemInfo, processOps, refreshProcesses, refreshSystem } =
useAppState();
const { status } = useSession();
const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps;
const [confirm, setConfirm] = useState<
| { kind: 'load' | 'unload'; pid: number; name: string }
| null
@@ -167,7 +143,7 @@ export function OverviewPage({
: '正在采集主机信息…'}
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshSystem}>
<Button variant="outline" size="sm" onClick={refreshSystem}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
@@ -270,7 +246,7 @@ export function OverviewPage({
加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程
</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={onRefreshProcesses}>
<Button variant="outline" size="sm" onClick={refreshProcesses}>
<RefreshCw className="size-3.5" /> 刷新
</Button>
</CardHeader>
@@ -292,10 +268,11 @@ export function OverviewPage({
) : (
<div className="grid grid-cols-1 gap-3 xl:grid-cols-2">
{processList.map((proc, idx) => {
const loading = processLoadingPid === proc.pid || proc.status === 'loading';
const unloading = processUnloadingPid === proc.pid;
const refreshing = processRefreshingPid === proc.pid;
const busy = loading || unloading || refreshing;
const op = statusOf(proc.pid);
const loading = op === 'load' || proc.status === 'loading';
const unloading = op === 'unload';
const refreshing = op === 'refresh';
const busy = op != null || proc.status === 'loading';
const isOnline = proc.status === 'online';
const canUnload = proc.injected;
// Refresh is meaningful whenever a hook may exist (so the user
@@ -355,7 +332,7 @@ export function OverviewPage({
disabled={busy}
aria-label={`刷新进程 ${proc.pid} 管道状态`}
title="刷新管道状态 / 重连"
onClick={() => onRefreshProcess(proc.pid)}
onClick={() => refresh(proc.pid)}
className="size-8 text-muted-foreground hover:text-foreground"
>
{refreshing ? (
@@ -449,8 +426,8 @@ export function OverviewPage({
destructive={confirm?.kind === 'unload'}
onConfirm={async () => {
if (!confirm) return;
if (confirm.kind === 'unload') await onUnloadProcess(confirm.pid);
else await onLoadProcess(confirm.pid);
if (confirm.kind === 'unload') await unload(confirm.pid);
else await load(confirm.pid);
}}
/>
</div>
@@ -14,18 +14,11 @@ import {
type Density,
type ThemeMode,
} from '@/contexts/ThemeContext';
import {
ChangePasswordPage,
type PasswordRule,
} from '@/components/pages/change-password-page';
import { ChangePasswordPage } from '@/components/pages/change-password-page';
import { useApi } from '@/lib/api';
import { useAppState } from '@/contexts/AppStateContext';
import { cn } from '@/lib/utils';
interface SettingsPageProps {
fetchApi: (url: string, options?: RequestInit) => Promise<Response>;
/** Called after successful logout (e.g. all-sessions invalidated). */
onLogout: () => void;
}
const MODE_OPTIONS: { value: ThemeMode; label: string; icon: typeof Sun }[] = [
{ value: 'light', label: '浅色', icon: Sun },
{ value: 'dark', label: '深色', icon: Moon },
@@ -37,7 +30,9 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
];
export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
export function SettingsPage() {
const api = useApi();
const { onLogout } = useAppState();
const {
mode, setMode,
accent, setAccent,
@@ -49,30 +44,12 @@ export function SettingsPage({ fetchApi, onLogout }: SettingsPageProps) {
const [showChangePwd, setShowChangePwd] = useState(false);
const [pwdSavedAt, setPwdSavedAt] = useState<number | null>(null);
const checkStrength = async (password: string) => {
const res = await fetchApi('/api/auth/check-strength', {
method: 'POST',
body: JSON.stringify({ password }),
});
const data = (await res.json().catch(() => ({}))) as { rules?: PasswordRule[]; valid?: boolean };
return { rules: data.rules ?? [], valid: !!data.valid };
};
const submitPwd = async (oldPassword: string, newPassword: string) => {
const res = await fetchApi('/api/auth/change-password', {
method: 'POST',
body: JSON.stringify({ oldPassword, newPassword }),
});
const data = (await res.json().catch(() => ({}))) as { success?: boolean; message?: string };
return { success: !!data.success, message: data.message };
};
if (showChangePwd) {
return (
<ChangePasswordPage
forced={false}
checkStrength={checkStrength}
submit={submitPwd}
checkStrength={(p) => api.checkPasswordStrength(p)}
submit={(o, n) => api.changePassword(o, n)}
onSuccess={() => {
setShowChangePwd(false);
setPwdSavedAt(Date.now());
@@ -0,0 +1,40 @@
import { createContext, useContext, type ReactNode } from 'react';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
/**
* Live mutable state owned by AppLayout and shared with the child route
* components rendered inside its `<Outlet />`. Pages used to receive these
* via prop drilling — now they pull from context so adding a new page does
* not touch AppLayout.
*/
export interface AppStateValue {
qqList: QQInfo[];
processList: HookProcessInfo[];
systemInfo: SystemInfo | null;
selectedUin: string | null;
setSelectedUin: (uin: string | null) => void;
processOps: HookProcessOps;
refreshProcesses: () => void;
refreshSystem: () => void;
/** Triggered from the topbar logout button. */
onLogout: () => void;
}
const AppStateContext = createContext<AppStateValue | null>(null);
export function AppStateProvider({
value,
children,
}: {
value: AppStateValue;
children: ReactNode;
}) {
return <AppStateContext.Provider value={value}>{children}</AppStateContext.Provider>;
}
export function useAppState(): AppStateValue {
const v = useContext(AppStateContext);
if (!v) throw new Error('useAppState must be used inside <AppStateProvider>');
return v;
}
@@ -0,0 +1,30 @@
import { createContext, useContext, type ReactNode } from 'react';
/**
* Auth-level state surfaced into the router subtree. `AuthBoundary` mints
* this and `AppLayout` consumes it — used to drive the status badge and to
* complete logout after page-local state has been cleared.
*/
export interface SessionValue {
status: string;
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
onLogoutComplete: () => void;
}
const SessionContext = createContext<SessionValue | null>(null);
export function SessionProvider({
value,
children,
}: {
value: SessionValue;
children: ReactNode;
}) {
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}
export function useSession(): SessionValue {
const v = useContext(SessionContext);
if (!v) throw new Error('useSession must be used inside <SessionProvider>');
return v;
}
@@ -0,0 +1,156 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useApi, type ProcessActionResult } from '@/lib/api';
export type HookProcessOpKind = 'load' | 'unload' | 'refresh';
export interface HookProcessOps {
/** Returns the in-flight op kind for a pid, or null if idle. */
statusOf(pid: number): HookProcessOpKind | null;
/** Latest user-facing status; auto-clears a few seconds after the last update. */
banner: string;
load(pid: number): Promise<void>;
unload(pid: number): Promise<void>;
refresh(pid: number): Promise<void>;
}
export interface UnloadFailedAlert {
pid: number;
error: string;
}
export interface UseHookProcessOpsResult {
ops: HookProcessOps;
unloadFailedAlert: UnloadFailedAlert | null;
dismissUnloadFailedAlert: () => void;
}
interface KindMessages {
start(pid: number): string;
ok(pid: number): string;
fail(message: string): string;
}
const KIND_MESSAGES: Record<HookProcessOpKind, KindMessages> = {
load: {
start: (pid) => `正在向进程 ${pid} 加载 SnowLuma…`,
ok: (pid) => `已向进程 ${pid} 注入 SnowLuma,等待管道连接…`,
fail: (m) => `加载失败:${m}`,
},
unload: {
start: (pid) => `正在从进程 ${pid} 卸载…`,
ok: (pid) => `已从进程 ${pid} 卸载`,
fail: (m) => `卸载失败:${m}`,
},
refresh: {
start: (pid) => `正在刷新进程 ${pid} 的管道状态…`,
ok: (pid) => `已刷新进程 ${pid} 的管道状态`,
fail: (m) => `刷新失败:${m}`,
},
};
const BANNER_CLEAR_MS = 4000;
/**
* Drives load/unload/refresh actions on Hook-target processes. Owns the
* per-pid inflight dedup, the per-kind status indicator, the banner message
* lifecycle, and the "unload silently failed" alert that surfaces when the
* backend reports the named pipe is still alive after an unload attempt.
*/
export function useHookProcessOps(
opts: { onAfterOp?: () => Promise<void> | void } = {},
): UseHookProcessOpsResult {
const api = useApi();
const [byPid, setByPid] = useState<Map<number, HookProcessOpKind>>(() => new Map());
const [banner, setBanner] = useState('');
const [unloadFailedAlert, setUnloadFailedAlert] = useState<UnloadFailedAlert | null>(null);
// Synchronous inflight guard — protects against rapid double-clicks that
// would race the byPid setter (state updates are batched, refs are not).
const inflightRef = useRef<Set<number>>(new Set());
const bannerTimerRef = useRef<number | null>(null);
const onAfterOpRef = useRef(opts.onAfterOp);
onAfterOpRef.current = opts.onAfterOp;
useEffect(
() => () => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
},
[],
);
const scheduleBannerClear = useCallback(() => {
if (bannerTimerRef.current != null) window.clearTimeout(bannerTimerRef.current);
bannerTimerRef.current = window.setTimeout(() => {
setBanner('');
bannerTimerRef.current = null;
}, BANNER_CLEAR_MS);
}, []);
const setKind = useCallback((pid: number, kind: HookProcessOpKind | null) => {
setByPid((prev) => {
const next = new Map(prev);
if (kind == null) next.delete(pid);
else next.set(pid, kind);
return next;
});
}, []);
const run = useCallback(
async (
pid: number,
kind: HookProcessOpKind,
action: () => Promise<ProcessActionResult>,
) => {
if (inflightRef.current.has(pid)) return;
inflightRef.current.add(pid);
setKind(pid, kind);
const messages = KIND_MESSAGES[kind];
setBanner(messages.start(pid));
try {
const result = await action();
if (kind === 'unload' && result.process?.status === 'connecting' && result.process.error) {
setUnloadFailedAlert({ pid, error: result.process.error });
setBanner(`进程 ${pid} 卸载失败`);
} else {
setBanner(messages.ok(pid));
}
await onAfterOpRef.current?.();
} catch (e) {
const msg = e instanceof Error ? e.message : '未知错误';
setBanner(messages.fail(msg));
} finally {
inflightRef.current.delete(pid);
setKind(pid, null);
scheduleBannerClear();
}
},
[setKind, scheduleBannerClear],
);
const load = useCallback(
(pid: number) => run(pid, 'load', () => api.processes.load(pid)),
[api, run],
);
const unload = useCallback(
(pid: number) => run(pid, 'unload', () => api.processes.unload(pid)),
[api, run],
);
const refresh = useCallback(
(pid: number) => run(pid, 'refresh', () => api.processes.refresh(pid)),
[api, run],
);
const statusOf = useCallback(
(pid: number): HookProcessOpKind | null => byPid.get(pid) ?? null,
[byPid],
);
const dismissUnloadFailedAlert = useCallback(() => setUnloadFailedAlert(null), []);
const ops = useMemo<HookProcessOps>(
() => ({ statusOf, banner, load, unload, refresh }),
[statusOf, banner, load, unload, refresh],
);
return { ops, unloadFailedAlert, dismissUnloadFailedAlert };
}
@@ -0,0 +1,147 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { OneBotConfig, QQInfo } from '@/types';
import { useApi } from '@/lib/api';
/**
* Per-UIN OneBotInstance configuration editor. Owns the full lifecycle:
* selection, load, in-memory edit (with dirty tracking), save (with refetch),
* and a "switch UIN while dirty" guard that surfaces a pending switch the
* view can confirm or cancel.
*/
export interface UseOneBotInstanceConfig {
selectedUin: string | null;
/** Loaded config for the current UIN. Null while loading or before a selection. */
config: OneBotConfig | null;
setConfig: (next: OneBotConfig) => void;
/** True if the in-memory config diverges from the last server-confirmed snapshot. */
dirty: boolean;
/**
* Request a UIN switch. If currently dirty, the switch is parked as
* `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it
* applies immediately.
*/
requestSwitchUin: (uin: string) => void;
/** Non-null while a switch is parked waiting for confirmation. */
pendingSwitchUin: string | null;
confirmSwitch: () => void;
cancelSwitch: () => void;
save: () => Promise<void>;
saveStatus: string;
}
const CLEAR_SAVE_STATUS_MS = 3000;
export interface UseOneBotInstanceConfigOptions {
/** Externally-owned current UIN. The hook reads it but does not own it. */
selectedUin: string | null;
/** Called when the hook wants to mutate selection (auto-select / confirmed switch). */
onSelectedUinChange: (uin: string | null) => void;
}
export function useOneBotInstanceConfig(
accounts: QQInfo[],
options: UseOneBotInstanceConfigOptions,
): UseOneBotInstanceConfig {
const api = useApi();
const { selectedUin, onSelectedUinChange } = options;
const [config, setConfigState] = useState<OneBotConfig | null>(null);
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
const [saveStatus, setSaveStatus] = useState('');
const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null);
const clearTimerRef = useRef<number | null>(null);
// Auto-select first account when none is selected yet.
useEffect(() => {
if (!selectedUin && accounts.length > 0) onSelectedUinChange(accounts[0].uin);
}, [accounts, selectedUin, onSelectedUinChange]);
// Load on UIN change. The api client already runs normalizeOneBotConfig.
useEffect(() => {
if (!selectedUin) {
setConfigState(null);
setSavedSnapshot(null);
return;
}
let cancelled = false;
(async () => {
try {
const loaded = await api.config.get(selectedUin);
if (cancelled) return;
setConfigState(loaded);
setSavedSnapshot(JSON.stringify(loaded));
} catch (e) {
console.error('load-config', e);
}
})();
return () => {
cancelled = true;
};
}, [selectedUin, api]);
useEffect(
() => () => {
if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
},
[],
);
const dirty = useMemo(() => {
if (config == null || savedSnapshot == null) return false;
return JSON.stringify(config) !== savedSnapshot;
}, [config, savedSnapshot]);
const setConfig = useCallback((next: OneBotConfig) => setConfigState(next), []);
const requestSwitchUin = useCallback(
(uin: string) => {
if (uin === selectedUin) return;
if (dirty) setPendingSwitchUin(uin);
else onSelectedUinChange(uin);
},
[dirty, selectedUin, onSelectedUinChange],
);
const confirmSwitch = useCallback(() => {
if (pendingSwitchUin == null) return;
onSelectedUinChange(pendingSwitchUin);
setPendingSwitchUin(null);
}, [pendingSwitchUin, onSelectedUinChange]);
const cancelSwitch = useCallback(() => setPendingSwitchUin(null), []);
const scheduleStatusClear = useCallback(() => {
if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current);
clearTimerRef.current = window.setTimeout(() => {
setSaveStatus('');
clearTimerRef.current = null;
}, CLEAR_SAVE_STATUS_MS);
}, []);
const save = useCallback(async () => {
if (!selectedUin || !config) return;
setSaveStatus('保存中...');
try {
const serverView = await api.config.save(selectedUin, config);
setConfigState(serverView);
setSavedSnapshot(JSON.stringify(serverView));
setSaveStatus('保存成功');
} catch (e) {
setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`);
} finally {
scheduleStatusClear();
}
}, [api, selectedUin, config, scheduleStatusClear]);
return {
selectedUin,
config,
setConfig,
dirty,
requestSwitchUin,
pendingSwitchUin,
confirmSwitch,
cancelSwitch,
save,
saveStatus,
};
}
+250
View File
@@ -0,0 +1,250 @@
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
ApiError,
type ApiClient,
type ChangePasswordResult,
type CreateApiClientOptions,
type LoginResult,
type LogsStreamOptions,
type ProcessActionResult,
type TokenStore,
} from './types';
import { localStorageTokenStore } from './token-store';
const DEFAULT_TOKEN_KEY = 'snowluma_token';
interface ErrorPayload {
message?: string;
error?: string;
code?: string;
}
async function readJson<T>(res: Response): Promise<T> {
try {
return (await res.json()) as T;
} catch {
return {} as T;
}
}
function extractErrorMessage(payload: ErrorPayload, fallback: string): string {
return payload.message || payload.error || fallback;
}
class HttpApiClient implements ApiClient {
private tokenStore: TokenStore;
private currentToken: string | null;
private onUnauthorized?: () => void;
// namespaced surfaces are bound up-front so callers can destructure
readonly processes: ApiClient['processes'];
readonly config: ApiClient['config'];
readonly logs: ApiClient['logs'];
constructor(opts: CreateApiClientOptions = {}) {
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
this.currentToken = this.tokenStore.load();
this.onUnauthorized = opts.onUnauthorized;
this.processes = {
list: () => this.getJson<{ list: HookProcessInfo[] }>('/api/processes').then((d) => d.list ?? []),
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`),
};
this.config = {
get: async (uin) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const data = await this.getJson<{ config?: unknown } | unknown>(url);
const raw =
typeof data === 'object' && data != null && 'config' in (data as Record<string, unknown>)
? (data as { config: unknown }).config
: data;
return normalizeOneBotConfig(raw);
},
save: async (uin, config) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
// POST returns { success, reloaded, message } — no config body. To
// honour the "save returns canonical server view" contract, refetch
// after a successful POST.
await this.fetchJson<unknown>(url, {
method: 'POST',
body: JSON.stringify(config),
});
return this.config.get(uin);
},
};
this.logs = {
list: async (limit = 500) => {
const data = await this.getJson<{ list: LogEntry[] }>(`/api/logs?limit=${limit}`);
return data.list ?? [];
},
stream: (options) => this.openLogStream(options),
};
}
// ---------- HTTP helpers ----------
async request(url: string, init: RequestInit = {}): Promise<Response> {
const headers: Record<string, string> = {
...((init.headers as Record<string, string> | undefined) ?? {}),
};
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
const res = await fetch(url, { ...init, headers });
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
}
return res;
}
/** Like request(), but throws ApiError on non-2xx and parses JSON. */
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
const res = await this.request(url, init);
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
throw new ApiError(res.status, extractErrorMessage(payload, res.statusText || '请求失败'), payload.code);
}
return readJson<T>(res);
}
private getJson<T>(url: string): Promise<T> {
return this.fetchJson<T>(url);
}
private postJson<T>(url: string, body?: unknown): Promise<T> {
return this.fetchJson<T>(url, {
method: 'POST',
body: body == null ? undefined : JSON.stringify(body),
});
}
// ---------- token management ----------
private setToken(token: string | null): void {
this.currentToken = token;
this.tokenStore.save(token);
}
// ---------- auth ----------
async login(password: string): Promise<LoginResult> {
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
// doesn't trigger a global sign-out side effect.
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
});
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
return { ok: false, message: extractErrorMessage(payload, '令牌错误') };
}
const payload = await readJson<{ token: string; mustChangePassword?: boolean }>(res);
this.setToken(payload.token);
return { ok: true, mustChangePassword: !!payload.mustChangePassword };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
async logout(): Promise<void> {
try {
await this.request('/api/logout', { method: 'POST' });
} catch {
/* ignore */
}
this.setToken(null);
}
async status(): Promise<boolean> {
if (!this.currentToken) return false;
try {
const res = await this.request('/api/status');
return res.ok;
} catch {
return false;
}
}
async mustChangePassword(): Promise<boolean> {
try {
const data = await this.getJson<{ mustChangePassword?: boolean }>('/api/auth/state');
return !!data.mustChangePassword;
} catch {
return false;
}
}
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
try {
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
'/api/auth/check-strength',
{ password },
);
return { rules: data.rules ?? [], valid: !!data.valid };
} catch {
return { rules: [], valid: false };
}
}
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
try {
const data = await this.postJson<{ success?: boolean; message?: string }>(
'/api/auth/change-password',
{ oldPassword, newPassword },
);
return { success: !!data.success, message: data.message };
} catch (e) {
if (e instanceof ApiError) return { success: false, message: e.message };
return { success: false, message: e instanceof Error ? e.message : '网络错误' };
}
}
// ---------- top-level resources ----------
async qqList(): Promise<QQInfo[]> {
const data = await this.getJson<{ list: QQInfo[] }>('/api/qq-list');
return data.list ?? [];
}
system(): Promise<SystemInfo> {
return this.getJson<SystemInfo>('/api/system');
}
// ---------- SSE ----------
private openLogStream(options: LogsStreamOptions): () => void {
if (!this.currentToken) {
options.onStatus?.('closed');
return () => {};
}
const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`;
const source = new EventSource(url);
source.onopen = () => options.onStatus?.('open');
source.onerror = () => options.onStatus?.('reconnecting');
source.onmessage = (event) => {
try {
const parsed = JSON.parse(event.data) as LogEntry | { type: string };
if ('type' in parsed) return; // control frame, not a log line
options.onLine(parsed);
} catch {
/* malformed frame, skip */
}
};
return () => {
source.close();
options.onStatus?.('closed');
};
}
}
export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
return new HttpApiClient(options);
}
+14
View File
@@ -0,0 +1,14 @@
import { createContext, useContext, type ReactNode } from 'react';
import type { ApiClient } from './types';
const ApiContext = createContext<ApiClient | null>(null);
export function ApiProvider({ client, children }: { client: ApiClient; children: ReactNode }) {
return <ApiContext.Provider value={client}>{children}</ApiContext.Provider>;
}
export function useApi(): ApiClient {
const client = useContext(ApiContext);
if (!client) throw new Error('useApi must be used inside <ApiProvider>');
return client;
}
+13
View File
@@ -0,0 +1,13 @@
export { createApiClient } from './client';
export { ApiProvider, useApi } from './context';
export { ApiError } from './types';
export type {
ApiClient,
ChangePasswordResult,
CreateApiClientOptions,
LoginResult,
LogsStreamOptions,
ProcessActionResult,
StreamStatus,
TokenStore,
} from './types';
+11
View File
@@ -0,0 +1,11 @@
import type { TokenStore } from './types';
export function localStorageTokenStore(key: string): TokenStore {
return {
load: () => localStorage.getItem(key),
save: (token) => {
if (token == null) localStorage.removeItem(key);
else localStorage.setItem(key, token);
},
};
}
+88
View File
@@ -0,0 +1,88 @@
import type {
HookProcessInfo,
LogEntry,
OneBotConfig,
QQInfo,
SystemInfo,
} from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
export class ApiError extends Error {
status: number;
code: string | undefined;
constructor(status: number, message: string, code?: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}
export type LoginResult =
| { ok: true; mustChangePassword: boolean }
| { ok: false; message: string };
export type ChangePasswordResult = { success: boolean; message?: string };
export type ProcessActionResult = {
process?: HookProcessInfo & { error?: string };
};
export type StreamStatus = 'open' | 'reconnecting' | 'closed';
export interface LogsStreamOptions {
onLine: (line: LogEntry) => void;
onStatus?: (status: StreamStatus) => void;
}
export interface ApiClient {
// ---- auth ----
login(password: string): Promise<LoginResult>;
logout(): Promise<void>;
/** True if the current token is still valid. */
status(): Promise<boolean>;
/** Whether the current session must rotate its password before doing anything else. */
mustChangePassword(): Promise<boolean>;
checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }>;
changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult>;
// ---- system ----
qqList(): Promise<QQInfo[]>;
system(): Promise<SystemInfo>;
// ---- hook processes ----
processes: {
list(): Promise<HookProcessInfo[]>;
load(pid: number): Promise<ProcessActionResult>;
unload(pid: number): Promise<ProcessActionResult>;
refresh(pid: number): Promise<ProcessActionResult>;
};
// ---- OneBotInstance per-UIN config ----
config: {
get(uin: string): Promise<OneBotConfig>;
save(uin: string, config: OneBotConfig): Promise<OneBotConfig>;
};
// ---- logs ----
logs: {
list(limit?: number): Promise<LogEntry[]>;
/** Subscribe to the SSE log stream. Returns a disposer. */
stream(options: LogsStreamOptions): () => void;
};
/** Escape hatch for endpoints not yet wrapped above. */
request(url: string, init?: RequestInit): Promise<Response>;
}
export interface TokenStore {
load(): string | null;
save(token: string | null): void;
}
export interface CreateApiClientOptions {
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
tokenStore?: TokenStore;
/** Fires whenever a request returns 401, after the token has been cleared. */
onUnauthorized?: () => void;
}
+34
View File
@@ -0,0 +1,34 @@
import type { MessageFormat, OneBotConfig } from '@/types';
/**
* Anti-corruption layer for the per-UIN config payload. Older backends emit
* `messageFormat` / `reportSelfMessage` at the top level instead of per
* adapter, and may omit them on adapters entirely. This collapses both shapes
* into the canonical {@link OneBotConfig} the editor expects.
*/
export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
const cfg = (raw ?? {}) as Record<string, unknown>;
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
const legacyReport = !!cfg.reportSelfMessage;
const normalize = (item: Record<string, unknown>): Record<string, unknown> => ({
...item,
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
reportSelfMessage:
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
});
const list = (x: unknown): Record<string, unknown>[] =>
Array.isArray(x) ? x.map((it) => normalize(it as Record<string, unknown>)) : [];
return {
networks: {
httpServers: list(nets.httpServers) as unknown as OneBotConfig['networks']['httpServers'],
httpClients: list(nets.httpClients) as unknown as OneBotConfig['networks']['httpClients'],
wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'],
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
},
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
};
}
+118
View File
@@ -0,0 +1,118 @@
import { useCallback, useEffect, useState } from 'react';
import { Outlet } from '@tanstack/react-router';
import { useTheme } from '@/contexts/ThemeContext';
import { useApi } from '@/lib/api';
import { useHookProcessOps } from '@/hooks/use-hook-process-ops';
import { MainLayout } from '@/components/layout/main-layout';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { AppStateProvider } from '@/contexts/AppStateContext';
import { useSession } from '@/contexts/SessionContext';
import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types';
/**
* The layout route. Owns the live state shared across the four pages
* (polling lists, processOps, selectedUin) and renders `<Outlet />` inside
* the chrome. The unload-failed alert sits here so it survives navigation
* away from the overview page.
*/
export function AppLayout() {
const api = useApi();
const { pollInterval } = useTheme();
const session = useSession();
const [qqList, setQqList] = useState<QQInfo[]>([]);
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
const [selectedUin, setSelectedUin] = useState<string | null>(null);
const refreshQqList = useCallback(async () => {
try {
setQqList(await api.qqList());
} catch (e) {
console.error('qq-list', e);
}
}, [api]);
const refreshProcesses = useCallback(async () => {
try {
setProcessList(await api.processes.list());
} catch (e) {
console.error('processes', e);
}
}, [api]);
const refreshSystem = useCallback(async () => {
try {
setSystemInfo(await api.system());
} catch (e) {
console.error('system', e);
}
}, [api]);
const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({
onAfterOp: refreshProcesses,
});
useEffect(() => {
if (pollInterval <= 0) return;
let cancelled = false;
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]);
};
tick();
const interval = setInterval(tick, pollInterval);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]);
const handleLogout = useCallback(async () => {
await api.logout();
setQqList([]);
setProcessList([]);
setSystemInfo(null);
setSelectedUin(null);
session.onLogoutComplete();
}, [api, session]);
return (
<AppStateProvider
value={{
qqList,
processList,
systemInfo,
selectedUin,
setSelectedUin,
processOps,
refreshProcesses,
refreshSystem,
onLogout: handleLogout,
}}
>
<MainLayout status={session.status} onLogout={handleLogout}>
<Outlet />
</MainLayout>
<ConfirmDialog
open={!!unloadFailedAlert}
onOpenChange={(open) => !open && dismissUnloadFailedAlert()}
title="卸载失败"
description={
unloadFailedAlert ? (
<>
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
<p className="mt-2 text-sm text-muted-foreground">
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
</p>
</>
) : null
}
confirmText="知道了"
onConfirm={dismissUnloadFailedAlert}
/>
</AppStateProvider>
);
}
+63
View File
@@ -0,0 +1,63 @@
import {
createRootRoute,
createRoute,
createRouter,
Outlet,
} from '@tanstack/react-router';
import { OverviewPage } from '@/components/pages/overview-page';
import { ConfigPage } from '@/components/pages/config-page';
import { LogsPage } from '@/components/pages/logs-page';
import { SettingsPage } from '@/components/pages/settings-page';
import { AppLayout } from './app-layout';
const rootRoute = createRootRoute({
component: () => <Outlet />,
});
const appLayoutRoute = createRoute({
id: 'app-layout',
getParentRoute: () => rootRoute,
component: AppLayout,
});
const overviewRoute = createRoute({
path: '/',
getParentRoute: () => appLayoutRoute,
component: OverviewPage,
});
const configRoute = createRoute({
path: '/config',
getParentRoute: () => appLayoutRoute,
component: ConfigPage,
});
const logsRoute = createRoute({
path: '/logs',
getParentRoute: () => appLayoutRoute,
component: LogsPage,
});
const settingsRoute = createRoute({
path: '/settings',
getParentRoute: () => appLayoutRoute,
component: SettingsPage,
});
const routeTree = rootRoute.addChildren([
appLayoutRoute.addChildren([overviewRoute, configRoute, logsRoute, settingsRoute]),
]);
export const appRouter = createRouter({
routeTree,
defaultPreload: 'intent',
});
declare module '@tanstack/react-router' {
interface Register {
router: typeof appRouter;
}
}
/** Paths registered on the layout — single source of truth for nav metadata. */
export type AppPath = '/' | '/config' | '/logs' | '/settings';
+913 -7
View File
File diff suppressed because it is too large. Load diff