Merge pull request #309 from SnowLuma/dev

chore: promote dev → main (f572be2)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-08-03 11:35:41 +00:00
commit ebbe90be7e
126 files changed
+4141 -673

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.13.0",
"version": "1.14.0",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+1 -1
View File
@@ -160,7 +160,7 @@ export class HookManager {
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.enumerate,
listLivePipes: () => QqHookClient.listLivePipes(),
listLivePipes: processes => QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
+130
View File
@@ -0,0 +1,130 @@
import { readFileSync } from 'fs';
import os from 'os';
import path from 'path';
export interface HookRuntimeDirDeps {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
ownUid?: number;
readText?: (file: string) => string;
}
function configuredDirectory(value: string | undefined, variable: string): string | null {
if (!value) return null;
if (!path.isAbsolute(value)) {
throw new Error(`${variable} must be an absolute path`);
}
return value;
}
function parseProcessEnvironment(raw: string): NodeJS.ProcessEnv {
const result: NodeJS.ProcessEnv = {};
for (const entry of raw.split('\0')) {
if (!entry) continue;
const separator = entry.indexOf('=');
if (separator <= 0) continue;
result[entry.slice(0, separator)] = entry.slice(separator + 1);
}
return result;
}
function parseRealUid(status: string): number | null {
const match = /^Uid:\s+(\d+)/m.exec(status);
if (!match) return null;
const uid = Number(match[1]);
return Number.isSafeInteger(uid) && uid >= 0 ? uid : null;
}
function isProcessGoneError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT' || code === 'ESRCH';
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function ownRuntimeDir(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
ownUid: number,
): string {
const explicit = configuredDirectory(
env.SNOWLUMA_HOOK_RUNTIME_DIR,
'SNOWLUMA_HOOK_RUNTIME_DIR',
);
if (explicit) return explicit;
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
if (xdg) return xdg;
if (platform === 'darwin') {
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
}
return `/tmp/snowluma-${ownUid}`;
}
/**
* Resolve the socket directory for the target QQ process. The supervisor may
* run under a different user, so its own runtime directory is not authoritative.
*/
export function resolveHookRuntimeDir(
targetPid?: number,
deps: HookRuntimeDirDeps = {},
): string {
const platform = deps.platform ?? process.platform;
const env = deps.env ?? process.env;
const ownUid = deps.ownUid
?? (typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid);
const readText = deps.readText ?? ((file: string) => readFileSync(file, 'utf8'));
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
return ownRuntimeDir(platform, env, ownUid);
}
let environError: unknown;
try {
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
const explicit = configuredDirectory(
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
);
if (explicit) return explicit;
const xdg = configuredDirectory(
targetEnv.XDG_RUNTIME_DIR,
`QQ process ${targetPid} XDG_RUNTIME_DIR`,
);
if (xdg) return xdg;
environError = new Error('runtime directory is not present');
} catch (error) {
// An invalid explicit path is configuration corruption and must remain
// visible. Permission/race failures are expected when /proc disappears;
// the status-file fallback below can still recover the target uid.
if (error instanceof Error && error.message.includes('must be an absolute path')) {
throw error;
}
environError = error;
}
let statusError: unknown;
try {
const uid = parseRealUid(readText(`/proc/${targetPid}/status`));
if (uid !== null) return `/tmp/snowluma-${uid}`;
statusError = new Error('real uid is not available');
} catch (error) {
statusError = error;
}
if (isProcessGoneError(statusError)
&& (isProcessGoneError(environError)
|| (environError instanceof Error
&& environError.message === 'runtime directory is not present'))) {
return ownRuntimeDir(platform, env, ownUid);
}
throw new Error(
`cannot resolve hook runtime directory for PID ${targetPid}: `
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
);
}
+79 -25
View File
@@ -15,10 +15,12 @@ import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to actively re-probe QQ's login state while connected but not yet
* logged in — the safety net for a login the native hook never pushed (Docker
* auto-login races/bypasses the pushed loginState frame). */
/** How often to re-check account identity while the connection is not ready.
* Identity alone never proves that requests can be served. */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000;
const LOGIN_HINT_MAX_ATTEMPTS = 3;
const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const;
/** QQ emits this response periodically while its MSF receive path is healthy.
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
@@ -99,6 +101,11 @@ export class HookSession extends EventEmitter {
private disposed = false;
private loginProbeTimer: ReturnType<typeof setInterval> | null = null;
private probing = false;
private acceptedLoginHintUin = '';
private loginHintAttemptUin = '';
private loginHintAttempts = 0;
private nextLoginHintAt = 0;
private nextLoginIdentityObservationAt = 0;
private _receiveHealthy = true;
private receiveWatchUin = '';
private receiveWatchArmed = false;
@@ -575,6 +582,7 @@ export class HookSession extends EventEmitter {
this.bound = false;
this.connected = false;
this.loggedIn = false;
this.resetLoginHint();
}
private handleLoginState(state: QqHookLoginState): void {
@@ -582,8 +590,7 @@ export class HookSession extends EventEmitter {
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// However login was observed (pushed frame or the active probe), the
// safety net's job is done.
// Login readiness has now been confirmed, so identity probing is done.
if (this.loggedIn) {
this.stopLoginReconcile();
// A PID can switch accounts without an intermediate logout edge. Never
@@ -639,13 +646,9 @@ export class HookSession extends EventEmitter {
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// The hook's loginState frame is edge-triggered (pushed only when the native
// observes the login transition). When that edge is missed — QQ auto-logged
// in before connect, or a silent session-restore path the hook doesn't
// intercept — we'd sit at 'loaded'/'connecting' forever. So while connected
// but not logged in, actively re-probe QQ's own ports and synthesize the
// login once it reports a real uin. Idempotent with the pushed-frame path
// (handleLoginState's wasLoggedIn guard dedups the 'login' emit).
// The local endpoint can identify an auto-restored account before the
// runtime is ready. Forward identity for reconciliation, but never synthesize
// online state from the probe.
private startLoginReconcile(): void {
if (this.loginProbeTimer || this.disposed) return;
@@ -666,34 +669,85 @@ export class HookSession extends EventEmitter {
// slow probe never stacks concurrent subprocess-spawning scans.
if (this.probing) return;
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (Date.now() < this.nextLoginIdentityObservationAt) return;
this.probing = true;
try {
let info: QqPortLoginInfo | null;
try {
info = await this.probeLogin(this.pid);
} catch {
} catch (error) {
this.log.trace(
'login identity probe failed: PID=%d err=%s',
this.pid,
errMsg(error),
);
return; // best-effort; the interval retries
}
// The await yielded — re-check we still want this before mutating state.
if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; }
if (info?.loggedIn && isRealUin(info.uin)) {
this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin);
// isRealUin guarantees a pure non-empty digit string, so BigInt() here
// cannot throw (keep that contract if isRealUin's regex is ever changed).
// Reconcile through QqHookClient instead of mutating HookSession alone:
// packet sending and login waiters must observe the same state before
// the login event starts Bridge / OneBot initialization.
this.client!.reconcileLoginState({
loggedIn: true,
uin: info.uin,
uinNumber: BigInt(info.uin),
});
if (info?.identityKnown && isRealUin(info.uin)) {
const client = this.client;
if (!client) return;
if (this.acceptedLoginHintUin === info.uin) {
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
return;
}
if (this.loginHintAttemptUin !== info.uin) {
this.loginHintAttemptUin = info.uin;
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
}
if (this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS
|| Date.now() < this.nextLoginHintAt) return;
const attempt = ++this.loginHintAttempts;
this.log.info('login identity discovered: PID=%d UIN=%s; awaiting readiness', this.pid, info.uin);
try {
await client.reconcileLoginIdentity(info.uin);
if (this.client !== client || this.disposed || !this.connected || this.loggedIn) return;
this.acceptedLoginHintUin = info.uin;
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed) return;
if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) {
this.log.warn(
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
this.pid,
info.uin,
attempt,
errMsg(error),
);
this.nextLoginIdentityObservationAt = Date.now()
+ LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} else {
this.nextLoginHintAt = Date.now()
+ LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
this.log.trace(
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
this.pid,
info.uin,
attempt,
errMsg(error),
);
}
}
}
} finally {
this.probing = false;
}
}
private resetLoginHint(): void {
this.acceptedLoginHintUin = '';
this.loginHintAttemptUin = '';
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
+19 -10
View File
@@ -11,8 +11,9 @@ export type PipeWatcherDeps = {
* case this tick keeps the prior process+pipe state instead of treating the
* missing data as "everything disappeared" (issue #158). */
listProcesses: () => HookProcessBaseInfo[] | null | Promise<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Native: PIDs that currently have a live SnowLuma named pipe. The current
* process snapshot lets Linux inspect each target user's runtime directory. */
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
@@ -158,12 +159,12 @@ export class PipeWatcher extends EventEmitter {
this.emit('tick');
return;
}
let livePipes: Set<number>;
let livePipes: Set<number> | null;
try {
livePipes = await this.listLivePipes();
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = new Set();
livePipes = null;
}
const newKnownPids = new Set<number>();
@@ -179,11 +180,19 @@ export class PipeWatcher extends EventEmitter {
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
if (livePipes === null) {
// Keep the last known pipe state for processes that still exist, while
// allowing confirmed process exits to complete their normal teardown.
for (const pid of this.livePipes) {
if (newKnownPids.has(pid)) newLivePipes.add(pid);
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
}
+219 -106
View File
@@ -6,14 +6,21 @@ import {
runWithTraceRequest,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { isRealUin } from '@snowluma/common/uin';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { resolveHookRuntimeDir } from './hook-runtime-dir';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
// Keep these byte limits in lockstep with nnphook's pipe_protocol.hpp. The
// native readers already enforce them; mirroring them here prevents the JS
// endpoint from buffering frames that the peer can never accept.
export const MAX_PIPE_CMD_BYTES = 4096;
export const MAX_PIPE_MSG_BYTES = 65536;
export const MAX_PIPE_BODY_BYTES = 16 * 1024 * 1024;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
@@ -28,6 +35,7 @@ export enum PipeOp {
error = 5,
recvPacket = 6,
loginState = 7,
loginIdentityHint = 17,
}
const PipeFlagWantReply = 1 << 0;
@@ -63,6 +71,7 @@ export interface QqHookSendReply {
export interface QqHookClientOptions {
ackTimeoutMs?: number;
replyTimeoutMs?: number;
runtimeDir?: string;
}
export interface QqHookSendOptions {
@@ -94,6 +103,20 @@ interface PendingAck {
wantReply: boolean;
}
function isMissingDirectoryError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT' || code === 'ENOTDIR';
}
function isUnavailableSocketError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ENOENT'
|| code === 'ENOTDIR'
|| code === 'ENOTSOCK'
|| code === 'ECONNREFUSED'
|| code === 'ECONNRESET';
}
/**
* Sync directory scan for `mojo.<pid>.control.sock` socket files in the
* runtime dir, returning the pid set. Used by the darwin path of
@@ -108,14 +131,15 @@ interface PendingAck {
* variant still gates the subsequent `pipe-up` emit via a real connect.
*/
export function listSnowlumaPipePidsSync(
runtimeDir = linuxRuntimeDir(),
runtimeDir = resolveHookRuntimeDir(),
): Set<number> {
const result = new Set<number>();
let names: string[];
try {
names = readdirSync(runtimeDir);
} catch {
return result;
} catch (error) {
if (isMissingDirectoryError(error)) return result;
throw error;
}
for (const name of names) {
const m = /^mojo\.(\d+)\.control\.sock$/i.exec(name);
@@ -126,37 +150,11 @@ export function listSnowlumaPipePidsSync(
return result;
}
function linuxRuntimeDir(): string {
// Name kept for historical reasons (the function predates the macOS port);
// applies to every non-win32 platform. The fallback order mirrors each
// platform hook's runtime_dir(): explicit override first, then the OS-
// native ephemeral-dir convention.
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// macOS: dylib defaults to "$TMPDIR/snowluma-hook" (apps/qq/macos/
// qq_hook_dylib.cpp's runtime_dir()). $TMPDIR is per-user on macOS
// (under /var/folders/.../T) so this is the right place — Linux's
// /tmp/snowluma-<uid> doesn't exist on a stock Mac.
if (process.platform === 'darwin') {
const tmpdir = process.env.TMPDIR;
if (tmpdir && tmpdir.length > 0) {
const trimmed = tmpdir.endsWith('/') ? tmpdir.slice(0, -1) : tmpdir;
return path.join(trimmed, 'snowluma-hook');
}
}
// Linux fallback: mirrors hook_stub.cpp runtime_dir() last-resort.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;
}
function mojoPipeName(pid: number, suffix: string): string {
function mojoPipeName(pid: number, suffix: string, runtimeDir = resolveHookRuntimeDir(pid)): string {
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
return path.join(runtimeDir, `mojo.${pid}.${suffix}.sock`);
}
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
@@ -165,16 +163,18 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
try {
const stat = await fs.stat(socketPath);
if (!stat.isSocket()) return false;
} catch {
return false;
} catch (error) {
if (isUnavailableSocketError(error)) return false;
throw error;
}
return new Promise<boolean>((resolve) => {
return new Promise<boolean>((resolve, reject) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch {
resolve(false);
} catch (error) {
if (isUnavailableSocketError(error)) resolve(false);
else reject(error);
return;
}
let done = false;
@@ -189,20 +189,31 @@ async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
};
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
socket.once('connect', () => finish(true));
socket.once('error', () => finish(false));
socket.once('error', error => {
if (isUnavailableSocketError(error)) finish(false);
else {
if (done) return;
done = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
reject(error);
}
});
});
}
export async function listLiveLinuxPipePids(
runtimeDir = linuxRuntimeDir(),
runtimeDir = resolveHookRuntimeDir(),
probe: LinuxPipeProbe = isConnectableUnixSocket,
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch {
return result;
} catch (error) {
if (isMissingDirectoryError(error)) return result;
throw error;
}
await Promise.all(names.map(async (name) => {
@@ -303,6 +314,7 @@ function encodeFrame({
const cmdBuf = Buffer.from(cmd, 'utf8');
const msgBuf = Buffer.from(msg, 'utf8');
const bodyBuf = toBuffer(body);
validatePipeFrameLengths(cmdBuf.length, msgBuf.length, bodyBuf.length);
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
@@ -317,45 +329,115 @@ function encodeFrame({
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
}
function validatePipeFrameLengths(cmdLen: number, msgLen: number, bodyLen: number): void {
const lengths = [
['command', cmdLen, MAX_PIPE_CMD_BYTES],
['message', msgLen, MAX_PIPE_MSG_BYTES],
['body', bodyLen, MAX_PIPE_BODY_BYTES],
] as const;
for (const [name, length, limit] of lengths) {
if (length > limit) {
throw new Error(`pipe frame ${name} length ${length} exceeds limit ${limit}`);
}
}
}
interface PendingPipeFrame {
op: number;
requestId: number;
status: number;
flags: number;
value0: bigint;
cmdLen: number;
msgLen: number;
bodyLen: number;
payload: Buffer;
received: number;
}
class FrameReader {
private buffer = Buffer.alloc(0);
private readonly header = Buffer.alloc(HEADER_SIZE);
private headerBytes = 0;
private pending: PendingPipeFrame | null = null;
constructor(private readonly onFrame: (frame: PipeFrame) => void) { }
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= HEADER_SIZE) {
const magic = this.buffer.readUInt32LE(0);
const version = this.buffer.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
let chunkOffset = 0;
while (chunkOffset < chunk.length) {
if (!this.pending) {
const headerBytes = Math.min(HEADER_SIZE - this.headerBytes, chunk.length - chunkOffset);
chunk.copy(
this.header,
this.headerBytes,
chunkOffset,
chunkOffset + headerBytes,
);
this.headerBytes += headerBytes;
chunkOffset += headerBytes;
if (this.headerBytes < HEADER_SIZE) return;
this.headerBytes = 0;
const magic = this.header.readUInt32LE(0);
const version = this.header.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
}
const cmdLen = this.header.readUInt32LE(20);
const msgLen = this.header.readUInt32LE(24);
const bodyLen = this.header.readUInt32LE(28);
validatePipeFrameLengths(cmdLen, msgLen, bodyLen);
const payloadLength = cmdLen + msgLen + bodyLen;
this.pending = {
op: this.header.readUInt16LE(6),
requestId: this.header.readUInt32LE(8),
status: this.header.readInt32LE(12),
flags: this.header.readUInt32LE(16),
value0: this.header.readBigUInt64LE(32),
cmdLen,
msgLen,
bodyLen,
payload: payloadLength === 0 ? Buffer.alloc(0) : Buffer.allocUnsafe(payloadLength),
received: 0,
};
}
const cmdLen = this.buffer.readUInt32LE(20);
const msgLen = this.buffer.readUInt32LE(24);
const bodyLen = this.buffer.readUInt32LE(28);
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
if (this.buffer.length < total) return;
const pending = this.pending;
const payloadBytes = Math.min(
pending.payload.length - pending.received,
chunk.length - chunkOffset,
);
if (payloadBytes > 0) {
chunk.copy(
pending.payload,
pending.received,
chunkOffset,
chunkOffset + payloadBytes,
);
pending.received += payloadBytes;
chunkOffset += payloadBytes;
}
if (pending.received < pending.payload.length) return;
this.pending = null;
const frame: PipeFrame = {
op: this.buffer.readUInt16LE(6),
requestId: this.buffer.readUInt32LE(8),
status: this.buffer.readInt32LE(12),
flags: this.buffer.readUInt32LE(16),
value0: this.buffer.readBigUInt64LE(32),
op: pending.op,
requestId: pending.requestId,
status: pending.status,
flags: pending.flags,
value0: pending.value0,
cmd: '',
msg: '',
body: Buffer.alloc(0),
};
let offset = HEADER_SIZE;
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
offset += cmdLen;
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
offset += msgLen;
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
this.buffer = this.buffer.subarray(total);
let offset = 0;
frame.cmd = pending.payload.subarray(offset, offset + pending.cmdLen).toString('utf8');
offset += pending.cmdLen;
frame.msg = pending.payload.subarray(offset, offset + pending.msgLen).toString('utf8');
offset += pending.msgLen;
frame.body = Buffer.from(pending.payload.subarray(offset, offset + pending.bodyLen));
this.onFrame(frame);
}
}
@@ -363,6 +445,7 @@ class FrameReader {
export class QqHookClient extends EventEmitter {
readonly pid: number;
readonly runtimeDir: string;
readonly defaultAckTimeoutMs: number;
readonly defaultReplyTimeoutMs: number;
@@ -385,9 +468,11 @@ export class QqHookClient extends EventEmitter {
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
runtimeDir = resolveHookRuntimeDir(pid),
}: QqHookClientOptions = {}) {
super();
this.pid = pid;
this.runtimeDir = runtimeDir;
this.defaultAckTimeoutMs = ackTimeoutMs;
this.defaultReplyTimeoutMs = replyTimeoutMs;
}
@@ -413,16 +498,14 @@ export class QqHookClient extends EventEmitter {
}
/**
* Reconcile a login edge that the native hook could not replay after the
* pipe connected. The client remains the single source of truth so packet
* sending, login waiters, and HookSession all observe the same transition.
* Forward an observed account identity for reconciliation. This does not
* change login state; readiness still requires peer confirmation.
*/
reconcileLoginState(state: QqHookLoginState): void {
this.applyLoginState({
loggedIn: state.loggedIn,
uin: state.uin || state.uinNumber.toString(),
uinNumber: state.uinNumber,
});
async reconcileLoginIdentity(uin: string): Promise<void> {
if (!isRealUin(uin)) {
throw new Error(`invalid QQ login identity hint: ${JSON.stringify(uin)}`);
}
await this.sendAckOnly(PipeOp.loginIdentityHint, BigInt(uin), 'login identity hint');
}
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
@@ -435,12 +518,12 @@ export class QqHookClient extends EventEmitter {
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
}
static controlPipeName(pid: number): string {
return mojoPipeName(pid, 'control');
static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
return mojoPipeName(pid, 'control', runtimeDir);
}
static recvPipeName(pid: number): string {
return mojoPipeName(pid, 'recv');
static recvPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
return mojoPipeName(pid, 'recv', runtimeDir);
}
/**
@@ -449,7 +532,7 @@ export class QqHookClient extends EventEmitter {
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
const live = await QqHookClient.listLivePipes([pid]);
return live.has(pid);
}
@@ -458,20 +541,24 @@ export class QqHookClient extends EventEmitter {
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
static async listLivePipes(pids: readonly number[] = []): Promise<Set<number>> {
const result = new Set<number>();
try {
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
} else {
const runtimeDirs = new Set<string>();
if (pids.length === 0) {
runtimeDirs.add(resolveHookRuntimeDir());
} else {
return await listLiveLinuxPipePids();
for (const pid of pids) runtimeDirs.add(resolveHookRuntimeDir(pid));
}
for (const runtimeDir of runtimeDirs) {
for (const pid of await listLiveLinuxPipePids(runtimeDir)) result.add(pid);
}
} catch {
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
@@ -528,18 +615,7 @@ export class QqHookClient extends EventEmitter {
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
// 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 requestId = this.allocateRequestId();
const startedAt = Date.now();
const bodyBytes = toBuffer(body);
const payload = encodeFrame({
@@ -763,12 +839,49 @@ export class QqHookClient extends EventEmitter {
return writePromise;
}
private allocateRequestId(): number {
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would lose
// precision past Number.MAX_SAFE_INTEGER. Zero remains the wire sentinel.
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;
return requestId;
}
private async sendAckOnly(op: PipeOp, value0: bigint, label: string): Promise<number> {
await this.connect();
const requestId = this.allocateRequestId();
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
ackDeferred.promise.catch(() => { /* observed by the await below */ });
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
wantReply: false,
});
try {
await this.writeControl(encodeFrame({ op, requestId, value0 }));
await withTimeout(
ackDeferred.promise,
this.defaultAckTimeoutMs,
`${label} ack ${requestId}`,
);
return requestId;
} catch (error) {
this.pendingAcks.delete(requestId);
throw error;
}
}
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const pipeName = kind === 'control'
? QqHookClient.controlPipeName(this.pid)
: QqHookClient.recvPipeName(this.pid);
? QqHookClient.controlPipeName(this.pid, this.runtimeDir)
: QqHookClient.recvPipeName(this.pid, this.runtimeDir);
let phase: 'connect' | 'hello' = 'connect';
runtimeLog.trace(
'hook_pipe_start pid=%d kind=%s pipeName=%j',
@@ -830,7 +943,7 @@ export class QqHookClient extends EventEmitter {
reader.push(chunk);
} catch (error) {
this.emit('error', error);
socket.destroy(error instanceof Error ? error : undefined);
socket.destroy();
}
});
socket.on('error', error => {
+8 -107
View File
@@ -1,6 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import { exec } from 'child_process';
import net from 'net';
import http from 'http';
import https from 'https';
import { promisify } from 'util';
@@ -8,9 +7,6 @@ import { promisify } from 'util';
const execAsync = promisify(exec);
const log = createLogger('LoginProbe');
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
const COMMAND_TIMEOUT_MS = 1500;
const OVERALL_PROBE_TIMEOUT_MS = 5000;
@@ -28,102 +24,11 @@ export interface QqPortLoginInfo {
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
/** The local QQ endpoint exposed an account identity. This does not prove
* the native protocol session is ready to send or receive packets. */
identityKnown: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
* probe reads are modelled; QQ sends more but they're irrelevant here. */
interface PtloginUin {
@@ -194,7 +99,7 @@ async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallba
port,
uin: String(account.uin || account.account || ''),
nickName: account.nickname || '',
loggedIn: true,
identityKnown: true,
};
}
@@ -264,7 +169,7 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
if (ports.length === 0) {
const totalPids = await getQqProcessCount();
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
return { port: 0, uin: '', loggedIn: false };
return { port: 0, uin: '', identityKnown: false };
}
return null;
}
@@ -294,17 +199,13 @@ async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo |
return {
port: ports[0] || 0,
uin: '',
loggedIn: false,
identityKnown: false,
};
}
}
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
for (const port of deepLinkPorts) {
const info = await probePort(port);
if (info) return info;
}
// Background discovery must remain passive. Interactive application
// endpoints are deliberately excluded from automatic probing.
return null;
}
@@ -0,0 +1,67 @@
import { describe, expect, it } from 'vitest';
import { resolveHookRuntimeDir } from '../src/hook-runtime-dir';
function procReader(files: Record<string, string>) {
return (file: string): string => {
const value = files[file];
if (value === undefined) throw new Error(`missing fixture: ${file}`);
return value;
};
}
describe('resolveHookRuntimeDir — Linux target process ownership', () => {
it('uses the QQ process runtime directory instead of the supervisor user directory', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'HOME=/home/rikka\0XDG_RUNTIME_DIR=/run/user/1000\0',
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/run/user/1000');
});
it('falls back to the QQ process uid when its environment has no runtime directory', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'HOME=/home/rikka\0',
'/proc/46301/status': 'Name:\tqq\nUid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/tmp/snowluma-1000');
});
it('fails visibly when target ownership cannot be determined', () => {
expect(() => resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: () => { throw new Error('permission denied'); },
})).toThrow(/cannot resolve hook runtime directory.*permission denied/);
});
it('uses the current convention when the target disappears during discovery', () => {
const gone = Object.assign(new Error('process disappeared'), { code: 'ENOENT' });
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: { XDG_RUNTIME_DIR: '/run/user/0' },
ownUid: 0,
readText: () => { throw gone; },
})).toBe('/run/user/0');
});
it('honours an explicit runtime directory inherited by the QQ process', () => {
expect(resolveHookRuntimeDir(46301, {
platform: 'linux',
env: {},
ownUid: 0,
readText: procReader({
'/proc/46301/environ': 'SNOWLUMA_HOOK_RUNTIME_DIR=/srv/snowluma-hook\0',
'/proc/46301/status': 'Uid:\t1000\t1000\t1000\t1000\n',
}),
})).toBe('/srv/snowluma-hook');
});
});
+108 -21
View File
@@ -33,7 +33,10 @@ class FakeClient extends EventEmitter {
isClosed = false;
isLoggedIn = false;
shouldFailConnect = false;
nativeReadyOnIdentityHint = false;
identityHintFailures = 0;
readonly sentPackets: Array<{ serviceCmd: string; body: Buffer }> = [];
readonly loginIdentityHints: string[] = [];
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
async connectAll(_opts: { recv: boolean }): Promise<void> {
@@ -46,6 +49,14 @@ class FakeClient extends EventEmitter {
this.loginState = { ...state };
this.emit('loginState', { ...this.loginState });
}
async reconcileLoginIdentity(uin: string): Promise<void> {
this.loginIdentityHints.push(uin);
if (this.identityHintFailures > 0) {
this.identityHintFailures--;
throw new Error('identity hint unavailable');
}
if (this.nativeReadyOnIdentityHint) this.fireLogin(uin);
}
async send(serviceCmd: string, body: Buffer) {
this.sentPackets.push({ serviceCmd, body: Buffer.from(body) });
return {
@@ -76,6 +87,8 @@ function makeSession(opts: {
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
} = {}) {
const pid = opts.pid ?? 1234;
let pipeLive = opts.pipeLive ?? false;
@@ -84,15 +97,17 @@ function makeSession(opts: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe reports "not logged in" so the reconcile safety net is inert
// unless a test opts into a logged-in probe (never hits the real port scan).
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false }));
// Default probe exposes no identity so the reconcile safety net is inert
// unless a test opts into a known account.
const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
const session = new HookSession(pid, {
injector,
makeClient: () => {
const c = new FakeClient();
if (opts.clientFailsConnect) c.shouldFailConnect = true;
c.nativeReadyOnIdentityHint = opts.nativeReadyOnIdentityHint ?? false;
c.identityHintFailures = opts.identityHintFailures ?? 0;
clients.push(c);
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
@@ -810,10 +825,11 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('keeps the packet sender usable when login is reconciled by the active probe', async () => {
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
nativeReadyOnIdentityHint: true,
});
let sender: PacketSender | undefined;
ctx.session.on('login', (_uin: string, nextSender: PacketSender) => {
@@ -839,13 +855,12 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
]);
});
it('reconciles login via the active probe when the pushed frame is missed', async () => {
// Probe reports logged-in; the FakeClient never fires a loginState frame
// (the missed-edge Docker case). The immediate reconcile probe must detect
// it and emit "login".
it('treats a port-probed account as an identity hint, not native login proof', async () => {
// Account identity does not prove request readiness. The bridge must wait
// for a login-state confirmation instead of synthesizing one.
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }),
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -853,18 +868,89 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await ctx.session.load();
ctx.session.onPipeUp();
await flush(); // connect (not logged in via frame) → starts reconcile
await flush(); // immediate probe resolves → handleLoginState
await flush(); // immediate probe resolves → forwards identity hint
expect(loginSpy).toHaveBeenCalledOnce();
expect(loginSpy.mock.calls[0]![0]).toBe('10001');
expect(ctx.session.status).toBe('online');
expect(ctx.session.uin).toBe('10001');
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
expect(loginSpy).not.toHaveBeenCalled();
expect(ctx.session.status).toBe('loaded');
expect(ctx.session.uin).toBe('0');
});
it('forwards the same identity at most once per pipe connection', async () => {
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('keeps observing identity after acknowledgement and forwards an account change', async () => {
vi.useFakeTimers();
let uin = '10001';
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
uin = '20002';
await vi.advanceTimersByTimeAsync(29_999);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
await vi.advanceTimersByTimeAsync(1);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '20002']);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('retries identity forwarding failures with a strict bound', async () => {
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
identityHintFailures: 3,
});
try {
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001']);
await vi.advanceTimersByTimeAsync(3000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001']);
await vi.advanceTimersByTimeAsync(9000);
expect(ctx.currentClient().loginIdentityHints).toEqual(['10001', '10001', '10001']);
await vi.advanceTimersByTimeAsync(30_000);
expect(ctx.currentClient().loginIdentityHints).toHaveLength(3);
} finally {
ctx.session.dispose();
vi.useRealTimers();
}
});
it('does not log in when the probe reports not-logged-in', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }),
probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -879,7 +965,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('ignores a probe with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }),
probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }),
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -908,10 +994,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('detects a login that lands on a LATER interval probe', async () => {
vi.useFakeTimers();
try {
let loggedIn = false;
let identityKnown = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }),
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }),
nativeReadyOnIdentityHint: true,
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -921,7 +1008,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
loggedIn = true; // QQ finishes auto-login
identityKnown = true; // QQ exposes the restored identity
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
expect(loginSpy).toHaveBeenCalledOnce();
@@ -934,7 +1021,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true }));
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -30,6 +30,27 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
}
describe('PipeWatcher', () => {
it('passes the current process snapshot to pipe discovery', async () => {
const processes = [
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
{ pid: 5678, name: 'qq', path: '/opt/QQ/qq' },
];
let observed: readonly HookProcessBaseInfo[] | undefined;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async current => {
observed = current;
return new Set();
},
intervalMs: 60_000,
});
await watcher.start();
expect(observed).toEqual(processes);
watcher.stop();
});
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
@@ -193,6 +214,38 @@ describe('PipeWatcher', () => {
watcher.stop();
});
it('preserves live sessions when pipe discovery temporarily fails', async () => {
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
let failPipeDiscovery = false;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listLivePipes: async () => {
if (failPipeDiscovery) throw new Error('permission denied');
return new Set([1234]);
},
intervalMs: 60_000,
});
await watcher.start();
expect(watcher.isPipeLive(1234)).toBe(true);
const events = captureEvents(watcher);
failPipeDiscovery = true;
await watcher.tickNow();
expect(events).toEqual([]);
expect(watcher.isProcessAlive(1234)).toBe(true);
expect(watcher.isPipeLive(1234)).toBe(true);
processes = [];
await watcher.tickNow();
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
expect(watcher.isProcessAlive(1234)).toBe(false);
expect(watcher.isPipeLive(1234)).toBe(false);
watcher.stop();
});
it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
@@ -15,6 +15,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
HEADER_SIZE,
listLiveLinuxPipePids,
MAX_PIPE_BODY_BYTES,
MAX_PIPE_CMD_BYTES,
MAX_PIPE_MSG_BYTES,
PIPE_MAGIC,
PIPE_VERSION,
PipeOp,
@@ -147,6 +150,205 @@ describe('listLiveLinuxPipePids', () => {
});
});
describe('QqHookClient — pipe frame limits', () => {
it('forwards a probed account as a native identity hint without changing login state', async () => {
const pid = 778819;
const writes: Buffer[] = [];
const connection = mockControlPipe(pid, (socket, payload) => {
writes.push(Buffer.from(payload));
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.sendAck,
requestId,
})));
});
const client = new QqHookClient(pid);
try {
await client.reconcileLoginIdentity('10001');
expect(writes).toHaveLength(1);
expect(writes[0]!.readUInt16LE(6)).toBe(PipeOp.loginIdentityHint);
expect(writes[0]!.readBigUInt64LE(32)).toBe(10001n);
expect(client.getLoginState()).toEqual({
loggedIn: false,
uin: '0',
uinNumber: 0n,
});
} finally {
client.close();
connection.mockRestore();
}
});
it.each([
['command', 20, MAX_PIPE_CMD_BYTES],
['message', 24, MAX_PIPE_MSG_BYTES],
['body', 28, MAX_PIPE_BODY_BYTES],
] as const)(
'rejects an oversized inbound %s before waiting for its payload',
async (name, lengthOffset, limit) => {
const pid = 778830;
let socket: net.Socket | null = null;
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket!.emit('connect');
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
header.writeUInt16LE(PipeOp.hello, 6);
header.writeUInt32LE(limit + 1, lengthOffset);
socket!.emit('data', header);
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
const connecting = client.connect().catch(() => undefined);
try {
const error = await new Promise<Error>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('oversized frame was not rejected')),
100,
);
client.once('error', (reason: unknown) => {
clearTimeout(timer);
resolve(reason instanceof Error ? reason : new Error(String(reason)));
});
});
expect(error.message).toBe(
`pipe frame ${name} length ${limit + 1} exceeds limit ${limit}`,
);
expect(socket?.destroyed).toBe(true);
} finally {
client.close();
await connecting;
createConnection.mockRestore();
}
});
it('rejects an oversized outbound command before writing to the pipe', async () => {
const pid = 778831;
const onWrite = vi.fn();
const connection = mockControlPipe(pid, onWrite);
const client = new QqHookClient(pid);
try {
await client.connect();
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES + 1), Buffer.alloc(0), {
ackTimeoutMs: 25,
})).rejects.toThrow(
`pipe frame command length ${MAX_PIPE_CMD_BYTES + 1} exceeds limit ${MAX_PIPE_CMD_BYTES}`,
);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
connection.mockRestore();
}
});
it('rejects an oversized outbound body before writing to the pipe', async () => {
const pid = 778832;
const onWrite = vi.fn();
const connection = mockControlPipe(pid, onWrite);
const client = new QqHookClient(pid);
try {
await client.connect();
await expect(client.sendNoReply(
'test.command',
Buffer.alloc(MAX_PIPE_BODY_BYTES + 1),
)).rejects.toThrow(
`pipe frame body length ${MAX_PIPE_BODY_BYTES + 1} exceeds limit ${MAX_PIPE_BODY_BYTES}`,
);
expect(onWrite).not.toHaveBeenCalled();
} finally {
client.close();
connection.mockRestore();
}
});
it('accepts values exactly at the command limit', async () => {
const pid = 778833;
const connection = mockControlPipe(pid, (socket, payload) => {
const requestId = payload.readUInt32LE(8);
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.sendAck,
requestId,
})));
});
const client = new QqHookClient(pid);
try {
await expect(client.sendNoReply('x'.repeat(MAX_PIPE_CMD_BYTES), Buffer.alloc(0)))
.resolves.toMatchObject({ requestId: 1 });
} finally {
client.close();
connection.mockRestore();
}
});
it('parses fragmented and coalesced frames without losing boundaries', async () => {
const pid = 778834;
const states: string[] = [];
const wire = Buffer.concat([
pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message: 'control' }),
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10001n, message: '10001' }),
pipeFrame({ op: PipeOp.loginState, status: 1, value0: 10002n, message: '10002' }),
]);
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => {
const cuts = [1, 7, 39, 40, 44, 83, wire.length - 1, wire.length];
let offset = 0;
for (const end of cuts) {
if (end > offset) socket.emit('data', wire.subarray(offset, end));
offset = end;
}
});
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
client.on('loginState', state => states.push(state.uin));
try {
const hello = await client.connect();
expect(hello).toMatchObject({ pipeName: 'control', pid });
expect(states).toEqual(['10001', '10002']);
} finally {
client.close();
createConnection.mockRestore();
}
});
it('accepts an inbound message exactly at the native limit', async () => {
const pid = 778835;
const message = 'x'.repeat(MAX_PIPE_MSG_BYTES);
const frame = pipeFrame({ op: PipeOp.hello, value0: BigInt(pid), message });
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* peer data is injected with emit('data') */ } }) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => {
for (let offset = 0; offset < frame.length; offset += 1024) {
socket.emit('data', frame.subarray(offset, offset + 1024));
}
});
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).resolves.toMatchObject({ pipeName: message, pid });
} finally {
client.close();
createConnection.mockRestore();
}
});
});
describe('QqHookClient — runtime TRACE', () => {
it('records control and receive pipe hello lifecycles under the parent request', async () => {
const pid = 778820;
+25 -1
View File
@@ -1,8 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const execMock = vi.hoisted(() => vi.fn());
const socketCtorMock = vi.hoisted(() => vi.fn(function MockSocket() {
throw new Error('interactive QQ probe must not run');
}));
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('net', () => ({
default: { Socket: socketCtorMock },
Socket: socketCtorMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
@@ -10,6 +17,7 @@ describe('probeQqLoginInfo — bounded execution', () => {
beforeEach(() => {
vi.useFakeTimers();
execMock.mockReset();
socketCtorMock.mockClear();
});
afterEach(() => {
@@ -33,7 +41,23 @@ describe('probeQqLoginInfo — bounded execution', () => {
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
loggedIn: false,
identityKnown: false,
});
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '8\n', stderr: '' });
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});
+10 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
@@ -63,6 +63,10 @@
"./uin": {
"types": "./src/uin.ts",
"default": "./src/uin.ts"
},
"./access-token": {
"types": "./src/access-token.ts",
"default": "./src/access-token.ts"
}
},
"scripts": {
@@ -73,5 +77,10 @@
"@types/node": "catalog:",
"typescript": "catalog:",
"vitest": "^4.1.4"
},
"dependencies": {
"@zxcvbn-ts/core": "^4.1.2",
"@zxcvbn-ts/language-common": "^4.1.3",
"@zxcvbn-ts/language-en": "^4.1.1"
}
}
+58
View File
@@ -0,0 +1,58 @@
import { ZxcvbnFactory } from '@zxcvbn-ts/core';
import { adjacencyGraphs, dictionary } from '@zxcvbn-ts/language-common';
import { translations } from '@zxcvbn-ts/language-en';
export const ACCESS_TOKEN_MIN_LENGTH = 16;
export const ACCESS_TOKEN_MIN_SCORE = 3;
export type AccessTokenAssessmentReason =
| 'empty'
| 'too-short'
| 'guessable'
| 'acceptable';
export interface AccessTokenAssessment {
acceptable: boolean;
reason: AccessTokenAssessmentReason;
score: number;
}
const checker = new ZxcvbnFactory({
translations,
graphs: adjacencyGraphs,
dictionary,
});
function normalizeUserInputs(values: readonly (string | number)[]): Array<string | number> {
const unique = new Set<string | number>(['SnowLuma', 'OneBot']);
for (const value of values) {
if (typeof value === 'number') {
if (Number.isFinite(value)) unique.add(value);
continue;
}
const trimmed = value.trim();
if (trimmed) unique.add(trimmed.slice(0, 256));
}
return [...unique].slice(0, 24);
}
/**
* Evaluate a newly chosen OneBot access token against the shared product
* policy. Callers decide whether an empty token is permitted in their own
* trust context; an empty value is never considered strong here.
*/
export function assessAccessToken(
token: string,
userInputs: readonly (string | number)[] = [],
): AccessTokenAssessment {
if (!token) return { acceptable: false, reason: 'empty', score: 0 };
if (token.length < ACCESS_TOKEN_MIN_LENGTH) {
return { acceptable: false, reason: 'too-short', score: 0 };
}
const score = checker.check(token, normalizeUserInputs(userInputs)).score;
if (score < ACCESS_TOKEN_MIN_SCORE) {
return { acceptable: false, reason: 'guessable', score };
}
return { acceptable: true, reason: 'acceptable', score };
}
+11 -7
View File
@@ -214,13 +214,12 @@ function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
forceInitialCredentials = false,
): void {
// Console / subscriber and file filters are independent. If no destination
// accepts the record, stop before formatting or building a LogEntry.
const passesConsole = forceInitialCredentials || shouldLog(level);
const passesConsole = shouldLog(level);
const passesFile = level !== 'trace'
&& (forceInitialCredentials || shouldLogToFile(level));
&& shouldLogToFile(level);
if (!passesConsole && !passesFile) return;
// `trace` is the high-volume full-chain diagnostic stream, intentionally
@@ -239,7 +238,7 @@ function emit(
const reqId = currentRequestId();
const formattedMessage = format(...realArgs);
const message = level === 'trace' || forceInitialCredentials
const message = level === 'trace'
? formattedMessage
: redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
@@ -364,12 +363,17 @@ export function runWithTraceRequest<T>(fn: () => T): T {
}
export function logInitialWebuiCredentials(password: string): void {
emit(
// This is deliberately not a LogEntry: application logs can be retained on
// disk, exported through WebUI, and delivered to subscribers. First-run
// credentials must only cross the process terminal boundary.
const line = render(
'info',
{ scope: 'WebUI' },
['initial credentials: user=admin password=%s', password],
true,
format('initial credentials: user=admin password=%s', password),
);
// Keep the same terminal control-character policy as regular console logs.
// eslint-disable-next-line no-control-regex
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// Request-correlation primitives remain available for callers that already own
+3 -3
View File
@@ -7,8 +7,8 @@ export interface RuntimeConfig {
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
* Defaults to false; the Docker image flips it on in supervisord.conf. */
hookAutoLoad?: boolean;
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
/** WebUI listener bind address. '127.0.0.1' = localhost-only (default),
* '0.0.0.0' = all IPv4 interfaces. Listener-level: change needs a restart. */
webuiHost?: string;
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
* only flips serving on/off. Listener-level: change needs a restart. */
@@ -28,7 +28,7 @@ const CONFIG_DIR = 'config';
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
const DEFAULT_WEBUI_PORT = 5099;
const DEFAULT_WEBUI_HOST = '0.0.0.0';
const DEFAULT_WEBUI_HOST = '127.0.0.1';
export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
export const DEFAULT_LOG_RETAIN_DAYS = 7;
export const DEFAULT_LOG_PER_UIN = false;
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import {
ACCESS_TOKEN_MIN_LENGTH,
ACCESS_TOKEN_MIN_SCORE,
assessAccessToken,
} from '../src/access-token';
describe('access token strength', () => {
it('requires the configured minimum length', () => {
expect(assessAccessToken('a'.repeat(ACCESS_TOKEN_MIN_LENGTH - 1))).toMatchObject({
acceptable: false,
reason: 'too-short',
});
});
it('scores system and user-specific words as guessable', () => {
expect(assessAccessToken('SnowLumaSnowLuma', ['SnowLuma', 'OneBot', '10001']))
.toMatchObject({ acceptable: false, reason: 'guessable' });
});
it('accepts a sufficiently long, hard-to-guess token', () => {
const result = assessAccessToken('E5xqVb7_9pLt2QwR4M8kZ1nY', ['SnowLuma', 'OneBot']);
expect(result.acceptable).toBe(true);
expect(result.reason).toBe('acceptable');
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
});
});
+15 -14
View File
@@ -289,25 +289,26 @@ describe('file output gating', () => {
]);
});
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
it('prints bootstrap credentials only to the current process terminal', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const snapshotBefore = fresh.getLogSnapshot();
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
fresh.logInitialWebuiCredentials('secret');
unsubscribe();
try {
fresh.logInitialWebuiCredentials('secret');
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
level: 'info',
scope: 'WebUI',
message: 'initial credentials: user=admin password=secret',
});
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
undefined,
);
expect(stdout).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
);
expect(entries).toEqual([]);
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
expect(fileWriteSpy).not.toHaveBeenCalled();
} finally {
unsubscribe();
stdout.mockRestore();
}
});
});
+4 -4
View File
@@ -8,7 +8,7 @@ describe('normalizeRuntimeConfig', () => {
expect(normalizeRuntimeConfig({})).toEqual({
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
@@ -47,7 +47,7 @@ describe('normalizeRuntimeConfig', () => {
trustProxy: 5, // non-string → default
});
expect(out.webuiPort).toBe(5099);
expect(out.webuiHost).toBe('0.0.0.0');
expect(out.webuiHost).toBe('127.0.0.1');
expect(out.webuiTls).toEqual({ enabled: false });
expect(out.trustProxy).toBe('');
});
@@ -69,12 +69,12 @@ describe('normalizeRuntimeConfig', () => {
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('127.0.0.1');
});
it('rejects a non-object input back to full defaults', () => {
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('127.0.0.1');
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.13.0",
"version": "1.14.0",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
+113 -4
View File
@@ -49,6 +49,99 @@ function entryToInfo(e: FlashFileEntry): FlashFileInfo {
};
}
const QFILE_SHARE_ORIGIN = 'https://qfile.qq.com';
const QFILE_SHARE_PAGE_MAX_BYTES = 2 * 1024 * 1024;
const QFILE_SHARE_TIMEOUT_MS = 20_000;
function officialQfileShareUrl(input: string): string {
const value = input.trim();
if (!value) throw new Error('get_fileset_id: share code is empty');
let code = value;
if (/^[a-z][a-z\d+.-]*:/i.test(value) || value.startsWith('//')) {
let parsed: URL;
try {
parsed = new URL(value);
} catch (error) {
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
}
if (
parsed.protocol !== 'https:'
|| parsed.hostname !== 'qfile.qq.com'
|| parsed.port !== ''
|| parsed.username !== ''
|| parsed.password !== ''
) {
throw new Error('get_fileset_id: expected an official QQ share URL');
}
const match = /^\/q\/([^/]+)\/?$/.exec(parsed.pathname);
if (!match) throw new Error('get_fileset_id: expected an official QQ share URL');
try {
code = decodeURIComponent(match[1]);
} catch (error) {
throw new Error('get_fileset_id: expected an official QQ share URL', { cause: error });
}
}
const hasForbiddenCharacter = Array.from(code).some((char) => {
const codePoint = char.codePointAt(0) ?? 0;
return codePoint <= 0x20 || codePoint === 0x7f || '/\\?#'.includes(char);
});
if (code.length > 256 || hasForbiddenCharacter) {
throw new Error('get_fileset_id: invalid share code');
}
return `${QFILE_SHARE_ORIGIN}/q/${encodeURIComponent(code)}`;
}
async function rejectShareResponse(response: Response, error: Error): Promise<never> {
try {
await response.body?.cancel(error);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], error.message);
}
throw error;
}
async function readSharePage(response: Response): Promise<string> {
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
await rejectShareResponse(response, new Error('get_fileset_id: invalid response length'));
}
if (Number(declaredLength) > QFILE_SHARE_PAGE_MAX_BYTES) {
await rejectShareResponse(response, new Error('get_fileset_id: share page too large'));
}
}
if (!response.body) throw new Error('get_fileset_id: share page response has no body');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let total = 0;
let html = '';
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
total += value.byteLength;
if (total > QFILE_SHARE_PAGE_MAX_BYTES) {
const error = new Error('get_fileset_id: share page too large');
try {
await reader.cancel(error);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], error.message);
}
throw error;
}
html += decoder.decode(value, { stream: true });
}
html += decoder.decode();
return html;
} finally {
reader.releaseLock();
}
}
// 手写 PNG 编码(zlib 压缩,避免引入图像库)。缩略图用随机纯色,每次 SHA1 不同,
// 避免命中服务端秒传缓存。
const CRC_TABLE: Uint32Array = (() => {
@@ -207,10 +300,26 @@ export class FlashTransferApi {
* 接口数据),直接 GET + 正则提取即可,无需复刻带签名的 trpc 调用。
*/
async getFilesetIdByCode(shareCode: string): Promise<string> {
const url = /^https?:\/\//i.test(shareCode) ? shareCode : `https://qfile.qq.com/q/${shareCode}`;
const resp = await fetch(url);
if (!resp.ok) throw new Error(`get_fileset_id: HTTP ${resp.status}`);
const html = await resp.text();
const url = officialQfileShareUrl(shareCode);
let resp: Response;
try {
resp = await fetch(url, {
redirect: 'manual',
signal: AbortSignal.timeout(QFILE_SHARE_TIMEOUT_MS),
});
} catch (error) {
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
throw new Error('get_fileset_id: share page request timed out', { cause: error });
}
throw error;
}
if (resp.status >= 300 && resp.status < 400) {
await rejectShareResponse(resp, new Error('get_fileset_id: share page redirect is not allowed'));
}
if (!resp.ok) {
await rejectShareResponse(resp, new Error(`get_fileset_id: HTTP ${resp.status}`));
}
const html = await readSharePage(resp);
// 网页里 fileset_id 以 JSON 嵌入(引号可能被转义为 \"),正则兼容两种形态。
const m = /fileset_id\\?"\s*:\s*\\?"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/.exec(html);
if (!m) throw new Error('get_fileset_id: fileset_id not found in share page');
+18 -3
View File
@@ -170,11 +170,22 @@ function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function enforceSensitiveFileMode(file: string): void {
// POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL
// remains authoritative. Avoid pretending chmod provides equivalent policy.
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
}
function atomicWrite(config: NotificationsConfig): void {
ensureConfigDir();
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), {
encoding: 'utf8',
mode: 0o600,
});
enforceSensitiveFileMode(tmp);
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
}
let cached: NotificationsConfig | null = null;
@@ -195,6 +206,10 @@ export function loadNotificationsConfig(): NotificationsConfig {
return fresh;
}
// Webhook URLs commonly embed credentials. Repair older permissive files
// before reading them into memory so upgrades close the exposure promptly.
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
try {
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
@@ -203,8 +218,8 @@ export function loadNotificationsConfig(): NotificationsConfig {
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
try {
atomicWrite(normalized);
} catch {
/* best-effort self-heal */
} catch (err) {
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
}
}
cached = normalized;
+6 -6
View File
@@ -4,9 +4,10 @@
// can't leak and an import can't path-traverse.
//
// Credentials are gated by a toggle on both export and import. The credential
// set is: webui.json (password hash), key.pem (TLS private key), AND every
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
// OneBot access token, so a no-credentials backup must NOT include them.
// set is: webui.json (password hash), key.pem (TLS private key),
// notifications.json (webhook URLs may embed secrets), AND every OneBot config
// (onebot.json + per-account onebot_<uin>.json) — those carry access tokens, so
// a no-credentials backup must NOT include them.
// cert.pem is public so it always travels.
//
// Pure functions here own bundle validation and semantic preflight. Filesystem
@@ -39,9 +40,8 @@ export interface BackupFileSpec {
export const BACKUP_FILES: readonly BackupFileSpec[] = [
{ name: 'runtime.json', binary: false, credential: false },
{ name: 'ui.json', binary: false, credential: false },
{ name: 'notifications.json', binary: false, credential: false },
// Global all-accounts SnowLuma settings (rkey fallback servers, …). Same
// class as notifications.json: global, opt-in, non-credential.
{ name: 'notifications.json', binary: false, credential: true },
// Global all-accounts SnowLuma settings (rkey fallback servers, …).
{ name: 'snowluma.json', binary: false, credential: false },
{ name: 'cert.pem', binary: false, credential: false },
{ name: 'ui-assets/background', binary: true, credential: false },
+29 -12
View File
@@ -28,15 +28,23 @@ export function describeTrustProxy(mode: TrustProxyMode): string {
}
}
function isLoopback(ip: string): boolean {
return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
export function isLoopbackClientIp(ip: string): boolean {
const normalized = ip.trim().toLowerCase();
if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true;
if (normalized.startsWith('::ffff:')) {
return isLoopbackClientIp(normalized.slice('::ffff:'.length));
}
const octets = normalized.split('.');
return octets.length === 4
&& octets[0] === '127'
&& octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
}
function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean {
switch (mode.kind) {
case 'none': return false;
case 'all': return true;
case 'loopback': return isLoopback(socketIp);
case 'loopback': return isLoopbackClientIp(socketIp);
case 'ip-list': return mode.ips.has(socketIp);
}
}
@@ -45,11 +53,15 @@ export function pickClientIp(
c: Pick<Context, 'req'>,
mode: TrustProxyMode,
getSocketIp: () => string,
fallbackIp = '127.0.0.1',
): string {
const socketIp = (() => {
try { return getSocketIp() || '127.0.0.1'; }
catch { return '127.0.0.1'; }
})();
let socketIp: string;
try {
socketIp = getSocketIp();
} catch {
return fallbackIp;
}
if (!socketIp) return fallbackIp;
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
@@ -64,9 +76,14 @@ export function pickClientIp(
}
/** Convenience binding for the live server: read socket via getConnInfo. */
export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string {
return (c) => pickClientIp(c, mode, () => {
try { return getConnInfo(c).remote.address ?? '127.0.0.1'; }
catch { return '127.0.0.1'; }
});
export function makeClientIpResolver(
mode: TrustProxyMode,
fallbackIp = '127.0.0.1',
): (c: Context) => string {
return (c) => pickClientIp(
c,
mode,
() => getConnInfo(c).remote.address ?? fallbackIp,
fallbackIp,
);
}
@@ -0,0 +1,81 @@
import { assessAccessToken } from '@snowluma/common/access-token';
import type { OneBotConfig } from '@snowluma/onebot/types';
import { isLoopbackClientIp } from './client-ip';
export class OneBotAccessTokenPolicyError extends Error {
constructor(message: string) {
super(message);
this.name = 'OneBotAccessTokenPolicyError';
}
}
export interface OneBotAccessTokenPolicyOptions {
clientIp: string;
uin: string;
}
type InboundKind = 'httpServers' | 'wsServers';
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
function sameTokenAtPreviousIdentity(
previous: OneBotConfig['networks'][InboundKind],
next: OneBotConfig['networks'][InboundKind],
nextName: string,
nextToken: string,
index: number,
): boolean {
const named = previous.find((adapter) => adapter.name === nextName);
if (named && (named.accessToken ?? '') === nextToken) return true;
// Preserve a legacy token when the operator only renames the same list item.
// Reordering keeps names stable and is covered by the lookup above.
const sameIndex = previous[index];
return sameIndex !== undefined
&& !next.some((adapter) => adapter.name === sameIndex.name)
&& (sameIndex.accessToken ?? '') === nextToken;
}
export function validateOneBotAccessTokenChanges(
previous: OneBotConfig | null,
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
): void {
const allowEmpty = isLoopbackClientIp(options.clientIp);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
for (let index = 0; index < nextList.length; index += 1) {
const adapter = nextList[index];
const token = adapter.accessToken ?? '';
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
if (!token) {
if (!allowEmpty) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”仅能从本机页面保存无令牌配置;请生成令牌后重试。`,
);
}
continue;
}
const host = adapter.host ?? '0.0.0.0';
const assessment = assessAccessToken(token, [
options.uin,
adapter.name,
kind,
host,
adapter.port,
]);
if (assessment.reason === 'too-short') {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
);
}
if (!assessment.acceptable) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
);
}
}
}
}
+7 -3
View File
@@ -1,6 +1,6 @@
import net from 'net';
function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
@@ -27,11 +27,15 @@ function isPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {
* Find an available TCP port starting from `start`, advancing by 1 up to `maxTries` attempts.
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(start: number, maxTries = 50): Promise<number> {
export async function findAvailablePort(
start: number,
options: { maxTries?: number; host?: string } = {},
): Promise<number> {
const { maxTries = 50, host = '127.0.0.1' } = options;
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port)) return port;
if (await isPortAvailable(port, host)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
@@ -0,0 +1,65 @@
import { bodyLimit } from 'hono/body-limit';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
import type { Context, Hono, MiddlewareHandler } from 'hono';
export const LOGIN_BODY_LIMIT_BYTES = 16 * 1024;
const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session';
const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
function isJsonMediaType(value: string | undefined): boolean {
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
return mediaType === 'application/json' || mediaType.endsWith('+json');
}
/** Install guards before the login route is registered. */
export function registerLoginRequestSecurity(app: Hono): void {
app.use('/api/login', bodyLimit({
maxSize: LOGIN_BODY_LIMIT_BYTES,
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
}));
app.use('/api/login', async (c, next) => {
if (!isJsonMediaType(c.req.header('content-type'))) {
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
}
return next();
});
}
/** Minimal response policy that does not restrict the current script/style bundle. */
export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
await next();
c.res.headers.set('X-Frame-Options', 'DENY');
c.res.headers.set('X-Content-Type-Options', 'nosniff');
c.res.headers.set('Referrer-Policy', 'no-referrer');
c.res.headers.set(
'Content-Security-Policy',
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
);
};
export function extractBearerToken(request: Request): string {
const authorization = request.headers.get('authorization');
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
}
const avatarCookieOptions = (secure: boolean) => ({
httpOnly: true,
sameSite: 'Strict' as const,
secure,
path: '/avatar',
});
export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void {
setCookie(c, AVATAR_SESSION_COOKIE, token, {
...avatarCookieOptions(secure),
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
});
}
export function clearAvatarSessionCookie(c: Context, secure: boolean): void {
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
}
export function readAvatarSessionToken(c: Context): string {
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
}
+75 -38
View File
@@ -17,6 +17,7 @@ import {
subscribeLogs,
} from '@snowluma/common/logger';
import {
assertValidOneBotConfig,
loadOneBotConfig,
OneBotConfigValidationError,
saveOneBotConfig,
@@ -47,7 +48,7 @@ import {
recordConsent,
resolveEnvironmentConsent,
} from './consent';
import { resolveTlsContext, validateTlsPair } from './tls';
import { requireTlsContext, resolveTlsContext, validateTlsPair } from './tls';
import { coerceSettingsPatch } from './system-settings';
import { buildBackup } from './backup';
import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore';
@@ -61,6 +62,10 @@ import { startConnectionDiffLoop } from './connection-diff-loop';
import { comparableConnectionSnapshot } from './connection-snapshot';
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
import {
OneBotAccessTokenPolicyError,
validateOneBotAccessTokenChanges,
} from './onebot-token-policy';
import { findAvailablePort } from './port';
import {
clearBackgroundImage,
@@ -79,6 +84,14 @@ import type { NotificationManager } from '../notifications/manager';
import { StorageManagementService } from './storage-management';
import { registerStorageRoutes } from './storage-routes';
import { LogStorageSettingsManager } from './storage-settings';
import {
clearAvatarSessionCookie,
extractBearerToken,
readAvatarSessionToken,
registerLoginRequestSecurity,
setAvatarSessionCookie,
webuiSecurityHeaders,
} from './request-security';
const log = createLogger('WebUI');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -199,21 +212,6 @@ const CONSENT_ALLOWLIST = new Set([
'/api/logout',
]);
// Endpoints that may authenticate via `?token=` query parameter. Reserved
// for SSE streams: EventSource cannot set custom headers, so these MUST
// accept the token via query. All other endpoints use the Authorization
// header so tokens never leak into access logs / Referer / browser history.
//
// Exported so the regression test can lock the invariant — a missing entry
// here silently 401s the EventSource and the whole push channel goes dark,
// which has happened (see /api/state/stream's first cut).
export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
'/api/logs/stream',
'/api/debug/stream',
'/api/state/stream',
]);
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
// Used to construct config file paths, so we MUST refuse anything else (path
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
@@ -449,6 +447,10 @@ export async function initWebUI(
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
const trustProxyMode = parseTrustProxy(listener.trustProxy);
const getClientIp = makeClientIpResolver(trustProxyMode);
// Security decisions must not silently turn an unreadable socket peer into
// localhost. The regular resolver keeps its compatibility fallback for
// rate-limit bucketing; this resolver fails closed with an empty address.
const getSecurityClientIp = makeClientIpResolver(trustProxyMode, '');
// Connection-status diff loop: OneBot adapters don't emit events for
// listening/connected/client-count changes, so we poll the snapshot at
@@ -491,7 +493,7 @@ export async function initWebUI(
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (auth.isDevMode()) {
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode enabled with the configured development credential');
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('════════════════════════════════════════════════════════════════');
@@ -533,6 +535,8 @@ export async function initWebUI(
}
const app = new Hono();
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
dataDir: 'data',
getLogStatus: getLogStorageStatus,
@@ -583,10 +587,7 @@ export async function initWebUI(
// nothing sensitive (no layout, no secrets) — see ui-config.ts.
if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next();
const authHeader = c.req.header('Authorization');
const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : '';
const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : '';
const token = bearerToken || queryToken;
const token = extractBearerToken(c.req.raw);
if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401);
const info = sessionTokens.get(token);
@@ -650,12 +651,14 @@ export async function initWebUI(
const token = randomBytes(32).toString('hex');
const mustChange = auth.mustChangePassword();
sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange });
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ success: true, token, mustChangePassword: mustChange });
});
app.post('/api/logout', (c) => {
const token = c.get('sessionToken' as never) as string | undefined;
if (token) sessionTokens.delete(token);
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
return c.json({ success: true });
});
@@ -709,6 +712,7 @@ export async function initWebUI(
// password was compromised, the attacker may already hold the current
// token; rotating credentials must rotate sessions too.
sessionTokens.clear();
clearAvatarSessionCookie(c, listener.tlsEnabled === true);
log.info('password updated; all sessions invalidated');
return c.json({ success: true, requireRelogin: true });
});
@@ -750,6 +754,12 @@ export async function initWebUI(
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
app.get('/avatar/:uin', async (c) => {
const sessionToken = readAvatarSessionToken(c);
const session = sessionTokens.get(sessionToken);
if (!session || Date.now() > session.expiresAt) {
if (sessionToken) sessionTokens.delete(sessionToken);
return c.text('unauthorized', 401);
}
const uin = c.req.param('uin');
if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400);
@@ -768,7 +778,8 @@ export async function initWebUI(
return new Response(cached.body, {
headers: {
'Content-Type': cached.contentType,
'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
'Cache-Control': `private, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`,
Vary: 'Cookie',
},
});
});
@@ -793,7 +804,13 @@ export async function initWebUI(
});
// ─── Read-only API ───────────────────────────────────────────────────────
app.get('/api/status', (c) => c.json({ status: 'running' }));
app.get('/api/status', (c) => {
// Refresh the path-scoped avatar cookie for a still-valid localStorage
// session (for example after upgrading from a version without the cookie).
const token = c.get('sessionToken' as never) as string;
setAvatarSessionCookie(c, token, listener.tlsEnabled === true);
return c.json({ status: 'running' });
});
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
@@ -1287,11 +1304,36 @@ export async function initWebUI(
return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400);
}
let nextConfig: OneBotConfig;
try {
saveOneBotConfig(uin, body as OneBotConfig);
assertValidOneBotConfig(body);
nextConfig = body;
let previousConfig: OneBotConfig | null = null;
try {
previousConfig = loadOneBotConfig(uin);
} catch (err) {
// A damaged existing file must not strand the recovery UI. Treat the
// submitted endpoints as new, apply the full policy, and let the
// subsequent atomic save either repair the file or fail visibly.
log.warn(
'could not read prior OneBot config for uin=%s before save: %s',
uin,
err instanceof Error ? err.message : String(err),
);
}
validateOneBotAccessTokenChanges(previousConfig, nextConfig, {
clientIp: getSecurityClientIp(c),
uin,
});
saveOneBotConfig(uin, nextConfig);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (err instanceof OneBotConfigValidationError) {
if (
err instanceof OneBotConfigValidationError
|| err instanceof OneBotAccessTokenPolicyError
) {
log.warn('reject invalid config for uin=%s: %s', uin, message);
return c.json({ success: false, saved: false, applied: false, message }, 400);
}
@@ -1303,7 +1345,7 @@ export async function initWebUI(
// Apply the exact validated value that was persisted above. Re-reading
// the path here would race concurrent POSTs (request A could load B and
// falsely report that A was applied).
const apply = await oneBotManager.reloadConfig(uin, body as OneBotConfig);
const apply = await oneBotManager.reloadConfig(uin, nextConfig);
const message = !apply.online
? '配置保存成功,当前会话未在线,将在下次连接时生效。'
: apply.applied
@@ -1530,26 +1572,21 @@ export async function initWebUI(
);
});
const finalPort = await findAvailablePort(desiredPort);
const host = listener.host || '127.0.0.1';
const finalPort = await findAvailablePort(desiredPort, { host });
if (finalPort !== desiredPort) {
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
}
boundPort = finalPort;
const host = listener.host || '0.0.0.0';
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
// TLS is an explicit transport promise. Once enabled, an unusable pair must
// abort startup instead of silently exposing the listener over plaintext.
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
let scheme = 'http';
if (listener.tlsEnabled) {
const tls = resolveTlsContext('config');
if (tls.ok && tls.cert && tls.key) {
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
scheme = 'https';
} else {
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
}
const tls = requireTlsContext('config');
tlsServe = { createServer: createHttpsServer, serverOptions: tls };
scheme = 'https';
}
await new Promise<void>((resolve) => {
+14
View File
@@ -20,6 +20,11 @@ export interface TlsResolution {
reason?: string;
}
export interface RequiredTlsContext {
cert: Buffer;
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
@@ -55,3 +60,12 @@ export function resolveTlsContext(configDir: string): TlsResolution {
if (!valid.ok) return { ok: false, reason: valid.reason };
return { ok: true, cert, key };
}
/** Resolve the configured pair for an enabled listener or abort startup. */
export function requireTlsContext(configDir: string): RequiredTlsContext {
const resolved = resolveTlsContext(configDir);
if (!resolved.ok || !resolved.cert || !resolved.key) {
throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`);
}
return { cert: resolved.cert, key: resolved.key };
}
+4
View File
@@ -128,6 +128,8 @@ export interface MockBridge {
findUidByUin: ReturnType<typeof vi.fn>;
findUinByUid: ReturnType<typeof vi.fn>;
findGroupMember: ReturnType<typeof vi.fn>;
updateFriendRemark: ReturnType<typeof vi.fn>;
updateGroupRemark: ReturnType<typeof vi.fn>;
forgetGroup: ReturnType<typeof vi.fn>;
};
events: { emit: ReturnType<typeof vi.fn> };
@@ -160,6 +162,8 @@ export function mockBridge(overrides: Partial<MockBridge> = {}): MockBridge {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
...(overrides.identity ?? {}),
} as MockBridge['identity'],
@@ -8,6 +8,7 @@ import type {
OidbFriendCategory,
OidbRobotUinRangeResponse,
OidbSvcTrpcTcp0xFD4_1Response,
OidbSvcTrpcTcp0xFE5_2Response,
OidbSvcTrpcTcp0xFE7_3Response,
} from '@snowluma/proto-defs/oidb';
import type {
@@ -86,6 +87,18 @@ function memberListPacket(body: OidbSvcTrpcTcp0xFE7_3Response): SendPacketResult
};
}
function groupListPacket(body: OidbSvcTrpcTcp0xFE5_2Response): SendPacketResult {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0xFE5_2Response>>({ body }),
),
};
}
function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) {
let index = 0;
const sendRawPacket = vi.fn(async (
@@ -131,6 +144,34 @@ function apiForCategoryChange(roster: OidbSvcTrpcTcp0xFD4_1Response) {
return { api, sendRawPacket };
}
describe('apis/contacts / group roster', () => {
it('maps QQ group remarks into the returned and remembered roster', async () => {
const rememberGroups = vi.fn();
const sendRawPacket = vi.fn(async () => groupListPacket({
groups: [{
groupUin: 123456789,
info: { groupName: 'Project', memberCount: 42, memberMax: 500 },
customInfo: { remark: ' My Project ' },
}],
}));
const api = new ContactsApi({
sendRawPacket,
identity: { rememberGroups },
} as any);
const groups = await api.fetchGroupList();
expect(groups).toEqual([expect.objectContaining({
groupId: 123456789,
groupName: 'Project',
remark: ' My Project ',
memberCount: 42,
memberMax: 500,
})]);
expect(rememberGroups).toHaveBeenCalledWith(groups);
});
});
describe('apis/contacts / categorized friend roster', () => {
it('keeps fetchFriendList flat while traversing cookie pages', async () => {
const cookie = Uint8Array.from([0x01]);
+20 -2
View File
@@ -1,10 +1,11 @@
import { describe, it, expect, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { protobuf_decode } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbDeleteFriend,
OidbFriendRequestAction,
OidbSetFriendRemarkResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
// Post-namespace migration: FriendApi is a thin facade over the
@@ -65,10 +66,27 @@ describe('apis/friend', () => {
});
it('setRemark uses the current set command for a non-empty remark', async () => {
const bridge = mockBridge();
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<OidbBase<OidbSetFriendRemarkResponse>>({
body: {
result: {
target: { targetUid: 'resolved-uid', targetUin: 10001n },
remark: 'best-friend',
},
},
})),
})),
});
await new FriendApi(bridge as any).setRemark(10001, 'best-friend');
expect(bridge.sendRawPacket.mock.calls[0]![0])
.toBe('OidbSvcTrpcTcp.0x912e_0');
expect(bridge.identity.updateFriendRemark)
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
});
it('setRemark uses the dedicated clear command for an empty remark', async () => {
@@ -328,6 +328,8 @@ describe('apis/group-file', () => {
findUidByUin: vi.fn(() => 'cached-uid'),
findUinByUid: vi.fn(() => 0),
findGroupMember: vi.fn(() => null),
updateFriendRemark: vi.fn(() => true),
updateGroupRemark: vi.fn(() => true),
forgetGroup: vi.fn(),
},
});
@@ -0,0 +1,101 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FlashTransferApi } from '../src/bridge/apis/flash-transfer';
const FILESET_ID = '8e40afa1-829d-498b-852f-092394ddb31f';
const SHARE_HTML = `<script>window.__DATA__={"fileset_id":"${FILESET_ID}"}</script>`;
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
function api(): FlashTransferApi {
return new FlashTransferApi({} as never);
}
describe('FlashTransferApi.getFilesetIdByCode', () => {
it('resolves a plain share code through the canonical production page', async () => {
const fetchMock = vi.fn(async (..._args: Parameters<typeof fetch>) => (
new Response(SHARE_HTML, { status: 200 })
));
globalThis.fetch = fetchMock as typeof fetch;
await expect(api().getFilesetIdByCode('K0sEqhYria')).resolves.toBe(FILESET_ID);
expect(fetchMock).toHaveBeenCalledOnce();
expect(fetchMock.mock.calls[0]?.[0]).toBe('https://qfile.qq.com/q/K0sEqhYria');
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ redirect: 'manual' });
expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal);
});
it('accepts the production HTTPS share URL and removes nonessential URL parts', async () => {
const fetchMock = vi.fn(async (..._args: Parameters<typeof fetch>) => (
new Response(SHARE_HTML, { status: 200 })
));
globalThis.fetch = fetchMock as typeof fetch;
await expect(
api().getFilesetIdByCode('HTTPS://QFILE.QQ.COM:443/q/K0sEqhYria?from=copy#copied'),
).resolves.toBe(FILESET_ID);
expect(fetchMock.mock.calls[0]?.[0]).toBe('https://qfile.qq.com/q/K0sEqhYria');
});
it.each([
'http://qfile.qq.com/q/K0sEqhYria',
'https://qfile.qq.com.evil.example/q/K0sEqhYria',
'https://user@qfile.qq.com/q/K0sEqhYria',
'https://qfile.qq.com:444/q/K0sEqhYria',
'https://qfile.qq.com/not-a-share/K0sEqhYria',
'https://test.qfile.qq.com/q/K0sEqhYria',
'https://qfile.qq.com./q/K0sEqhYria',
'//127.0.0.1/private',
])('rejects a non-production share URL before fetching: %s', async (input) => {
const fetchMock = vi.fn<typeof fetch>();
globalThis.fetch = fetchMock as typeof fetch;
await expect(api().getFilesetIdByCode(input)).rejects.toThrow(/official QQ share URL/i);
expect(fetchMock).not.toHaveBeenCalled();
});
it('rejects encoded path separators instead of reinterpreting them as a code', async () => {
const fetchMock = vi.fn<typeof fetch>();
globalThis.fetch = fetchMock as typeof fetch;
await expect(
api().getFilesetIdByCode('https://qfile.qq.com/q/%2F%2F127.0.0.1%2Fprivate'),
).rejects.toThrow(/invalid share code/i);
expect(fetchMock).not.toHaveBeenCalled();
});
it('does not follow redirects returned by the share page', async () => {
globalThis.fetch = vi.fn(async () => new Response(null, {
status: 302,
headers: { Location: 'http://127.0.0.1/private' },
})) as typeof fetch;
await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/redirect/i);
});
it('rejects an oversized streamed share page even if it contains an id', async () => {
const oversized = `${SHARE_HTML}${'x'.repeat(2 * 1024 * 1024)}`;
globalThis.fetch = vi.fn(async () => new Response(oversized, { status: 200 })) as typeof fetch;
await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/too large/i);
});
it('rejects an oversized declared response before reading its body', async () => {
let cancelled = false;
const body = new ReadableStream<Uint8Array>({
cancel() {
cancelled = true;
},
});
globalThis.fetch = vi.fn(async () => new Response(body, {
status: 200,
headers: { 'Content-Length': String(2 * 1024 * 1024 + 1) },
})) as typeof fetch;
await expect(api().getFilesetIdByCode('K0sEqhYria')).rejects.toThrow(/too large/i);
expect(cancelled).toBe(true);
});
});
@@ -214,6 +214,102 @@ describe('IdentityService', () => {
}
});
it('keeps friend remark updates after reopening the persistent cache', () => {
const dbPath = tempDbPath('update-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'friend',
remark: 'old-remark',
}]);
expect(identity.updateFriendRemark('u_friend', 22222, 'new-remark')).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
identity.close();
}
});
it('keeps exact group remark updates after reopening the persistent cache', () => {
const dbPath = tempDbPath('update-group-remark');
const remark = ' project group ';
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberGroups([{ ...makeGroup(), remark: 'old-remark' }]);
expect(identity.updateGroupRemark(GROUP_ID, remark)).toBe(true);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findGroup(GROUP_ID)?.remark).toBe(remark);
identity.close();
}
});
it('does not invent a group while applying a remark update', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([makeGroup()]);
expect(identity.updateGroupRemark(987654321, 'unknown')).toBe(false);
expect(identity.groups).toHaveLength(1);
expect(identity.findGroup(GROUP_ID)?.remark).toBe('');
expect(identity.findGroup(987654321)).toBeNull();
identity.close();
});
it.each([
['empty', ''],
['whitespace-only', ' '],
['surrounding-whitespace', ' padded remark '],
])('preserves %s friend remarks exactly after reopening', (_label, remark) => {
const dbPath = tempDbPath('exact-friend-remark');
{
const identity = new IdentityService(SELF_UIN, dbPath);
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'friend',
remark: 'old-remark',
}]);
expect(identity.updateFriendRemark('u_friend', 22222, remark)).toBe(true);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
}
{
const identity = new IdentityService(SELF_UIN, dbPath);
expect(identity.findFriend(22222)?.remark).toBe(remark);
identity.close();
}
});
it('rejects conflicting friend identities before mutating the roster', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberFriends([
{ uin: 22222, uid: 'u_first', nickname: 'first', remark: 'first-remark' },
{ uin: 33333, uid: 'u_second', nickname: 'second', remark: 'second-remark' },
]);
expect(() => identity.updateFriendRemark('u_first', 33333, 'wrong'))
.toThrow(/identity mismatch/);
expect(identity.findFriend(22222)?.remark).toBe('first-remark');
expect(identity.findFriend(33333)?.remark).toBe('second-remark');
});
it('keeps a failed observation in memory, reports degraded, and retries to healthy', async () => {
vi.useFakeTimers();
const dbPath = tempDbPath('retry-recovery');
@@ -684,6 +780,7 @@ describe('IdentityService', () => {
['nickname', () => { identity.nickname = 'after-close'; }],
['self profile', () => identity.setSelfProfile(profile)],
['group member update', () => identity.updateGroupMember(GROUP_ID, { ...member, card: 'after-close' })],
['group remark update', () => identity.updateGroupRemark(GROUP_ID, 'after-close')],
['friends', () => identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: '', remark: '' }])],
['groups', () => identity.rememberGroups([])],
['forget group', () => identity.forgetGroup(GROUP_ID)],
+68 -2
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { parseMsgPush, MSG_PUSH_CMD } from '@snowluma/protocol/msg-push';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
// Proton's call-site analyzer keys off the literal type identifier
// printed in `protobuf_encode<X>` — it walks imports by *original*
@@ -15,7 +17,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type {
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange,
OnlineDeviceNotify, ProfileLikeTip,
OnlineDeviceNotify, ProfileLikeTip, FriendRemarkChangedNotify,
} from '@snowluma/proto-defs/notify';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
@@ -440,6 +442,70 @@ describe('parseMsgPush Event0x210 subType=179/226 (NewFriend → friend_add)', (
});
});
describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)', () => {
function makeFriendRemarkPacket(
uid: string,
uin: number,
remark: string,
): PacketInfo {
const content = protobuf_encode<FriendRemarkChangedNotify>({
change: {
target: { uid, uin: BigInt(uin) },
remark,
},
updateTime: 1710000000,
nickname: 'Alice',
changeType: 1,
});
return makeEvent0x210PacketAny(364, content);
}
it('decodes a pure internal synchronization event', () => {
const identity = makeIdentity();
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'Alice',
remark: 'old-remark',
}]);
expect(parseMsgPush(
makeFriendRemarkPacket('u_friend', 22222, 'new-remark'),
identity,
)).toEqual([{
kind: 'friend_remark_changed',
time: 1710000000,
selfUin: Number(SELF_UIN),
userUid: 'u_friend',
userUin: 22222,
remark: 'new-remark',
}]);
expect(identity.findFriend(22222)?.remark).toBe('old-remark');
});
it('applies the synchronization at the packet-pipeline boundary', async () => {
const identity = makeIdentity();
identity.rememberFriends([{
uin: 22222,
uid: 'u_friend',
nickname: 'Alice',
remark: 'old-remark',
}]);
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
resolveStrangerProfile: vi.fn(async () => null),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
await pipeline.process(makeFriendRemarkPacket('u_friend', 22222, 'new-remark'));
expect(identity.findFriend(22222)?.remark).toBe('new-remark');
});
});
describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输入)', () => {
// RE'd from wrapper.linux.node aio_input_state_worker.cc: 0x210/0x115 sys_msg,
// body = InputStatusNotify {fromUid, toUid, notifyItem{eventType@f4}}.
@@ -160,7 +160,11 @@ describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () =>
const mod = await import('../src/notifications/config');
const cfg = mod.loadNotificationsConfig();
expect(cfg).toEqual(mod.defaultNotificationsConfig());
expect(fs.existsSync(path.join('config', 'notifications.json'))).toBe(true);
const file = path.join('config', 'notifications.json');
expect(fs.existsSync(file)).toBe(true);
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('round-trips a saved config across a fresh module load', async () => {
@@ -177,6 +181,42 @@ describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () =>
expect(mod2.loadNotificationsConfig()).toEqual(saved);
});
it('repairs permissive permissions on an existing sensitive config', async () => {
const file = path.join('config', 'notifications.json');
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(file, JSON.stringify({
version: 1,
debounceSeconds: 30,
channels: [{ id: 'ops', url: 'https://example.com/private-hook' }],
}), { encoding: 'utf8', mode: 0o644 });
if (process.platform !== 'win32') fs.chmodSync(file, 0o644);
const mod = await import('../src/notifications/config');
expect(mod.loadNotificationsConfig().channels).toHaveLength(1);
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('keeps restrictive permissions after replacing an existing config', async () => {
const file = path.join('config', 'notifications.json');
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(file, JSON.stringify({ version: 1, debounceSeconds: 30, channels: [] }), {
encoding: 'utf8',
mode: 0o644,
});
if (process.platform !== 'win32') fs.chmodSync(file, 0o644);
const mod = await import('../src/notifications/config');
mod.saveNotificationsConfig({
channels: [{ id: 'ops', url: 'https://example.com/private-hook' }],
});
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('section-merges partial saves (debounce-only keeps channels)', async () => {
const mod = await import('../src/notifications/config');
mod.saveNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import { makeDefaultOneBotConfig } from '@snowluma/onebot/config';
import {
OneBotAccessTokenPolicyError,
validateOneBotAccessTokenChanges,
} from '../src/webui/onebot-token-policy';
function validate(
previous: ReturnType<typeof makeDefaultOneBotConfig> | null,
next: ReturnType<typeof makeDefaultOneBotConfig>,
clientIp: string,
): void {
validateOneBotAccessTokenChanges(previous, next, { clientIp, uin: '10001' });
}
describe('OneBot access token save policy', () => {
it('rejects clearing an inbound token from a non-loopback client', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
expect(() => validate(previous, next, '192.0.2.10')).toThrow(/本机/);
});
it('treats every inbound token as new when no readable prior config exists', () => {
const next = makeDefaultOneBotConfig();
next.networks.httpServers[0].accessToken = undefined;
expect(() => validate(null, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
});
it('allows a loopback client to deliberately clear an inbound token', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.wsServers[0].accessToken = undefined;
expect(() => validate(previous, next, '127.0.0.2')).not.toThrow();
});
it('rejects a newly changed weak inbound token', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpServers[0].accessToken = 'SnowLumaSnowLuma';
expect(() => validate(previous, next, '127.0.0.1')).toThrow(/容易被猜中/);
});
it('does not strand installations whose legacy token is unchanged', () => {
const previous = makeDefaultOneBotConfig();
previous.networks.httpServers[0].accessToken = 'legacy';
const next = structuredClone(previous);
next.networks.httpServers[0].name = 'renamed-http';
next.networks.httpServers[0].port = 3100;
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('allows remote edits that leave an existing empty inbound token unchanged', () => {
const previous = makeDefaultOneBotConfig();
previous.networks.httpServers[0].accessToken = undefined;
const next = structuredClone(previous);
next.networks.httpServers[0].port = 3100;
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('preserves legacy tokens when existing endpoints are reordered by name', () => {
const previous = makeDefaultOneBotConfig();
previous.networks.httpServers[0].accessToken = 'legacy';
previous.networks.httpServers.push({
...previous.networks.httpServers[0],
name: 'second-http',
port: 3100,
});
const next = structuredClone(previous);
next.networks.httpServers.reverse();
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('does not mistake an inserted endpoint for a renamed legacy endpoint', () => {
const previous = makeDefaultOneBotConfig();
previous.networks.httpServers[0].accessToken = 'legacy';
const next = structuredClone(previous);
next.networks.httpServers.unshift({
...next.networks.httpServers[0],
name: 'new-http',
port: 3100,
});
expect(() => validate(previous, next, '192.0.2.10')).toThrow(OneBotAccessTokenPolicyError);
});
it('does not impose local inbound-token policy on outbound adapters', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.httpClients.push({
name: 'remote-service',
url: 'https://example.com/events',
accessToken: 'remote-chosen-token',
messageFormat: 'array',
reportSelfMessage: false,
});
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
it('accepts a newly changed strong inbound token', () => {
const previous = makeDefaultOneBotConfig();
const next = structuredClone(previous);
next.networks.wsServers[0].accessToken = 'E5xqVb7_9pLt2QwR4M8kZ1nY';
expect(() => validate(previous, next, '192.0.2.10')).not.toThrow();
});
});
+28 -8
View File
@@ -27,9 +27,10 @@ describe('buildBackup', () => {
expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' });
});
it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => {
it('treats notification endpoints and all authentication material as credentials', () => {
const map = {
'runtime.json': Buffer.from('{}'),
'notifications.json': Buffer.from('{"channels":[]}'),
'webui.json': Buffer.from('{"hash":"x"}'),
'key.pem': Buffer.from('KEY'),
'cert.pem': Buffer.from('CERT'),
@@ -42,7 +43,7 @@ describe('buildBackup', () => {
expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']);
const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS);
expect(Object.keys(withCreds.files).sort()).toEqual(
['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
['cert.pem', 'key.pem', 'notifications.json', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
);
});
@@ -61,6 +62,7 @@ describe('buildBackup', () => {
describe('specFor', () => {
it('resolves static names and per-uin onebot pattern; rejects others', () => {
expect(specFor('runtime.json')?.credential).toBe(false);
expect(specFor('notifications.json')?.credential).toBe(true);
expect(specFor('onebot.json')?.credential).toBe(true);
expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true });
expect(specFor('onebot_.json')).toBeNull();
@@ -71,9 +73,9 @@ describe('specFor', () => {
});
});
it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => {
it('BACKUP_FILES marks notification endpoints and authentication material as credentials', () => {
const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort();
expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']);
expect(creds).toEqual(['key.pem', 'notifications.json', 'onebot.json', 'webui.json']);
expect(specFor('cert.pem')?.credential).toBe(false);
});
@@ -111,7 +113,7 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({
webuiPort: 5099,
hookAutoLoad: false,
webuiHost: '0.0.0.0',
webuiHost: '127.0.0.1',
webuiTls: { enabled: false },
trustProxy: '',
logMaxTotalMb: 1024,
@@ -156,10 +158,23 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
}),
},
}),
{ restoreCredentials: false, readCurrent: () => null },
{ restoreCredentials: true, readCurrent: () => null },
)).toThrow(/notifications\.json.*channels/i);
});
it('skips notification endpoints when credential restore is disabled', () => {
const prepared = prepareRestorePlan(
backupWith({
'notifications.json': { encoding: 'utf8', data: '{private malformed value' },
'runtime.json': { encoding: 'utf8', data: '{}' },
}),
{ restoreCredentials: false, readCurrent: () => null },
);
expect(prepared.skipped).toEqual(['notifications.json']);
expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']);
});
it('does not validate credential files that the operator chose to skip', () => {
const prepared = prepareRestorePlan(
backupWith({
@@ -278,13 +293,18 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
const prepared = prepareRestorePlan(
backupWith({
'webui.json': { encoding: 'utf8', data: JSON.stringify(validAuth) },
'notifications.json': {
encoding: 'utf8',
data: JSON.stringify({ version: 1, debounceSeconds: 30, channels: [] }),
},
}),
{ restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] },
);
expect(prepared.restore).toEqual([
expect(prepared.restore).toEqual(expect.arrayContaining([
expect.objectContaining({ name: 'webui.json', mode: 0o600 }),
]);
expect.objectContaining({ name: 'notifications.json', mode: 0o600 }),
]));
});
it('rejects an encoding that does not match the allowlisted file kind', () => {
@@ -1,11 +1,24 @@
import { describe, expect, it } from 'vitest';
import {
describeTrustProxy,
isLoopbackClientIp,
parseTrustProxy,
pickClientIp,
type TrustProxyMode,
} from '../src/webui/client-ip';
describe('isLoopbackClientIp', () => {
it.each(['127.0.0.1', '127.0.0.2', '::1', '0:0:0:0:0:0:0:1', '::ffff:127.0.0.9'])(
'accepts loopback address %s',
(address) => expect(isLoopbackClientIp(address)).toBe(true),
);
it.each(['', 'localhost', '0.0.0.0', '192.168.1.2', '::ffff:192.168.1.2'])(
'rejects non-loopback or unverified address %s',
(address) => expect(isLoopbackClientIp(address)).toBe(false),
);
});
function mockCtx(headers: Record<string, string> = {}) {
return {
req: {
@@ -79,6 +92,23 @@ describe('pickClientIp', () => {
const mode: TrustProxyMode = { kind: 'none' };
expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1');
});
it('can fail closed when a security decision cannot resolve the socket peer', () => {
const mode: TrustProxyMode = { kind: 'none' };
expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); }, '')).toBe('');
});
it('does not trust forwarded headers when the socket peer is unknown', () => {
const mode: TrustProxyMode = { kind: 'all' };
expect(
pickClientIp(
mockCtx({ 'x-real-ip': '127.0.0.1' }),
mode,
() => { throw new Error('boom'); },
'',
),
).toBe('');
});
});
describe('describeTrustProxy', () => {
@@ -0,0 +1,97 @@
import { Hono } from 'hono';
import { describe, expect, it } from 'vitest';
import {
clearAvatarSessionCookie,
extractBearerToken,
LOGIN_BODY_LIMIT_BYTES,
readAvatarSessionToken,
registerLoginRequestSecurity,
setAvatarSessionCookie,
webuiSecurityHeaders,
} from '../src/webui/request-security';
describe('WebUI public request security', () => {
it('rejects an oversized login body before JSON parsing', async () => {
const app = new Hono();
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
app.post('/api/login', async (c) => c.json(await c.req.json()));
const response = await app.request('/api/login', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ password: 'x'.repeat(LOGIN_BODY_LIMIT_BYTES) }),
});
expect(response.status).toBe(413);
expect(response.headers.get('x-frame-options')).toBe('DENY');
await expect(response.json()).resolves.toMatchObject({ success: false });
});
it('accepts normal JSON login requests and rejects misleading content types', async () => {
const app = new Hono();
registerLoginRequestSecurity(app);
app.post('/api/login', async (c) => c.json(await c.req.json()));
const accepted = await app.request('/api/login', {
method: 'POST',
headers: { 'content-type': 'application/problem+json' },
body: JSON.stringify({ password: 'normal-password' }),
});
const rejected = await app.request('/api/login', {
method: 'POST',
headers: { 'content-type': 'text/plain' },
body: JSON.stringify({ password: 'normal-password' }),
});
expect(accepted.status).toBe(200);
expect(rejected.status).toBe(415);
});
it('never treats a query parameter as a bearer credential', () => {
expect(extractBearerToken(new Request('http://localhost/api/state/stream?token=leaked'))).toBe('');
expect(extractBearerToken(new Request('http://localhost/api/state/stream', {
headers: { authorization: 'Bearer header-token' },
}))).toBe('header-token');
});
it('round-trips an HttpOnly avatar session cookie and clears it on logout', async () => {
const app = new Hono();
app.get('/set', (c) => {
setAvatarSessionCookie(c, 'session-token', false);
return c.text('ok');
});
app.get('/read', (c) => c.text(readAvatarSessionToken(c)));
app.get('/clear', (c) => {
clearAvatarSessionCookie(c, false);
return c.text('ok');
});
const setResponse = await app.request('/set');
const setCookie = setResponse.headers.get('set-cookie') ?? '';
expect(setCookie).toContain('HttpOnly');
expect(setCookie).toContain('SameSite=Strict');
expect(setCookie).toContain('Path=/avatar');
const cookie = setCookie.split(';', 1)[0];
const readResponse = await app.request('/read', { headers: { cookie } });
expect(await readResponse.text()).toBe('session-token');
const clearResponse = await app.request('/clear');
expect(clearResponse.headers.get('set-cookie')).toMatch(/Max-Age=0/i);
});
it('adds security headers without imposing a script or style policy', async () => {
const app = new Hono();
app.use('*', webuiSecurityHeaders);
app.get('/', (c) => c.html('<main>SnowLuma</main>'));
const response = await app.request('/');
expect(response.headers.get('x-frame-options')).toBe('DENY');
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
expect(response.headers.get('referrer-policy')).toBe('no-referrer');
expect(response.headers.get('content-security-policy')).toBe(
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
);
});
});
@@ -1,24 +1,19 @@
import { describe, expect, it } from 'vitest';
import { SSE_TOKEN_QUERY_PATHS } from '../src/webui/server';
import { extractBearerToken } from '../src/webui/request-security';
// Regression lock for a class of bug that has bricked an SSE endpoint
// before: EventSource cannot set Authorization headers, so every SSE
// path MUST appear in this allowlist or the auth middleware computes
// `queryToken = ''` and 401s every connect. A missing entry is silent —
// the only symptom is "live updates don't work, refresh fixes it" — so
// keep this list short and verified.
describe('SSE_TOKEN_QUERY_PATHS', () => {
it('contains every SSE stream the WebUI subscribes to', () => {
expect(SSE_TOKEN_QUERY_PATHS.has('/api/logs/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/debug/stream')).toBe(true);
expect(SSE_TOKEN_QUERY_PATHS.has('/api/state/stream')).toBe(true);
describe('WebUI stream authentication', () => {
it('accepts bearer credentials for every live stream', () => {
for (const path of ['/api/logs/stream', '/api/debug/stream', '/api/state/stream']) {
const request = new Request(`http://localhost${path}`, {
headers: { authorization: 'Bearer stream-token' },
});
expect(extractBearerToken(request)).toBe('stream-token');
}
});
it('does NOT carry any non-stream endpoint — token-via-query is reserved for SSE', () => {
// The auth middleware accepts `?token=...` for these paths only; any
// bearer-only endpoint listed here would leak tokens via access logs.
for (const path of SSE_TOKEN_QUERY_PATHS) {
expect(path.endsWith('/stream')).toBe(true);
it('does not accept tokens from stream query parameters', () => {
for (const path of ['/api/logs/stream', '/api/debug/stream', '/api/state/stream']) {
expect(extractBearerToken(new Request(`http://localhost${path}?token=leaked`))).toBe('');
}
});
});
+18 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { validateTlsPair, resolveTlsContext } from '../src/webui/tls';
import { requireTlsContext, validateTlsPair, resolveTlsContext } from '../src/webui/tls';
// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext
// only parses — expiry is irrelevant — so this stays valid for the test forever.
@@ -99,4 +99,21 @@ describe('resolveTlsContext', () => {
expect(r.ok).toBe(false);
expect(r.reason).toBeTruthy();
});
it('refuses to start an enabled TLS listener with an unusable certificate pair', () => {
expect(() => requireTlsContext(dir)).toThrow(/TLS.*missing/i);
fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage');
fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage');
expect(() => requireTlsContext(dir)).toThrow(/TLS.*invalid/i);
});
it('returns a validated certificate pair for an enabled TLS listener', () => {
fs.writeFileSync(path.join(dir, 'cert.pem'), CERT);
fs.writeFileSync(path.join(dir, 'key.pem'), KEY);
const tls = requireTlsContext(dir);
expect(tls.cert.toString()).toContain('BEGIN CERTIFICATE');
expect(tls.key.toString()).toContain('PRIVATE KEY');
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.13.0",
"version": "1.14.0",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+5 -3
View File
@@ -3038,7 +3038,7 @@
{
"name": "get_fileset_id",
"aliases": [],
"summary": "从分享码/链接获取 fileset_id",
"summary": "从 QQ 闪传分享码或官方分享链接获取 fileset_id",
"returns": "{ fileset_id }:解析出的文件集 ID。",
"returnsSchema": {
"type": "object",
@@ -3061,7 +3061,8 @@
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接"
}
],
"invariants": [],
@@ -3070,7 +3071,8 @@
"properties": {
"share_code": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接"
}
},
"required": [
+5 -3
View File
@@ -3041,7 +3041,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_fileset_id",
"aliases": [],
"summary": "从分享码/链接获取 fileset_id",
"summary": "从 QQ 闪传分享码或官方分享链接获取 fileset_id",
"returns": "{ fileset_id }:解析出的文件集 ID。",
"returnsSchema": {
"type": "object",
@@ -3064,7 +3064,8 @@ export const ACTIONS: CatalogAction[] = [
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接"
}
],
"invariants": [],
@@ -3073,7 +3074,8 @@ export const ACTIONS: CatalogAction[] = [
"properties": {
"share_code": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接"
}
},
"required": [
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
+25 -10
View File
@@ -82,18 +82,30 @@ function essenceContentToSegment(content: GroupEssenceContent): JsonObject {
url: essenceString(content.image_url, 'msg_content.image_url', false),
},
};
case 4:
case 4: {
const fileName = essenceString(content.file_name, 'msg_content.file_name', false);
const fileId = essenceString(content.file_id, 'msg_content.file_id', false);
const fileSize = essenceNonNegativeNumber(
content.file_size,
'msg_content.file_size',
);
const busId = essenceNonNegativeNumber(
content.file_bus_id,
'msg_content.file_bus_id',
);
return {
type: 'video',
type: 'file',
data: {
file: '',
url: essenceString(
content.file_thumbnail_url,
'msg_content.file_thumbnail_url',
false,
),
file: fileName,
file_id: fileId,
file_size: fileSize,
name: fileName,
id: fileId,
size: fileSize,
busid: busId,
},
};
}
default:
throw new Error(`unsupported group essence content type: ${content.msg_type}`);
}
@@ -2593,7 +2605,7 @@ export const actions = [
defineAction({
name: 'get_fileset_id',
summary: '从分享码/链接获取 fileset_id',
summary: '从 QQ 闪传分享码或官方分享链接获取 fileset_id',
readOnly: true,
returns: '{ fileset_id }:解析出的文件集 ID。',
returnsSchema: {
@@ -2603,7 +2615,10 @@ export const actions = [
},
required: ['fileset_id'],
},
params: { share_code: f.string({ allowEmpty: false }) },
params: {
share_code: f.string({ allowEmpty: false })
.describe('QQ 闪传分享码,或 https://qfile.qq.com/q/... 官方分享链接'),
},
run: async (p, ctx) => {
const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code);
return okResponse({ fileset_id: filesetId });
@@ -26,7 +26,11 @@ import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming';
import { STREAM_ROOT, registerActiveStreamItem } from '../stream-storage';
import {
STREAM_ROOT,
ensureStreamDirectory,
registerActiveStreamItem,
} from '../stream-storage';
const DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size
@@ -224,6 +228,7 @@ async function resolveDownload(
let st: fs.Stats | null = null;
try { st = fs.statSync(local); } catch { st = null; }
if (st?.isFile()) {
ensureStreamDirectory(STREAM_ROOT);
// Fence against the *real* path so a symlink inside the root can't point
// out (lexical resolve alone would follow it).
let real = local;
+2 -1
View File
@@ -30,6 +30,7 @@ import {
STREAM_ROOT,
STREAM_UPLOAD_DIR,
clearInactiveStreamStorage,
ensureStreamDirectory,
registerActiveStreamItem,
} from '../stream-storage';
@@ -149,7 +150,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`);
assertWithin(STREAM_UPLOAD_DIR, tempDir);
assertWithin(STREAM_UPLOAD_DIR, finalPath);
fs.mkdirSync(tempDir, { recursive: true });
ensureStreamDirectory(tempDir);
const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
+2 -2
View File
@@ -45,7 +45,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
networks: {
httpServers: [{
name: 'http-default',
host: '0.0.0.0',
host: '127.0.0.1',
port: 3000,
path: '/',
enableWebSocket: false,
@@ -56,7 +56,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
httpClients: [],
wsServers: [{
name: 'ws-default',
host: '0.0.0.0',
host: '127.0.0.1',
port: 3001,
path: '/',
role: 'Universal',
@@ -105,6 +105,8 @@ const CONVERTERS: ConverterRegistry = {
ptt_trans_result: null,
// Internal-only cache snapshot consumed by Bridge.getOnlineClients().
online_devices_changed: null,
// Internal-only identity synchronization from another QQ client.
friend_remark_changed: null,
};
export async function convertEvent(
@@ -160,7 +160,11 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
let webSocketServer: WebSocketServer | null = null;
try {
if (this.config.enableWebSocket === true) {
webSocketServer = new WebSocketServer({ server });
webSocketServer = new WebSocketServer({
server,
verifyClient: ({ req }: { req: IncomingMessage }) =>
this.webSocketConnections.authorizeUpgrade(req),
});
webSocketServer.on('connection', (socket, request) => {
this.webSocketConnections.accept(socket, request);
});
@@ -1,5 +1,6 @@
import { WebSocketServer } from '@snowluma/websocket';
import { createLogger } from '@snowluma/common/logger';
import type { IncomingMessage } from 'node:http';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
@@ -105,6 +106,8 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: normalizePath(this.config.path),
verifyClient: ({ req }: { req: IncomingMessage }) =>
this.connections.authorizeUpgrade(req),
});
} catch (error) {
this.recordTransportFailure(error);
@@ -110,12 +110,20 @@ export class WsServerConnections {
}
}
/** Authenticate the HTTP upgrade before a WebSocket object is allocated. */
authorizeUpgrade(request: IncomingMessage): boolean {
const authorized = isAuthorized(request, this.config.accessToken ?? '');
if (!authorized) this.log.debug('[%s] rejected unauthorized WebSocket upgrade', this.name);
return authorized;
}
accept(socket: WebSocket, request: IncomingMessage): void {
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
safeClose(socket, 1012, 'server closing');
return;
}
if (!isAuthorized(request, this.config.accessToken ?? '')) {
// Defence in depth for custom/future listeners that bypass verifyClient.
if (!this.authorizeUpgrade(request)) {
safeClose(socket, 1008, 'invalid access token');
return;
}
+77 -20
View File
@@ -24,11 +24,32 @@ export class StreamStorage {
private nextActiveItemId = 1;
constructor(root: string) {
this.root = resolveWithExistingAncestor(root);
this.root = resolveManagedRoot(root);
this.uploadDir = path.join(this.root, 'upload');
this.downloadDir = path.join(this.root, 'download');
}
/**
* Create a directory inside the managed root without following a substituted
* directory link. Existing directories remain usable when they belong to the
* current account and cannot be modified by other local accounts.
*/
ensureDirectory(directory: string): void {
const resolved = path.resolve(directory);
if (resolved !== this.root && !isStrictDescendant(this.root, resolved)) {
throw new Error(`stream directory is outside the managed root: ${directory}`);
}
let current = this.root;
ensureManagedDirectory(current);
const relative = path.relative(this.root, resolved);
if (!relative) return;
for (const segment of relative.split(path.sep)) {
current = path.join(current, segment);
ensureManagedDirectory(current);
}
}
registerActiveItem(paths: string[]): () => void {
const normalized = paths.map((item) => {
const resolved = path.resolve(item);
@@ -91,9 +112,7 @@ export class StreamStorage {
private assertRootDirectoryOrMissing(): boolean {
try {
const stat = fs.lstatSync(this.root);
if (!stat.isDirectory()) {
throw new Error(`managed stream root is not a directory: ${this.root}`);
}
assertManagedDirectory(this.root, stat);
return true;
} catch (error) {
if (isMissing(error)) return false;
@@ -201,23 +220,57 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveWithExistingAncestor(input: string): string {
let existing = path.resolve(input);
const suffix: string[] = [];
while (true) {
try {
fs.lstatSync(existing);
break;
} catch (error) {
if (!isMissing(error)) throw error;
const parent = path.dirname(existing);
if (parent === existing) throw error;
suffix.unshift(path.basename(existing));
existing = parent;
}
function assertManagedDirectory(directory: string, stat: fs.Stats): void {
if (stat.isSymbolicLink()) {
throw new Error(`managed stream directory must not be a symbolic link: ${directory}`);
}
const canonical = fs.realpathSync(existing);
return path.join(canonical, ...suffix);
if (!stat.isDirectory()) {
throw new Error(`managed stream path is not a directory: ${directory}`);
}
const currentUid = typeof process.getuid === 'function' ? process.getuid() : undefined;
if (currentUid !== undefined && stat.uid !== currentUid) {
throw new Error(`managed stream directory is owned by another account: ${directory}`);
}
if (process.platform !== 'win32' && (stat.mode & 0o022) !== 0) {
throw new Error(`managed stream directory is writable by other accounts: ${directory}`);
}
}
function ensureManagedDirectory(directory: string): void {
let stat: fs.Stats;
try {
stat = fs.lstatSync(directory);
} catch (error) {
if (!isMissing(error)) throw error;
try {
fs.mkdirSync(directory, { mode: 0o700 });
} catch (mkdirError) {
if (!(mkdirError instanceof Error && 'code' in mkdirError && mkdirError.code === 'EEXIST')) {
throw mkdirError;
}
}
stat = fs.lstatSync(directory);
}
assertManagedDirectory(directory, stat);
}
function resolveManagedRoot(input: string): string {
const absolute = path.resolve(input);
try {
const stat = fs.lstatSync(absolute);
assertManagedDirectory(absolute, stat);
return fs.realpathSync(absolute);
} catch (error) {
if (!isMissing(error)) throw error;
}
const parent = path.dirname(absolute);
const parentStat = fs.statSync(parent);
if (!parentStat.isDirectory()) {
throw new Error(`managed stream parent is not a directory: ${parent}`);
}
return path.join(fs.realpathSync(parent), path.basename(absolute));
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream'));
@@ -229,6 +282,10 @@ export function registerActiveStreamItem(paths: string[]): () => void {
return streamStorage.registerActiveItem(paths);
}
export function ensureStreamDirectory(directory: string): void {
streamStorage.ensureDirectory(directory);
}
export function snapshotStreamStorage(): StreamStorageSnapshot {
return streamStorage.snapshot();
}
+6 -2
View File
@@ -18,13 +18,14 @@ describe('makeDefaultOneBotConfig', () => {
const config = makeDefaultOneBotConfig();
expect(config.networks.httpServers).toHaveLength(1);
expect(config.networks.httpServers[0].name).toBe('http-default');
expect(config.networks.httpServers[0].host).toBe('0.0.0.0');
expect(config.networks.httpServers[0].host).toBe('127.0.0.1');
expect(config.networks.httpServers[0].port).toBe(3000);
expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
expect(config.networks.httpServers[0].messageFormat).toBe('array');
expect(config.networks.httpServers[0].reportSelfMessage).toBe(false);
expect(config.networks.httpClients).toEqual([]);
expect(config.networks.wsServers).toHaveLength(1);
expect(config.networks.wsServers[0].host).toBe('127.0.0.1');
expect(config.networks.wsServers[0].port).toBe(3001);
expect(config.networks.wsServers[0].role).toBe('Universal');
expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
@@ -87,6 +88,7 @@ describe('assertValidOneBotConfig', () => {
it('rejects enabled servers with the same normalized host and port', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpServers[0].host = '0.0.0.0';
config.networks.wsServers.push({
name: 'conflicting-ws',
host: '0.0.0.0',
@@ -107,6 +109,7 @@ describe('assertValidOneBotConfig', () => {
expect(() => assertValidOneBotConfig(blank)).toThrow(/\.host/);
const wildcard = makeDefaultOneBotConfig();
wildcard.networks.httpServers[0].host = '0.0.0.0';
wildcard.networks.wsServers.push({
name: 'specific-ws',
host: '127.0.0.1',
@@ -182,13 +185,14 @@ describe('saveOneBotConfig validation boundary', () => {
const config = makeDefaultOneBotConfig();
config.networks.wsServers.push({
name: 'same-bind',
host: '127.0.0.1',
port: 3000,
path: '/ws',
messageFormat: 'array',
reportSelfMessage: false,
});
expect(() => saveOneBotConfig('10001', config)).toThrow(/server binding 0\.0\.0\.0:3000/);
expect(() => saveOneBotConfig('10001', config)).toThrow(/server binding 127\.0\.0\.1:3000/);
expect(fs.existsSync(path.join(tempDir, 'config', 'onebot_10001.json'))).toBe(false);
} finally {
process.chdir(previous);
@@ -80,6 +80,18 @@ function makeTempMessage(senderUin: number): TempMessage {
}
describe('convertEvent — message kinds', () => {
it('keeps friend remark synchronization internal', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_remark_changed',
time: 1700000000,
selfUin: SELF_ID,
userUid: 'u_friend',
userUin: PEER_UIN,
remark: 'new remark',
});
expect(out).toBeNull();
});
it('friend_message peer → post_type "message", sub_type "friend"', async () => {
const out = await convertEvent(bareCtx(), makeFriendMessage(PEER_UIN));
expect(out).not.toBeNull();
+123 -3
View File
@@ -185,6 +185,27 @@ describe('extended-actions / set_self_longnick', () => {
});
});
describe('extended-actions / set_friend_remark', () => {
it('reports a confirmed server rejection instead of returning success', async () => {
const setFriendRemark = vi.fn(async () => {
throw new Error('friend remark was rejected');
});
const bridge = fakeBridge({ setFriendRemark });
const response = await makeHandler(fakeCtx(bridge)).handle('set_friend_remark', {
user_id: 10001,
remark: 'best-friend',
});
expect(setFriendRemark).toHaveBeenCalledWith(10001, 'best-friend');
expect(response).toMatchObject({
status: 'failed',
retcode: 100,
wording: 'friend remark was rejected',
});
});
});
describe('extended-actions / group notice options', () => {
it('coerces and forwards every supported announcement option', async () => {
const sendNotice = vi.fn(async () => ({ ec: 0 }));
@@ -277,6 +298,21 @@ describe('extended-actions / get_essence_msg_list', () => {
});
it('converts every documented digest content type into OneBot segments', async () => {
const plainFile = {
msg_type: 4,
file_name: 'notes.txt',
file_bus_id: 102,
file_id: 'plain-file-id',
file_size: '1234',
};
const previewableFile = {
msg_type: 4,
file_name: 'clip.mp4',
file_bus_id: 102,
file_id: 'video-file-id',
file_thumbnail_url: 'https://example.test/video.jpg',
file_size: '5678',
};
const getEssenceAll = vi.fn(async () => [{
retcode: 0,
data: {
@@ -285,7 +321,8 @@ describe('extended-actions / get_essence_msg_list', () => {
msg_content: [
{ msg_type: 2, face_index: 66 },
{ msg_type: 3, image_url: 'https://example.test/image.jpg' },
{ msg_type: 4, file_thumbnail_url: 'https://example.test/video.jpg' },
plainFile,
previewableFile,
],
})],
},
@@ -299,7 +336,30 @@ describe('extended-actions / get_essence_msg_list', () => {
expect((response.data as JsonObject[])[0]?.content).toEqual([
{ type: 'face', data: { id: '66' } },
{ type: 'image', data: { file: '', url: 'https://example.test/image.jpg' } },
{ type: 'video', data: { file: '', url: 'https://example.test/video.jpg' } },
{
type: 'file',
data: {
file: 'notes.txt',
file_id: 'plain-file-id',
file_size: 1234,
name: 'notes.txt',
id: 'plain-file-id',
size: 1234,
busid: 102,
},
},
{
type: 'file',
data: {
file: 'clip.mp4',
file_id: 'video-file-id',
file_size: 5678,
name: 'clip.mp4',
id: 'video-file-id',
size: 5678,
busid: 102,
},
},
]);
});
@@ -496,7 +556,30 @@ describe('extended-actions / get_essence_msg_list', () => {
[{ msg_type: 1 }, 'msg_content.text'],
[{ msg_type: 2 }, 'msg_content.face_index'],
[{ msg_type: 3 }, 'msg_content.image_url'],
[{ msg_type: 4 }, 'msg_content.file_thumbnail_url'],
[{
msg_type: 4,
file_bus_id: 102,
file_id: 'file-id',
file_size: '1',
}, 'msg_content.file_name'],
[{
msg_type: 4,
file_name: 'file.txt',
file_bus_id: 102,
file_size: '1',
}, 'msg_content.file_id'],
[{
msg_type: 4,
file_name: 'file.txt',
file_bus_id: 102,
file_id: 'file-id',
}, 'msg_content.file_size'],
[{
msg_type: 4,
file_name: 'file.txt',
file_id: 'file-id',
file_size: '1',
}, 'msg_content.file_bus_id'],
])('rejects digest content missing its required field: %s', async (content, field) => {
const getEssenceAll = vi.fn(async () => [{
retcode: 0,
@@ -521,6 +604,43 @@ describe('extended-actions / get_essence_msg_list', () => {
expect(cacheMessageMetas).not.toHaveBeenCalled();
});
it.each([
[{
msg_type: 4,
file_name: 'file.txt',
file_bus_id: 102,
file_id: 'file-id',
file_size: '-1',
}, 'msg_content.file_size'],
[{
msg_type: 4,
file_name: 'file.txt',
file_bus_id: 'not-a-number',
file_id: 'file-id',
file_size: '1',
}, 'msg_content.file_bus_id'],
])('rejects digest content with an invalid file field: %s', async (content, field) => {
const getEssenceAll = vi.fn(async () => [{
retcode: 0,
data: {
is_end: true,
msg_list: [fakeEssenceMessage({ msg_content: [content] })],
},
}]);
const bridge = fakeBridge({ apis: { web: { getEssenceAll } } });
const cacheMessageMetas = vi.fn();
const response = await makeHandler(fakeCtx(bridge, { cacheMessageMetas }))
.handle('get_essence_msg_list', { group_id: 123456789 });
expect(response).toMatchObject({
status: 'failed',
retcode: 100,
wording: expect.stringContaining(field),
});
expect(cacheMessageMetas).not.toHaveBeenCalled();
});
it('rejects blank numeric fields instead of coercing them to zero', async () => {
const getEssenceAll = vi.fn(async () => [{
retcode: 0,
@@ -34,6 +34,13 @@ function waitForOpen(socket: WebSocket): Promise<void> {
});
}
function waitForHandshakeError(socket: WebSocket): Promise<string> {
return new Promise((resolve, reject) => {
socket.once('open', () => reject(new Error('unauthorized WebSocket completed the upgrade')));
socket.once('error', (error: Error) => resolve(error.message));
});
}
function waitForMessage(socket: WebSocket): Promise<JsonObject> {
return new Promise((resolve, reject) => {
socket.once('message', (raw: Buffer) => {
@@ -130,6 +137,28 @@ describe('HttpServerAdapter — optional WebSocket transport', () => {
});
});
it('rejects an invalid WebSocket token before completing the HTTP upgrade', async () => {
const config = {
name: 'pre-upgrade-auth',
host: '127.0.0.1',
port: 0,
path: '/',
enabled: true,
enableWebSocket: true,
accessToken: 'expected-token',
messageFormat: 'array',
reportSelfMessage: false,
} satisfies HttpServerNetwork & { enableWebSocket: boolean };
adapter = new HttpServerAdapter(config.name, config, context());
await adapter.open();
const address = (adapter as unknown as { server: http.Server }).server.address() as AddressInfo;
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api?access_token=wrong-token`);
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 401');
expect(adapter.describeStatus().detail).toBe('监听中 · WebSocket 0 个客户端');
});
it('records and drops a valid WebSocket action after API quiesce', async () => {
const ctx = context();
const api = ctx.api as unknown as {
@@ -97,6 +97,48 @@ describe('StreamStorage', () => {
.toThrow(/root inspection denied/);
});
it('rejects a managed root that is already a symbolic link', () => {
const externalDir = path.join(container, 'external');
const externalFile = path.join(externalDir, 'keep.bin');
writeSized(externalFile, 12);
fs.symlinkSync(externalDir, root);
expect(() => new StreamStorage(root)).toThrow(/symbolic link/i);
expect(fs.readFileSync(externalFile)).toHaveLength(12);
});
it('rejects a symbolic-link replacement before creating managed children', () => {
const externalDir = path.join(container, 'late-external');
fs.mkdirSync(externalDir);
fs.symlinkSync(externalDir, root);
expect(() => storage.ensureDirectory(storage.uploadDir)).toThrow(/symbolic link/i);
expect(fs.readdirSync(externalDir)).toEqual([]);
});
it.runIf(typeof process.getuid === 'function')('rejects a root owned by another account', () => {
fs.mkdirSync(root);
const uid = process.getuid!();
vi.spyOn(process, 'getuid').mockReturnValue(uid + 1);
expect(() => new StreamStorage(root)).toThrow(/owned by another account/i);
});
it.runIf(process.platform !== 'win32')('rejects a root writable by other accounts', () => {
fs.mkdirSync(root, { mode: 0o777 });
fs.chmodSync(root, 0o777);
expect(() => new StreamStorage(root)).toThrow(/writable by other accounts/i);
});
it('keeps ordinary existing directories usable', () => {
fs.mkdirSync(root, { mode: 0o755 });
const existing = new StreamStorage(root);
expect(() => existing.ensureDirectory(existing.uploadDir)).not.toThrow();
expect(fs.lstatSync(existing.uploadDir).isDirectory()).toBe(true);
});
it('removes a symlink without following it outside the managed root', () => {
const externalDir = path.join(root, '..', `${path.basename(root)}-external`);
const externalFile = path.join(externalDir, 'keep.bin');
@@ -7,8 +7,12 @@ const { FakeWebSocketServer, servers } = vi.hoisted(() => {
class FakeWebSocketServer extends EventEmitter {
closeCallback: ((error?: Error) => void) | null = null;
constructor(_options: unknown) {
readonly options: {
verifyClient?: (info: { req: { headers: Record<string, string>; url?: string } }) => boolean;
};
constructor(options: unknown) {
super();
this.options = options as typeof this.options;
servers.push(this);
}
close(callback?: (error?: Error) => void): void {
@@ -73,6 +77,19 @@ describe('WsServerAdapter bind/release lifecycle promises', () => {
expect(adapter.describeStatus().status).toBe('ok');
});
it('provides standalone upgrade authentication before accepting a connection', () => {
const adapter = new WsServerAdapter('ws', {
...config(),
accessToken: 'expected-token',
}, CTX);
void adapter.open();
const verify = servers[0].options.verifyClient;
expect(verify).toBeTypeOf('function');
expect(verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } })).toBe(false);
expect(verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } })).toBe(true);
});
it('rejects bind errors and exposes them as degraded', async () => {
const adapter = new WsServerAdapter('ws', config(), CTX);
const opening = adapter.open();
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
+18
View File
@@ -12,6 +12,24 @@ export interface OperatorInfo {
operatorField?: pb<1, OperatorField1>;
}
export interface FriendRemarkChangedTarget {
uin?: pb<3, uint_64>;
uid?: pb<7, string>;
}
export interface FriendRemarkChangedValue {
target?: pb<1, FriendRemarkChangedTarget>;
remark?: pb<2, string>;
}
/** Event0x210 / subType 364 — server-authoritative friend remark update. */
export interface FriendRemarkChangedNotify {
change?: pb<1, FriendRemarkChangedValue>;
updateTime?: pb<3, uint_32>;
nickname?: pb<4, string>;
changeType?: pb<5, uint_32>;
}
export interface GroupChange {
groupUin?: pb<1, uint_32>;
flag?: pb<2, uint_32>;
+11 -1
View File
@@ -275,7 +275,8 @@ export interface OidbGroupListConfig1 {
export interface OidbGroupListConfig2 {
field1?: pb<1, bool>;
field2?: pb<2, bool>;
field3?: pb<3, bool>;
/** Request the bot-local label returned as group.customInfo.remark. */
remark?: pb<3, bool>;
field4?: pb<4, bool>;
field5?: pb<5, bool>;
field6?: pb<6, bool>;
@@ -918,6 +919,7 @@ export interface OidbStrangerStatusReq {
key?: pb_repeated<3, OidbStrangerStatusKey>;
}
export interface OidbFriendRemarkTarget {
targetUin?: pb<3, uint_64>;
targetUid?: pb<7, string>;
}
export interface OidbSetFriendRemarkChange {
@@ -930,6 +932,14 @@ export interface OidbSetFriendRemark {
// the default changes the request shape used by StrangerRemarkSetWorker.
scene?: pb_optional<2, uint_32>;
}
export interface OidbSetFriendRemarkError {
code?: pb<2, int_32>;
message?: pb<3, string>;
}
export interface OidbSetFriendRemarkResponse {
result?: pb<1, OidbSetFriendRemarkChange>;
error?: pb<3, OidbSetFriendRemarkError>;
}
export interface OidbClearFriendRemark {
target?: pb<1, OidbFriendRemarkTarget>;
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
+13
View File
@@ -526,6 +526,18 @@ export interface OnlineDevicesChangedEvent extends QQEvent {
devices: OnlineDeviceInfo[];
}
/**
* A friend or stranger remark changed on another client (Event 0x210 /
* subType 364). Internal-only: the packet pipeline consumes this event to
* keep the identity cache synchronized; it is not forwarded to OneBot.
*/
export interface FriendRemarkChangedEvent extends QQEvent {
kind: 'friend_remark_changed';
userUid: string;
userUin: number;
remark: string;
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -551,4 +563,5 @@ export type QQEventVariant =
| GroupTitleChangeEvent
| FriendProfileLikeEvent
| OnlineDevicesChangedEvent
| FriendRemarkChangedEvent
| BotOfflineEvent;
+85 -2
View File
@@ -322,6 +322,85 @@ export class IdentityService {
this.runWrite('group member update', () => this.transaction(() => this.upsertGroupMember(persisted)));
}
/** Apply a server-confirmed update to the bot's local label for one group. */
updateGroupRemark(groupId: number, remark: string): boolean {
this.beginObservation('group remark update');
if (!Number.isSafeInteger(groupId) || groupId <= 0) {
throw new Error(`group remark update has invalid group id: ${groupId}`);
}
if (typeof remark !== 'string') {
throw new Error('group remark update must be a string');
}
const group = this.groups_.get(groupId);
if (!group) return false;
const observed: QQGroupInfo = { ...group, remark };
const persisted: GroupInput = {
groupId,
groupName: observed.groupName,
remark: observed.remark,
memberCount: observed.memberCount,
memberMax: observed.memberMax,
};
this.groups_.set(groupId, observed);
this.runWrite(
'group remark update',
() => this.transaction(() => this.upsertGroup(persisted)),
);
return true;
}
/** Apply the server-authoritative friend/stranger remark synchronization push. */
updateFriendRemark(uid: string, uin: number, remark: string): boolean {
this.beginObservation('friend remark update');
const normalizedUid = normalizeUid(uid);
const normalizedUin = normalizeUin(uin);
if (!normalizedUid && normalizedUin === null) {
throw new Error('friend remark update is missing both UID and UIN');
}
const byUid = normalizedUid
? this.friends_.find((friend) => friend.uid === normalizedUid) ?? null
: null;
const byUin = normalizedUin !== null
? this.friends_.find((friend) => friend.uin === normalizedUin) ?? null
: null;
if (byUid && byUin && byUid !== byUin) {
throw new Error(`friend remark update identity mismatch: uid=${normalizedUid} uin=${normalizedUin}`);
}
const friend = byUid ?? byUin;
if (friend && normalizedUid && friend.uid && friend.uid !== normalizedUid) {
throw new Error(`friend remark update UID mismatch for uin=${friend.uin}`);
}
if (friend && normalizedUin !== null && friend.uin !== normalizedUin) {
throw new Error(`friend remark update UIN mismatch for uid=${friend.uid}`);
}
const observedUid = normalizedUid || friend?.uid || '';
const observedUin = normalizedUin ?? friend?.uin ?? 0;
if (friend) {
const index = this.friends_.indexOf(friend);
this.friends_[index] = { ...friend, remark };
}
const profile = observedUin > 0 ? this.userProfiles_.get(observedUin) : undefined;
if (profile) this.userProfiles_.set(observedUin, { ...profile, remark });
this.rememberUidUin(observedUid, observedUin);
const persisted: UserInput = {
uid: observedUid || undefined,
uin: observedUin > 0 ? observedUin : undefined,
remark,
isFriend: friend ? true : undefined,
};
this.runWrite(
'friend remark update',
() => this.transaction(() => this.upsertUser(persisted)),
);
return friend !== null;
}
// ─── ID translation ───
/**
@@ -816,7 +895,7 @@ export class IdentityService {
uid: uid || primary?.uid || null,
uin: uin ?? primary?.uin ?? null,
nickname: mergeOptionalText(input.nickname, primary?.nickname ?? ''),
remark: mergeOptionalText(input.remark, primary?.remark ?? ''),
remark: mergeOptionalExactText(input.remark, primary?.remark ?? ''),
isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0),
source: mergeOptionalText(input.source, primary?.source ?? ''),
updatedAt: nowSeconds(),
@@ -882,7 +961,7 @@ export class IdentityService {
).run(
input.groupId,
mergeOptionalText(input.groupName, existing?.group_name ?? ''),
mergeOptionalText(input.remark, existing?.remark ?? ''),
mergeOptionalExactText(input.remark, existing?.remark ?? ''),
normalizeNonNegative(input.memberCount, existing?.member_count ?? 0),
normalizeNonNegative(input.memberMax, existing?.member_max ?? 0),
nowSeconds(),
@@ -1247,6 +1326,10 @@ function mergeOptionalText(value: unknown, fallback: string): string {
return value === undefined ? fallback : normalizeText(value);
}
function mergeOptionalExactText(value: unknown, fallback: string): string {
return value === undefined ? fallback : (typeof value === 'string' ? value : '');
}
function normalizeNonNegative(value: unknown, fallback: number): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
return fallback;
@@ -10,6 +10,7 @@ import type {
} from '../../events';
import type {
FriendRecall,
FriendRemarkChangedNotify,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
@@ -46,6 +47,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice: return decodeOnlineDevices(ctx);
case Event0x210SubType.FriendRemarkChangedNotice: return decodeFriendRemarkChanged(ctx);
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
@@ -70,6 +72,32 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
return [];
};
function decodeFriendRemarkChanged(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
const change = notify?.change;
const uid = change?.target?.uid?.trim() ?? '';
const rawUin = change?.target?.uin;
const uin = rawUin === undefined ? 0 : Number(rawUin);
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
}
if (!uid && uin <= 0) {
throw new Error('friend remark synchronization is missing both UID and UIN');
}
if (change?.remark === undefined) {
throw new Error(`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`);
}
if (ctx.isHistorical) return [];
return [{
kind: 'friend_remark_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUid: uid,
userUin: uin,
remark: change.remark,
}];
}
const COMPUTER_CLIENT_TYPES = new Set([1, 5, 15]);
const PHONE_CLIENT_TYPES = new Set([2, 3, 4, 6, 7, 12]);
const PAD_CLIENT_TYPES = new Set([8, 9, 10, 11, 13]);
+2
View File
@@ -90,6 +90,8 @@ export enum Event0x210SubType {
* does not issue a separate network request.
*/
OnlineDevicesNotice = 349,
/** Server-authoritative friend/stranger remark synchronization push. */
FriendRemarkChangedNotice = 364,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
@@ -5,8 +5,9 @@
// per-group fields to include. Asking for everything blows the
// named-pipe write buffer on accounts with ~200+ groups (see #42),
// so we keep `config1.*` mostly on but turn off the costly
// `field5002`/`field5003` and entire `config2` block that never map
// back to a decoded field anyway.
// `field5002`/`field5003` and the unused `config2` fields. `config2.remark`
// is the bot-local group remark returned as `customInfo.remark`, so it is the
// sole optional field enabled in that block.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0xFE5_2Response } from '@snowluma/proto-defs/oidb';
@@ -37,7 +38,7 @@ export namespace FetchGroupList {
field32: allTrue, field5001: allTrue, field5002: false, field5003: false,
},
config2: {
field1: false, field2: false, field3: false, field4: false,
field1: false, field2: false, remark: true, field4: false,
field5: false, field6: false, field7: false, field8: false,
},
config3: { field5: allTrue, field6: allTrue },
@@ -3,11 +3,17 @@
// StrangerRemarkSetWorker with scene=0.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { OidbSetFriendRemark } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import { createLogger } from '@snowluma/common/logger';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbSetFriendRemark,
OidbSetFriendRemarkResponse,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, OidbError, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
const log = createLogger('Bridge.Friend');
export namespace SetFriendRemark {
export const command = 0x912E;
export const subCommand = 0;
@@ -17,24 +23,83 @@ export namespace SetFriendRemark {
remark: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'resolveUserUid'>;
interface WireParams {
targetUid: string;
remark: string;
}
export const serialize = async (ctx: Deps, p: Params): Promise<OidbSetFriendRemark> => ({
export interface Result {
targetUid: string;
targetUin: number;
remark: string;
}
export type Deps = OidbSender & Pick<BridgeContext, 'identity' | 'resolveUserUid'>;
export const serialize = (_ctx: Deps, p: WireParams): OidbSetFriendRemark => ({
change: {
target: { targetUid: await ctx.resolveUserUid(p.userId) },
target: { targetUid: p.targetUid },
remark: p.remark,
},
scene: 0,
});
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
export const deserialize = (_ctx: Deps, response: OidbSetFriendRemarkResponse): Result => {
if (response.error) {
const code = response.error.code ?? 0;
const message = response.error.message ?? '';
if (code !== 0) throw new OidbError(code, message, command, subCommand);
throw new Error(`invalid friend remark response: error result has no failure code${message ? ` (${message})` : ''}`);
}
const result = response.result;
if (!result) throw new Error('invalid friend remark response: missing result');
const targetUid = result?.target?.targetUid ?? '';
const rawTargetUin = result?.target?.targetUin ?? '';
const targetUin = rawTargetUin ? Number(rawTargetUin) : 0;
if (rawTargetUin && (!Number.isSafeInteger(targetUin) || targetUin <= 0)) {
throw new Error(`invalid friend remark response: invalid target UIN ${rawTargetUin}`);
}
return { targetUid, targetUin, remark: result?.remark ?? '' };
};
export const encode = (env: OidbBase<OidbSetFriendRemark>): Uint8Array =>
protobuf_encode<OidbBase<OidbSetFriendRemark>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const decode = (bytes: Uint8Array): OidbBase<OidbSetFriendRemarkResponse> =>
protobuf_decode<OidbBase<OidbSetFriendRemarkResponse>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetFriendRemark, params);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
const targetUid = await deps.resolveUserUid(params.userId);
const result = await invokeOidb(deps, SetFriendRemark, {
targetUid,
remark: params.remark,
});
if (result.targetUid !== targetUid) {
throw new Error(`friend remark response target mismatch: expected UID ${targetUid}, got ${result.targetUid || '(missing)'}`);
}
if (result.targetUin > 0 && result.targetUin !== params.userId) {
throw new Error(`friend remark response target mismatch: expected UIN ${params.userId}, got ${result.targetUin}`);
}
if (result.remark !== params.remark) {
throw new Error('friend remark response value does not match the requested remark');
}
// The server-side mutation has already completed. A local cache failure
// must remain observable, but reporting the Action as failed here would
// encourage callers to repeat an operation that QQ already accepted.
try {
deps.identity.updateFriendRemark(
result.targetUid,
result.targetUin || params.userId,
result.remark,
);
} catch (error: unknown) {
log.error(
'local identity synchronization failed after confirmed friend remark update: uid=%s uin=%d: %s',
result.targetUid,
result.targetUin || params.userId,
error instanceof Error ? error.message : String(error),
);
}
};
}
@@ -2,16 +2,20 @@
// the bot sees this — the group's actual name is untouched).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0xf16Req } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
import type { BridgeContext } from '../../bridge-context';
const log = createLogger('Bridge.GroupAdmin');
export namespace SetGroupRemark {
export const command = 0xF16;
export const subCommand = 1;
export interface Params { groupId: number; remark: string; }
export type Deps = OidbSender;
export type Deps = OidbSender & Pick<BridgeContext, 'identity'>;
export const serialize = (_ctx: Deps, p: Params): Oidb0xf16Req => ({
inner: { groupId: BigInt(p.groupId), remark: p.remark },
@@ -24,6 +28,28 @@ export namespace SetGroupRemark {
export const decode = (bytes: Uint8Array): OidbBase<OidbEmpty> =>
protobuf_decode<OidbBase<OidbEmpty>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, SetGroupRemark, params);
export const invoke = async (deps: Deps, params: Params): Promise<void> => {
await invokeOidb(deps, SetGroupRemark, params);
// QQ has already accepted the mutation. Keep the local roster coherent,
// but never turn a local-cache problem into a false remote failure that
// encourages callers to repeat the mutation.
try {
const updated = deps.identity.updateGroupRemark(params.groupId, params.remark);
if (!updated) {
log.warn(
'local group roster did not contain server-confirmed remark target: uin=%s group=%d',
deps.identity.uin,
params.groupId,
);
}
} catch (error: unknown) {
log.error(
'local identity synchronization failed after confirmed group remark update: uin=%s group=%d: %s',
deps.identity.uin,
params.groupId,
error instanceof Error ? error.message : String(error),
);
}
};
}
+15
View File
@@ -691,6 +691,21 @@ export class IncomingPacketPipeline {
source: 'friend_request',
});
break;
case 'friend_remark_changed': {
const rosterUpdated = this.deps.identity.updateFriendRemark(
event.userUid,
event.userUin,
event.remark,
);
this.log.debug(
'friend remark synchronized (uid=%s uin=%d length=%d rosterUpdated=%s)',
event.userUid,
event.userUin,
event.remark.length,
rosterUpdated,
);
break;
}
case 'group_invite': {
// Defensive: never cache a uid→uin mapping where uin equals
// the group's own uin — that's the pollution signature the
@@ -9,7 +9,11 @@ export interface GroupEssenceContent {
text?: string;
face_index?: number;
image_url?: string;
file_name?: string;
file_bus_id?: number | string;
file_id?: string;
file_thumbnail_url?: string;
file_size?: number | string;
}
export interface GroupEssenceMessage {
@@ -28,13 +28,17 @@ describe('FetchGroupList namespace', () => {
expect(env.reserved).toBe(1);
});
it('sends the verbatim config blob (field5002/5003 OFF to avoid EPIPE on big rosters)', async () => {
it('requests group remarks without enabling the other costly optional fields', async () => {
const sender = makeSender();
await FetchGroupList.invoke(sender);
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupListRequest>>(bytes);
expect(env.body?.config?.config1?.groupName).toBe(true);
expect(env.body?.config?.config1?.memberCount).toBe(true);
expect(env.body?.config?.config2?.remark).toBe(true);
for (const field of ['field1', 'field2', 'field4', 'field5', 'field6', 'field7', 'field8'] as const) {
expect(env.body?.config?.config2?.[field] ?? false, field).toBe(false);
}
// proto3 default false — omitted on wire, decoded as null.
expect(env.body?.config?.config1?.field5002 ?? false).toBe(false);
expect(env.body?.config?.config1?.field5003 ?? false).toBe(false);
@@ -1,14 +1,32 @@
import { describe, expect, it, vi } from 'vitest';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetFriendRemark } from '../../../src/oidb-services/friend/set-friend-remark';
import { env, m, s, v } from '../_pb-oracle';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
function successBody(uid = 'resolved-uid', remark = 'best-friend', uin = 0): number[] {
return m(1, [
...m(1, [
...(uin > 0 ? v(3, uin) : []),
...s(7, uid),
]),
...s(2, remark),
]);
}
function makeDeps(responseBody = successBody()) {
const r: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(env(0x912E, 0, responseBody, false), 'hex'),
};
return {
sendRawPacket: vi.fn(async () => r),
resolveUserUid: vi.fn(async () => 'resolved-uid'),
identity: { updateFriendRemark: vi.fn() },
};
}
@@ -39,4 +57,88 @@ describe('SetFriendRemark namespace', () => {
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
expect(deps.resolveUserUid).toHaveBeenCalledWith(10001);
});
it('updates identity only after the server confirms the requested value', async () => {
const deps = makeDeps(successBody('resolved-uid', 'best-friend', 10001));
await SetFriendRemark.invoke(deps, { userId: 10001, remark: 'best-friend' });
expect(deps.identity.updateFriendRemark)
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
});
it('reports local synchronization failures without retrying a confirmed remote update', async () => {
const deps = makeDeps(successBody('resolved-uid', 'best-friend', 10001));
deps.identity.updateFriendRemark.mockImplementation(() => {
throw new Error('identity cache unavailable');
});
const captured: LogEntry[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'Bridge.Friend') captured.push(entry);
});
try {
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).resolves.toBeUndefined();
} finally {
unsubscribe();
}
expect(deps.sendRawPacket).toHaveBeenCalledTimes(1);
expect(captured).toContainEqual(expect.objectContaining({
level: 'error',
message: expect.stringContaining('identity cache unavailable'),
}));
});
it('rejects a business failure carried inside a successful OIDB response', async () => {
const deps = makeDeps(m(3, [
...v(2, 120),
...s(3, 'remark rejected'),
]));
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).rejects.toThrow(/remark rejected/);
expect(deps.identity.updateFriendRemark).not.toHaveBeenCalled();
});
it('rejects a response that contains neither a result nor a business error', async () => {
const deps = makeDeps([]);
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).rejects.toThrow(/missing result/);
});
it('rejects a success result for a different target', async () => {
const deps = makeDeps(successBody('another-uid'));
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).rejects.toThrow(/target mismatch/);
});
it('rejects a success result that does not confirm the requested remark', async () => {
const deps = makeDeps(successBody('resolved-uid', 'old-remark'));
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).rejects.toThrow(/does not match/);
});
it('rejects a success result carrying a different numeric account', async () => {
const deps = makeDeps(successBody('resolved-uid', 'best-friend', 20002));
await expect(SetFriendRemark.invoke(deps, {
userId: 10001,
remark: 'best-friend',
})).rejects.toThrow(/expected UIN 10001, got 20002/);
});
});
@@ -8,7 +8,10 @@ import { SetGroupRemark } from '../../../src/oidb-services/group-admin/set-group
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
return { sendRawPacket: vi.fn(async () => r) };
return {
sendRawPacket: vi.fn(async () => r),
identity: { uin: '10001', updateGroupRemark: vi.fn(() => true) },
};
}
describe('SetGroupRemark namespace', () => {
@@ -25,4 +28,27 @@ describe('SetGroupRemark namespace', () => {
const env = protobuf_decode<OidbBase<Oidb0xf16Req>>(bytes);
expect(env.body?.inner).toMatchObject({ groupId: 12345n, remark: 'my group' });
});
it('updates the local group roster after QQ confirms the remark', async () => {
const deps = makeDeps();
await SetGroupRemark.invoke(deps as any, { groupId: 12345, remark: 'my group' });
expect(deps.identity.updateGroupRemark).toHaveBeenCalledWith(12345, 'my group');
});
it('does not update the local roster when QQ rejects the mutation', async () => {
const deps = makeDeps();
deps.sendRawPacket.mockResolvedValueOnce({
success: false,
gotResponse: true,
errorCode: 120,
errorMessage: 'denied',
responseData: Buffer.alloc(0),
});
await expect(
SetGroupRemark.invoke(deps as any, { groupId: 12345, remark: 'not-applied' }),
).rejects.toThrow();
expect(deps.identity.updateGroupRemark).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.13.0",
"version": "1.14.0",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.13.0",
"version": "1.14.0",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.13.0",
"version": "1.14.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
+4
View File
@@ -23,6 +23,10 @@ status, OneBot configuration, logs, storage, and server settings.
- Password change flows use floating labels and inline validation consistently.
- Password strength details appear only while the new-password field has focus
and leave with the same motion language when focus moves away.
- The first-run wizard keeps agreement text as the primary reading surface and
aligns each step's actions inside one responsive footer. Settings includes a
visible developer page for safely replaying this wizard and exercising the
page-level crash screen; replayed consent and passwords are never persisted.
## Local development
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.13.0",
"version": "1.14.0",
"type": "module",
"scripts": {
"dev": "vite",
+111 -27
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { RouterProvider } from '@tanstack/react-router';
import { AlertTriangle, LogOut, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -17,6 +17,7 @@ import { DebugTaskProvider } from '@/contexts/DebugTaskContext';
import { TaskBadge } from '@/components/debug/task-badge';
import { AdaptivePointer } from '@/components/ui/adaptive-pointer';
import { GlobalContextMenu } from '@/components/ui/global-context-menu';
import { InsecureRemoteAccessBanner } from '@/components/insecure-remote-access-banner';
import {
actionErrorMessage,
ActionFeedbackProvider,
@@ -25,6 +26,15 @@ import {
} from '@/contexts/ActionFeedbackContext';
import type { AgreementsPayload } from '@/lib/api/types';
import { appRouter } from '@/router';
import {
browserPath,
DEVELOPER_ONBOARDING_RETURN_KEY,
DEVELOPER_ONBOARDING_URL,
DEVELOPER_SETTINGS_URL,
developerOnboardingReturnPath,
isDeveloperOnboardingLocation,
} from '@/lib/onboarding-navigation';
import { onboardingExecution } from '@/lib/onboarding-actions';
interface AppProps {
onboardingSteps?: AdditionalOnboardingStep[];
@@ -34,6 +44,7 @@ export default function App({ onboardingSteps = [] }: AppProps) {
return (
<ActionFeedbackProvider>
<ThemeProvider>
<InsecureRemoteAccessBanner />
<ActionFeedbackViewport />
<AdaptivePointer />
<GlobalContextMenu />
@@ -72,6 +83,10 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
const [agreementsError, setAgreementsError] = useState<string | null>(null);
const [needsConsent, setNeedsConsent] = useState(false);
const [onboardingFinished, setOnboardingFinished] = useState(false);
const [replayingOnboarding, setReplayingOnboarding] = useState(
() => typeof window !== 'undefined' && isDeveloperOnboardingLocation(window.location),
);
const onboardingReturnPath = useRef<string | null>(null);
// The password from *this* session's login, carried into the forced
// change-password gate so it doesn't have to render an old-password field
// (which browsers autofill, misleading users on upgrade). Stays undefined
@@ -145,6 +160,8 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
setAgreementsError(null);
setNeedsConsent(false);
setOnboardingFinished(false);
setReplayingOnboarding(false);
onboardingReturnPath.current = null;
setLoginPassword(undefined);
}, []);
@@ -153,6 +170,47 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
handleLoggedOut();
}, [client, handleLoggedOut]);
const restartOnboarding = useCallback(() => {
const currentPath = browserPath(window.location);
const returnPath = isDeveloperOnboardingLocation(window.location)
? DEVELOPER_SETTINGS_URL
: currentPath;
onboardingReturnPath.current = returnPath;
const currentState = typeof window.history.state === 'object' && window.history.state !== null
? window.history.state as Record<string, unknown>
: {};
setReplayingOnboarding(true);
appRouter.history.push(
DEVELOPER_ONBOARDING_URL,
{ ...currentState, [DEVELOPER_ONBOARDING_RETURN_KEY]: returnPath },
);
}, []);
const exitOnboardingReplay = useCallback(() => {
const returnPath = onboardingReturnPath.current
?? developerOnboardingReturnPath(window.history.state);
onboardingReturnPath.current = null;
if (returnPath && isDeveloperOnboardingLocation(window.location)) {
// The developer page pushed the replay entry, so browser Back is the
// authoritative way to restore both the URL and its router history.
appRouter.history.back();
return;
}
appRouter.history.replace(returnPath ?? DEVELOPER_SETTINGS_URL);
setReplayingOnboarding(false);
}, []);
useEffect(() => {
const syncReplayToLocation = () => {
const replaying = isDeveloperOnboardingLocation(appRouter.history.location);
if (!replaying) onboardingReturnPath.current = null;
setReplayingOnboarding(replaying);
};
return appRouter.history.subscribe(syncReplayToLocation);
}, []);
let view: React.ReactNode;
if (authLoading || showAuthSkeleton) {
view = <Splash>{authChecked ? '加载中…' : '初始化中…'}</Splash>;
@@ -177,12 +235,19 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
onLogout={() => { void handleDecline(); }}
/>
);
} else if (!onboardingFinished && (needsConsent || mustChange || onboardingSteps.length > 0) && agreements) {
} else if (
agreements
&& (
replayingOnboarding
|| (!onboardingFinished && (needsConsent || mustChange || onboardingSteps.length > 0))
)
) {
view = (
<OnboardingGate
payload={agreements}
needsConsent={needsConsent}
mustChangePassword={mustChange}
needsConsent={replayingOnboarding || needsConsent}
mustChangePassword={replayingOnboarding || mustChange}
replay={replayingOnboarding}
additionalSteps={onboardingSteps}
knownOldPassword={loginPassword}
onConsentComplete={() => setNeedsConsent(false)}
@@ -190,14 +255,26 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
setMustChange(false);
setLoginPassword(undefined);
}}
onComplete={() => setOnboardingFinished(true)}
onComplete={() => {
if (replayingOnboarding) {
exitOnboardingReplay();
return;
}
setOnboardingFinished(true);
}}
onStale={refreshAgreements}
onDecline={handleDecline}
onDecline={replayingOnboarding ? exitOnboardingReplay : handleDecline}
/>
);
} else {
view = (
<SessionProvider value={{ status, onLogoutComplete: handleLoggedOut }}>
<SessionProvider
value={{
status,
onLogoutComplete: handleLoggedOut,
restartOnboarding,
}}
>
<RouterProvider router={appRouter} />
</SessionProvider>
);
@@ -300,6 +377,7 @@ function OnboardingGate({
payload,
needsConsent,
mustChangePassword,
replay,
knownOldPassword,
onConsentComplete,
onPasswordComplete,
@@ -311,6 +389,7 @@ function OnboardingGate({
payload: AgreementsPayload;
needsConsent: boolean;
mustChangePassword: boolean;
replay: boolean;
knownOldPassword?: string;
onConsentComplete: () => void;
onPasswordComplete: () => void;
@@ -321,21 +400,11 @@ function OnboardingGate({
}) {
const api = useApi();
const { runAction } = useActionFeedback();
return (
<OnboardingWizardPage
documents={payload.documents}
agreementVersion={payload.version}
needsConsent={needsConsent}
mustChangePassword={mustChangePassword}
knownOldPassword={knownOldPassword}
onDecline={onDecline}
onConsentComplete={onConsentComplete}
onPasswordComplete={onPasswordComplete}
onComplete={onComplete}
additionalSteps={additionalSteps}
checkStrength={(password) => api.checkPasswordStrength(password)}
submitPassword={(oldPassword, newPassword) => api.changePassword(oldPassword, newPassword)}
onAccept={async () => {
const execution = onboardingExecution(
replay,
{
changePassword: (oldPassword, newPassword) => api.changePassword(oldPassword, newPassword),
acceptAgreements: async () => {
const result = await runAction(
{
title: '正在记录协议确认',
@@ -346,16 +415,31 @@ function OnboardingGate({
},
() => api.agreements.recordConsent(payload.version),
);
if (result.success) {
return { success: true };
}
// 409: the agreement text changed under us — re-fetch and re-prompt.
if (result.success) return { success: true };
if (result.currentVersion && result.currentVersion !== payload.version) {
onStale();
return { success: false, message: '协议已更新,已为你载入最新版本,请重新阅读后确认。' };
}
return { success: false, message: result.message ?? '提交失败,请重试' };
}}
},
},
);
return (
<OnboardingWizardPage
documents={payload.documents}
agreementVersion={payload.version}
needsConsent={needsConsent}
mustChangePassword={mustChangePassword}
knownOldPassword={knownOldPassword}
passwordMode={execution.passwordMode}
onDecline={onDecline}
onConsentComplete={replay ? () => undefined : onConsentComplete}
onPasswordComplete={replay ? () => undefined : onPasswordComplete}
onComplete={onComplete}
additionalSteps={additionalSteps}
checkStrength={(password) => api.checkPasswordStrength(password)}
submitPassword={execution.actions.changePassword}
onAccept={execution.actions.acceptAgreements}
/>
);
}
@@ -30,7 +30,7 @@ export interface NetworkTabDescriptor<K extends NetworkKind> {
defaultEntry: (suffix: number) => OneBotNetworks[K][number];
}
function genToken(): string {
export function generateAccessToken(): string {
const bytes = new Uint8Array(32);
globalThis.crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
@@ -48,11 +48,11 @@ const httpServersTab: NetworkTabDescriptor<'httpServers'> = {
},
defaultEntry: (suffix): HttpServerNetwork => ({
name: `http-${suffix}`,
host: '0.0.0.0',
host: '127.0.0.1',
port: 3000,
path: '/',
enableWebSocket: false,
accessToken: genToken(),
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}),
@@ -85,11 +85,11 @@ const wsServersTab: NetworkTabDescriptor<'wsServers'> = {
},
defaultEntry: (suffix): WsServerNetwork => ({
name: `ws-${suffix}`,
host: '0.0.0.0',
host: '127.0.0.1',
port: 3001,
path: '/',
role: 'Universal' as WsRole,
accessToken: genToken(),
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}),
@@ -7,7 +7,7 @@
// captioned sections, soft rounded cards, settings rows with a label on the
// left and a control (toggle / custom dropdown) on the right.
import { useRef, useState, type ReactNode } from 'react';
import { useId, useMemo, useRef, useState, type ReactNode } from 'react';
import { motion } from 'motion/react';
import {
ArrowLeftRight,
@@ -17,6 +17,7 @@ import {
Eye,
EyeOff,
Radio,
RefreshCw,
Server,
type LucideIcon,
} from 'lucide-react';
@@ -27,6 +28,11 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ToggleSwitch } from '@/components/ui/toggle-switch';
import { cn } from '@/lib/utils';
import {
accessTokenFeedback,
type AccessTokenFeedback,
} from '@/lib/access-token-feedback';
import { isLoopbackHostname } from '@/lib/transport-security';
import type {
HttpClientNetwork,
HttpServerNetwork,
@@ -37,7 +43,7 @@ import type {
WsRole,
WsServerNetwork,
} from '@/types';
import { NETWORK_TABS } from './defaults';
import { generateAccessToken, NETWORK_TABS } from './defaults';
type AnyAdapter<K extends NetworkKind> = OneBotNetworks[K][number];
@@ -59,11 +65,13 @@ interface NodeEditDialogProps<K extends NetworkKind> {
isEdit: boolean;
/** Names of every other adapter in the same list, for duplicate check. */
otherNames: string[];
/** Account context used when evaluating user-chosen access tokens. */
uin: string;
onSubmit: (item: AnyAdapter<K>) => void;
}
export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps<K>) {
const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props;
const { open, onOpenChange, kind, initial, isEdit, otherNames, uin, onSubmit } = props;
const tab = NETWORK_TABS[kind];
const Icon: LucideIcon = KIND_ICON[kind];
@@ -76,7 +84,24 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
const blankName = trimmedName.length === 0;
const duplicateName = !blankName && otherNames.includes(trimmedName);
const canSave = !blankName && !duplicateName;
const isInboundServer = kind === 'httpServers' || kind === 'wsServers';
const tokenChanged = (draft.accessToken ?? '') !== (initial.accessToken ?? '');
const enforceTokenPolicy = isInboundServer && (!isEdit || tokenChanged);
const allowEmptyToken = typeof window !== 'undefined'
&& isLoopbackHostname(window.location.hostname);
const inbound = isInboundServer ? draft as HttpServerNetwork | WsServerNetwork : null;
const tokenFeedback = useMemo(
() => enforceTokenPolicy
? accessTokenFeedback(
draft.accessToken ?? '',
[uin, draft.name ?? '', kind, inbound?.host ?? '', inbound?.port ?? 0],
allowEmptyToken,
)
: undefined,
[allowEmptyToken, draft.accessToken, draft.name, enforceTokenPolicy, inbound?.host, inbound?.port, kind, uin],
);
const canSave = !blankName && !duplicateName && (tokenFeedback?.valid ?? true);
const patch = (changes: Partial<AnyAdapter<K>>) => setDraft({ ...draft, ...changes } as AnyAdapter<K>);
@@ -155,9 +180,11 @@ export function NodeEditDialog<K extends NetworkKind>(props: NodeEditDialogProps
<div className="p-4">
<TokenField
label="授权 Token"
placeholder="不填则无密码"
placeholder={isInboundServer ? '留空则关闭鉴权(仅允许本机保存)' : '按对端要求填写'}
value={draft.accessToken}
onChange={(v) => patch({ accessToken: v || undefined } as Partial<AnyAdapter<K>>)}
onGenerate={() => patch({ accessToken: generateAccessToken() } as Partial<AnyAdapter<K>>)}
feedback={tokenFeedback}
/>
</div>
</Section>
@@ -259,7 +286,7 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
@@ -307,7 +334,7 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="0.0.0.0"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
@@ -381,7 +408,9 @@ interface TokenFieldProps {
label: string;
value: string | undefined;
onChange: (v: string) => void;
onGenerate: () => void;
placeholder?: string;
feedback?: AccessTokenFeedback;
}
/** Insecure-context clipboard fallback. Returns true on success.
@@ -411,10 +440,11 @@ function legacyCopyToClipboard(value: string): boolean {
* unmasks it and a copy button shoves the current value to the system
* clipboard with a short "已复制" confirmation flash.
*/
function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
function TokenField({ label, value, onChange, onGenerate, placeholder, feedback }: TokenFieldProps) {
const [visible, setVisible] = useState(false);
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<number | null>(null);
const feedbackId = useId();
const handleCopy = async () => {
if (!value) return;
@@ -449,8 +479,20 @@ function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
placeholder={placeholder}
autoComplete="off"
spellCheck={false}
aria-invalid={feedback?.tone === 'error' || undefined}
aria-describedby={feedback ? feedbackId : undefined}
className="flex-1 font-mono"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={onGenerate}
aria-label="生成新的随机令牌"
title="生成新的随机令牌"
>
<RefreshCw className="size-4" />
</Button>
<Button
type="button"
variant="outline"
@@ -473,6 +515,22 @@ function TokenField({ label, value, onChange, placeholder }: TokenFieldProps) {
{visible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
</Button>
</div>
{feedback && (
<p
id={feedbackId}
aria-live="polite"
className={cn(
'text-xs',
feedback.tone === 'error'
? 'text-destructive'
: feedback.tone === 'warning'
? 'text-warning'
: 'text-success',
)}
>
{feedback.message}
</p>
)}
</div>
);
}
@@ -81,7 +81,7 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
useEffect(() => { if (accounts[0] && !uin) setUin(accounts[0].uin); }, [accounts, uin]);
// Prefill from the API browser's 试一下 (nonce lets the same action re-trigger).
useEffect(() => {
if (presetAction) { setActionName(presetAction.name); setParamMode('form'); setResult(null); setFrames([]); setShowHistory(false); }
if (presetAction) { setActionName(presetAction.name); setFields({}); setParamMode('form'); setResult(null); setFrames([]); setShowHistory(false); }
}, [presetAction]);
const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]);
@@ -234,7 +234,7 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
<Picker
ariaLabel="选择 action"
value={actionName}
onChange={(v) => { setActionName(v); setResult(null); setFrames([]); }}
onChange={(v) => { setActionName(v); setFields({}); setResult(null); setFrames([]); }}
options={actionOptions}
placeholder="search action…"
validateRaw={(s) => s.trim().length > 0}
@@ -265,8 +265,9 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
<div className="flex flex-col gap-3.5">
{doc!.params.length === 0 && <p className="text-[12px] text-muted-foreground">该接口无参数。</p>}
{doc!.params.map((p) => (
<Field key={p.name} label={<>{p.name}<span className="ml-1 font-normal text-muted-foreground/70">{p.type}{p.required ? ' · 必填' : ''}</span></>}>
<Field key={`${actionName}:${p.name}`} label={<>{p.name}<span className="ml-1 font-normal text-muted-foreground/70">{p.type}{p.required ? ' · 必填' : ''}</span></>}>
<ParamField param={p} value={fields[p.name] ?? ''} uin={uin} groupContext={fields['group_id'] ?? ''}
actionName={actionName}
onChange={(v) => setFields((f) => {
const next = { ...f, [p.name]: v };
// Changing the group resets any sibling member picker — its
@@ -99,7 +99,7 @@ export function LiveActivity() {
const [query, setQuery] = useState('');
const idRef = useRef(0);
// Pausing truly drops the EventSource instead of connecting-and-discarding:
// Pausing truly drops the live fetch stream instead of connecting-and-discarding:
// `paused` is an effect dependency, so it closes the stream on pause and
// reopens it on resume. (The always-on-across-tabs behaviour is intentional —
// debug-page keeps this mounted so actions fired from other tabs still land in
@@ -34,6 +34,7 @@ type SegBody =
| { k: 'markdown'; content: string }
| { k: 'node'; user_id: string; nickname: string; content: Seg[] };
export type Seg = SegBody & { _id: string };
export type MessageBuilderMode = 'auto' | 'message' | 'forward' | 'node-content';
let segSeq = 0;
const nid = () => `s${segSeq++}`;
@@ -101,18 +102,41 @@ const ADVANCED: { k: SegBody['k']; label: string; icon: React.ReactNode }[] = [
{ k: 'node', label: '合并转发节点', icon: <Forward className="h-4 w-4" /> },
];
/** Segment kinds exposed by the add menu for a builder context. */
export function messageBuilderSegmentKinds(
mode: MessageBuilderMode,
segments: Seg[],
): SegBody['k'][] {
const all = [...COMMON, ...ADVANCED].map((item) => item.k);
if (mode === 'auto') return all;
if (mode === 'message') return all.filter((kind) => kind !== 'node');
if (mode === 'forward') return ['node'];
// A forward node may contain either an ordinary message or another list of
// nodes, never a mixture. Window shake is also rejected anywhere inside a
// forward payload. Lock the menu to the branch selected by the first child.
const forwardSafe = all.filter((kind) => kind !== 'poke');
if (segments.length === 0) return forwardSafe;
if (segments.every((segment) => segment.k === 'node')) return ['node'];
if (segments.every((segment) => segment.k !== 'node')) {
return forwardSafe.filter((kind) => kind !== 'node');
}
return [];
}
const LABELS: Record<SegBody['k'], string> = {
text: '文本', at: '@', image: '图片', face: '表情', reply: '回复', record: '语音', video: '视频',
file: '文件', mface: '商城表情', poke: '戳一戳', json: 'JSON', xml: 'XML', markdown: 'Markdown', node: '转发节点',
};
export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }: {
export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0, mode = 'auto' }: {
segments: Seg[];
onChange: (segs: Seg[]) => void;
uin: string;
/** group context for @ member picking (empty for private targets). */
groupId: string;
depth?: number;
mode?: MessageBuilderMode;
}) {
const [showAdd, setShowAdd] = useState(false);
const [dragFrom, setDragFrom] = useState<number | null>(null);
@@ -140,6 +164,11 @@ export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }:
: depth === 1
? 'max(0px, calc(var(--radius) - 0.25rem))'
: 'max(0px, calc(var(--radius) - 0.5rem))';
const allowedKinds = new Set(messageBuilderSegmentKinds(mode, segments));
const commonOptions = COMMON.filter((item) => allowedKinds.has(item.k));
const advancedOptions = ADVANCED.filter((item) => allowedKinds.has(item.k));
const primaryOptions = mode === 'forward' ? advancedOptions : commonOptions;
const secondaryOptions = mode === 'forward' ? [] : advancedOptions;
return (
// The root is a bounded compose canvas, so its empty hint reads as an
@@ -152,7 +181,9 @@ export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }:
style={nested ? undefined : { borderRadius: canvasRadius }}
>
{segments.length === 0 && (
<p className="py-4 text-center text-xs text-muted-foreground">空消息 — 点下方「添加段」开始</p>
<p className="py-4 text-center text-xs text-muted-foreground">
{mode === 'forward' ? '空转发 — 点下方添加转发节点' : '空消息 — 点下方「添加段」开始'}
</p>
)}
{segments.map((s, i) => (
@@ -201,24 +232,24 @@ export function MessageBuilder({ segments, onChange, uin, groupId, depth = 0 }:
{showAdd && (
<div className="absolute z-30 mt-1.5 w-64 rounded-xl border border-border/60 bg-popover p-2 shadow-lg">
<div className="grid grid-cols-4 gap-1">
{COMMON.map((c) => (
{primaryOptions.map((c) => (
<button key={c.k} type="button" onClick={() => add(c.k)}
className="flex flex-col items-center gap-1 rounded-sm p-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground">
{c.icon}{c.label}
</button>
))}
</div>
<details className="mt-1.5">
{secondaryOptions.length > 0 && <details className="mt-1.5">
<summary className="cursor-pointer list-none px-1 text-xs text-muted-foreground hover:text-foreground"><span className="inline-flex items-center gap-1"><ChevronDown className="h-3 w-3" /> 进阶段</span></summary>
<div className="mt-1 grid grid-cols-4 gap-1">
{ADVANCED.map((c) => (
{secondaryOptions.map((c) => (
<button key={c.k} type="button" onClick={() => add(c.k)}
className="flex flex-col items-center gap-1 rounded-sm p-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground">
{c.icon}{c.label}
</button>
))}
</div>
</details>
</details>}
</div>
)}
</div>
@@ -278,7 +309,7 @@ function SegmentEditor({ seg, onChange, uin, groupId, depth }: { seg: Seg; onCha
<div>
<span className="mb-1 block text-xs text-muted-foreground">节点内容(可再嵌套)</span>
{depth < 3 ? (
<MessageBuilder segments={seg.content} onChange={(c) => onChange({ ...seg, content: c })} uin={uin} groupId={groupId} depth={depth + 1} />
<MessageBuilder segments={seg.content} onChange={(c) => onChange({ ...seg, content: c })} uin={uin} groupId={groupId} depth={depth + 1} mode="node-content" />
) : (
<p className="text-xs text-destructive">嵌套层级过深</p>
)}
@@ -11,7 +11,12 @@ import { Picker } from '@/components/ui/picker';
import { FaceGrid } from '@/components/ui/face-grid';
import { FileSource } from '@/components/debug/file-source';
import { Segmented } from '@/components/debug/segmented';
import { MessageBuilder, toOneBot, type Seg } from '@/components/debug/message-builder';
import {
MessageBuilder,
toOneBot,
type MessageBuilderMode,
type Seg,
} from '@/components/debug/message-builder';
import { useFriends, useGroups, useGroupMembers } from '@/hooks/use-debug-contacts';
import type { DebugActionParam, FieldRole } from '@/types';
@@ -47,13 +52,15 @@ function MemberPicker({ uin, groupId, value, onChange }: { uin: string; groupId:
const MEDIA_ROLES: FieldRole[] = ['file', 'image', 'record', 'video'];
export function ParamField({ param, value, onChange, uin, groupContext }: {
export function ParamField({ param, value, onChange, uin, groupContext, actionName }: {
param: DebugActionParam;
value: string;
onChange: (v: string) => void;
uin: string;
/** value of the sibling group_id field (for member_id pickers). */
groupContext: string;
/** Selected Action controls which message shapes the visual builder offers. */
actionName: string;
}) {
const role = param.role;
@@ -108,7 +115,8 @@ export function ParamField({ param, value, onChange, uin, groupContext }: {
);
}
if (param.type === 'message') {
return <MessageParamField value={value} onChange={onChange} uin={uin} groupContext={groupContext} />;
return <MessageParamField value={value} onChange={onChange} uin={uin} groupContext={groupContext}
mode={messageBuilderModeForAction(actionName)} />;
}
if (isNumericType(param.type)) {
return <Input type="number" value={value} onChange={(e) => onChange(e.target.value)}
@@ -118,12 +126,22 @@ export function ParamField({ param, value, onChange, uin, groupContext }: {
placeholder={param.desc || (param.default !== undefined ? `默认 ${JSON.stringify(param.default)}` : '')} />;
}
export function messageBuilderModeForAction(actionName: string): MessageBuilderMode {
return /(?:forward|foward)_msg$/.test(actionName) ? 'forward' : 'message';
}
// Message param: the visual builder (keeps its own Seg[] model and emits the
// serialized OneBot array as the string param value) with a raw-text escape
// hatch. The builder is one-way (builder → value); switching to 原文 edits the
// string directly — the tester's global JSON mode covers full raw editing.
function MessageParamField({ value, onChange, uin, groupContext }: { value: string; onChange: (v: string) => void; uin: string; groupContext: string }) {
const [mode, setMode] = useState<'build' | 'raw'>('build');
function MessageParamField({ value, onChange, uin, groupContext, mode }: {
value: string;
onChange: (v: string) => void;
uin: string;
groupContext: string;
mode: MessageBuilderMode;
}) {
const [inputMode, setInputMode] = useState<'build' | 'raw'>('build');
const [segs, setSegs] = useState<Seg[]>([]);
const updateSegs = (next: Seg[]) => {
@@ -134,10 +152,10 @@ function MessageParamField({ value, onChange, uin, groupContext }: { value: stri
return (
<div className="flex flex-col gap-2">
<div className="flex justify-end">
<Segmented value={mode} onChange={setMode} options={[{ value: 'build', label: '构建器' }, { value: 'raw', label: '原文' }]} />
<Segmented value={inputMode} onChange={setInputMode} options={[{ value: 'build', label: '构建器' }, { value: 'raw', label: '原文' }]} />
</div>
{mode === 'build' ? (
<MessageBuilder segments={segs} onChange={updateSegs} uin={uin} groupId={groupContext} />
{inputMode === 'build' ? (
<MessageBuilder segments={segs} onChange={updateSegs} uin={uin} groupId={groupContext} mode={mode} />
) : (
<textarea
value={value}
@@ -0,0 +1,53 @@
import { useState } from 'react';
import { AlertTriangle, X } from 'lucide-react';
import { shouldWarnAboutInsecureRemoteAccess } from '@/lib/transport-security';
const DISMISS_KEY = 'snowluma.insecure-remote-access.dismissed.v1';
function readDismissed(): boolean {
if (typeof window === 'undefined') return false;
try {
return window.localStorage.getItem(DISMISS_KEY) === '1';
} catch (error) {
console.warn('failed to read insecure transport notice preference', error);
return false;
}
}
export function InsecureRemoteAccessBanner() {
const [dismissed, setDismissed] = useState(readDismissed);
const visible = typeof window !== 'undefined'
&& shouldWarnAboutInsecureRemoteAccess(window.location)
&& !dismissed;
if (!visible) return null;
const dismiss = () => {
setDismissed(true);
try {
window.localStorage.setItem(DISMISS_KEY, '1');
} catch (error) {
console.warn('failed to persist insecure transport notice preference', error);
}
};
return (
<div
role="alert"
className="sticky top-0 z-[100] flex items-center justify-center gap-3 border-b border-amber-500/35 bg-amber-100 px-4 py-2.5 text-sm text-amber-950 shadow-sm dark:bg-amber-950 dark:text-amber-100"
>
<AlertTriangle className="size-4 shrink-0" aria-hidden="true" />
<p className="max-w-4xl leading-relaxed">
当前页面通过远程 HTTP 访问,登录凭据和操作内容可能被同网络设备读取;请在设置中启用 HTTPS,或通过受信任的 HTTPS 反向代理访问。
</p>
<button
type="button"
aria-label="关闭远程 HTTP 访问提醒"
className="ml-auto inline-flex size-8 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-amber-500/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-700"
onClick={dismiss}
>
<X className="size-4" aria-hidden="true" />
</button>
</div>
);
}
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more