lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
+525
-447
File diff suppressed because it is too large.
Load diff
@@ -1,58 +1,74 @@
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { packetTimeoutMs } from './packet-timeout';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
QqHookClient,
|
||||
type QqHookSendReply,
|
||||
} from './qq-hook-client';
|
||||
|
||||
export type OutboundHealthListener = (healthy: boolean) => void;
|
||||
|
||||
export class HookPacketClient implements PacketSender {
|
||||
private outboundHealthy = true;
|
||||
private outboundHealthy = true;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) { }
|
||||
constructor(
|
||||
private readonly client: QqHookClient,
|
||||
private readonly onOutboundHealthChanged?: OutboundHealthListener,
|
||||
) {}
|
||||
|
||||
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = packetTimeoutMs()): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
|
||||
async sendPacket(
|
||||
serviceCmd: string,
|
||||
body: Buffer,
|
||||
timeoutMs = packetTimeoutMs(),
|
||||
): Promise<SendPacketResult> {
|
||||
if (!this.client.isLoggedIn) {
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: 'qq_hook client is not logged in',
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = (await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
})) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message || '',
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof HookPipeRequestError &&
|
||||
error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE
|
||||
) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const reply = await this.client.send(serviceCmd, body, {
|
||||
wantReply: true,
|
||||
replyTimeoutMs: timeoutMs,
|
||||
}) as QqHookSendReply;
|
||||
this.setOutboundHealthy(true);
|
||||
return {
|
||||
success: reply.error === 0,
|
||||
gotResponse: true,
|
||||
errorCode: reply.error,
|
||||
errorMessage: reply.message || '',
|
||||
responseData: reply.body,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof HookPipeRequestError
|
||||
&& error.status === PIPE_STATUS_CONNECTION_UNAVAILABLE) {
|
||||
this.setOutboundHealthy(false);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorCode: -1,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
responseData: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) {
|
||||
return;
|
||||
}
|
||||
|
||||
private setOutboundHealthy(healthy: boolean): void {
|
||||
if (this.outboundHealthy === healthy) return;
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
this.outboundHealthy = healthy;
|
||||
this.onOutboundHealthChanged?.(healthy);
|
||||
}
|
||||
}
|
||||
@@ -3,128 +3,166 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
export interface HookRuntimeDirDeps {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
ownUid?: number;
|
||||
readText?: (file: string) => string;
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
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';
|
||||
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);
|
||||
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;
|
||||
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
'SNOWLUMA_HOOK_RUNTIME_DIR',
|
||||
);
|
||||
|
||||
const xdg = configuredDirectory(env.XDG_RUNTIME_DIR, 'XDG_RUNTIME_DIR');
|
||||
if (xdg) return xdg;
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
const tmpdir = configuredDirectory(env.TMPDIR, 'TMPDIR');
|
||||
if (tmpdir) return path.join(tmpdir, 'snowluma-hook');
|
||||
}
|
||||
return `/tmp/snowluma-${ownUid}`;
|
||||
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'));
|
||||
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;
|
||||
if (platform !== 'linux' || !Number.isSafeInteger(targetPid) || targetPid! <= 0) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
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;
|
||||
}
|
||||
let environError: unknown;
|
||||
|
||||
if (isProcessGoneError(statusError)
|
||||
&& (isProcessGoneError(environError)
|
||||
|| (environError instanceof Error
|
||||
&& environError.message === 'runtime directory is not present'))) {
|
||||
return ownRuntimeDir(platform, env, ownUid);
|
||||
}
|
||||
try {
|
||||
const targetEnv = parseProcessEnvironment(readText(`/proc/${targetPid}/environ`));
|
||||
const explicit = configuredDirectory(
|
||||
targetEnv.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
`QQ process ${targetPid} SNOWLUMA_HOOK_RUNTIME_DIR`,
|
||||
);
|
||||
|
||||
throw new Error(
|
||||
`cannot resolve hook runtime directory for PID ${targetPid}: `
|
||||
+ `environment=${errorMessage(environError)}; status=${errorMessage(statusError)}`,
|
||||
);
|
||||
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)}`,
|
||||
);
|
||||
}
|
||||
+1030
-809
File diff suppressed because it is too large.
Load diff
@@ -9,10 +9,10 @@ import type { HookProcessStatus } from './types';
|
||||
* `loggedIn` *before* tearing the client down, since teardown clears it.
|
||||
*/
|
||||
export interface HookFlags {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
wasLoggedIn: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,7 +25,13 @@ export interface HookFlags {
|
||||
* here.
|
||||
*/
|
||||
export function statusFor(flags: HookFlags): HookProcessStatus {
|
||||
if (!flags.injected) return 'available';
|
||||
if (flags.connected) return flags.loggedIn ? 'online' : 'loaded';
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
if (!flags.injected) {
|
||||
return 'available';
|
||||
}
|
||||
|
||||
if (flags.connected) {
|
||||
return flags.loggedIn ? 'online' : 'loaded';
|
||||
}
|
||||
|
||||
return flags.wasLoggedIn ? 'disconnected' : 'connecting';
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
export {
|
||||
HookManager, type BridgeManagerSink, type HookManagerDeps, type HookProcessBaseInfo, type HookProcessInfo,
|
||||
type HookProcessStatus, type QqPortLoginInfo
|
||||
HookManager,
|
||||
type BridgeManagerSink,
|
||||
type HookManagerDeps,
|
||||
type HookProcessBaseInfo,
|
||||
type HookProcessInfo,
|
||||
type HookProcessStatus,
|
||||
type QqPortLoginInfo,
|
||||
} from './hook-manager';
|
||||
|
||||
+108
-84
@@ -7,135 +7,159 @@ import { listSnowlumaPipePidsSync } from './qq-hook-client';
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ManualMapHandle {
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
exceptionTable: bigint;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface NativeHookAddon {
|
||||
getAllMainProcess(): number[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
getAllMainProcess(): number[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
}
|
||||
|
||||
export interface HookProcessBaseInfo {
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
pid: number;
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface HookInjectResult {
|
||||
method: 'loadModuleManual';
|
||||
handle?: ManualMapHandle;
|
||||
method: 'loadModuleManual';
|
||||
handle?: ManualMapHandle;
|
||||
}
|
||||
|
||||
let nativeAddon: NativeHookAddon | null = null;
|
||||
let nativeLoadError: string | null = null;
|
||||
|
||||
function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
const mod = { exports: {} as Record<string, unknown> };
|
||||
process.dlopen(mod, addonPath);
|
||||
return mod.exports as unknown as NativeHookAddon;
|
||||
}
|
||||
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
return `snowluma-win32-x64.${ext}`;
|
||||
}
|
||||
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
|
||||
function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
if (existsSync(fullPath)) return fullPath;
|
||||
}
|
||||
return null;
|
||||
const fileName = platformBinaryName(ext);
|
||||
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
|
||||
if (existsSync(fullPath)) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getNativeHookAddon(): NativeHookAddon | null {
|
||||
if (nativeAddon) return nativeAddon;
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
return null;
|
||||
}
|
||||
if (nativeAddon) {
|
||||
return nativeAddon;
|
||||
}
|
||||
|
||||
const addonPath = resolveHookNativePath('node');
|
||||
|
||||
if (!addonPath) {
|
||||
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
nativeAddon = loadNativeAddon(addonPath);
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getNativeHookLoadError(): string | null {
|
||||
return nativeLoadError;
|
||||
return nativeLoadError;
|
||||
}
|
||||
|
||||
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) return [];
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter(pid => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
// in the runtime dir as a known process (the watcher's subsequent
|
||||
// connectable-probe gates the pipe-up emit, so a stale dangling socket
|
||||
// here doesn't drive a false connect).
|
||||
if (process.platform === 'darwin') {
|
||||
return [...listSnowlumaPipePidsSync()]
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
}
|
||||
|
||||
export async function injectHookProcess(pid: number): Promise<HookInjectResult> {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
const injectableExt = platformInjectableExt();
|
||||
const dllPath = resolveHookNativePath(injectableExt);
|
||||
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
|
||||
}
|
||||
|
||||
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) };
|
||||
}
|
||||
|
||||
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
addon.unloadModuleManual(pid, handle);
|
||||
}
|
||||
@@ -4,5 +4,5 @@ import { positiveIntEnv } from '@snowluma/common/env';
|
||||
export const DEFAULT_PACKET_TIMEOUT_MS = 15_000;
|
||||
|
||||
export function packetTimeoutMs(env?: NodeJS.ProcessEnv): number {
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
return positiveIntEnv('SNOWLUMA_PACKET_TIMEOUT_MS', DEFAULT_PACKET_TIMEOUT_MS, { env });
|
||||
}
|
||||
+215
-182
@@ -6,17 +6,17 @@ const DEFAULT_INTERVAL_MS = 1500;
|
||||
const MIN_INTERVAL_MS = 250;
|
||||
|
||||
export type PipeWatcherDeps = {
|
||||
/** Native: list QQ.exe processes currently running. May be async and may
|
||||
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
|
||||
* 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. 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;
|
||||
/** Native: list QQ.exe processes currently running. May be async and may
|
||||
* return `null` (UNKNOWN) when enumeration timed out / failed — in which
|
||||
* 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. 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;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -40,191 +40,224 @@ export type PipeWatcherDeps = {
|
||||
* dispose logic when QQ.exe is killed with a live pipe.
|
||||
*/
|
||||
export class PipeWatcher extends EventEmitter {
|
||||
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
|
||||
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
|
||||
private readonly intervalMs: number;
|
||||
private readonly log: Logger;
|
||||
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
|
||||
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
|
||||
private readonly intervalMs: number;
|
||||
private readonly log: Logger;
|
||||
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
private livePipes = new Set<number>();
|
||||
private knownPids = new Set<number>();
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private ticking = false;
|
||||
private pendingWake = false;
|
||||
private startPromise: Promise<void> | null = null;
|
||||
private stopped = false;
|
||||
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) return this.startPromise;
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) return;
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
constructor(deps: PipeWatcherDeps) {
|
||||
super();
|
||||
this.listProcesses = deps.listProcesses;
|
||||
this.listLivePipes = deps.listLivePipes;
|
||||
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
|
||||
this.log = deps.log ?? createLogger('PipeWatcher');
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) return;
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
/** Was this PID's pipe live as of the last completed tick? */
|
||||
isPipeLive(pid: number): boolean {
|
||||
return this.livePipes.has(pid);
|
||||
}
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
/** Was this PID alive as of the last completed tick? */
|
||||
isProcessAlive(pid: number): boolean {
|
||||
return this.knownPids.has(pid);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
/**
|
||||
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
|
||||
* and begin the polling loop. Idempotent.
|
||||
*/
|
||||
start(): Promise<void> {
|
||||
if (this.startPromise) {
|
||||
return this.startPromise;
|
||||
}
|
||||
|
||||
this.startPromise = (async () => {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
})();
|
||||
return this.startPromise;
|
||||
}
|
||||
this.ticking = true;
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = null;
|
||||
}
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
let livePipes: Set<number> | null;
|
||||
try {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = null;
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
for (const proc of processes) newKnownPids.add(proc.pid);
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
if (!this.knownPids.has(proc.pid)) {
|
||||
this.emit('process-discovered', proc);
|
||||
/** Pull the next scheduled tick forward to the next event-loop turn. */
|
||||
wake(): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 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>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
|
||||
// subscribers can run disconnect logic before dispose logic.
|
||||
for (const pid of this.livePipes) {
|
||||
if (!newLivePipes.has(pid)) {
|
||||
this.emit('pipe-down', pid);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => { void this.tickOnce(); });
|
||||
}
|
||||
this.scheduleNext(0);
|
||||
}
|
||||
|
||||
/** Force a single tick now. Resolves after diff events have been emitted. */
|
||||
tickNow(): Promise<void> {
|
||||
return this.tickOnce();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stop();
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
private scheduleNext(delayMs: number): void {
|
||||
if (this.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
this.timer = setTimeout(
|
||||
() => {
|
||||
this.timer = null;
|
||||
void this.tickAndReschedule();
|
||||
},
|
||||
Math.max(0, delayMs),
|
||||
);
|
||||
}
|
||||
|
||||
private async tickAndReschedule(): Promise<void> {
|
||||
try {
|
||||
await this.tickOnce();
|
||||
} finally {
|
||||
this.scheduleNext(this.intervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read processes + live pipes, emit diff events. If another tick is
|
||||
* already running, mark a follow-up tick so we don't lose a wake().
|
||||
*/
|
||||
private async tickOnce(): Promise<void> {
|
||||
if (this.ticking) {
|
||||
this.pendingWake = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.ticking = true;
|
||||
|
||||
try {
|
||||
let processes: HookProcessBaseInfo[] | null;
|
||||
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
processes = null;
|
||||
}
|
||||
|
||||
// UNKNOWN (timeout / failure): keep the prior process + pipe snapshot.
|
||||
// Treating missing data as "everything disappeared" would fire
|
||||
// process-gone for every live PID and dispose healthy sessions — the
|
||||
// freeze-then-teardown footgun behind issue #158. Still emit 'tick' so
|
||||
// the manager's per-tick reconnect retries keep running off last-known
|
||||
// live pipes.
|
||||
if (processes === null) {
|
||||
this.emit('tick');
|
||||
return;
|
||||
}
|
||||
|
||||
let livePipes: Set<number> | null;
|
||||
|
||||
try {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
livePipes = null;
|
||||
}
|
||||
|
||||
const newKnownPids = new Set<number>();
|
||||
|
||||
for (const proc of processes) {
|
||||
newKnownPids.add(proc.pid);
|
||||
}
|
||||
|
||||
// 1. Newly discovered processes.
|
||||
for (const proc of processes) {
|
||||
if (!this.knownPids.has(proc.pid)) {
|
||||
this.emit('process-discovered', proc);
|
||||
}
|
||||
}
|
||||
|
||||
// 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>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
|
||||
// subscribers can run disconnect logic before dispose logic.
|
||||
for (const pid of this.livePipes) {
|
||||
if (!newLivePipes.has(pid)) {
|
||||
this.emit('pipe-down', pid);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Processes that disappeared.
|
||||
for (const pid of this.knownPids) {
|
||||
if (!newKnownPids.has(pid)) {
|
||||
this.emit('process-gone', pid);
|
||||
}
|
||||
}
|
||||
|
||||
this.knownPids = newKnownPids;
|
||||
this.livePipes = newLivePipes;
|
||||
this.emit('tick');
|
||||
} finally {
|
||||
this.ticking = false;
|
||||
|
||||
if (this.pendingWake) {
|
||||
this.pendingWake = false;
|
||||
// Defer to break sync recursion if a listener calls wake().
|
||||
setImmediate(() => {
|
||||
void this.tickOnce();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -29,30 +29,30 @@ import type { HookProcessBaseInfo } from './injector';
|
||||
* exactly today's behaviour, no worse.
|
||||
*/
|
||||
export interface ProcessEnumerator {
|
||||
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
|
||||
* out / failed and the caller should keep its prior state. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
|
||||
* out / failed and the caller should keep its prior state. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface NativeEnumeratorDeps {
|
||||
/** Resolved path to the hook `.node` addon, or null when there is none
|
||||
* (macOS / missing) — in which case we never spawn a worker. */
|
||||
addonPath: string | null;
|
||||
/** Synchronous lister used when worker isolation is unavailable. Returns
|
||||
* today's value (and may itself block — that's the no-worse-than-before
|
||||
* fallback). */
|
||||
fallbackSync: () => HookProcessBaseInfo[];
|
||||
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
|
||||
processName: string;
|
||||
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
|
||||
* enumeration (single-digit ms) but well under a human "is it dead?". */
|
||||
timeoutMs?: number;
|
||||
/** Cap on abandoned (blocked) workers before we stop spawning more and just
|
||||
* return UNKNOWN until they drain. Bounds thread growth across a long
|
||||
* hot-update window. Default 4. */
|
||||
maxOrphans?: number;
|
||||
log?: Logger;
|
||||
/** Resolved path to the hook `.node` addon, or null when there is none
|
||||
* (macOS / missing) — in which case we never spawn a worker. */
|
||||
addonPath: string | null;
|
||||
/** Synchronous lister used when worker isolation is unavailable. Returns
|
||||
* today's value (and may itself block — that's the no-worse-than-before
|
||||
* fallback). */
|
||||
fallbackSync: () => HookProcessBaseInfo[];
|
||||
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
|
||||
processName: string;
|
||||
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
|
||||
* enumeration (single-digit ms) but well under a human "is it dead?". */
|
||||
timeoutMs?: number;
|
||||
/** Cap on abandoned (blocked) workers before we stop spawning more and just
|
||||
* return UNKNOWN until they drain. Bounds thread growth across a long
|
||||
* hot-update window. Default 4. */
|
||||
maxOrphans?: number;
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4000;
|
||||
@@ -87,152 +87,205 @@ if (addon) {
|
||||
`;
|
||||
|
||||
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
}
|
||||
|
||||
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() { /* nothing to tear down */ },
|
||||
};
|
||||
}
|
||||
|
||||
const addonPath = deps.addonPath;
|
||||
let worker: Worker | null = null;
|
||||
/** Set once we learn the addon can't load in a worker — permanent fallback. */
|
||||
let isolationBroken = false;
|
||||
let orphans = 0;
|
||||
let seq = 0;
|
||||
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
|
||||
let disposed = false;
|
||||
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') return;
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn('process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration', msg.error ?? '');
|
||||
isolationBroken = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
if (!entry) return;
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
if (worker === w) teardownWorker();
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (!w) return;
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => { orphans = Math.max(0, orphans - 1); });
|
||||
void w.terminate().catch(() => { /* already gone */ });
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
/* nothing to tear down */
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) return syncFallback();
|
||||
const addonPath = deps.addonPath;
|
||||
let worker: Worker | null = null;
|
||||
/** Set once we learn the addon can't load in a worker — permanent fallback. */
|
||||
let isolationBroken = false;
|
||||
let orphans = 0;
|
||||
let seq = 0;
|
||||
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
|
||||
let disposed = false;
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn(
|
||||
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
|
||||
msg.error ?? '',
|
||||
);
|
||||
isolationBroken = true;
|
||||
|
||||
for (const { resolve } of pending.values()) {
|
||||
resolve(null);
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
|
||||
if (worker === w) {
|
||||
teardownWorker();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
|
||||
if (!w) {
|
||||
return;
|
||||
}
|
||||
spawnWorker();
|
||||
}
|
||||
const w = worker;
|
||||
if (!w) return syncFallback();
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => {
|
||||
orphans = Math.max(0, orphans - 1);
|
||||
});
|
||||
void w.terminate().catch(() => {
|
||||
/* already gone */
|
||||
});
|
||||
};
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
if (timer) clearTimeout(timer);
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { resolve } of pending.values()) resolve(null);
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
if (w) void w.terminate().catch(() => { /* ignore */ });
|
||||
},
|
||||
};
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
|
||||
spawnWorker();
|
||||
}
|
||||
|
||||
const w = worker;
|
||||
|
||||
if (!w) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
});
|
||||
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
log.warn(
|
||||
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
|
||||
timeoutMs,
|
||||
);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapPids(outcome, deps.processName);
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
|
||||
for (const { resolve } of pending.values()) {
|
||||
resolve(null);
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
|
||||
if (w) {
|
||||
void w.terminate().catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
+1186
-931
File diff suppressed because it is too large.
Load diff
@@ -9,11 +9,15 @@ const log = createLogger('LoginProbe');
|
||||
const probeNotes = new Map<number, string>();
|
||||
|
||||
function noteProbe(pid: number, result: string, ports: number, processes: number | null): void {
|
||||
const processText = processes === null ? '' : ` processes=${processes}`;
|
||||
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
|
||||
if (probeNotes.get(pid) === message) return;
|
||||
probeNotes.set(pid, message);
|
||||
log.info(message);
|
||||
const processText = processes === null ? '' : ` processes=${processes}`;
|
||||
const message = `login probe: PID=${pid} result=${result} ports=${ports}${processText}`;
|
||||
|
||||
if (probeNotes.get(pid) === message) {
|
||||
return;
|
||||
}
|
||||
|
||||
probeNotes.set(pid, message);
|
||||
log.info(message);
|
||||
}
|
||||
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
@@ -29,21 +33,21 @@ const EXEC_OPTIONS = { timeout: COMMAND_TIMEOUT_MS, killSignal: 'SIGKILL' as con
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
/** 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;
|
||||
port: number;
|
||||
uin: string;
|
||||
uid?: string;
|
||||
nickName?: string;
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,192 +59,236 @@ interface PtloginUin {
|
||||
* problem, no answer" and should fall through to the deep-link fallback.
|
||||
*/
|
||||
async function fetchPtlogin(port: number, useHttps: boolean): Promise<PtloginUin[] | null> {
|
||||
return new Promise((resolve) => {
|
||||
const protocol = useHttps ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
return new Promise((resolve) => {
|
||||
const protocol = useHttps ? 'https' : 'http';
|
||||
const url = `${protocol}://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
const headers = {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
};
|
||||
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
const handleResponse = (res: http.IncomingMessage) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => {
|
||||
text += chunk.toString();
|
||||
});
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const req = useHttps
|
||||
? https.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false }, handleResponse)
|
||||
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
|
||||
const req = useHttps
|
||||
? https.get(
|
||||
url,
|
||||
{ headers, timeout: CONNECTION_TIMEOUT_MS, rejectUnauthorized: false },
|
||||
handleResponse,
|
||||
)
|
||||
: http.get(url, { headers, timeout: CONNECTION_TIMEOUT_MS }, handleResponse);
|
||||
|
||||
req.on('error', () => resolve(null));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
req.on('error', () => resolve(null));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
const useHttps = port % 2 !== 0;
|
||||
const useHttps = port % 2 !== 0;
|
||||
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
const res1 = await fetchPtlogin(port, useHttps);
|
||||
const res2 = await fetchPtlogin(port, useHttps);
|
||||
|
||||
if (res1 === null && res2 === null) return 'fallback';
|
||||
if (res1 === null && res2 === null) {
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
const usable = [res1, res2].filter((r): r is PtloginUin[] => r !== null);
|
||||
const target = usable.reduce((a, b) => (a.length <= b.length ? a : b));
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
identityKnown: true,
|
||||
};
|
||||
}
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
identityKnown: true,
|
||||
};
|
||||
}
|
||||
|
||||
return 'fallback';
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync(
|
||||
'tasklist /fi "imagename eq QQ.exe" /nh',
|
||||
EXEC_OPTIONS,
|
||||
);
|
||||
return stdout
|
||||
.toLowerCase()
|
||||
.split('\n')
|
||||
.filter((line) => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq', EXEC_OPTIONS);
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[] | null> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('netstat -ano', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
for (const line of lines) {
|
||||
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) continue;
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
|
||||
if (parts.length < 5) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const owningPid = parts[parts.length - 1];
|
||||
|
||||
if (owningPid !== String(pid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
|
||||
if (!portMatch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
const { stdout } = await execAsync('ss -tlnp', EXEC_OPTIONS);
|
||||
const ports = new Set<number>();
|
||||
const lines = stdout.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.includes(`pid=${pid},`) && !line.includes(`pid=${pid})`)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
|
||||
if (match) {
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(ports);
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probeQqLoginInfoInternal(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
if (ports === null) {
|
||||
noteProbe(pid, 'unavailable', 0, null);
|
||||
return null;
|
||||
}
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', 0, totalPids);
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
if (ports === null) {
|
||||
noteProbe(pid, 'unavailable', 0, null);
|
||||
return null;
|
||||
}
|
||||
noteProbe(pid, 'inconclusive', 0, totalPids);
|
||||
return null;
|
||||
}
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
const matchedOddPorts = ports.filter(p => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter(p => EVEN_PT_PORTS.includes(p));
|
||||
if (ports.length === 0) {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
let ptPortsToTry: number[] = [];
|
||||
if (matchedOddPorts.length > 0) {
|
||||
ptPortsToTry = matchedOddPorts;
|
||||
} else if (matchedEvenPorts.length > 0) {
|
||||
ptPortsToTry = matchedEvenPorts;
|
||||
}
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', 0, totalPids);
|
||||
return { port: 0, uin: '', identityKnown: false };
|
||||
}
|
||||
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
noteProbe(pid, 'inconclusive', 0, totalPids);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', ports.length, totalPids);
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
noteProbe(pid, 'inconclusive', ports.length, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
|
||||
return null;
|
||||
const ODD_PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const EVEN_PT_PORTS = [4302, 4304, 4306, 4308, 4310];
|
||||
|
||||
const matchedOddPorts = ports.filter((p) => ODD_PT_PORTS.includes(p));
|
||||
const matchedEvenPorts = ports.filter((p) => EVEN_PT_PORTS.includes(p));
|
||||
|
||||
let ptPortsToTry: number[] = [];
|
||||
|
||||
if (matchedOddPorts.length > 0) {
|
||||
ptPortsToTry = matchedOddPorts;
|
||||
} else if (matchedEvenPorts.length > 0) {
|
||||
ptPortsToTry = matchedEvenPorts;
|
||||
}
|
||||
|
||||
if (ptPortsToTry.length > 0) {
|
||||
for (const port of ptPortsToTry) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
noteProbe(pid, 'no-ports', ports.length, totalPids);
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
};
|
||||
}
|
||||
|
||||
noteProbe(pid, 'inconclusive', ports.length, totalPids);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Background discovery must remain passive. Interactive application
|
||||
// endpoints are deliberately excluded from automatic probing.
|
||||
noteProbe(pid, 'no-match', ptPortsToTry.length, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>(resolve => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(null);
|
||||
}, OVERALL_PROBE_TIMEOUT_MS);
|
||||
});
|
||||
try {
|
||||
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
|
||||
if (timedOut) log.warn('login check timed out: PID=%d', pid);
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let timedOut = false;
|
||||
const timeout = new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
resolve(null);
|
||||
}, OVERALL_PROBE_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await Promise.race([probeQqLoginInfoInternal(pid), timeout]);
|
||||
|
||||
if (timedOut) {
|
||||
log.warn('login check timed out: PID=%d', pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
export type HookProcessStatus =
|
||||
| 'available'
|
||||
| 'loading'
|
||||
| 'connecting'
|
||||
| 'loaded'
|
||||
| 'online'
|
||||
| 'error'
|
||||
| 'disconnected';
|
||||
'available' | 'loading' | 'connecting' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
|
||||
/** Public-facing snapshot of a per-PID HookSession. */
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
}
|
||||
@@ -13,203 +13,228 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
// browser without REST polling.
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
interface Harness {
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
manager: HookManager;
|
||||
pipeWatcher: PipeWatcher;
|
||||
bridgeManager: BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
setProcesses: (next: number[]) => void;
|
||||
setLivePipes: (next: number[]) => void;
|
||||
onSessionsChanged: ReturnType<typeof vi.fn>;
|
||||
clientFactory: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { /* succeed without doing anything */ };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => { pids = next; },
|
||||
setLivePipes: (next) => { live = new Set(next); },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => { throw new Error('listener boom'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
const clientFactory = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
/* succeed without doing anything */
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false; c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
c.close = () => { c.isClosed = true; };
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
onPidReceiveHealthChanged: vi.fn(),
|
||||
} as unknown as BridgeManagerSink & { onPidReceiveHealthChanged: ReturnType<typeof vi.fn> };
|
||||
const onSessionsChanged = vi.fn();
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
onSessionsChanged,
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
pipeWatcher,
|
||||
bridgeManager,
|
||||
onSessionsChanged,
|
||||
clientFactory,
|
||||
setProcesses: (next) => {
|
||||
pids = next;
|
||||
},
|
||||
setLivePipes: (next) => {
|
||||
live = new Set(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.onSessionsChanged', () => {
|
||||
it('fires when the watcher discovers a new QQ process', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
await ctx.pipeWatcher.start();
|
||||
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports a process is gone', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('fires when the watcher reports the pipe came up (status: connecting → loaded)', async () => {
|
||||
const ctx = makeManager({ processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
// Inject so the session is in 'connecting' state; the next pipe-up
|
||||
// makes attemptConnect succeed and status flips to 'loaded'.
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await flush();
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
|
||||
ctx.setLivePipes([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('survives a throwing onSessionsChanged callback — the watcher loop keeps running', async () => {
|
||||
const ctx = makeManager({ processes: [] });
|
||||
ctx.onSessionsChanged.mockImplementation(() => {
|
||||
throw new Error('listener boom');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
ctx.setProcesses([4242]);
|
||||
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
|
||||
await flush();
|
||||
// A second tick still fires the callback — it wasn't unregistered by
|
||||
// the prior throw.
|
||||
ctx.onSessionsChanged.mockClear();
|
||||
ctx.setProcesses([4242, 5555]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
expect(ctx.onSessionsChanged).toHaveBeenCalled();
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
const manager = new HookManager({
|
||||
bridgeManager: {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: vi.fn(() => {
|
||||
const c = new EventEmitter() as any;
|
||||
c.isClosed = false;
|
||||
c.isLoggedIn = false;
|
||||
c.getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
c.connectAll = async () => undefined;
|
||||
|
||||
c.close = () => {
|
||||
c.isClosed = true;
|
||||
};
|
||||
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
await pipeWatcher.start();
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
const list = await manager.listProcesses();
|
||||
expect(list).toHaveLength(1);
|
||||
expect(list[0].pid).toBe(4242);
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager receive-health wiring (#233)', () => {
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
it('forwards stale and recovered receive health for the owning PID', async () => {
|
||||
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await ctx.manager.loadProcess(4242);
|
||||
await ctx.manager.refreshProcess(4242);
|
||||
await flush();
|
||||
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
const client = ctx.clientFactory.mock.results[0]!.value as EventEmitter;
|
||||
client.emit('loginState', { loggedIn: true, uin: '10001', uinNumber: 10001n });
|
||||
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'Date'] });
|
||||
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
try {
|
||||
client.emit('packet', {
|
||||
seq: 1,
|
||||
error: 0,
|
||||
cmd: 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
vi.advanceTimersByTime(105_000);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(4242, true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenCalledWith(4242, false);
|
||||
|
||||
client.emit('packet', {
|
||||
seq: 2,
|
||||
error: 0,
|
||||
cmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||
uin: '10001',
|
||||
body: Buffer.alloc(0),
|
||||
});
|
||||
expect(ctx.bridgeManager.onPidReceiveHealthChanged).toHaveBeenLastCalledWith(
|
||||
4242,
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9,420 +9,463 @@ import type { HookInjectResult, ManualMapHandle } from '../src/injector';
|
||||
import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function managerTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
|
||||
);
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Hook');
|
||||
}
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
onSessionsChanged?: () => void;
|
||||
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(opts.inject ?? (() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(
|
||||
opts.inject ??
|
||||
(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
);
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
|
||||
(c as any).connectAll = async () => {
|
||||
throw new Error('test: never really connect');
|
||||
};
|
||||
|
||||
(c as any).close = () => {
|
||||
(c as any).isClosed = true;
|
||||
};
|
||||
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => {
|
||||
pids = next;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
describe('HookManager runtime TRACE', () => {
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const sessionsChanged = vi.fn();
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: false,
|
||||
processes: [],
|
||||
onSessionsChanged: sessionsChanged,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
|
||||
const facts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
const baseline = managerTrace(entries).length;
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
expect(managerTrace(entries)).toHaveLength(baseline);
|
||||
|
||||
ctx.setProcesses([4242]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
|
||||
const facts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_manager_fact '),
|
||||
);
|
||||
expect(facts.map((entry) => entry.message)).toEqual([
|
||||
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
|
||||
'hook_manager_fact event=process_gone pid=4242 tracked=true',
|
||||
]);
|
||||
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
it('records bounded transient retries and recovery as separate attempts', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
})
|
||||
.mockImplementationOnce(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
}));
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/,
|
||||
),
|
||||
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
expect(attempts[2]!.req).toBe(attempts[3]!.req);
|
||||
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
|
||||
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
let resolveInjection!: (result: HookInjectResult) => void;
|
||||
const injection = new Promise<HookInjectResult>((resolve) => {
|
||||
resolveInjection = resolve;
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({
|
||||
autoLoadOnDiscovery: true,
|
||||
processes: [4242],
|
||||
inject: () => injection,
|
||||
});
|
||||
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
const manualLoad = ctx.manager.loadProcess(4242);
|
||||
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
|
||||
await manualLoad;
|
||||
await flush();
|
||||
|
||||
const attempts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_'),
|
||||
);
|
||||
expect(attempts.map((entry) => entry.message)).toEqual([
|
||||
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
|
||||
expect.stringMatching(
|
||||
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
|
||||
),
|
||||
]);
|
||||
expect(attempts[0]!.req).toBe(attempts[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(error);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'permanent failure',
|
||||
error: 'ptrace denied',
|
||||
ticks: 1,
|
||||
attempts: 1,
|
||||
reason: 'permanent_failure',
|
||||
},
|
||||
{
|
||||
name: 'retry exhaustion',
|
||||
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
|
||||
ticks: 4,
|
||||
attempts: 3,
|
||||
reason: 'retry_exhausted',
|
||||
},
|
||||
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error(error); });
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
try {
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
const starts = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
for (let tick = 0; tick < ticks; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const starts = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_start '),
|
||||
);
|
||||
const terminals = managerTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('hook_autoload_terminal '),
|
||||
);
|
||||
expect(starts).toHaveLength(attempts);
|
||||
expect(terminals).toHaveLength(attempts);
|
||||
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
ctx.manager.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => { throw new Error('ptrace denied'); });
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('retries a transient libc mapping failure on the next watcher tick', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(4242);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('does not retry permanent auto-load errors', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error('ptrace denied');
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('stops retrying a transient libc mapping failure after three attempts', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementation(() => {
|
||||
throw new Error(
|
||||
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
|
||||
);
|
||||
});
|
||||
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
for (let tick = 0; tick < 4; tick += 1) {
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
}
|
||||
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(3);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// `shouldAutoLoadPid` reads /proc/<pid>/cmdline directly, so we point
|
||||
// it at a temporary directory that mimics the procfs layout. This lets
|
||||
// the tests run on macOS / CI without a live Linux QQ process.
|
||||
describe('shouldAutoLoadPid', () => {
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
let tmpProc: string;
|
||||
const originalReadFileSync = fs.readFileSync;
|
||||
const log = createLogger('test');
|
||||
const originalPlatform = process.platform;
|
||||
const originalAutoLoadAll = process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((p: string, ...rest: unknown[]) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
if (match) {
|
||||
return originalReadFileSync(path.join(tmpProc, match[1], 'cmdline'), ...(rest as [BufferEncoding]));
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
beforeEach(() => {
|
||||
tmpProc = fs.mkdtempSync(path.join(os.tmpdir(), 'hookmgr-proc-'));
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
// Redirect readFileSync('/proc/<pid>/cmdline') to the tmp dir.
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = ((
|
||||
p: string,
|
||||
...rest: unknown[]
|
||||
) => {
|
||||
const match = /^\/proc\/(\d+)\/cmdline$/.exec(p);
|
||||
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
if (originalAutoLoadAll === undefined) delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
else process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
if (match) {
|
||||
return originalReadFileSync(
|
||||
path.join(tmpProc, match[1], 'cmdline'),
|
||||
...(rest as [BufferEncoding]),
|
||||
);
|
||||
}
|
||||
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
return originalReadFileSync(p, ...(rest as [BufferEncoding]));
|
||||
}) as typeof fs.readFileSync;
|
||||
});
|
||||
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
afterEach(() => {
|
||||
(fs.readFileSync as unknown as typeof fs.readFileSync) = originalReadFileSync;
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
|
||||
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
if (originalAutoLoadAll === undefined) {
|
||||
delete process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = originalAutoLoadAll;
|
||||
}
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, ['/opt/QQ/qq', '--type=utility', '--utility-sub-type=network.mojom.NetworkService']);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
fs.rmSync(tmpProc, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
function writeCmdline(pid: number, args: string[]): void {
|
||||
const dir = path.join(tmpProc, String(pid));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'cmdline'), args.join('\0') + '\0');
|
||||
}
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
it('allows the QQ main process (no --type=)', () => {
|
||||
writeCmdline(50, ['qq', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(50, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
it('rejects Electron zygotes', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote', '--no-zygote-sandbox', '--no-sandbox']);
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects renderer/gpu/utility children', () => {
|
||||
writeCmdline(70, ['/opt/QQ/qq', '--type=renderer']);
|
||||
writeCmdline(71, ['/opt/QQ/qq', '--type=gpu-process']);
|
||||
writeCmdline(72, [
|
||||
'/opt/QQ/qq',
|
||||
'--type=utility',
|
||||
'--utility-sub-type=network.mojom.NetworkService',
|
||||
]);
|
||||
expect(shouldAutoLoadPid(70, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(71, log)).toBe(false);
|
||||
expect(shouldAutoLoadPid(72, log)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows everything if SNOWLUMA_HOOK_AUTOLOAD_ALL=1 (escape hatch)', () => {
|
||||
writeCmdline(59, ['/opt/QQ/qq', '--type=zygote']);
|
||||
process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL = '1';
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows on non-linux platforms (filter is a Linux-only workaround)', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
// No cmdline file needed — we return true before touching procfs.
|
||||
expect(shouldAutoLoadPid(59, log)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows when /proc is unreadable (dead PID, permission issue)', () => {
|
||||
expect(shouldAutoLoadPid(99999, log)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,60 +1,70 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HookPacketClient } from '../src/hook-packet-client';
|
||||
import {
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
HookPipeRequestError,
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
type QqHookClient,
|
||||
} from '../src/qq-hook-client';
|
||||
|
||||
function fakeClient(send: QqHookClient['send']): QqHookClient {
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
return {
|
||||
isLoggedIn: true,
|
||||
send,
|
||||
} as unknown as QqHookClient;
|
||||
}
|
||||
|
||||
describe('HookPacketClient outbound health', () => {
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
))
|
||||
.mockRejectedValueOnce(new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
))
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
it('reports native connection loss once and recovers after a successful request', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
1,
|
||||
),
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
new HookPipeRequestError(
|
||||
'The QQ connection changed. Please restart QQ and try again.',
|
||||
PIPE_STATUS_CONNECTION_UNAVAILABLE,
|
||||
2,
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
requestId: 3,
|
||||
error: 0,
|
||||
message: '',
|
||||
body: Buffer.from('ok'),
|
||||
});
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: true, gotResponse: true });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
await sender.sendPacket('Test.Command', Buffer.alloc(0));
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
});
|
||||
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
expect(healthChanged.mock.calls).toEqual([[false], [true]]);
|
||||
});
|
||||
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi.fn<QqHookClient['send']>().mockRejectedValue(
|
||||
new HookPipeRequestError('This request is not valid.', -38, 1),
|
||||
);
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
it('does not classify ordinary request rejection as connection loss', async () => {
|
||||
const healthChanged = vi.fn();
|
||||
const send = vi
|
||||
.fn<QqHookClient['send']>()
|
||||
.mockRejectedValue(new HookPipeRequestError('This request is not valid.', -38, 1));
|
||||
const sender = new HookPacketClient(fakeClient(send), healthChanged);
|
||||
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0)))
|
||||
.resolves.toMatchObject({ success: false, gotResponse: false });
|
||||
await expect(sender.sendPacket('Test.Command', Buffer.alloc(0))).resolves.toMatchObject({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
});
|
||||
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(healthChanged).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -13,87 +13,101 @@ import type { BridgeManagerSink } from '../src/hook-manager';
|
||||
import type { QqHookClient } from '../src/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { loggedIn: false, uin: '0', uinNumber: 0n }; }
|
||||
close() {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
async connectAll(_opts: { recv: boolean }) {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
}
|
||||
close() {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
it('after N pipe up/down cycles: no Bridge calls, no client accumulation', async () => {
|
||||
const PID = 61;
|
||||
const liveSet = new Set<number>([PID]);
|
||||
const clients: FakeClient[] = [];
|
||||
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect(
|
||||
alive.length,
|
||||
`live clients after ${CYCLES} cycles: ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManagerSink;
|
||||
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
});
|
||||
|
||||
// Initial discovery + first connect.
|
||||
await pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Drive 50 pipe up/down cycles with the QQ process staying alive but
|
||||
// the pipe (= QQ control socket) bouncing every "tick".
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
liveSet.delete(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
liveSet.add(PID);
|
||||
await pipeWatcher.tickNow();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// The "QQ never logs in" hypothesis: BridgeManager should never have
|
||||
// been told about a login or a disconnect.
|
||||
expect(bridgeManager.onHookLogin).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPidDisconnected).not.toHaveBeenCalled();
|
||||
expect(bridgeManager.onPacket).not.toHaveBeenCalled();
|
||||
|
||||
// Hook layer should hold at most one live client.
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect(alive.length, `live clients after ${CYCLES} cycles: ${alive.length}`).toBeLessThanOrEqual(1);
|
||||
|
||||
// Total clients minted = roughly one per up cycle. Sanity bound:
|
||||
// we must have actually exercised the reconnect path.
|
||||
expect(clients.length).toBeGreaterThan(1);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -24,100 +24,119 @@ import type { QqHookClient } from '../src/qq-hook-client';
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
|
||||
class FakeClient extends EventEmitter {
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
isClosed = false;
|
||||
isLoggedIn = false;
|
||||
private loginState = { loggedIn: false, uin: '0', uinNumber: 0n };
|
||||
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) throw new Error('client is closed');
|
||||
}
|
||||
getLoginState() { return { ...this.loginState }; }
|
||||
close(): void {
|
||||
if (this.isClosed) return;
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
async connectAll(_opts: { recv: boolean }): Promise<void> {
|
||||
if (this.isClosed) {
|
||||
throw new Error('client is closed');
|
||||
}
|
||||
}
|
||||
getLoginState() {
|
||||
return { ...this.loginState };
|
||||
}
|
||||
close(): void {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
function totalListenerCount(emitter: EventEmitter): number {
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
return emitter.eventNames().reduce((n, evt) => n + emitter.listenerCount(evt), 0);
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
const flush = () => new Promise<void>((r) => setImmediate(r));
|
||||
|
||||
describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
it('does not accumulate live FakeClient instances across N pipe up/down cycles', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 50;
|
||||
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
const alive = clients.filter((c) => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(
|
||||
alive.length,
|
||||
`expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
handle: DUMMY_HANDLE,
|
||||
})),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
|
||||
const CYCLES = 50;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const alive = clients.filter(c => !c.isClosed);
|
||||
expect.soft(clients.length).toBeGreaterThan(1);
|
||||
expect(alive.length, `expected ≤1 live client after ${CYCLES} reconnects, got ${alive.length}`)
|
||||
.toBeLessThanOrEqual(1);
|
||||
});
|
||||
const CYCLES = 20;
|
||||
|
||||
it('drops all listeners from each torn-down client', async () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
injector: {
|
||||
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: () => {
|
||||
const c = new FakeClient();
|
||||
clients.push(c);
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(
|
||||
lc,
|
||||
`client #${i} of ${clients.length} still has ${lc} listeners after teardown`,
|
||||
).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
|
||||
const CYCLES = 20;
|
||||
for (let i = 0; i < CYCLES; i++) {
|
||||
pipeLive = false;
|
||||
session.onPipeDown();
|
||||
await flush();
|
||||
pipeLive = true;
|
||||
session.onPipeUp();
|
||||
await flush();
|
||||
}
|
||||
|
||||
// Every client except the current one should have 0 listeners attached.
|
||||
// (HookSession.tearDownClient does client.removeAllListeners().)
|
||||
for (let i = 0; i < clients.length - 1; i++) {
|
||||
const lc = totalListenerCount(clients[i]);
|
||||
expect(lc, `client #${i} of ${clients.length} still has ${lc} listeners after teardown`)
|
||||
.toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,66 +2,84 @@ 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;
|
||||
};
|
||||
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('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('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('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('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');
|
||||
});
|
||||
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');
|
||||
});
|
||||
});
|
||||
+1209
-1086
File diff suppressed because it is too large.
Load diff
@@ -3,54 +3,66 @@ import { statusFor, type HookFlags } from '../src/hook-status';
|
||||
import type { HookProcessStatus } from '../src/types';
|
||||
|
||||
const F = (o: Partial<HookFlags>): HookFlags => ({
|
||||
injected: false, connected: false, loggedIn: false, wasLoggedIn: false, ...o,
|
||||
injected: false,
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
wasLoggedIn: false,
|
||||
...o,
|
||||
});
|
||||
|
||||
describe('statusFor — settled HookProcessStatus derivation', () => {
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true }))).toBe('available');
|
||||
});
|
||||
it('not injected → available (regardless of other flags)', () => {
|
||||
expect(statusFor(F({ injected: false }))).toBe('available');
|
||||
// !injected dominates: stale connected/loggedIn bits must not leak through.
|
||||
expect(
|
||||
statusFor(F({ injected: false, connected: true, loggedIn: true, wasLoggedIn: true })),
|
||||
).toBe('available');
|
||||
});
|
||||
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
it('injected, connected, loggedIn → online', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: true }))).toBe('online');
|
||||
});
|
||||
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
it('injected, connected, not loggedIn → loaded', () => {
|
||||
expect(statusFor(F({ injected: true, connected: true, loggedIn: false }))).toBe('loaded');
|
||||
});
|
||||
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe('disconnected');
|
||||
});
|
||||
it('injected, not connected, had logged in → disconnected', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: true }))).toBe(
|
||||
'disconnected',
|
||||
);
|
||||
});
|
||||
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
it('injected, not connected, never logged in → connecting', () => {
|
||||
expect(statusFor(F({ injected: true, connected: false, wasLoggedIn: false }))).toBe(
|
||||
'connecting',
|
||||
);
|
||||
});
|
||||
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
it('disconnected vs connecting differ ONLY by wasLoggedIn (same injected+!connected)', () => {
|
||||
const base = { injected: true, connected: false, loggedIn: false };
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: true }))).toBe('disconnected');
|
||||
expect(statusFor(F({ ...base, wasLoggedIn: false }))).toBe('connecting');
|
||||
});
|
||||
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
it('covers exactly the five settled states across the flag space', () => {
|
||||
const seen = new Set<HookProcessStatus>();
|
||||
|
||||
for (const injected of [false, true]) {
|
||||
for (const connected of [false, true]) {
|
||||
for (const loggedIn of [false, true]) {
|
||||
for (const wasLoggedIn of [false, true]) {
|
||||
seen.add(statusFor({ injected, connected, loggedIn, wasLoggedIn }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
|
||||
expect([...seen].sort()).toEqual(
|
||||
['available', 'connecting', 'disconnected', 'loaded', 'online'].sort(),
|
||||
);
|
||||
// The two out-of-band states are never produced by the pure derivation.
|
||||
expect(seen.has('loading')).toBe(false);
|
||||
expect(seen.has('error')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,21 +3,21 @@ import { fileURLToPath } from 'url';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { existsSyncMock, listPidsMock } = vi.hoisted(() => ({
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
existsSyncMock: vi.fn<(target: string) => boolean>(() => false),
|
||||
listPidsMock: vi.fn(() => new Set<number>()),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
const actual = await importOriginal<typeof import('fs')>();
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: Parameters<typeof actual.existsSync>[0]) =>
|
||||
existsSyncMock(String(target)),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../src/qq-hook-client', () => ({
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
}));
|
||||
|
||||
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
|
||||
@@ -25,378 +25,391 @@ const ORIGINAL_PLATFORM = process.platform;
|
||||
const ORIGINAL_ARCH = process.arch;
|
||||
|
||||
const HANDLE = {
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
base: 0x7fff0000n,
|
||||
entry: 0x7fff1234n,
|
||||
exceptionTable: 0x7fff5678n,
|
||||
size: 8192,
|
||||
};
|
||||
|
||||
function setPlatform(platform: NodeJS.Platform, arch: string): void {
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: arch, configurable: true });
|
||||
}
|
||||
|
||||
function restorePlatform(): void {
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
Object.defineProperty(process, 'platform', { value: ORIGINAL_PLATFORM, configurable: true });
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
}
|
||||
|
||||
function nativeSearchDirs(cwd = process.cwd()): string[] {
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
];
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
|
||||
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
|
||||
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
|
||||
}
|
||||
|
||||
function allowExisting(paths: readonly string[]): void {
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
const allowed = new Set(paths);
|
||||
existsSyncMock.mockImplementation((target) => allowed.has(target));
|
||||
}
|
||||
|
||||
function fakeAddon(overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {}) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
function fakeAddon(
|
||||
overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {},
|
||||
) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
}
|
||||
|
||||
function installDlopen(addon: object) {
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
return vi.spyOn(process, 'dlopen').mockImplementation((mod) => {
|
||||
(mod as { exports: object }).exports = addon;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInjector() {
|
||||
return import('../src/injector');
|
||||
return import('../src/injector');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
existsSyncMock.mockReset();
|
||||
existsSyncMock.mockReturnValue(false);
|
||||
listPidsMock.mockReset();
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
restorePlatform();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('resolveHookNativePath', () => {
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
it('returns null after probing every search directory', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return false;
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
});
|
||||
|
||||
it('returns the first existing candidate and stops scanning', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const winner = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const later = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const probed: string[] = [];
|
||||
existsSyncMock.mockImplementation((target) => {
|
||||
probed.push(target);
|
||||
return target === winner || target === later;
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(probed).toEqual([winner]);
|
||||
});
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('so')).toBe(winner);
|
||||
});
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('dll')).toBe(winner);
|
||||
});
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('uses the generic platform-arch name on win32 arm64', async () => {
|
||||
setPlatform('win32', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-win32-arm64.node', 1);
|
||||
allowExisting([winner]);
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join(
|
||||
'/tmp/sl-injector-cwd',
|
||||
'dist',
|
||||
'native',
|
||||
'snowluma-darwin-arm64.node',
|
||||
);
|
||||
allowExisting([winner]);
|
||||
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join('/tmp/sl-injector-cwd', 'dist', 'native', 'snowluma-darwin-arm64.node');
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getNativeHookAddon / getNativeHookLoadError', () => {
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
it('starts with a null load error before any probe', async () => {
|
||||
const { getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
it('returns null and records a missing-binary error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const dlopen = vi.spyOn(process, 'dlopen');
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
it('dlopens the resolved .node once and caches the addon', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
const addon = fakeAddon();
|
||||
const dlopen = installDlopen(addon);
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
const first = getNativeHookAddon();
|
||||
const second = getNativeHookAddon();
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
expect(first).toBe(addon);
|
||||
expect(second).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
expect(dlopen).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen.mock.calls[0]![1]).toBe(nodePath);
|
||||
});
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
it('stores Error.message when process.dlopen throws', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw new Error('not a valid Node addon');
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('not a valid Node addon');
|
||||
});
|
||||
|
||||
it('stringifies a non-Error dlopen failure', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(() => {
|
||||
throw 42;
|
||||
});
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('42');
|
||||
});
|
||||
|
||||
it('retries after a failed load when a binary later appears', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 1);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { getNativeHookAddon, getNativeHookLoadError } = await loadInjector();
|
||||
expect(getNativeHookAddon()).toBeNull();
|
||||
expect(getNativeHookLoadError()).toBe('No hook native addon found for linux-x64');
|
||||
|
||||
allowExisting([nodePath]);
|
||||
expect(getNativeHookAddon()).toBe(addon);
|
||||
expect(getNativeHookLoadError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('listHookProcesses', () => {
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
]);
|
||||
expect(listPidsMock).toHaveBeenCalledTimes(1);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
it('on darwin returns an empty list when no control sockets exist', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}));
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}),
|
||||
);
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
{ pid: 9, name: 'QQ.exe', path: '' },
|
||||
]);
|
||||
});
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('injectHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
|
||||
it('awaits a thenable loadModuleManual handle', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({
|
||||
loadModuleManual: () => Promise.resolve(HANDLE),
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
it('throws when the addon exists but the injectable is missing', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
installDlopen(fakeAddon());
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
it('awaits a thenable loadModuleManual handle', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
|
||||
const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({
|
||||
loadModuleManual: () => Promise.resolve(HANDLE),
|
||||
});
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(77)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(4242)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath);
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
|
||||
});
|
||||
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(77)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}));
|
||||
it('injects snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
|
||||
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
|
||||
allowExisting([nodePath, dllPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(5150)).resolves.toEqual({
|
||||
method: 'loadModuleManual',
|
||||
handle: HANDLE,
|
||||
});
|
||||
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath);
|
||||
});
|
||||
|
||||
it('propagates a rejected loadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.so', 0),
|
||||
]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
loadModuleManual: () => Promise.reject(new Error('map failed')),
|
||||
}),
|
||||
);
|
||||
|
||||
const { injectHookProcess } = await loadInjector();
|
||||
await expect(injectHookProcess(7)).rejects.toThrow('map failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unloadHookProcess', () => {
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow('No hook native addon found for linux-x64');
|
||||
});
|
||||
it('throws the missing-addon load error', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(() => unloadHookProcess(4242, HANDLE)).toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
it('forwards pid and handle to unloadModuleManual', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
|
||||
const addon = fakeAddon();
|
||||
installDlopen(addon);
|
||||
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
const { unloadHookProcess } = await loadInjector();
|
||||
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined();
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1);
|
||||
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE);
|
||||
});
|
||||
});
|
||||
@@ -6,25 +6,25 @@ const PACKET = 'SNOWLUMA_PACKET_TIMEOUT_MS';
|
||||
const ACK = 'SNOWLUMA_HOOK_ACK_TIMEOUT_MS';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
delete process.env[PACKET];
|
||||
delete process.env[ACK];
|
||||
});
|
||||
|
||||
describe('packet and hook ack timeouts', () => {
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
it('keeps the 15 second packet default', () => {
|
||||
expect(packetTimeoutMs({})).toBe(15_000);
|
||||
});
|
||||
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
it('reads SNOWLUMA_PACKET_TIMEOUT_MS', () => {
|
||||
expect(packetTimeoutMs({ [PACKET]: '8000' })).toBe(8000);
|
||||
expect(packetTimeoutMs({ [PACKET]: '0' })).toBe(15_000);
|
||||
});
|
||||
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
it('uses SNOWLUMA_HOOK_ACK_TIMEOUT_MS when the client is not given one', () => {
|
||||
process.env[ACK] = '1200';
|
||||
const client = new QqHookClient(1, { runtimeDir: '/tmp' });
|
||||
expect(client.defaultAckTimeoutMs).toBe(1200);
|
||||
const explicit = new QqHookClient(1, { runtimeDir: '/tmp', ackTimeoutMs: 50 });
|
||||
expect(explicit.defaultAckTimeoutMs).toBe(50);
|
||||
});
|
||||
});
|
||||
@@ -3,282 +3,312 @@ import { PipeWatcher } from '../src/pipe-watcher';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<number> }) {
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => { processes = p; },
|
||||
setLive: (s: Set<number>) => { live = s; },
|
||||
};
|
||||
let processes = initial.processes;
|
||||
let live = initial.live;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => processes,
|
||||
// Defensively copy so the watcher can't mutate the test's reference.
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
|
||||
});
|
||||
return {
|
||||
watcher,
|
||||
setProcesses: (p: HookProcessBaseInfo[]) => {
|
||||
processes = p;
|
||||
},
|
||||
setLive: (s: Set<number>) => {
|
||||
live = s;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type EventRow = [string, unknown];
|
||||
|
||||
function captureEvents(watcher: PipeWatcher): EventRow[] {
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', info => events.push(['discovered', (info as HookProcessBaseInfo).pid]));
|
||||
watcher.on('process-gone', pid => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', pid => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', pid => events.push(['down', pid]));
|
||||
return events;
|
||||
const events: EventRow[] = [];
|
||||
watcher.on('process-discovered', (info) =>
|
||||
events.push(['discovered', (info as HookProcessBaseInfo).pid]),
|
||||
);
|
||||
watcher.on('process-gone', (pid) => events.push(['gone', pid]));
|
||||
watcher.on('pipe-up', (pid) => events.push(['up', pid]));
|
||||
watcher.on('pipe-down', (pid) => events.push(['down', pid]));
|
||||
return events;
|
||||
}
|
||||
|
||||
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,
|
||||
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();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(observed).toEqual(processes);
|
||||
watcher.stop();
|
||||
});
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
it('start() emits process-discovered + pipe-up for live PIDs on first tick', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(true);
|
||||
expect(ctx.watcher.isProcessAlive(1234)).toBe(true);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234]]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234], ['down', 1234], ['up', 1234]]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => { ticks++; });
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>(resolve => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) throw new Error('boom');
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
it('pipe-down emitted when a previously-live pipe disappears', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([['discovered', 1234], ['up', 1234]]);
|
||||
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,
|
||||
expect(events).toEqual([['down', 1234]]);
|
||||
expect(ctx.watcher.isPipeLive(1234)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
const events = captureEvents(watcher);
|
||||
it('process-gone + pipe-down both emitted (pipe-down first) when QQ.exe is killed with a live pipe', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
failPipeDiscovery = true;
|
||||
await watcher.tickNow();
|
||||
ctx.setProcesses([]);
|
||||
ctx.setLive(new Set());
|
||||
await ctx.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]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
it('ignores live pipes whose process is not running', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [],
|
||||
live: new Set([9999]),
|
||||
});
|
||||
const events = captureEvents(ctx.watcher);
|
||||
await ctx.watcher.start();
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
expect(events).toEqual([]);
|
||||
expect(ctx.watcher.isPipeLive(9999)).toBe(false);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
it('emits pipe-up again after a pipe-down → pipe-up cycle', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([['down', 1234], ['gone', 1234]]);
|
||||
watcher.stop();
|
||||
});
|
||||
ctx.setLive(new Set());
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
]);
|
||||
|
||||
ctx.setLive(new Set([1234]));
|
||||
await ctx.watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['up', 1234],
|
||||
['down', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('does not double-emit on idempotent ticks (no state change)', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set([1234]),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
await ctx.watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('emits "tick" after every poll', async () => {
|
||||
const ctx = setupWatcher({ processes: [], live: new Set() });
|
||||
let ticks = 0;
|
||||
ctx.watcher.on('tick', () => {
|
||||
ticks++;
|
||||
});
|
||||
|
||||
await ctx.watcher.start();
|
||||
expect(ticks).toBe(1);
|
||||
|
||||
await ctx.watcher.tickNow();
|
||||
expect(ticks).toBe(2);
|
||||
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('wake() pulls the next tick forward', async () => {
|
||||
const ctx = setupWatcher({
|
||||
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
|
||||
live: new Set(),
|
||||
});
|
||||
await ctx.watcher.start();
|
||||
const events = captureEvents(ctx.watcher);
|
||||
|
||||
// Wait on 'tick' rather than guessing how many event-loop turns
|
||||
// setTimeout(0) needs (it's clamped to ~1ms and races setImmediate).
|
||||
const nextTick = new Promise<void>((resolve) => ctx.watcher.once('tick', () => resolve()));
|
||||
ctx.setLive(new Set([1234]));
|
||||
ctx.watcher.wake();
|
||||
await nextTick;
|
||||
|
||||
expect(events).toEqual([['up', 1234]]);
|
||||
ctx.watcher.stop();
|
||||
});
|
||||
|
||||
it('survives a throwing listProcesses without crashing the watcher', async () => {
|
||||
let processes: HookProcessBaseInfo[] = [];
|
||||
let live = new Set<number>();
|
||||
let shouldThrow = true;
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => {
|
||||
if (shouldThrow) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return processes;
|
||||
},
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(false);
|
||||
|
||||
shouldThrow = false;
|
||||
processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
|
||||
live = new Set([1234]);
|
||||
const events = captureEvents(watcher);
|
||||
await watcher.tickNow();
|
||||
|
||||
expect(events).toEqual([
|
||||
['discovered', 1234],
|
||||
['up', 1234],
|
||||
]);
|
||||
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]);
|
||||
const watcher = new PipeWatcher({
|
||||
listProcesses: () => result,
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
|
||||
await watcher.start();
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
const events = captureEvents(watcher);
|
||||
|
||||
// Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ
|
||||
// hot-update). Prior process + pipe state MUST be preserved — no teardown.
|
||||
result = null;
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
expect(watcher.isProcessAlive(1234)).toBe(true);
|
||||
expect(watcher.isPipeLive(1234)).toBe(true);
|
||||
|
||||
// Enumeration recovers with the same set → still no churn.
|
||||
result = [{ pid: 1234, name: 'qq', path: '' }];
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([]);
|
||||
|
||||
// A REAL disappearance (empty list, not null) still fires the teardown.
|
||||
result = [];
|
||||
live = new Set();
|
||||
await watcher.tickNow();
|
||||
expect(events).toEqual([
|
||||
['down', 1234],
|
||||
['gone', 1234],
|
||||
]);
|
||||
watcher.stop();
|
||||
});
|
||||
});
|
||||
@@ -5,51 +5,53 @@ import type { HookProcessBaseInfo } from '../src/injector';
|
||||
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
|
||||
|
||||
describe('createNativeProcessEnumerator', () => {
|
||||
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
|
||||
it('returns the sync lister result', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => [QQ(10), QQ(20)],
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
|
||||
en.dispose();
|
||||
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
|
||||
it('returns the sync lister result', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => [QQ(10), QQ(20)],
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
|
||||
en.dispose();
|
||||
});
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => { throw new Error('boom'); },
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
describe('worker isolation that cannot load the addon → permanent fallback', () => {
|
||||
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
|
||||
const fallback = vi.fn(() => [QQ(7)]);
|
||||
const en = createNativeProcessEnumerator({
|
||||
// A path that exists nowhere → process.dlopen throws in the worker →
|
||||
// the worker posts 'fatal' → isolation is abandoned for good.
|
||||
addonPath: '/nonexistent/snowluma-test.node',
|
||||
fallbackSync: fallback,
|
||||
processName: 'qq',
|
||||
timeoutMs: 200,
|
||||
});
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
|
||||
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
|
||||
// already, then subsequent calls take the synchronous fallback.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const second = await en.enumerate();
|
||||
expect(second).toEqual([QQ(7)]);
|
||||
expect(fallback).toHaveBeenCalled();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('worker isolation that cannot load the addon → permanent fallback', () => {
|
||||
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
|
||||
const fallback = vi.fn(() => [QQ(7)]);
|
||||
const en = createNativeProcessEnumerator({
|
||||
// A path that exists nowhere → process.dlopen throws in the worker →
|
||||
// the worker posts 'fatal' → isolation is abandoned for good.
|
||||
addonPath: '/nonexistent/snowluma-test.node',
|
||||
fallbackSync: fallback,
|
||||
processName: 'qq',
|
||||
timeoutMs: 200,
|
||||
});
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
|
||||
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
|
||||
// already, then subsequent calls take the synchronous fallback.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const second = await en.enumerate();
|
||||
expect(second).toEqual([QQ(7)]);
|
||||
expect(fallback).toHaveBeenCalled();
|
||||
en.dispose();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,63 +1,65 @@
|
||||
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');
|
||||
}));
|
||||
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,
|
||||
default: { Socket: socketCtorMock },
|
||||
Socket: socketCtorMock,
|
||||
}));
|
||||
|
||||
import { probeQqLoginInfo } from '../src/qq-port-probe';
|
||||
|
||||
describe('probeQqLoginInfo — bounded execution', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockReset();
|
||||
socketCtorMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('allows a later probe after a timed-out attempt', async () => {
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const first = probeQqLoginInfo(4242);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
await expect(first).resolves.toBeNull();
|
||||
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '', stderr: '' });
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '1\n', stderr: '' });
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
execMock.mockReset();
|
||||
socketCtorMock.mockClear();
|
||||
});
|
||||
});
|
||||
|
||||
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: '',
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('allows a later probe after a timed-out attempt', async () => {
|
||||
execMock.mockImplementation(() => undefined);
|
||||
const first = probeQqLoginInfo(4242);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
await expect(first).resolves.toBeNull();
|
||||
|
||||
execMock
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '', stderr: '' });
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '1\n', stderr: '' });
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
identityKnown: false,
|
||||
});
|
||||
})
|
||||
.mockImplementationOnce((_command, _options, callback) => {
|
||||
callback(null, { stdout: '8\n', stderr: '' });
|
||||
});
|
||||
});
|
||||
|
||||
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
|
||||
expect(socketCtorMock).not.toHaveBeenCalled();
|
||||
});
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -5,35 +5,40 @@ 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 type AccessTokenAssessmentReason = 'empty' | 'too-short' | 'guessable' | 'acceptable';
|
||||
|
||||
export interface AccessTokenAssessment {
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
acceptable: boolean;
|
||||
reason: AccessTokenAssessmentReason;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const checker = new ZxcvbnFactory({
|
||||
translations,
|
||||
graphs: adjacencyGraphs,
|
||||
dictionary,
|
||||
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 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));
|
||||
}
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (trimmed) unique.add(trimmed.slice(0, 256));
|
||||
}
|
||||
return [...unique].slice(0, 24);
|
||||
|
||||
return [...unique].slice(0, 24);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,17 +47,22 @@ function normalizeUserInputs(values: readonly (string | number)[]): Array<string
|
||||
* trust context; an empty value is never considered strong here.
|
||||
*/
|
||||
export function assessAccessToken(
|
||||
token: string,
|
||||
userInputs: readonly (string | number)[] = [],
|
||||
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 };
|
||||
}
|
||||
if (!token) {
|
||||
return { acceptable: false, reason: 'empty', 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 };
|
||||
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 };
|
||||
}
|
||||
@@ -7,24 +7,28 @@
|
||||
|
||||
/** True only for a plain, non-null, non-array object. */
|
||||
export function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** The value when it is a real boolean, else the fallback. Strings/numbers
|
||||
* are NOT coerced — `'true'` and `1` both yield the fallback. */
|
||||
export function boolOr(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
/** A finite number (numeric strings coerced) clamped to `[min, max]`, else
|
||||
* the fallback. Fractional precision is preserved — use `clampInt` to floor. */
|
||||
export function clampNum(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
/** `clampNum` truncated toward zero — clamp first, then drop the fraction. */
|
||||
export function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
return Math.trunc(clampNum(value, min, max, fallback));
|
||||
}
|
||||
@@ -12,16 +12,21 @@
|
||||
* shape that was previously hand-rolled at each such call site.
|
||||
*/
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
items: readonly T[],
|
||||
concurrency: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!;
|
||||
}
|
||||
return results;
|
||||
const limit = Math.max(1, Math.trunc(concurrency));
|
||||
const results = new Array<R>(items.length);
|
||||
|
||||
for (let i = 0; i < items.length; i += limit) {
|
||||
const batch = items.slice(i, i + limit);
|
||||
const settled = await Promise.all(batch.map((item, j) => fn(item, i + j)));
|
||||
|
||||
for (let j = 0; j < settled.length; j++) {
|
||||
results[i + j] = settled[j]!;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
+19
-13
@@ -11,18 +11,24 @@ const MAX_POSITIVE_INT = 2_147_483_647;
|
||||
* value is ignored, with a warning, and also returns `fallback`.
|
||||
*/
|
||||
export function positiveIntEnv(
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
name: string,
|
||||
fallback: number,
|
||||
options?: { max?: number; env?: NodeJS.ProcessEnv },
|
||||
): number {
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
if (typeof raw !== 'string' || !raw.trim()) return fallback;
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
return parsed;
|
||||
const max = options?.max ?? MAX_POSITIVE_INT;
|
||||
const raw = (options?.env ?? process.env)[name];
|
||||
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const value = raw.trim();
|
||||
const parsed = /^[1-9]\d*$/.test(value) ? Number(value) : Number.NaN;
|
||||
|
||||
if (!Number.isSafeInteger(parsed) || parsed > max) {
|
||||
log.warn('%s=%j is ignored; expected a positive integer up to %d', name, raw, max);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
+30
-21
@@ -2,34 +2,43 @@ const HEX_CHARS = '0123456789abcdef';
|
||||
const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
return h;
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
const limit = Math.max(0, Math.min(maxBytes, data.length));
|
||||
const head = toHex(data.subarray(0, limit));
|
||||
return data.length > limit ? `${head}...` : head;
|
||||
}
|
||||
|
||||
export function fromHex(hex: string): Buffer {
|
||||
if (hex.length % 2 !== 0) throw new Error('Invalid hex string length');
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return buf;
|
||||
if (hex.length % 2 !== 0) {
|
||||
throw new Error('Invalid hex string length');
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(hex.length / 2);
|
||||
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
buf[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
|
||||
export interface JsonObject {
|
||||
[key: string]: JsonValue;
|
||||
[key: string]: JsonValue;
|
||||
}
|
||||
export type JsonArray = JsonValue[];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,41 +6,70 @@ const C1_OSC = 0x9d;
|
||||
const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]);
|
||||
|
||||
function skipCsi(line: string, start: number): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code >= 0x40 && code <= 0x7e) return i + 1;
|
||||
}
|
||||
return line.length;
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code >= 0x40 && code <= 0x7e) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipControlString(line: string, start: number, allowBell: boolean): number {
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (allowBell && code === BEL) return i + 1;
|
||||
if (code === C1_ST) return i + 1;
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2;
|
||||
}
|
||||
return line.length;
|
||||
for (let i = start; i < line.length; i += 1) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (allowBell && code === BEL) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === C1_ST) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
if (code === ESC && line.charCodeAt(i + 1) === 0x5c) {
|
||||
return i + 2;
|
||||
}
|
||||
}
|
||||
|
||||
return line.length;
|
||||
}
|
||||
|
||||
function skipEscSequence(line: string, start: number): number {
|
||||
if (start >= line.length) return line.length;
|
||||
if (start >= line.length) {
|
||||
return line.length;
|
||||
}
|
||||
|
||||
const first = line.charCodeAt(start);
|
||||
if (first === 0x5b) return skipCsi(line, start + 1);
|
||||
if (first === 0x5d) return skipControlString(line, start + 1, true);
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
const first = line.charCodeAt(start);
|
||||
|
||||
let i = start;
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
if (code < 0x20 || code > 0x2f) break;
|
||||
i += 1;
|
||||
}
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
if (first === 0x5b) {
|
||||
return skipCsi(line, start + 1);
|
||||
}
|
||||
|
||||
if (first === 0x5d) {
|
||||
return skipControlString(line, start + 1, true);
|
||||
}
|
||||
|
||||
if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) {
|
||||
return skipControlString(line, start + 1, false);
|
||||
}
|
||||
|
||||
let i = start;
|
||||
|
||||
while (i < line.length) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code < 0x20 || code > 0x2f) {
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const final = line.charCodeAt(i);
|
||||
return final >= 0x30 && final <= 0x7e ? i + 1 : start;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,29 +82,34 @@ function skipEscSequence(line: string, start: number): number {
|
||||
* invisible payload into persisted or downloaded logs.
|
||||
*/
|
||||
export function sanitizeLogLine(line: string): string {
|
||||
let plain = '';
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
let plain = '';
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
for (let i = 0; i < line.length;) {
|
||||
const code = line.charCodeAt(i);
|
||||
|
||||
if (code === ESC) {
|
||||
i = skipEscSequence(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_CSI) {
|
||||
i = skipCsi(line, i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (code === C1_OSC || C1_STRING_STARTERS.has(code)) {
|
||||
i = skipControlString(line, i + 1, code === C1_OSC);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
plain += line[i];
|
||||
i += 1;
|
||||
}
|
||||
return plain;
|
||||
return plain;
|
||||
}
|
||||
+308
-238
@@ -1,54 +1,67 @@
|
||||
const MAX_FIELD = 40;
|
||||
const MAX_TOTAL = 200;
|
||||
const SENSITIVE_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
'authorization',
|
||||
'cookie',
|
||||
'credential',
|
||||
'credentials',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function isSensitiveKey(key: string): boolean {
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
const segments = key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
return segments.some((segment, index) => {
|
||||
if (SENSITIVE_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function valueRepr(v: unknown, key?: string): string {
|
||||
if (key !== undefined && isSensitiveKey(key)) return '"***"';
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) return `[len=${v.length}]`;
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
if (key !== undefined && isSensitiveKey(key)) {
|
||||
return '"***"';
|
||||
}
|
||||
|
||||
if (v === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`;
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(v);
|
||||
case 'object':
|
||||
if (Array.isArray(v)) {
|
||||
return `[len=${v.length}]`;
|
||||
}
|
||||
|
||||
return '{...}';
|
||||
default:
|
||||
return typeof v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,218 +73,265 @@ function valueRepr(v: unknown, key?: string): string {
|
||||
* replaced with `...` so the next field doesn't get half-rendered.
|
||||
*/
|
||||
export function summarizeParams(params: unknown): string {
|
||||
if (params === null || params === undefined) return '{}';
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL
|
||||
? `${s.slice(0, MAX_TOTAL - 3)}...`
|
||||
: s;
|
||||
}
|
||||
if (Array.isArray(params)) return `[len=${params.length}]`;
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
if (params === null || params === undefined) {
|
||||
return '{}';
|
||||
}
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
return out.join(' ');
|
||||
|
||||
if (typeof params !== 'object') {
|
||||
const s = String(params);
|
||||
return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL - 3)}...` : s;
|
||||
}
|
||||
|
||||
if (Array.isArray(params)) {
|
||||
return `[len=${params.length}]`;
|
||||
}
|
||||
|
||||
const out: string[] = [];
|
||||
let total = 0;
|
||||
|
||||
for (const [k, v] of Object.entries(params as Record<string, unknown>)) {
|
||||
const entry = `${k}=${valueRepr(v, k)}`;
|
||||
const separatorLength = out.length > 0 ? 1 : 0;
|
||||
|
||||
if (total + separatorLength + entry.length > MAX_TOTAL) {
|
||||
if (out.length === 0) {
|
||||
return `${entry.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
const rendered = out.join(' ');
|
||||
return rendered.length + 4 <= MAX_TOTAL
|
||||
? `${rendered} ...`
|
||||
: `${rendered.slice(0, MAX_TOTAL - 3)}...`;
|
||||
}
|
||||
|
||||
out.push(entry);
|
||||
total += separatorLength + entry.length;
|
||||
}
|
||||
|
||||
return out.join(' ');
|
||||
}
|
||||
|
||||
const ASSIGNMENT_START = /(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const ASSIGNMENT_START =
|
||||
/(^|[^A-Za-z0-9_-])(["']?)([-_]*(?=[A-Za-z0-9_.-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9_.-]*)\2(\s*[:=]\s*)/gi;
|
||||
const AUTHORIZATION_BOUNDARY_SEGMENTS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
'authorization',
|
||||
'cookie',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'token',
|
||||
'apikey',
|
||||
'privatekey',
|
||||
'sessionkey',
|
||||
]);
|
||||
|
||||
function keySegments(key: string): string[] {
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
return key
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.split(/[-_.\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((segment) => segment.toLowerCase());
|
||||
}
|
||||
|
||||
function isKeyKind(key: string, kind: 'authorization' | 'cookie'): boolean {
|
||||
return keySegments(key).includes(kind);
|
||||
return keySegments(key).includes(kind);
|
||||
}
|
||||
|
||||
function isAuthorizationBoundaryKey(key: string): boolean {
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) return true;
|
||||
const next = segments[index + 1];
|
||||
return next === 'key' && (
|
||||
segment === 'api'
|
||||
|| segment === 'private'
|
||||
|| segment === 'session'
|
||||
);
|
||||
});
|
||||
const segments = keySegments(key);
|
||||
return segments.some((segment, index) => {
|
||||
if (AUTHORIZATION_BOUNDARY_SEGMENTS.has(segment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const next = segments[index + 1];
|
||||
return (
|
||||
next === 'key' && (segment === 'api' || segment === 'private' || segment === 'session')
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function quotedValueEnd(message: string, start: number): number | undefined {
|
||||
const quote = message[start];
|
||||
if (quote !== '"' && quote !== "'") return undefined;
|
||||
const quote = message[start];
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return message.length;
|
||||
|
||||
for (let index = start + 1; index < message.length; index += 1) {
|
||||
if (message[index] === '\\') {
|
||||
index += 1;
|
||||
} else if (message[index] === quote) {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return message.length;
|
||||
}
|
||||
|
||||
function cookieValueEnd(message: string, start: number): number {
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
const initialQuotedEnd = quotedValueEnd(message, start);
|
||||
let end: number;
|
||||
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
if (message[semicolon] !== ';') break;
|
||||
if (initialQuotedEnd !== undefined) {
|
||||
end = initialQuotedEnd;
|
||||
} else {
|
||||
end = start;
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
let nameEnd = nameStart;
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) nameEnd += 1;
|
||||
if (nameEnd === nameStart) break;
|
||||
|
||||
end = nameEnd;
|
||||
if (message[end] !== '=') continue;
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
continue;
|
||||
while (end < message.length) {
|
||||
let semicolon: number = end;
|
||||
|
||||
while (message[semicolon] === ' ' || message[semicolon] === '\t') {
|
||||
semicolon += 1;
|
||||
}
|
||||
|
||||
if (message[semicolon] !== ';') {
|
||||
break;
|
||||
}
|
||||
|
||||
let nameStart = semicolon + 1;
|
||||
|
||||
while (message[nameStart] === ' ' || message[nameStart] === '\t') {
|
||||
nameStart += 1;
|
||||
}
|
||||
|
||||
let nameEnd = nameStart;
|
||||
|
||||
while (/[A-Za-z0-9_-]/.test(message[nameEnd] ?? '')) {
|
||||
nameEnd += 1;
|
||||
}
|
||||
|
||||
if (nameEnd === nameStart) {
|
||||
break;
|
||||
}
|
||||
|
||||
end = nameEnd;
|
||||
|
||||
if (message[end] !== '=') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute = message.slice(nameStart, nameEnd).toLowerCase();
|
||||
const valueStart = end + 1;
|
||||
const quotedEnd = quotedValueEnd(message, valueStart);
|
||||
|
||||
if (quotedEnd !== undefined) {
|
||||
end = quotedEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attribute !== 'expires') {
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
|
||||
if (nextField && nextField.index < end) {
|
||||
end = nextField.index;
|
||||
}
|
||||
}
|
||||
|
||||
end = valueStart;
|
||||
while (end < message.length && !/[;}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
assignments.lastIndex = valueStart;
|
||||
const nextField = assignments.exec(message);
|
||||
if (nextField && nextField.index < end) end = nextField.index;
|
||||
}
|
||||
return end;
|
||||
return end;
|
||||
}
|
||||
|
||||
function genericValueEnd(message: string, start: number): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
let end = start;
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
|
||||
let end = start;
|
||||
|
||||
while (end < message.length && !/[\s,}\]&\r\n]/.test(message[end]!)) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
function authorizationValueEnd(
|
||||
message: string,
|
||||
start: number,
|
||||
query: boolean,
|
||||
): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
if (quotedEnd !== undefined) return quotedEnd;
|
||||
function authorizationValueEnd(message: string, start: number, query: boolean): number {
|
||||
const quotedEnd = quotedValueEnd(message, start);
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
if (structural >= 0) end = start + structural;
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
if (quotedEnd !== undefined) {
|
||||
return quotedEnd;
|
||||
}
|
||||
}
|
||||
return end;
|
||||
|
||||
if (query) {
|
||||
const queryEnd = message.indexOf('&', start);
|
||||
return queryEnd >= 0 ? queryEnd : message.length;
|
||||
}
|
||||
|
||||
let end = message.length;
|
||||
const structural = message.slice(start).search(/[\r\n}\]]/);
|
||||
|
||||
if (structural >= 0) {
|
||||
end = start + structural;
|
||||
}
|
||||
|
||||
const assignments = new RegExp(ASSIGNMENT_START.source, 'gi');
|
||||
const remaining = message.slice(start, end);
|
||||
|
||||
for (let match = assignments.exec(remaining); match; match = assignments.exec(remaining)) {
|
||||
if (isAuthorizationBoundaryKey(match[3]!)) {
|
||||
end = start + match.index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return end;
|
||||
}
|
||||
|
||||
/** Redact explicit authentication assignments in ordinary formatted logs. */
|
||||
export function redactLogMessage(message: string): string {
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
ASSIGNMENT_START.lastIndex = 0;
|
||||
|
||||
for (let match = ASSIGNMENT_START.exec(message); match; match = ASSIGNMENT_START.exec(message)) {
|
||||
const key = match[3]!;
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(
|
||||
match.index + 1,
|
||||
ASSIGNMENT_START.lastIndex - 1,
|
||||
);
|
||||
continue;
|
||||
for (
|
||||
let match = ASSIGNMENT_START.exec(message);
|
||||
match;
|
||||
match = ASSIGNMENT_START.exec(message)
|
||||
) {
|
||||
const key = match[3]!;
|
||||
|
||||
if (!isSensitiveKey(key)) {
|
||||
ASSIGNMENT_START.lastIndex = Math.max(match.index + 1, ASSIGNMENT_START.lastIndex - 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(message, valueStart, match[1] === '?' || match[1] === '&')
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
const valueStart = ASSIGNMENT_START.lastIndex;
|
||||
const valueEnd = isKeyKind(key, 'authorization')
|
||||
? authorizationValueEnd(
|
||||
message,
|
||||
valueStart,
|
||||
match[1] === '?' || match[1] === '&',
|
||||
)
|
||||
: isKeyKind(key, 'cookie')
|
||||
? cookieValueEnd(message, valueStart)
|
||||
: genericValueEnd(message, valueStart);
|
||||
|
||||
out += message.slice(cursor, valueStart) + '***';
|
||||
cursor = valueEnd;
|
||||
ASSIGNMENT_START.lastIndex = valueEnd;
|
||||
}
|
||||
|
||||
return out + message.slice(cursor);
|
||||
return out + message.slice(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,34 +340,44 @@ export function redactLogMessage(message: string): string {
|
||||
* unredacted so a reproduction contains the complete business input.
|
||||
*/
|
||||
export function renderParamsVerbose(params: unknown): string {
|
||||
const seen = new WeakSet<object>();
|
||||
const seen = new WeakSet<object>();
|
||||
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) return 'null';
|
||||
if (value === undefined) return 'undefined';
|
||||
const walk = (value: unknown): string => {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) return '"[circular]"';
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
if (value === undefined) {
|
||||
return 'undefined';
|
||||
}
|
||||
|
||||
return walk(params);
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return JSON.stringify(value);
|
||||
case 'number':
|
||||
case 'boolean':
|
||||
case 'bigint':
|
||||
return String(value);
|
||||
|
||||
case 'object': {
|
||||
if (seen.has(value as object)) {
|
||||
return '"[circular]"';
|
||||
}
|
||||
|
||||
seen.add(value as object);
|
||||
const out = Array.isArray(value)
|
||||
? `[${value.map((item) => walk(item)).join(',')}]`
|
||||
: `{${Object.entries(value as Record<string, unknown>)
|
||||
.map(([key, item]) => `${key}:${walk(item)}`)
|
||||
.join(',')}}`;
|
||||
seen.delete(value as object);
|
||||
return out;
|
||||
}
|
||||
|
||||
default:
|
||||
return typeof value;
|
||||
}
|
||||
};
|
||||
|
||||
return walk(params);
|
||||
}
|
||||
+293
-244
@@ -3,64 +3,64 @@ import { getFileTransport } from './log-file-transport';
|
||||
import { redactLogMessage } from './log-summary';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import {
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
} from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type FileLogLevel = Exclude<LogLevel, 'trace'>;
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
id: number;
|
||||
time: string;
|
||||
level: LogLevel;
|
||||
scope: string;
|
||||
/** QQ uin, when the source logger was derived via `.child({ uin })`. */
|
||||
uin?: number;
|
||||
/** Correlation id, when emitted inside a `runWithRequestId(...)` scope. */
|
||||
req?: number;
|
||||
message: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface LogOptions {
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
scope: string;
|
||||
uin?: number;
|
||||
/** Free-form meta carried across `.child(...)` calls. Currently only
|
||||
* `uin` is rendered, but the bag is preserved for future fields
|
||||
* (requestId / traceId / etc.). */
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const UIN_SLOT_WIDTH = 12;
|
||||
|
||||
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
trace: 5,
|
||||
debug: 10,
|
||||
info: 20,
|
||||
success: 25,
|
||||
warn: 30,
|
||||
error: 40,
|
||||
};
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
trace: 'TRACE',
|
||||
debug: 'DEBUG',
|
||||
info: 'INFO',
|
||||
success: 'OK',
|
||||
warn: 'WARN',
|
||||
error: 'ERROR',
|
||||
};
|
||||
|
||||
const COLOR_CODE: Record<LogLevel, number> = {
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
trace: 90,
|
||||
debug: 90,
|
||||
info: 36,
|
||||
success: 32,
|
||||
warn: 33,
|
||||
error: 31,
|
||||
};
|
||||
|
||||
const COLOR_SCOPE = 35;
|
||||
@@ -70,9 +70,10 @@ const MAX_LOG_ENTRIES = 1000;
|
||||
|
||||
/** Trace ring cap — env-tunable since trace is the high-volume stream. */
|
||||
function resolveTraceBufferMax(): number {
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
const raw = Number.parseInt(process.env.SNOWLUMA_TRACE_BUFFER ?? '', 10);
|
||||
return Number.isFinite(raw) && raw >= 100 ? raw : 5000;
|
||||
}
|
||||
|
||||
const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
|
||||
/**
|
||||
@@ -80,32 +81,40 @@ const TRACE_BUFFER_MAX = resolveTraceBufferMax();
|
||||
* so the high-throughput trace stream never pays an O(n) shift per overflow.
|
||||
*/
|
||||
class RingBuffer<T> {
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
if (this.count < this.cap) this.count += 1;
|
||||
else this.start = (this.start + 1) % this.cap; // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
for (let i = 0; i < take; i += 1) out[i] = this.buf[(first + i) % this.cap]!;
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
private readonly buf: (T | undefined)[];
|
||||
private start = 0;
|
||||
private count = 0;
|
||||
constructor(private readonly cap: number) {
|
||||
this.buf = new Array<T | undefined>(cap);
|
||||
}
|
||||
push(item: T): void {
|
||||
const end = (this.start + this.count) % this.cap;
|
||||
this.buf[end] = item;
|
||||
|
||||
if (this.count < this.cap) {
|
||||
this.count += 1;
|
||||
} else {
|
||||
this.start = (this.start + 1) % this.cap;
|
||||
} // full → overwrite oldest
|
||||
}
|
||||
/** Most recent `n` items, oldest→newest. */
|
||||
recent(n: number): T[] {
|
||||
const take = Math.max(0, Math.min(Math.trunc(n), this.count));
|
||||
const out: T[] = new Array<T>(take);
|
||||
const first = this.start + (this.count - take);
|
||||
|
||||
for (let i = 0; i < take; i += 1) {
|
||||
out[i] = this.buf[(first + i) % this.cap]!;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
toArray(): T[] {
|
||||
return this.recent(this.count);
|
||||
}
|
||||
get size(): number {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
const logRing = new RingBuffer<LogEntry>(MAX_LOG_ENTRIES);
|
||||
@@ -114,25 +123,44 @@ const logSubscribers = new Set<(entry: LogEntry) => void>();
|
||||
let nextLogId = 1;
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
if (raw === 'trace' || raw === 'debug' || raw === 'info' || raw === 'success' || raw === 'warn' || raw === 'error') {
|
||||
return raw;
|
||||
}
|
||||
return 'info';
|
||||
const raw = (process.env.SNOWLUMA_LOG_LEVEL ?? 'info').toLowerCase();
|
||||
|
||||
if (
|
||||
raw === 'trace' ||
|
||||
raw === 'debug' ||
|
||||
raw === 'info' ||
|
||||
raw === 'success' ||
|
||||
raw === 'warn' ||
|
||||
raw === 'error'
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
return 'info';
|
||||
}
|
||||
|
||||
function resolveFileMinLevel(): FileLogLevel {
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
if (raw === undefined || raw.trim() === '') return 'debug';
|
||||
const raw = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === 'debug' || normalized === 'info' || normalized === 'success' ||
|
||||
normalized === 'warn' || normalized === 'error') {
|
||||
return normalized;
|
||||
}
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return 'debug';
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
if (
|
||||
normalized === 'debug' ||
|
||||
normalized === 'info' ||
|
||||
normalized === 'success' ||
|
||||
normalized === 'warn' ||
|
||||
normalized === 'error'
|
||||
) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
}
|
||||
|
||||
// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but
|
||||
@@ -145,141 +173,158 @@ let currentLevel: LogLevel = resolveMinLevel();
|
||||
const currentFileLevel: FileLogLevel = resolveFileMinLevel();
|
||||
|
||||
function shouldLog(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel];
|
||||
}
|
||||
|
||||
function shouldLogToFile(level: LogLevel): boolean {
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentFileLevel];
|
||||
}
|
||||
|
||||
export const LOG_LEVELS: readonly LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
|
||||
export const LOG_LEVELS: readonly LogLevel[] = [
|
||||
'trace',
|
||||
'debug',
|
||||
'info',
|
||||
'success',
|
||||
'warn',
|
||||
'error',
|
||||
];
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return currentLevel;
|
||||
return currentLevel;
|
||||
}
|
||||
|
||||
|
||||
// Change the console / subscriber level at runtime.
|
||||
// Invalid input is a no-op (returns false).
|
||||
// Does not affect the file transport log level.
|
||||
|
||||
export function setLogLevel(level: string): boolean {
|
||||
const lower = String(level).toLowerCase();
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) return false;
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
const lower = String(level).toLowerCase();
|
||||
|
||||
if (!LOG_LEVELS.includes(lower as LogLevel)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
currentLevel = lower as LogLevel;
|
||||
return true;
|
||||
}
|
||||
|
||||
function useColor(): boolean {
|
||||
if (process.env.NO_COLOR === '1') return false;
|
||||
return Boolean(process.stdout.isTTY);
|
||||
if (process.env.NO_COLOR === '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(process.stdout.isTTY);
|
||||
}
|
||||
|
||||
function ansi(code: number, text: string): string {
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
return `\x1b[${code}m${text}${COLOR_RESET}`;
|
||||
}
|
||||
|
||||
function currentTime(): string {
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
const d = new Date();
|
||||
const hh = String(d.getHours()).padStart(2, '0');
|
||||
const mm = String(d.getMinutes()).padStart(2, '0');
|
||||
const ss = String(d.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
function render(level: LogLevel, options: LogOptions, message: string, reqId?: number): string {
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
const ts = currentTime();
|
||||
const label = LEVEL_LABEL[level].padEnd(5, ' ');
|
||||
const uinTag = options.uin !== undefined ? `[${options.uin}]` : '';
|
||||
const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH);
|
||||
const reqTag = reqId !== undefined ? `[req#${reqId}]` : '';
|
||||
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
if (!useColor()) {
|
||||
return `${ts} ${label} ${uinSlot} [${options.scope}] ${reqTag ? `${reqTag} ` : ''}${message}`;
|
||||
}
|
||||
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
const cTs = ansi(COLOR_DIM, ts);
|
||||
const cLabel = ansi(COLOR_CODE[level], label);
|
||||
// Pad first, then color only the visible tag so escape codes don't eat
|
||||
// into the alignment width.
|
||||
const cUin = uinTag
|
||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||
return `${cTs} ${cLabel} ${cUin} ${cScope} ${cReq}${message}`;
|
||||
}
|
||||
|
||||
function emit(
|
||||
level: LogLevel,
|
||||
options: LogOptions,
|
||||
args: unknown[],
|
||||
): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace'
|
||||
&& shouldLogToFile(level);
|
||||
if (!passesConsole && !passesFile) return;
|
||||
function emit(level: LogLevel, options: LogOptions, args: unknown[]): void {
|
||||
// Console / subscriber and file filters are independent. If no destination
|
||||
// accepts the record, stop before formatting or building a LogEntry.
|
||||
const passesConsole = shouldLog(level);
|
||||
const passesFile = level !== 'trace' && shouldLogToFile(level);
|
||||
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) return;
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace'
|
||||
? formattedMessage
|
||||
: redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
for (const subscriber of logSubscribers) subscriber(entry);
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
if (!passesConsole && !passesFile) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
|
||||
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
|
||||
// the line to its per-account sub-file in addition to the shared one.
|
||||
if (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
// `trace` is the high-volume full-chain diagnostic stream, intentionally
|
||||
// excluded from disk to avoid I/O saturation. When console is not dialed
|
||||
// to trace, the early return below skips format/render/disk entirely.
|
||||
// Set SNOWLUMA_LOG_LEVEL=trace to inspect trace output in console/memory;
|
||||
// trace never reaches disk regardless.
|
||||
if (level === 'trace' && !passesConsole) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Lazy trace form: `log.trace(() => ['…', deepRender(x)])`. The producer
|
||||
// (and its expensive deep render) only runs now that trace is confirmed live.
|
||||
let realArgs = args;
|
||||
|
||||
if (level === 'trace' && args.length === 1 && typeof args[0] === 'function') {
|
||||
realArgs = (args[0] as () => unknown[])();
|
||||
}
|
||||
|
||||
const reqId = currentRequestId();
|
||||
const formattedMessage = format(...realArgs);
|
||||
const message = level === 'trace' ? formattedMessage : redactLogMessage(formattedMessage);
|
||||
const line = render(level, options, message, reqId);
|
||||
const entry: LogEntry = {
|
||||
id: nextLogId++,
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope: options.scope,
|
||||
...(options.uin !== undefined ? { uin: options.uin } : {}),
|
||||
...(reqId !== undefined ? { req: reqId } : {}),
|
||||
message,
|
||||
line: sanitizeLogLine(line),
|
||||
};
|
||||
|
||||
if (passesConsole) {
|
||||
// Trace gets its own ring so its volume never evicts the normal log buffer.
|
||||
(level === 'trace' ? traceRing : logRing).push(entry);
|
||||
|
||||
for (const subscriber of logSubscribers) {
|
||||
subscriber(entry);
|
||||
}
|
||||
|
||||
const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout;
|
||||
// Strip ASCII control characters before writing to terminal to prevent
|
||||
// BEL (0x07) in user-provided strings (e.g. group member names) from
|
||||
// triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A)
|
||||
// and ESC (0x1B) so multi-line records (stack traces) and ANSI color
|
||||
// sequences emitted by render() pass through intact.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const consoleLine = line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n';
|
||||
|
||||
try {
|
||||
stream.write(consoleLine);
|
||||
} catch {
|
||||
// A full Docker json-file log volume can make stdout/stderr throw.
|
||||
// Logging must not take down message handling or the WebUI.
|
||||
}
|
||||
}
|
||||
|
||||
// File transport sees levels >= currentFileLevel (SNOWLUMA_LOG_FILE_LEVEL,
|
||||
// default debug). `trace` is memory / WebUI only (omitted here to avoid huge
|
||||
// on-disk volume). ANSI stripping happens inside the transport. UIN routes
|
||||
// the line to its per-account sub-file in addition to the shared one.
|
||||
if (passesFile) {
|
||||
getFileTransport().write(line, options.uin);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,97 +334,101 @@ function emit(
|
||||
* has finalized the write.
|
||||
*/
|
||||
export function closeLogger(): Promise<void> {
|
||||
return getFileTransport().close();
|
||||
return getFileTransport().close();
|
||||
}
|
||||
|
||||
function mergeLogRings(): LogEntry[] {
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
return traceRing.size > 0
|
||||
? [...logRing.toArray(), ...traceRing.toArray()].sort((a, b) => a.id - b.id)
|
||||
: logRing.toArray();
|
||||
}
|
||||
|
||||
export function getLogSnapshot(): LogEntry[] {
|
||||
return mergeLogRings();
|
||||
return mergeLogRings();
|
||||
}
|
||||
|
||||
export function getRecentLogs(limit = 300): LogEntry[] {
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
const n = Math.max(1, Math.trunc(limit));
|
||||
return mergeLogRings().slice(-n);
|
||||
}
|
||||
|
||||
export function subscribeLogs(callback: (entry: LogEntry) => void): () => void {
|
||||
logSubscribers.add(callback);
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
logSubscribers.add(callback);
|
||||
|
||||
return () => {
|
||||
logSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number;[k: string]: unknown }) => Logger;
|
||||
/**
|
||||
* High-volume, memory-only diagnostic level (never written to disk). Pass a
|
||||
* lazy producer — `trace(() => ['msg %s', expensiveRender(x)])` — so the
|
||||
* arguments (and any costly rendering) are built only when trace is active.
|
||||
* A plain `trace('msg', x)` works too but evaluates its args eagerly.
|
||||
*/
|
||||
trace: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
info: (...args: unknown[]) => void;
|
||||
success: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Derive a new logger that inherits this one's scope and carries
|
||||
* additional metadata. Currently `uin` is the only key with rendering
|
||||
* support (shown in the `[UIN]` slot and routed to a per-UIN file);
|
||||
* other keys are preserved on the options bag for forward compat.
|
||||
*/
|
||||
child: (meta: { uin?: number; [k: string]: unknown }) => Logger;
|
||||
}
|
||||
|
||||
function makeLogger(opts: LogOptions): Logger {
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
return {
|
||||
trace: (...args: unknown[]) => emit('trace', opts, args),
|
||||
debug: (...args: unknown[]) => emit('debug', opts, args),
|
||||
info: (...args: unknown[]) => emit('info', opts, args),
|
||||
success: (...args: unknown[]) => emit('success', opts, args),
|
||||
warn: (...args: unknown[]) => emit('warn', opts, args),
|
||||
error: (...args: unknown[]) => emit('error', opts, args),
|
||||
child: (meta) => {
|
||||
const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin;
|
||||
return makeLogger({
|
||||
scope: opts.scope,
|
||||
uin: nextUin,
|
||||
meta: { ...(opts.meta ?? {}), ...meta },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createLogger(scope: string): Logger {
|
||||
return makeLogger({ scope });
|
||||
return makeLogger({ scope });
|
||||
}
|
||||
|
||||
export function renderTraceBytes(body: Uint8Array): string {
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('hex');
|
||||
}
|
||||
|
||||
export function runWithTraceRequest<T>(fn: () => T): T {
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') return fn();
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
if (currentRequestId() !== undefined || currentLevel !== 'trace') {
|
||||
return fn();
|
||||
}
|
||||
|
||||
return runWithRequestId(nextRequestId(), fn);
|
||||
}
|
||||
|
||||
export function logInitialWebuiCredentials(password: string): void {
|
||||
// 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' },
|
||||
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');
|
||||
// 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' },
|
||||
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
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface SendPacketResult {
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer | null;
|
||||
}
|
||||
|
||||
export interface PacketSender {
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
sendPacket(serviceCmd: string, body: Buffer, timeoutMs?: number): Promise<SendPacketResult>;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
export interface PacketInfo {
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
pid: number;
|
||||
uin: string;
|
||||
packetType?: number;
|
||||
serviceCmd: string;
|
||||
seqId: number;
|
||||
retCode: number;
|
||||
fromClient: boolean;
|
||||
body: Uint8Array;
|
||||
}
|
||||
export type PacketSink = (packet: PacketInfo) => void;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
interface RequestStore {
|
||||
id: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore | undefined>();
|
||||
@@ -13,9 +13,13 @@ let counter = 0;
|
||||
* unambiguous.
|
||||
*/
|
||||
export function nextRequestId(): number {
|
||||
counter = (counter + 1) >>> 0;
|
||||
if (counter === 0) counter = 1;
|
||||
return counter;
|
||||
counter = (counter + 1) >>> 0;
|
||||
|
||||
if (counter === 0) {
|
||||
counter = 1;
|
||||
}
|
||||
|
||||
return counter;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,15 +30,15 @@ export function nextRequestId(): number {
|
||||
* journey (entry → outbound packets → exit) under one `[req#N]` tag.
|
||||
*/
|
||||
export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** Run `fn` without inheriting an ambient request id. */
|
||||
export function runWithoutRequestContext<T>(fn: () => T): T {
|
||||
return storage.run(undefined, fn);
|
||||
return storage.run(undefined, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
return storage.getStore()?.id;
|
||||
}
|
||||
+297
-201
@@ -2,26 +2,26 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* 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. '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. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* 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. '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. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
/** Aggregate cap for every managed file below the log root. */
|
||||
logMaxTotalMb?: number;
|
||||
/** Calendar-day retention. Zero disables date-based deletion. */
|
||||
logRetainDays?: number;
|
||||
/** Duplicate UIN-scoped lines into logs/<uin>/ in addition to the shared log. */
|
||||
logPerUin?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
@@ -33,38 +33,38 @@ export const DEFAULT_LOG_MAX_TOTAL_MB = 1024;
|
||||
export const DEFAULT_LOG_RETAIN_DAYS = 7;
|
||||
export const DEFAULT_LOG_PER_UIN = false;
|
||||
export const MAX_LOG_TOTAL_MB = Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024));
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(
|
||||
Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000),
|
||||
);
|
||||
export const MAX_LOG_RETAIN_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / (24 * 60 * 60 * 1000));
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: {
|
||||
enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false,
|
||||
},
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
logMaxTotalMb: normalizeRequiredInteger(
|
||||
obj.logMaxTotalMb,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'logMaxTotalMb',
|
||||
),
|
||||
logRetainDays: normalizeRequiredInteger(
|
||||
obj.logRetainDays,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'logRetainDays',
|
||||
),
|
||||
logPerUin: normalizeRequiredBool(obj.logPerUin, DEFAULT_LOG_PER_UIN, 'logPerUin'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,61 +73,79 @@ export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
if (port !== undefined) {
|
||||
out.webuiPort = port;
|
||||
}
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
if (logMaxTotalMb !== undefined) out.logMaxTotalMb = logMaxTotalMb;
|
||||
if (typeof host === 'string' && host.trim()) {
|
||||
out.webuiHost = host.trim();
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
if (logRetainDays !== undefined) out.logRetainDays = logRetainDays;
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(
|
||||
env.SNOWLUMA_LOG_PER_UIN,
|
||||
'SNOWLUMA_LOG_PER_UIN',
|
||||
);
|
||||
if (logPerUin !== undefined) out.logPerUin = logPerUin;
|
||||
if (typeof tp === 'string') {
|
||||
out.trustProxy = tp;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
if (webuiTls !== undefined) out.webuiTls = { enabled: webuiTls };
|
||||
const logMaxTotalMb = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_MAX_TOTAL_MB,
|
||||
1,
|
||||
MAX_LOG_TOTAL_MB,
|
||||
'SNOWLUMA_LOG_MAX_TOTAL_MB',
|
||||
);
|
||||
|
||||
return out;
|
||||
if (logMaxTotalMb !== undefined) {
|
||||
out.logMaxTotalMb = logMaxTotalMb;
|
||||
}
|
||||
|
||||
const logRetainDays = parseRequiredIntegerEnv(
|
||||
env.SNOWLUMA_LOG_RETAIN_DAYS,
|
||||
0,
|
||||
MAX_LOG_RETAIN_DAYS,
|
||||
'SNOWLUMA_LOG_RETAIN_DAYS',
|
||||
);
|
||||
|
||||
if (logRetainDays !== undefined) {
|
||||
out.logRetainDays = logRetainDays;
|
||||
}
|
||||
|
||||
const logPerUin = parseRequiredBoolEnv(env.SNOWLUMA_LOG_PER_UIN, 'SNOWLUMA_LOG_PER_UIN');
|
||||
|
||||
if (logPerUin !== undefined) {
|
||||
out.logPerUin = logPerUin;
|
||||
}
|
||||
|
||||
const webuiTls = parseRequiredBoolEnv(env.SNOWLUMA_WEBUI_TLS, 'SNOWLUMA_WEBUI_TLS');
|
||||
|
||||
if (webuiTls !== undefined) {
|
||||
out.webuiTls = { enabled: webuiTls };
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,7 +153,7 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,165 +162,243 @@ export function readRuntimeConfig(): RuntimeConfig {
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
try {
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
const temporaryPath = `${RUNTIME_CONFIG_PATH}.tmp-${String(process.pid)}`;
|
||||
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
fs.writeFileSync(temporaryPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
fs.renameSync(temporaryPath, RUNTIME_CONFIG_PATH);
|
||||
} catch (error) {
|
||||
try {
|
||||
fs.unlinkSync(temporaryPath);
|
||||
} catch (cleanupError) {
|
||||
if (!isErrnoCode(cleanupError, 'ENOENT')) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'failed to persist runtime config and remove its temporary file',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
&& parsed.logMaxTotalMb === n.logMaxTotalMb
|
||||
&& parsed.logRetainDays === n.logRetainDays
|
||||
&& parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort &&
|
||||
parsed.hookAutoLoad === n.hookAutoLoad &&
|
||||
parsed.webuiHost === n.webuiHost &&
|
||||
parsedTls === n.webuiTls?.enabled &&
|
||||
parsed.trustProxy === n.trustProxy &&
|
||||
parsed.logMaxTotalMb === n.logMaxTotalMb &&
|
||||
parsed.logRetainDays === n.logRetainDays &&
|
||||
parsed.logPerUin === n.logPerUin
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
|
||||
if (!Number.isFinite(n)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const port = Math.trunc(n);
|
||||
|
||||
if (port <= 0 || port > 65535) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
if (n > 0 && n <= 65535) return n;
|
||||
return fallback;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
if (port > 0 && port <= 65535) return port;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
if (n > 0 && n <= 65535) {
|
||||
return n;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
|
||||
if (Number.isFinite(n)) {
|
||||
const port = Math.trunc(n);
|
||||
|
||||
if (port > 0 && port <= 65535) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeRequiredInteger(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number {
|
||||
if (value === undefined) return fallback;
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
if (
|
||||
typeof n === 'number'
|
||||
&& Number.isSafeInteger(n)
|
||||
&& n >= min
|
||||
&& n <= max
|
||||
) {
|
||||
return n;
|
||||
}
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const n = typeof value === 'string' && value.trim() ? Number(value.trim()) : value;
|
||||
|
||||
if (typeof n === 'number' && Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function normalizeRequiredBool(
|
||||
value: unknown,
|
||||
fallback: boolean,
|
||||
field: string,
|
||||
): boolean {
|
||||
if (value === undefined) return fallback;
|
||||
const parsed = parseBoolValue(value);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
function normalizeRequiredBool(value: unknown, fallback: boolean, field: string): boolean {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(value);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return value !== 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function parseRequiredIntegerEnv(
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
raw: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
field: string,
|
||||
): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) return n;
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const n = Number(raw.trim());
|
||||
|
||||
if (Number.isSafeInteger(n) && n >= min && n <= max) {
|
||||
return n;
|
||||
}
|
||||
|
||||
throw new RangeError(`${field} must be an integer in ${String(min)}..${String(max)}`);
|
||||
}
|
||||
|
||||
function parseRequiredBoolEnv(raw: unknown, field: string): boolean | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const parsed = parseBoolValue(raw);
|
||||
if (parsed !== undefined) return parsed;
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
if (typeof raw !== 'string' || !raw.trim()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parsed = parseBoolValue(raw);
|
||||
|
||||
if (parsed !== undefined) {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
throw new TypeError(`${field} must be a boolean`);
|
||||
}
|
||||
|
||||
function parseBoolValue(raw: unknown): boolean | undefined {
|
||||
if (typeof raw === 'boolean') return raw;
|
||||
if (raw === 1) return true;
|
||||
if (raw === 0) return false;
|
||||
if (typeof raw !== 'string') return undefined;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') return true;
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') return false;
|
||||
return undefined;
|
||||
if (typeof raw === 'boolean') {
|
||||
return raw;
|
||||
}
|
||||
|
||||
if (raw === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (raw === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = raw.trim().toLowerCase();
|
||||
|
||||
if (value === 'true' || value === '1' || value === 'yes' || value === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value === 'false' || value === '0' || value === 'no' || value === 'off') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isErrnoCode(error: unknown, code: string): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
return error instanceof Error && 'code' in error && error.code === code;
|
||||
}
|
||||
@@ -16,78 +16,90 @@
|
||||
*/
|
||||
|
||||
export interface SingleFlightCacheOptions<K, V> {
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
/** Freshness window in ms. A cached entry older than this is reloaded. */
|
||||
ttlMs: number;
|
||||
/** Load the value for a key. Rejections propagate and are never cached. */
|
||||
load: (key: K) => Promise<V>;
|
||||
/**
|
||||
* Decide whether a resolved value should be cached. Default: always.
|
||||
* Return `false` to leave an entry uncached (e.g. an error-shaped result the
|
||||
* next call should retry) while still de-duping concurrent in-flight callers.
|
||||
*/
|
||||
shouldCache?: (value: V) => boolean;
|
||||
/** Clock, injectable for tests. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class SingleFlightCache<K, V> {
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
private readonly ttlMs: number;
|
||||
private readonly load: (key: K) => Promise<V>;
|
||||
private readonly shouldCache: (value: V) => boolean;
|
||||
private readonly now: () => number;
|
||||
private readonly fresh = new Map<K, { at: number; value: V }>();
|
||||
private readonly inflight = new Map<K, Promise<V>>();
|
||||
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value);
|
||||
constructor(opts: SingleFlightCacheOptions<K, V>) {
|
||||
this.ttlMs = opts.ttlMs;
|
||||
this.load = opts.load;
|
||||
this.shouldCache = opts.shouldCache ?? (() => true);
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
const existing = this.inflight.get(key);
|
||||
if (existing) return existing;
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value });
|
||||
return value;
|
||||
} finally {
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** Drop a cached entry. Does not abort an in-flight load. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
/**
|
||||
* Get the value for `key`.
|
||||
*
|
||||
* - Returns a fresh cached value when the last load was within `ttlMs`.
|
||||
* - Otherwise de-dupes concurrent callers onto a single `load()` and caches
|
||||
* the result (subject to `shouldCache`). A rejected `load` propagates to
|
||||
* every joined caller, clears the in-flight slot, and is not cached.
|
||||
* - `force` bypasses the freshness check but still joins an in-flight load
|
||||
* rather than starting a second one.
|
||||
*/
|
||||
get(key: K, opts: { force?: boolean } = {}): Promise<V> {
|
||||
if (!opts.force) {
|
||||
const hit = this.fresh.get(key);
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
if (hit && this.now() - hit.at < this.ttlMs) {
|
||||
return Promise.resolve(hit.value);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = this.inflight.get(key);
|
||||
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const task = (async () => {
|
||||
try {
|
||||
const value = await this.load(key);
|
||||
|
||||
if (this.shouldCache(value)) {
|
||||
this.fresh.set(key, { at: this.now(), value });
|
||||
}
|
||||
|
||||
return value;
|
||||
} finally {
|
||||
this.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
this.inflight.set(key, task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** Drop a cached entry. Does not abort an in-flight load. */
|
||||
invalidate(key: K): void {
|
||||
this.fresh.delete(key);
|
||||
}
|
||||
|
||||
/** Drop all cached entries. Does not abort in-flight loads. */
|
||||
clear(): void {
|
||||
this.fresh.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function createSingleFlightCache<K, V>(
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
opts: SingleFlightCacheOptions<K, V>,
|
||||
): SingleFlightCache<K, V> {
|
||||
return new SingleFlightCache(opts);
|
||||
return new SingleFlightCache(opts);
|
||||
}
|
||||
@@ -7,5 +7,5 @@
|
||||
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
|
||||
// string. Keep that contract if the pattern ever changes.
|
||||
export function isRealUin(uin: string): boolean {
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
return /^\d{5,10}$/.test(uin);
|
||||
}
|
||||
@@ -1,28 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
ACCESS_TOKEN_MIN_LENGTH,
|
||||
ACCESS_TOKEN_MIN_SCORE,
|
||||
assessAccessToken,
|
||||
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('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('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']);
|
||||
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);
|
||||
});
|
||||
expect(result.acceptable).toBe(true);
|
||||
expect(result.reason).toBe('acceptable');
|
||||
expect(result.score).toBeGreaterThanOrEqual(ACCESS_TOKEN_MIN_SCORE);
|
||||
});
|
||||
});
|
||||
@@ -2,77 +2,77 @@ import { describe, it, expect } from 'vitest';
|
||||
import { isObject, boolOr, clampNum, clampInt } from '../src/coerce';
|
||||
|
||||
describe('isObject', () => {
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
it('is true only for plain non-null non-array objects', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ a: 1 })).toBe(true);
|
||||
expect(isObject(null)).toBe(false);
|
||||
expect(isObject([])).toBe(false);
|
||||
expect(isObject('x')).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('boolOr', () => {
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
it('returns the value only when it is a real boolean, else the fallback', () => {
|
||||
expect(boolOr(true, false)).toBe(true);
|
||||
expect(boolOr(false, true)).toBe(false);
|
||||
expect(boolOr('true', false)).toBe(false); // strings are NOT coerced
|
||||
expect(boolOr(1, false)).toBe(false);
|
||||
expect(boolOr(undefined, true)).toBe(true);
|
||||
expect(boolOr(null, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampNum', () => {
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
it('passes finite numbers through, clamped to [min,max]', () => {
|
||||
expect(clampNum(5, 0, 10, -1)).toBe(5);
|
||||
expect(clampNum(-3, 0, 10, -1)).toBe(0); // below min
|
||||
expect(clampNum(99, 0, 10, -1)).toBe(10); // above max
|
||||
});
|
||||
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
it('coerces numeric strings', () => {
|
||||
expect(clampNum('7', 0, 10, -1)).toBe(7);
|
||||
expect(clampNum('7.5', 0, 10, -1)).toBe(7.5); // NOT truncated (that is clampInt)
|
||||
});
|
||||
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
it('falls back on non-finite / non-numeric input', () => {
|
||||
expect(clampNum('abc', 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(NaN, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(Infinity, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(undefined, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum(null, 0, 10, 3)).toBe(3);
|
||||
expect(clampNum({}, 0, 10, 3)).toBe(3);
|
||||
});
|
||||
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
it('preserves fractional precision within bounds', () => {
|
||||
expect(clampNum(0.42, 0, 1, 0)).toBe(0.42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clampInt', () => {
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
it('is clampNum truncated toward zero', () => {
|
||||
expect(clampInt(7.9, 0, 10, -1)).toBe(7);
|
||||
expect(clampInt('7.9', 0, 10, -1)).toBe(7);
|
||||
expect(clampInt(5, 0, 10, -1)).toBe(5);
|
||||
});
|
||||
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
it('clamps before truncating', () => {
|
||||
expect(clampInt(99.9, 0, 10, -1)).toBe(10);
|
||||
expect(clampInt(-3.5, 0, 10, -1)).toBe(0);
|
||||
});
|
||||
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
it('clamp-then-trunc ordering: a fractional lower bound is crossed by the clamp, not the trunc', () => {
|
||||
// Distinguishes clamp→trunc (this contract) from trunc→clamp: input 2.4
|
||||
// with min 2.5 → clamp lifts to 2.5, then trunc → 2. A trunc-first impl
|
||||
// would floor to 2 then clamp up to 2.5. Pins the order for the shared
|
||||
// primitive (future callers may use fractional bounds).
|
||||
expect(clampInt(2.4, 2.5, 10, 0)).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
it('falls back on non-finite input', () => {
|
||||
expect(clampInt('abc', 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(NaN, 0, 10, 4)).toBe(4);
|
||||
expect(clampInt(undefined, 0, 10, 4)).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -4,65 +4,78 @@ import { mapWithConcurrency } from '../src/concurrency';
|
||||
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
||||
|
||||
describe('mapWithConcurrency', () => {
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
it('returns results in input order', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
|
||||
expect(out).toEqual([10, 20, 30, 40, 50]);
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
it('passes the absolute index (across batch boundaries)', async () => {
|
||||
const seen: Array<[number, number]> = [];
|
||||
await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => {
|
||||
seen.push([i, item.charCodeAt(0)]);
|
||||
return i;
|
||||
});
|
||||
expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]);
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => {
|
||||
let inFlight = 0;
|
||||
let peak = 0;
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
order.push(n);
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBeLessThanOrEqual(3);
|
||||
// batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts.
|
||||
expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]);
|
||||
expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]);
|
||||
expect(order[6]).toBe(6);
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; });
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0, inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n;
|
||||
it('handles a length not divisible by concurrency (short final batch)', async () => {
|
||||
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n);
|
||||
expect(out).toEqual([1, 2, 3, 4, 5]);
|
||||
});
|
||||
|
||||
it('runs everything in one batch when concurrency >= length', async () => {
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([1, 2, 3]);
|
||||
expect(peak).toBe(3);
|
||||
});
|
||||
|
||||
it('returns [] for an empty input without calling fn', async () => {
|
||||
let called = 0;
|
||||
const out = await mapWithConcurrency([], 4, async (n) => {
|
||||
called++;
|
||||
return n;
|
||||
});
|
||||
expect(out).toEqual([]);
|
||||
expect(called).toBe(0);
|
||||
});
|
||||
|
||||
it('treats concurrency < 1 as 1 (fully serial)', async () => {
|
||||
let peak = 0,
|
||||
inFlight = 0;
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (n) => {
|
||||
inFlight++;
|
||||
peak = Math.max(peak, inFlight);
|
||||
await tick();
|
||||
inFlight--;
|
||||
return n;
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
expect(peak).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,33 @@ import { describe, expect, it } from 'vitest';
|
||||
import { positiveIntEnv } from '../src/env';
|
||||
|
||||
describe('positiveIntEnv', () => {
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(15);
|
||||
});
|
||||
it('returns the fallback when the variable is absent or blank', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: {} })).toBe(15);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: ' ' } })).toBe(
|
||||
15,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } })).toBe(2500);
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
})).toBe(80);
|
||||
});
|
||||
it('reads a positive integer and honors the max', () => {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, { env: { SNOWLUMA_TEST_INT: '2500' } }),
|
||||
).toBe(2500);
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: '80' },
|
||||
}),
|
||||
).toBe(80);
|
||||
});
|
||||
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
})).toBe(15);
|
||||
}
|
||||
});
|
||||
it('ignores zero, negatives, fractions, and values above the max', () => {
|
||||
for (const raw of ['0', '-5', '1.5', 'nope', '70000']) {
|
||||
expect(
|
||||
positiveIntEnv('SNOWLUMA_TEST_INT', 15, {
|
||||
max: 65535,
|
||||
env: { SNOWLUMA_TEST_INT: raw },
|
||||
}),
|
||||
).toBe(15);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,25 @@ import { describe, expect, it } from 'vitest';
|
||||
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
|
||||
|
||||
describe('hex', () => {
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
expect(toHexUpper(b)).toBe('000FA0FF');
|
||||
expect(toHex(Uint8Array.of())).toBe('');
|
||||
});
|
||||
|
||||
it('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
it('hexPreview appends "..." only past maxBytes', () => {
|
||||
const b = Uint8Array.from([1, 2, 3, 4, 5]);
|
||||
expect(hexPreview(b)).toBe('0102030405'); // under the default 64-byte cap
|
||||
expect(hexPreview(b, 5)).toBe('0102030405'); // exactly at the cap → no ellipsis
|
||||
expect(hexPreview(b, 2)).toBe('0102...'); // truncated
|
||||
expect(hexPreview(b, 0)).toBe('...'); // nothing shown, but bytes remain
|
||||
});
|
||||
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
it('fromHex round-trips toHex and rejects odd-length input', () => {
|
||||
const b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
|
||||
expect(fromHex(toHex(b)).equals(b)).toBe(true);
|
||||
expect(toHex(fromHex('00ffa0'))).toBe('00ffa0');
|
||||
expect(() => fromHex('abc')).toThrow();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,25 +2,25 @@ import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeLogLine } from '../src/log-sanitize';
|
||||
|
||||
describe('sanitizeLogLine', () => {
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
it('removes SGR styling in seven-bit and eight-bit forms', () => {
|
||||
expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green');
|
||||
});
|
||||
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(
|
||||
sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'),
|
||||
).toBe('visible');
|
||||
});
|
||||
it('removes OSC hyperlinks without removing their visible label', () => {
|
||||
expect(sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07')).toBe(
|
||||
'visible',
|
||||
);
|
||||
});
|
||||
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
it('removes terminal control-string payloads', () => {
|
||||
expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter');
|
||||
});
|
||||
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
it('preserves tabs and newlines while removing other controls', () => {
|
||||
expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree');
|
||||
});
|
||||
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
it('does not leak unterminated terminal strings', () => {
|
||||
expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible');
|
||||
});
|
||||
});
|
||||
@@ -1,234 +1,230 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
redactLogMessage,
|
||||
renderParamsVerbose,
|
||||
summarizeParams,
|
||||
} from '../src/log-summary';
|
||||
import { redactLogMessage, renderParamsVerbose, summarizeParams } from '../src/log-summary';
|
||||
|
||||
describe('summarizeParams', () => {
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] }))
|
||||
.toBe('a=1 b="x" c={...} e=[len=2]');
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) }))
|
||||
.toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
it('renders null/undefined as {}', () => {
|
||||
expect(summarizeParams(null)).toBe('{}');
|
||||
expect(summarizeParams(undefined)).toBe('{}');
|
||||
});
|
||||
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
it('renders a top-level non-object via String() WITHOUT quotes', () => {
|
||||
// The reported change-request: a top-level primitive is NOT JSON-quoted.
|
||||
expect(summarizeParams('hello')).toBe('hello');
|
||||
expect(summarizeParams(123)).toBe('123');
|
||||
});
|
||||
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
})).toBe(
|
||||
'retoken="visible" cookietown="visible" myauthorization="visible"',
|
||||
);
|
||||
});
|
||||
it('collapses a top-level array to [len=N]', () => {
|
||||
expect(summarizeParams([1, 2, 3])).toBe('[len=3]');
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
for (let i = 0; i < 60; i++) big['key' + i] = i;
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
it('quotes string fields, collapses nested values, truncates long strings', () => {
|
||||
expect(summarizeParams({ a: 1, b: 'x', c: { d: 1 }, e: [1, 2] })).toBe(
|
||||
'a=1 b="x" c={...} e=[len=2]',
|
||||
);
|
||||
expect(summarizeParams({ s: 'x'.repeat(50) })).toBe(`s="${'x'.repeat(40)}..."`);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
it('redacts authentication fields without exposing their values', () => {
|
||||
const out = summarizeParams({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
Authorization: 'Bearer authorization-value',
|
||||
user_password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
group_id: 12345,
|
||||
});
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
expect(out).toContain('token="***"');
|
||||
expect(out).toContain('Cookie="***"');
|
||||
expect(out).toContain('Authorization="***"');
|
||||
expect(out).toContain('user_password="***"');
|
||||
expect(out).toContain('apiKey="***"');
|
||||
expect(out).toContain('group_id=12345');
|
||||
expect(out).not.toMatch(
|
||||
/token-value|cookie-value|authorization-value|password-value|key-value/,
|
||||
);
|
||||
});
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
it('does not treat sensitive substrings inside ordinary keys as credentials', () => {
|
||||
expect(
|
||||
summarizeParams({
|
||||
retoken: 'visible',
|
||||
cookietown: 'visible',
|
||||
myauthorization: 'visible',
|
||||
}),
|
||||
).toBe('retoken="visible" cookietown="visible" myauthorization="visible"');
|
||||
});
|
||||
|
||||
it('caps total output and appends "..." on overflow', () => {
|
||||
const big: Record<string, number> = {};
|
||||
|
||||
for (let i = 0; i < 60; i++) {
|
||||
big['key' + i] = i;
|
||||
}
|
||||
|
||||
const out = summarizeParams(big);
|
||||
expect(out.startsWith('key0=0')).toBe(true);
|
||||
expect(out.endsWith('...')).toBe(true);
|
||||
expect(out.length).toBeLessThanOrEqual(200);
|
||||
});
|
||||
|
||||
it('caps a single oversized first key and top-level primitive', () => {
|
||||
const oversizedKey = 'k'.repeat(300);
|
||||
|
||||
const objectOut = summarizeParams({ [oversizedKey]: 'value' });
|
||||
const primitiveOut = summarizeParams('x'.repeat(300));
|
||||
|
||||
expect(objectOut).toHaveLength(200);
|
||||
expect(objectOut.endsWith('...')).toBe(true);
|
||||
expect(primitiveOut).toHaveLength(200);
|
||||
expect(primitiveOut.endsWith('...')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('redactLogMessage', () => {
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
it('redacts explicit authentication assignments without changing prose', () => {
|
||||
const out = redactLogMessage(
|
||||
'password=secret Authorization: Bearer bearer-secret cookie="cookie secret" password change required',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'password=*** Authorization: *** cookie=*** password change required',
|
||||
);
|
||||
});
|
||||
expect(out).toBe('password=*** Authorization: *** cookie=*** password change required');
|
||||
});
|
||||
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
it('redacts quoted object keys, Basic auth, and complete Cookie values', () => {
|
||||
const out = redactLogMessage(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
const expires = redactLogMessage(
|
||||
'Cookie=session=expires-secret; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Path=/; HttpOnly safe=visible',
|
||||
);
|
||||
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
expect(out).toContain('json={"authorization":***}');
|
||||
expect(out).toContain("object={ 'api-key': *** }");
|
||||
expect(out).toContain('Authorization: *** Cookie=***');
|
||||
expect(expires).toBe('Cookie=*** safe=visible');
|
||||
expect(out).not.toMatch(/json-auth|api-secret|header-auth|cookie-secret|Path=|HttpOnly/);
|
||||
expect(expires).not.toMatch(/expires-secret|Expires|21 Oct|Path=|HttpOnly/);
|
||||
});
|
||||
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, '
|
||||
+ 'SignedHeaders=host;x-date, Signature=aws-secret\n'
|
||||
+ 'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
it('redacts complete multi-parameter Authorization values', () => {
|
||||
const out = redactLogMessage(
|
||||
'Authorization: Digest username="alice", realm="qq", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID/20260730/cn/service/aws4_request, ' +
|
||||
'SignedHeaders=host;x-date, Signature=aws-secret\n' +
|
||||
'Authorization: Bearer bearer-secret Cookie=session=cookie-secret; Path=/',
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
'Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***',
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
expect(out).toBe('Authorization: ***\nauthorization=***\nAuthorization: *** Cookie=***');
|
||||
expect(out).not.toMatch(
|
||||
/alice|realm|digest-secret|AKID|SignedHeaders|aws-secret|bearer-secret|cookie-secret|Path=/,
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
it('redacts camelCase authentication keys without matching larger words', () => {
|
||||
const out = redactLogMessage(
|
||||
`authToken=auth-secret idToken=id-secret clientSecret=client-secret {"userPassword":"password-secret"}`,
|
||||
);
|
||||
|
||||
expect(out).toBe(
|
||||
`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`,
|
||||
);
|
||||
expect(out).not.toMatch(
|
||||
/auth-secret|id-secret|client-secret|password-secret/,
|
||||
);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
expect(out).toBe(`authToken=*** idToken=*** clientSecret=*** {"userPassword":***}`);
|
||||
expect(out).not.toMatch(/auth-secret|id-secret|client-secret|password-secret/);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
)).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
it('redacts leading separator and numeric authentication keys without matching larger words', () => {
|
||||
expect(
|
||||
redactLogMessage(
|
||||
'_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret retoken=visible',
|
||||
),
|
||||
).toBe('_token=*** --password=*** 2faToken=*** retoken=visible');
|
||||
});
|
||||
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage(
|
||||
'params=authToken=auth-secret params=cookie="cookie-secret"',
|
||||
)).toBe('params=authToken=*** params=cookie=***');
|
||||
});
|
||||
it('redacts nested assignments inside non-sensitive wrapper values', () => {
|
||||
expect(redactLogMessage('params=authToken=auth-secret params=cookie="cookie-secret"')).toBe(
|
||||
'params=authToken=*** params=cookie=***',
|
||||
);
|
||||
});
|
||||
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value'))
|
||||
.toBe('Authorization: ***');
|
||||
});
|
||||
it('redacts the entire Authorization value when it starts with a marker', () => {
|
||||
expect(redactLogMessage('Authorization: *** secret-value')).toBe('Authorization: ***');
|
||||
});
|
||||
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz '
|
||||
+ 'request.token=plain-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
it('redacts property paths and URL query authentication values', () => {
|
||||
const out = redactLogMessage(
|
||||
'headers.authorization=Basic dXNlcjpwYXNz ' +
|
||||
'request.token=plain-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
expect(out).toContain('headers.authorization=***');
|
||||
expect(out).toContain('request.token=***');
|
||||
expect(out).toContain('/callback?access_token=***&x=1');
|
||||
expect(out).toContain('https://host/?api_key=***');
|
||||
expect(out).not.toMatch(/dXNlcjpwYXNz|plain-token|query-secret|url-secret/);
|
||||
});
|
||||
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret '
|
||||
+ 'headers.authorization=Basic auth-secret '
|
||||
+ 'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
it('redacts prefixed authentication keys without matching larger words', () => {
|
||||
const redacted = redactLogMessage(
|
||||
'x-api-key=api-secret user_password=password-secret ' +
|
||||
'headers.authorization=Basic auth-secret ' +
|
||||
'x-cookie="session=cookie-secret"; Path=/; HttpOnly',
|
||||
);
|
||||
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/);
|
||||
expect(redactLogMessage(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
)).toBe('retoken=value cookietown=value myauthorization=value');
|
||||
});
|
||||
expect(redacted).toContain('x-api-key=***');
|
||||
expect(redacted).toContain('user_password=***');
|
||||
expect(redacted).toContain('headers.authorization=***');
|
||||
expect(redacted).toContain('x-cookie=***');
|
||||
expect(redacted).not.toMatch(
|
||||
/api-secret|password-secret|auth-secret|cookie-secret|Path=|HttpOnly/,
|
||||
);
|
||||
expect(redactLogMessage('retoken=value cookietown=value myauthorization=value')).toBe(
|
||||
'retoken=value cookietown=value myauthorization=value',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderParamsVerbose', () => {
|
||||
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
it('keeps authentication fields unredacted for complete TRACE diagnostics', () => {
|
||||
const out = renderParamsVerbose({
|
||||
token: 'token-value',
|
||||
Cookie: 'cookie-value',
|
||||
password: 'password-value',
|
||||
apiKey: 'key-value',
|
||||
});
|
||||
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
|
||||
expect(out).toContain('token:"token-value"');
|
||||
expect(out).toContain('Cookie:"cookie-value"');
|
||||
expect(out).toContain('password:"password-value"');
|
||||
expect(out).toContain('apiKey:"key-value"');
|
||||
expect(out).not.toContain('"***"');
|
||||
});
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
|
||||
it('does not truncate TRACE values or their enclosing object', () => {
|
||||
const unicodeValue = '雪'.repeat(800);
|
||||
const out = renderParamsVerbose({ blob: unicodeValue, tail: 'complete' });
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
|
||||
expect(out).toContain(`blob:${JSON.stringify(unicodeValue)}`);
|
||||
expect(out).toContain('tail:"complete"');
|
||||
expect(out).not.toMatch(/…<\d+B>|\.\.\./);
|
||||
});
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
|
||||
it('guards against circular references', () => {
|
||||
const o: Record<string, unknown> = { a: 1 };
|
||||
o.self = o;
|
||||
expect(renderParamsVerbose(o)).toContain('"[circular]"');
|
||||
});
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
|
||||
it('renders shared non-cyclic references in every branch', () => {
|
||||
const shared = { value: 1 };
|
||||
expect(renderParamsVerbose({ left: shared, right: shared })).toBe(
|
||||
'{left:{value:1},right:{value:1}}',
|
||||
);
|
||||
});
|
||||
|
||||
expect(renderParamsVerbose({ left: shared, right: shared }))
|
||||
.toBe('{left:{value:1},right:{value:1}}');
|
||||
});
|
||||
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
it('renders nested structure with primitives intact', () => {
|
||||
expect(renderParamsVerbose({ a: 1, b: [true, 'x'] })).toBe('{a:1,b:[true,"x"]}');
|
||||
});
|
||||
});
|
||||
@@ -1,83 +1,84 @@
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { externalFileLevel, externalLogLevel, fileWriteSpy } = vi.hoisted(() => {
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
const savedFileLevel = process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
return {
|
||||
externalFileLevel: savedFileLevel,
|
||||
externalLogLevel: savedLogLevel,
|
||||
fileWriteSpy: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Capture file transport writes via a spy so tests can assert on what reaches
|
||||
// the file.
|
||||
vi.mock('../src/log-file-transport', () => ({
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
getFileTransport: () => ({ write: fileWriteSpy, close: async () => {} }),
|
||||
}));
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '../src/logger';
|
||||
import { createLogger, subscribeLogs, type LogEntry } from '../src/logger';
|
||||
|
||||
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
|
||||
// → uncaughtException. The padding must clamp at zero.
|
||||
describe('logger UIN slot padding', () => {
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
let prevTTY: boolean | undefined;
|
||||
let prevNoColor: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||
else process.env.NO_COLOR = prevNoColor;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
beforeEach(() => {
|
||||
prevTTY = process.stdout.isTTY;
|
||||
prevNoColor = process.env.NO_COLOR;
|
||||
// Force the colored render path (the only one that used .repeat()).
|
||||
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||
delete process.env.NO_COLOR;
|
||||
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
afterEach(() => {
|
||||
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
if (prevNoColor === undefined) {
|
||||
delete process.env.NO_COLOR;
|
||||
} else {
|
||||
process.env.NO_COLOR = prevNoColor;
|
||||
}
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||
expect(() => log.info('phantom account line')).not.toThrow();
|
||||
expect(() => log.error('phantom error line')).not.toThrow();
|
||||
});
|
||||
|
||||
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||
});
|
||||
|
||||
it('does not throw when the console stream cannot accept the line', () => {
|
||||
vi.mocked(process.stderr.write).mockImplementation(() => {
|
||||
throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
|
||||
});
|
||||
expect(() => createLogger('Test').error('disk is full')).not.toThrow();
|
||||
});
|
||||
|
||||
it('keeps structured subscriber lines plain while terminal output stays colored', () => {
|
||||
const captured: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => captured.push(entry));
|
||||
|
||||
createLogger('WebUI.Export').info('download me');
|
||||
unsubscribe();
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/);
|
||||
expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b['));
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Independent file-level filtering ─────────────────────────────────────
|
||||
@@ -85,237 +86,253 @@ describe('logger UIN slot padding', () => {
|
||||
const SAVED_FILE_LEVEL = externalFileLevel;
|
||||
|
||||
async function loadLoggerForFileLevel(level?: string) {
|
||||
if (level === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
if (level === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = level;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
return import('../src/logger');
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
vi.resetModules();
|
||||
fileWriteSpy.mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (SAVED_FILE_LEVEL === undefined) delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
if (externalLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
else process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
if (SAVED_FILE_LEVEL === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_FILE_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_FILE_LEVEL = SAVED_FILE_LEVEL;
|
||||
}
|
||||
|
||||
if (externalLogLevel === undefined) {
|
||||
delete process.env.SNOWLUMA_LOG_LEVEL;
|
||||
} else {
|
||||
process.env.SNOWLUMA_LOG_LEVEL = externalLogLevel;
|
||||
}
|
||||
});
|
||||
|
||||
describe('file output gating', () => {
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
const cases = [
|
||||
{ level: undefined, expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'debug', expected: ['debug', 'info', 'success', 'warn', 'error'] },
|
||||
{ level: 'info', expected: ['info', 'success', 'warn', 'error'] },
|
||||
{ level: 'success', expected: ['success', 'warn', 'error'] },
|
||||
{ level: 'warn', expected: ['warn', 'error'] },
|
||||
{ level: 'error', expected: ['error'] },
|
||||
] as const;
|
||||
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
for (const testCase of cases) {
|
||||
it(`writes exactly the enabled levels for ${testCase.level ?? 'the default'}`, async () => {
|
||||
const fresh = await loadLoggerForFileLevel(testCase.level);
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
fresh.setLogLevel('trace');
|
||||
log.trace('trace');
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
log.success('success');
|
||||
log.warn('warn');
|
||||
log.error('error');
|
||||
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) => String(line).split('] ').at(-1));
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token '
|
||||
+ 'GET /callback?access_token=query-secret&x=1 '
|
||||
+ 'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n'
|
||||
+ 'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client '
|
||||
+ `json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual([
|
||||
'normal-after',
|
||||
]);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
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();
|
||||
const messages = fileWriteSpy.mock.calls.map(([line]) =>
|
||||
String(line).split('] ').at(-1),
|
||||
);
|
||||
expect(messages).toEqual(testCase.expected);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts surrounding whitespace and mixed case', async () => {
|
||||
const fresh = await loadLoggerForFileLevel(' INFO ');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.debug('debug');
|
||||
log.info('info');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(expect.stringContaining('info'), undefined);
|
||||
});
|
||||
|
||||
it.each(['trace', 'verbose', 'erorr'])(
|
||||
'rejects unsupported file level %s at startup',
|
||||
async (level) => {
|
||||
await expect(loadLoggerForFileLevel(level)).rejects.toThrow(
|
||||
'SNOWLUMA_LOG_FILE_LEVEL must be one of: debug, info, success, warn, error',
|
||||
);
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('does not let the runtime console level change file output', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('info');
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
fresh.setLogLevel('error');
|
||||
log.info('persisted-info');
|
||||
fresh.setLogLevel('trace');
|
||||
log.debug('filtered-debug');
|
||||
|
||||
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
|
||||
expect(fileWriteSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('persisted-info'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('skips rendering when both console and file filters reject a record', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('error');
|
||||
fresh.setLogLevel('error');
|
||||
const rendered = vi.fn(() => 'expensive');
|
||||
const value = { [Symbol.toPrimitive]: rendered };
|
||||
|
||||
fresh.createLogger('Test').debug('value=%s', value);
|
||||
|
||||
expect(rendered).not.toHaveBeenCalled();
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps trace out of files in an explicit file-threshold check', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
fresh.createLogger('Test').trace('full chain');
|
||||
|
||||
expect(fileWriteSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redacts authentication assignments from ordinary logs but not TRACE', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
fresh.setLogLevel('trace');
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
|
||||
const log = fresh.createLogger('Test');
|
||||
|
||||
log.info(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s safe=%s',
|
||||
'ordinary-password',
|
||||
'ordinary-authorization',
|
||||
'ordinary-cookie',
|
||||
'ordinary-token',
|
||||
'visible',
|
||||
);
|
||||
log.trace(
|
||||
'password=%s Authorization: Bearer %s Cookie=%s token=%s',
|
||||
'trace-password',
|
||||
'trace-authorization',
|
||||
'trace-cookie',
|
||||
'trace-token',
|
||||
);
|
||||
log.info(
|
||||
`json={"authorization":"Basic json-auth"} object={ 'api-key': 'api-secret' } Authorization: Basic header-auth Cookie=session=cookie-secret; Path=/; HttpOnly`,
|
||||
);
|
||||
log.info(
|
||||
'headers.authorization=Basic dotted-auth request.token=dotted-token ' +
|
||||
'GET /callback?access_token=query-secret&x=1 ' +
|
||||
'url=https://host/?api_key=url-secret',
|
||||
);
|
||||
log.info(
|
||||
'Authorization: Digest username="alice", response="digest-secret"\n' +
|
||||
'authorization=AWS4-HMAC-SHA256 Credential=AKID, Signature=aws-secret',
|
||||
);
|
||||
log.info(
|
||||
'authToken=camel-auth idToken=camel-id clientSecret=camel-client ' +
|
||||
`json={"userPassword":"camel-password"}`,
|
||||
);
|
||||
log.info('_token=underscore-secret --password=cli-secret 2faToken=two-factor-secret');
|
||||
log.info('Authorization: *** marker-secret');
|
||||
log.trace(
|
||||
`json={"authorization":"Basic trace-json-auth"} Authorization: Basic trace-header-auth Cookie=session=trace-cookie; Path=/`,
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
const ordinaryEntries = entries.filter((entry) => entry.level === 'info');
|
||||
const ordinary = ordinaryEntries.map((entry) => entry.message).join('\n');
|
||||
expect(ordinary).toContain('password=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('Cookie=***');
|
||||
expect(ordinary).toContain('token=***');
|
||||
expect(ordinary).toContain('headers.authorization=***');
|
||||
expect(ordinary).toContain('request.token=***');
|
||||
expect(ordinary).toContain('/callback?access_token=***&x=1');
|
||||
expect(ordinary).toContain('https://host/?api_key=***');
|
||||
expect(ordinary).toContain('Authorization: ***\nauthorization=***');
|
||||
expect(ordinary).toContain('authToken=***');
|
||||
expect(ordinary).toContain('idToken=***');
|
||||
expect(ordinary).toContain('clientSecret=***');
|
||||
expect(ordinary).toContain(`json={"userPassword":***}`);
|
||||
expect(ordinary).toContain('_token=***');
|
||||
expect(ordinary).toContain('--password=***');
|
||||
expect(ordinary).toContain('2faToken=***');
|
||||
expect(ordinary).toContain('Authorization: ***');
|
||||
expect(ordinary).toContain('safe=visible');
|
||||
expect(ordinary).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|camel-auth|camel-id|camel-client|camel-password|underscore-secret|cli-secret|two-factor-secret|marker-secret/,
|
||||
);
|
||||
|
||||
const trace = entries
|
||||
.filter((entry) => entry.level === 'trace')
|
||||
.map((entry) => entry.message)
|
||||
.join('\n');
|
||||
expect(trace).toContain('trace-password');
|
||||
expect(trace).toContain('trace-authorization');
|
||||
expect(trace).toContain('trace-cookie');
|
||||
expect(trace).toContain('trace-token');
|
||||
expect(trace).toContain('trace-json-auth');
|
||||
expect(trace).toContain('trace-header-auth');
|
||||
|
||||
const persisted = fileWriteSpy.mock.calls.map(([line]) => String(line)).join('\n');
|
||||
expect(persisted).not.toMatch(
|
||||
/ordinary-password|ordinary-authorization|ordinary-cookie|ordinary-token|json-auth|api-secret|header-auth|cookie-secret|dotted-auth|dotted-token|query-secret|url-secret|digest-secret|AKID|aws-secret|trace-password|trace-json-auth/,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the complete retained normal and TRACE snapshot in record order', async () => {
|
||||
const fresh = await loadLoggerForFileLevel('debug');
|
||||
const log = fresh.createLogger('Export');
|
||||
fresh.setLogLevel('trace');
|
||||
|
||||
log.info('normal-before');
|
||||
log.trace('trace-hex=001122aabbcc');
|
||||
log.warn('normal-after');
|
||||
|
||||
expect(fresh.getRecentLogs(1).map((entry) => entry.message)).toEqual(['normal-after']);
|
||||
expect(fresh.getLogSnapshot().map((entry) => entry.message)).toEqual([
|
||||
'normal-before',
|
||||
'trace-hex=001122aabbcc',
|
||||
'normal-after',
|
||||
]);
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
try {
|
||||
fresh.logInitialWebuiCredentials('secret');
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,33 +2,33 @@ import { describe, expect, it } from 'vitest';
|
||||
import { currentRequestId, nextRequestId, runWithRequestId } from '../src/request-context';
|
||||
|
||||
describe('request-context', () => {
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
it('nextRequestId increments monotonically and stays a positive integer', () => {
|
||||
const a = nextRequestId();
|
||||
const b = nextRequestId();
|
||||
expect(a).toBeGreaterThan(0);
|
||||
expect(b).toBe(a + 1);
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
it('runWithRequestId binds the id across sync + async, with nested scopes restoring', async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
runWithRequestId(42, () => {
|
||||
expect(currentRequestId()).toBe(42);
|
||||
runWithRequestId(99, () => {
|
||||
expect(currentRequestId()).toBe(99);
|
||||
});
|
||||
expect(currentRequestId()).toBe(42); // outer scope restored after the nested one
|
||||
});
|
||||
|
||||
expect(currentRequestId()).toBeUndefined(); // cleared outside any scope
|
||||
|
||||
await runWithRequestId(7, async () => {
|
||||
await Promise.resolve();
|
||||
expect(currentRequestId()).toBe(7); // survives awaits in the same async chain
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
it('returns the callback result', () => {
|
||||
expect(runWithRequestId(1, () => 'value')).toBe('value');
|
||||
});
|
||||
});
|
||||
@@ -4,199 +4,226 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
logMaxTotalMb: 1024,
|
||||
logRetainDays: 7,
|
||||
logPerUin: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
it('passes through valid values', () => {
|
||||
expect(
|
||||
normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
}),
|
||||
).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
logMaxTotalMb: 2048,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 }))
|
||||
.toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' }))
|
||||
.toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER }))
|
||||
.toThrow(/logRetainDays/);
|
||||
});
|
||||
it('fails fast on invalid persisted log settings', () => {
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: 0 })).toThrow(/logMaxTotalMb/);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: -1 })).toThrow(/logRetainDays/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: 'maybe' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logPerUin: '' })).toThrow(/logPerUin/);
|
||||
expect(() => normalizeRuntimeConfig({ logMaxTotalMb: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logMaxTotalMb/,
|
||||
);
|
||||
expect(() => normalizeRuntimeConfig({ logRetainDays: Number.MAX_SAFE_INTEGER })).toThrow(
|
||||
/logRetainDays/,
|
||||
);
|
||||
});
|
||||
|
||||
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('127.0.0.1');
|
||||
});
|
||||
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('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('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('127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
})).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
})).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() => resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
})).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
}),
|
||||
).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
|
||||
it('parses log storage overrides including retainDays=0', () => {
|
||||
expect(
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '4096',
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '0',
|
||||
SNOWLUMA_LOG_PER_UIN: '1',
|
||||
}),
|
||||
).toEqual({
|
||||
logMaxTotalMb: 4096,
|
||||
logRetainDays: 0,
|
||||
logPerUin: true,
|
||||
});
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' }))
|
||||
.toThrow(/SNOWLUMA_WEBUI_TLS/);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
it('fails fast on invalid log storage overrides', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: '0',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: '-1',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_PER_UIN: 'maybe',
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_PER_UIN/);
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
it('fails fast when converted log storage overrides would be unsafe', () => {
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_MAX_TOTAL_MB: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_MAX_TOTAL_MB/);
|
||||
expect(() =>
|
||||
resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_LOG_RETAIN_DAYS: String(Number.MAX_SAFE_INTEGER),
|
||||
}),
|
||||
).toThrow(/SNOWLUMA_LOG_RETAIN_DAYS/);
|
||||
});
|
||||
|
||||
it('parses SNOWLUMA_WEBUI_TLS over the saved switch', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '1' })).toEqual({
|
||||
webuiTls: { enabled: true },
|
||||
});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: '0' })).toEqual({
|
||||
webuiTls: { enabled: false },
|
||||
});
|
||||
expect(() => resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TLS: 'maybe' })).toThrow(
|
||||
/SNOWLUMA_WEBUI_TLS/,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({
|
||||
trustProxy: '0',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs');
|
||||
const os = await import('os');
|
||||
const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
process.chdir(prevCwd);
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
if (prevPortEnv === undefined) {
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
} else {
|
||||
process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
}
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 }))
|
||||
.toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs');
|
||||
const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
|
||||
it('keeps the previous runtime file intact when atomic replacement fails', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
updateRuntimeConfig({ logRetainDays: 7 });
|
||||
const runtimePath = path.join('config', 'runtime.json');
|
||||
const before = fs.readFileSync(runtimePath, 'utf8');
|
||||
vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('disk replacement failed'), { code: 'EIO' });
|
||||
});
|
||||
|
||||
expect(() => updateRuntimeConfig({ logRetainDays: 0 })).toThrow(/disk replacement failed/);
|
||||
expect(fs.readFileSync(runtimePath, 'utf8')).toBe(before);
|
||||
expect(fs.readdirSync('config').filter((name) => name.includes('.tmp-'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,129 +3,148 @@ import { createSingleFlightCache } from '../src/single-flight-cache';
|
||||
|
||||
/** A promise whose resolve/reject is exposed, for driving single-flight races. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
||||
return { promise, resolve, reject };
|
||||
let resolve!: (v: T) => void;
|
||||
let reject!: (e: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe('SingleFlightCache', () => {
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 100, load, now: () => clock });
|
||||
it('caches within the TTL and reloads once expired', async () => {
|
||||
let clock = 1000;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 100,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
clock = 1050; // still fresh (< 100)
|
||||
expect(await cache.get('a')).toBe('a@1000');
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load, now: () => clock });
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error });
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
if (attempt === 1) throw new Error('boom');
|
||||
return 'ok';
|
||||
clock = 1101; // 101ms since store → expired
|
||||
expect(await cache.get('a')).toBe('a@1101');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
it('de-dupes concurrent callers onto a single load (single-flight)', async () => {
|
||||
const d = deferred<string>();
|
||||
const load = vi.fn(() => d.promise);
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
const p3 = cache.get('k');
|
||||
expect(load).toHaveBeenCalledTimes(1); // only one load in flight
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
d.resolve('v');
|
||||
expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
it('keys independently — different keys load separately', async () => {
|
||||
const load = vi.fn(async (k: number) => k * 2);
|
||||
const cache = createSingleFlightCache<number, number>({ ttlMs: 1000, load });
|
||||
expect(await cache.get(1)).toBe(2);
|
||||
expect(await cache.get(2)).toBe(4);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
it('force bypasses the freshness check but still joins an in-flight load', async () => {
|
||||
let clock = 0;
|
||||
const load = vi.fn(async (k: string) => `${k}@${clock}`);
|
||||
const cache = createSingleFlightCache<string, string>({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
now: () => clock,
|
||||
});
|
||||
|
||||
expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh
|
||||
clock = 5; // still fresh
|
||||
expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// force still single-flights: two concurrent forced gets share one load.
|
||||
const d = deferred<string>();
|
||||
load.mockImplementationOnce(() => d.promise);
|
||||
const p1 = cache.get('a', { force: true });
|
||||
const p2 = cache.get('a', { force: true });
|
||||
expect(load).toHaveBeenCalledTimes(3); // not 4
|
||||
d.resolve('shared');
|
||||
expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']);
|
||||
});
|
||||
|
||||
it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => {
|
||||
let n = 0;
|
||||
const load = vi.fn(async () => ({ error: true as boolean, n: ++n }));
|
||||
const cache = createSingleFlightCache({
|
||||
ttlMs: 10_000,
|
||||
load,
|
||||
shouldCache: (v) => !v.error,
|
||||
});
|
||||
|
||||
// concurrent callers still share one load...
|
||||
const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]);
|
||||
expect(a).toEqual({ error: true, n: 1 });
|
||||
expect(b).toEqual({ error: true, n: 1 });
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but nothing was cached, so the next call reloads.
|
||||
expect(await cache.get('k')).toEqual({ error: true, n: 2 });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
// a good result IS cached.
|
||||
load.mockImplementationOnce(async () => ({ error: false, n: ++n }));
|
||||
const good = await cache.get('k');
|
||||
expect(good).toEqual({ error: false, n: 3 });
|
||||
expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => {
|
||||
let attempt = 0;
|
||||
const load = vi.fn(async () => {
|
||||
attempt++;
|
||||
|
||||
if (attempt === 1) {
|
||||
throw new Error('boom');
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
});
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
|
||||
const p1 = cache.get('k');
|
||||
const p2 = cache.get('k');
|
||||
await expect(p1).rejects.toThrow('boom');
|
||||
await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
|
||||
// in-flight cleared + not cached → next call retries and succeeds.
|
||||
expect(await cache.get('k')).toBe('ok');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('invalidate drops a cached entry; clear drops all', async () => {
|
||||
const load = vi.fn(async (k: string) => k.toUpperCase());
|
||||
const cache = createSingleFlightCache<string, string>({ ttlMs: 10_000, load });
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
cache.invalidate('a');
|
||||
await cache.get('a'); // reloads
|
||||
await cache.get('b'); // still cached
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
|
||||
cache.clear();
|
||||
await cache.get('a');
|
||||
await cache.get('b');
|
||||
expect(load).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
});
|
||||
@@ -1,117 +1,117 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
setLogLevel,
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
setLogLevel,
|
||||
} from '../src/logger';
|
||||
|
||||
const originalLevel = getLogLevel();
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(originalLevel);
|
||||
setLogLevel(originalLevel);
|
||||
});
|
||||
|
||||
describe('TRACE diagnostics contract', () => {
|
||||
it('renders every byte as continuous lowercase hexadecimal', () => {
|
||||
expect(renderTraceBytes(new Uint8Array())).toBe('');
|
||||
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff])))
|
||||
.toBe('00010f10ff');
|
||||
});
|
||||
|
||||
it('renders only the addressed Uint8Array view', () => {
|
||||
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
|
||||
|
||||
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
|
||||
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
|
||||
});
|
||||
|
||||
it('does not render bytes while TRACE is disabled', () => {
|
||||
setLogLevel('info');
|
||||
let rendered = false;
|
||||
|
||||
createLogger('Trace.Contract').trace(() => {
|
||||
rendered = true;
|
||||
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
|
||||
it('renders every byte as continuous lowercase hexadecimal', () => {
|
||||
expect(renderTraceBytes(new Uint8Array())).toBe('');
|
||||
expect(renderTraceBytes(new Uint8Array([0x00, 0x01, 0x0f, 0x10, 0xff]))).toBe('00010f10ff');
|
||||
});
|
||||
|
||||
expect(rendered).toBe(false);
|
||||
});
|
||||
it('renders only the addressed Uint8Array view', () => {
|
||||
const backing = new Uint8Array([0xaa, 0x00, 0x0f, 0xff, 0xbb]);
|
||||
|
||||
it('creates distinct request contexts that survive asynchronous work', async () => {
|
||||
setLogLevel('info');
|
||||
const beforeDisabled = nextRequestId();
|
||||
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
|
||||
const afterDisabled = nextRequestId();
|
||||
expect(afterDisabled).toBe(beforeDisabled + 1);
|
||||
|
||||
setLogLevel('trace');
|
||||
const observeContext = () => runWithTraceRequest(async () => {
|
||||
const before = currentRequestId();
|
||||
await Promise.resolve();
|
||||
const after = currentRequestId();
|
||||
expect(after).toBe(before);
|
||||
return after;
|
||||
expect(renderTraceBytes(backing.subarray(1, 4))).toBe('000fff');
|
||||
expect(renderTraceBytes(Buffer.from(backing.buffer).subarray(2, 4))).toBe('0fff');
|
||||
});
|
||||
|
||||
const first = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
const second = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
it('does not render bytes while TRACE is disabled', () => {
|
||||
setLogLevel('info');
|
||||
let rendered = false;
|
||||
|
||||
expect(first).toEqual(expect.any(Number));
|
||||
expect(first).toBeGreaterThan(0);
|
||||
expect(second).toEqual(expect.any(Number));
|
||||
expect(second).toBeGreaterThan(0);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
createLogger('Trace.Contract').trace(() => {
|
||||
rendered = true;
|
||||
return ['body=%s', renderTraceBytes(new Uint8Array([0xff]))];
|
||||
});
|
||||
|
||||
it('allocates once for nested TRACE contexts and reuses the request id', () => {
|
||||
setLogLevel('trace');
|
||||
const before = nextRequestId();
|
||||
|
||||
const observed = runWithTraceRequest(() => {
|
||||
const outer = currentRequestId();
|
||||
const inner = runWithTraceRequest(() => currentRequestId());
|
||||
return { outer, inner };
|
||||
expect(rendered).toBe(false);
|
||||
});
|
||||
|
||||
const after = nextRequestId();
|
||||
expect(observed.outer).toEqual(expect.any(Number));
|
||||
expect(observed.inner).toBe(observed.outer);
|
||||
expect(observed.outer).toBe(before + 1);
|
||||
expect(after).toBe(before + 2);
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
it('creates distinct request contexts that survive asynchronous work', async () => {
|
||||
setLogLevel('info');
|
||||
const beforeDisabled = nextRequestId();
|
||||
expect(runWithTraceRequest(() => currentRequestId())).toBeUndefined();
|
||||
const afterDisabled = nextRequestId();
|
||||
expect(afterDisabled).toBe(beforeDisabled + 1);
|
||||
|
||||
it('detaches long-lived resources from the current request context', async () => {
|
||||
await runWithRequestId(4243, async () => {
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
const detached = await runWithoutRequestContext(async () => {
|
||||
setLogLevel('trace');
|
||||
const observeContext = () =>
|
||||
runWithTraceRequest(async () => {
|
||||
const before = currentRequestId();
|
||||
await Promise.resolve();
|
||||
const after = currentRequestId();
|
||||
expect(after).toBe(before);
|
||||
return after;
|
||||
});
|
||||
|
||||
const first = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
const second = await observeContext();
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(detached).toBeUndefined();
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses an existing request context even while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
|
||||
await runWithRequestId(4242, async () => {
|
||||
const observed = await runWithTraceRequest(async () => {
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(observed).toBe(4242);
|
||||
expect(first).toEqual(expect.any(Number));
|
||||
expect(first).toBeGreaterThan(0);
|
||||
expect(second).toEqual(expect.any(Number));
|
||||
expect(second).toBeGreaterThan(0);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
|
||||
it('allocates once for nested TRACE contexts and reuses the request id', () => {
|
||||
setLogLevel('trace');
|
||||
const before = nextRequestId();
|
||||
|
||||
const observed = runWithTraceRequest(() => {
|
||||
const outer = currentRequestId();
|
||||
const inner = runWithTraceRequest(() => currentRequestId());
|
||||
return { outer, inner };
|
||||
});
|
||||
|
||||
const after = nextRequestId();
|
||||
expect(observed.outer).toEqual(expect.any(Number));
|
||||
expect(observed.inner).toBe(observed.outer);
|
||||
expect(observed.outer).toBe(before + 1);
|
||||
expect(after).toBe(before + 2);
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('detaches long-lived resources from the current request context', async () => {
|
||||
await runWithRequestId(4243, async () => {
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
const detached = await runWithoutRequestContext(async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(detached).toBeUndefined();
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses an existing request context even while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
|
||||
await runWithRequestId(4242, async () => {
|
||||
const observed = await runWithTraceRequest(async () => {
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(observed).toBe(4242);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,39 +2,39 @@ import { describe, expect, it } from 'vitest';
|
||||
import { isRealUin } from '../src/uin';
|
||||
|
||||
describe('isRealUin', () => {
|
||||
it('accepts real QQ UINs (5..10 digits)', () => {
|
||||
expect(isRealUin('10001')).toBe(true); // 5-digit floor
|
||||
expect(isRealUin('123456789')).toBe(true);
|
||||
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
|
||||
});
|
||||
it('accepts real QQ UINs (5..10 digits)', () => {
|
||||
expect(isRealUin('10001')).toBe(true); // 5-digit floor
|
||||
expect(isRealUin('123456789')).toBe(true);
|
||||
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
|
||||
});
|
||||
|
||||
it('rejects the empty string and "0"', () => {
|
||||
expect(isRealUin('')).toBe(false);
|
||||
expect(isRealUin('0')).toBe(false);
|
||||
});
|
||||
it('rejects the empty string and "0"', () => {
|
||||
expect(isRealUin('')).toBe(false);
|
||||
expect(isRealUin('0')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects too-short UINs (< 5 digits)', () => {
|
||||
expect(isRealUin('1')).toBe(false);
|
||||
expect(isRealUin('1234')).toBe(false);
|
||||
});
|
||||
it('rejects too-short UINs (< 5 digits)', () => {
|
||||
expect(isRealUin('1')).toBe(false);
|
||||
expect(isRealUin('1234')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
|
||||
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
|
||||
expect(isRealUin('1614019567632')).toBe(false);
|
||||
expect(isRealUin('2014024115056')).toBe(false);
|
||||
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
|
||||
});
|
||||
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
|
||||
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
|
||||
expect(isRealUin('1614019567632')).toBe(false);
|
||||
expect(isRealUin('2014024115056')).toBe(false);
|
||||
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
|
||||
});
|
||||
|
||||
it('rejects non-digit strings (path traversal / injection guards)', () => {
|
||||
expect(isRealUin('12345a')).toBe(false);
|
||||
expect(isRealUin('12 345')).toBe(false);
|
||||
expect(isRealUin('../etc')).toBe(false);
|
||||
expect(isRealUin('123456\n')).toBe(false);
|
||||
});
|
||||
it('rejects non-digit strings (path traversal / injection guards)', () => {
|
||||
expect(isRealUin('12345a')).toBe(false);
|
||||
expect(isRealUin('12 345')).toBe(false);
|
||||
expect(isRealUin('../etc')).toBe(false);
|
||||
expect(isRealUin('123456\n')).toBe(false);
|
||||
});
|
||||
|
||||
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||
const uin = '123456789';
|
||||
expect(isRealUin(uin)).toBe(true);
|
||||
expect(() => BigInt(uin)).not.toThrow();
|
||||
});
|
||||
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||
const uin = '123456789';
|
||||
expect(isRealUin(uin)).toBe(true);
|
||||
expect(() => BigInt(uin)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,28 +1,28 @@
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import {
|
||||
getCollectionList,
|
||||
type CollectionListResult,
|
||||
} from '@snowluma/protocol/web/collection';
|
||||
import { getCollectionList, type CollectionListResult } from '@snowluma/protocol/web/collection';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
const COLLECTION_DOMAIN = 'weiyun.com';
|
||||
|
||||
/** Read-only access to the account's QQ collection list. */
|
||||
export class CollectionApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
async list(category = 0, count = 50): Promise<CollectionListResult> {
|
||||
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
|
||||
domainList: [COLLECTION_DOMAIN],
|
||||
});
|
||||
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
|
||||
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
|
||||
async list(category = 0, count = 50): Promise<CollectionListResult> {
|
||||
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
|
||||
domainList: [COLLECTION_DOMAIN],
|
||||
});
|
||||
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
|
||||
|
||||
return getCollectionList({
|
||||
uin: this.ctx.identity.uin,
|
||||
pskey,
|
||||
category,
|
||||
count,
|
||||
});
|
||||
}
|
||||
if (!pskey) {
|
||||
throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
|
||||
}
|
||||
|
||||
return getCollectionList({
|
||||
uin: this.ctx.identity.uin,
|
||||
pskey,
|
||||
category,
|
||||
count,
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,15 @@
|
||||
import { FetchAiVoice } from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice';
|
||||
import {
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
FetchAiVoiceList,
|
||||
type AiVoiceCategory as NamespaceAiVoiceCategory,
|
||||
} from '@snowluma/protocol/oidb-services/extras/fetch-ai-voice-list';
|
||||
import { GetStrangerStatus, type StrangerStatus as NamespaceStrangerStatus } from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetGroupTodoList,
|
||||
type GroupTodoListItem as NamespaceGroupTodoListItem,
|
||||
GetStrangerStatus,
|
||||
type StrangerStatus as NamespaceStrangerStatus,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-stranger-status';
|
||||
import {
|
||||
GetGroupTodoList,
|
||||
type GroupTodoListItem as NamespaceGroupTodoListItem,
|
||||
} from '@snowluma/protocol/oidb-services/extras/get-group-todo-list';
|
||||
import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
@@ -22,18 +25,18 @@ import type { MediaIndexNode } from './shared';
|
||||
* element + its message meta. `uuid`/`md5Hex` come from the cached record;
|
||||
* the uins + scene from the message meta. */
|
||||
export interface PttTransInput {
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
isGroup: boolean;
|
||||
msgId: number;
|
||||
senderUin: number;
|
||||
/** Receiver uin (c2c) or group uin (group). */
|
||||
peerUin: number;
|
||||
uuid: string;
|
||||
md5Hex: string;
|
||||
duration: number;
|
||||
size: number;
|
||||
format: number;
|
||||
/** Group ptt numeric file id (group only; optional). */
|
||||
fileId?: number;
|
||||
}
|
||||
|
||||
// ─────────────── public types (re-exported from bridge.ts as before) ───
|
||||
@@ -42,21 +45,21 @@ export type StrangerStatus = NamespaceStrangerStatus;
|
||||
export type GroupTodoListItem = NamespaceGroupTodoListItem;
|
||||
|
||||
export const AiVoiceChatType = {
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
Unknown: 0,
|
||||
Sound: 1,
|
||||
Sing: 2,
|
||||
} as const;
|
||||
export type AiVoiceChatType = typeof AiVoiceChatType[keyof typeof AiVoiceChatType];
|
||||
export type AiVoiceChatType = (typeof AiVoiceChatType)[keyof typeof AiVoiceChatType];
|
||||
|
||||
export type AiVoiceCategory = NamespaceAiVoiceCategory;
|
||||
export interface AiVoiceItem {
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
voiceId: string;
|
||||
voiceDisplayName: string;
|
||||
voiceExampleUrl: string;
|
||||
}
|
||||
|
||||
export interface AiVoiceSendReceipt {
|
||||
sequence: number;
|
||||
sequence: number;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge.Extras');
|
||||
@@ -67,280 +70,368 @@ const AI_VOICE_CLAIM_LIMIT = 256;
|
||||
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
|
||||
|
||||
function normalizeMediaUuid(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
return typeof value === 'string' ? value.trim() : '';
|
||||
}
|
||||
|
||||
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
|
||||
const expectedUuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (!expectedUuid) return false;
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') continue;
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
if (actualUuid === expectedUuid) return true;
|
||||
}
|
||||
return false;
|
||||
const expectedUuid = normalizeMediaUuid(node.fileUuid);
|
||||
|
||||
if (!expectedUuid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const element of event.elements) {
|
||||
if (element.type !== 'record') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
|
||||
|
||||
if (actualUuid === expectedUuid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
|
||||
const uuid = normalizeMediaUuid(node.fileUuid);
|
||||
if (uuid) return `uuid:${uuid.slice(-12)}`;
|
||||
return 'missing';
|
||||
const uuid = normalizeMediaUuid(node.fileUuid);
|
||||
|
||||
if (uuid) {
|
||||
return `uuid:${uuid.slice(-12)}`;
|
||||
}
|
||||
|
||||
return 'missing';
|
||||
}
|
||||
|
||||
export class ExtrasApi {
|
||||
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
|
||||
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
|
||||
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
|
||||
// ─────────────── Group todo query / mutations (0x9474 / 0xF90) ───────────────
|
||||
|
||||
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
|
||||
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
|
||||
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
|
||||
return items;
|
||||
}
|
||||
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Keeps the action response user-safe while retaining the underlying
|
||||
* failure in the service log for diagnosis.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
if (!status) log.warn('user status query returned no status target=%d', uin);
|
||||
return status;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'user status query failed target=%d: %s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return null;
|
||||
async getGroupTodoList(groupId: number): Promise<GroupTodoListItem[]> {
|
||||
const items = await GetGroupTodoList.invoke(this.ctx, { groupId });
|
||||
log.debug('group todo list fetched group=%d count=%d', groupId, items.length);
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(groupId: number, chatType: AiVoiceChatType | number): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned node plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma. The synthesis response does not contain a
|
||||
* reliable message sequence; callers that need one must use `sendAiVoice`,
|
||||
* which correlates the subsequent self-message receipt.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
|
||||
if (node) {
|
||||
log.debug(
|
||||
'AI voice synthesis completed group=%d media=%s polls=%d',
|
||||
groupId,
|
||||
describeAiVoiceFingerprint(node),
|
||||
i + 1,
|
||||
);
|
||||
return node as MediaIndexNode;
|
||||
}
|
||||
setGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'set' });
|
||||
}
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish an AI voice and wait for QQ's canonical self-message receipt.
|
||||
*
|
||||
* The 0x929B completion response carries the media node but, on live QQ,
|
||||
* omits the group message sequence. Subscribe before publishing so an echo
|
||||
* that wins the response race is buffered, then correlate by the exact media
|
||||
* UUID. Never guess from content hashes or "the next voice in the group":
|
||||
* concurrent requests can legitimately render byte-identical audio.
|
||||
*/
|
||||
async sendAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
|
||||
): Promise<AiVoiceSendReceipt> {
|
||||
const candidates: GroupMessageEvent[] = [];
|
||||
let candidatesOverflowed = false;
|
||||
let expectedNode: MediaIndexNode | null = null;
|
||||
let receiptSettled = false;
|
||||
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
|
||||
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
|
||||
resolveReceipt = resolve;
|
||||
});
|
||||
|
||||
const claim = (event: GroupMessageEvent): boolean => {
|
||||
if (receiptSettled) return false;
|
||||
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
|
||||
this.claimedAiVoiceReceiptKeys.add(key);
|
||||
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
|
||||
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
|
||||
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
}
|
||||
receiptSettled = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const accept = (event: GroupMessageEvent): void => {
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
|
||||
if (!event.elements.some(element => element.type === 'record')) return;
|
||||
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
|
||||
resolveReceipt?.(event);
|
||||
return;
|
||||
}
|
||||
candidates.push(event);
|
||||
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
|
||||
candidates.shift();
|
||||
candidatesOverflowed = true;
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = this.ctx.events.on('group_message', accept);
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
|
||||
expectedNode = node;
|
||||
const fingerprint = describeAiVoiceFingerprint(node);
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
|
||||
}
|
||||
|
||||
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
|
||||
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
);
|
||||
}
|
||||
const event = buffered ?? await Promise.race([
|
||||
receiptPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
|
||||
+ `(group=${groupId} media=${fingerprint})`,
|
||||
));
|
||||
}, receiptTimeoutMs);
|
||||
timeout.unref?.();
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
|
||||
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
|
||||
groupId,
|
||||
fingerprint,
|
||||
event.msgSeq,
|
||||
event.msgId,
|
||||
);
|
||||
return {
|
||||
sequence: event.msgSeq,
|
||||
};
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
unsubscribe();
|
||||
completeGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'complete' });
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
|
||||
* return the recognised text IF the response carries it inline (the
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId).
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
|
||||
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
|
||||
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
|
||||
const md5 = input.md5Hex.toLowerCase();
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0, md5, duration: input.duration, size: input.size,
|
||||
format: input.format, uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId), senderUin: BigInt(input.senderUin), receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid, duration: input.duration, size: input.size, format: input.format, md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
cancelGroupTodo(groupId: number, msgSeq: bigint): Promise<void> {
|
||||
return GroupTodo.invoke(this.ctx, { groupId, msgSeq, action: 'cancel' });
|
||||
}
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
if (item?.errCode) {
|
||||
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode, input.isGroup,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format, input.uuid ? 'set' : 'EMPTY', input.duration, input.size,
|
||||
);
|
||||
throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
}
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode a voice record (`get_record out_format`, #165). `source` is a
|
||||
* URL / local path / `base64://…` (the record's download URL in practice);
|
||||
* it is loaded then transcoded to `format` via the bundled SILK-capable
|
||||
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
|
||||
* failed conversion.
|
||||
*/
|
||||
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
|
||||
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
|
||||
// default so a tampered/oversized source can't be pulled in.
|
||||
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
|
||||
return convertAudioBytes(bytes, format);
|
||||
}
|
||||
// ─────────────── Stranger online/ext status (0xFE1_2) ───────────────
|
||||
|
||||
/**
|
||||
* Keeps the action response user-safe while retaining the underlying
|
||||
* failure in the service log for diagnosis.
|
||||
*/
|
||||
async getStrangerStatus(uin: number): Promise<StrangerStatus | null> {
|
||||
try {
|
||||
const status = await GetStrangerStatus.invoke(this.ctx, { uin });
|
||||
|
||||
if (!status) {
|
||||
log.warn('user status query returned no status target=%d', uin);
|
||||
}
|
||||
|
||||
return status;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
'user status query failed target=%d: %s',
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── AI voice (0x929D / 0x929B) ───────────────
|
||||
|
||||
fetchAiVoiceList(
|
||||
groupId: number,
|
||||
chatType: AiVoiceChatType | number,
|
||||
): Promise<AiVoiceCategory[]> {
|
||||
return FetchAiVoiceList.invoke(this.ctx, { groupId, chatType });
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger AI voice synthesis. Server may return an empty msgInfo while
|
||||
* the render is in-flight; we retry until a node materialises or the
|
||||
* cap is hit. napcat uses the same 30-retry budget.
|
||||
*
|
||||
* The returned node plugs directly into
|
||||
* `apis.groupFile.getPttUrl`, which already handles every other
|
||||
* download-URL fetch in SnowLuma. The synthesis response does not contain a
|
||||
* reliable message sequence; callers that need one must use `sendAiVoice`,
|
||||
* which correlates the subsequent self-message receipt.
|
||||
*/
|
||||
async fetchAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
maxRetries = 30,
|
||||
): Promise<MediaIndexNode> {
|
||||
// Random 32-bit session id — server uses this to deduplicate polls.
|
||||
const sessionId = Math.floor(Math.random() * 0xffffffff) >>> 0;
|
||||
|
||||
for (let i = 0; i < maxRetries; i++) {
|
||||
const node = await FetchAiVoice.invoke(this.ctx, {
|
||||
groupId,
|
||||
voiceId,
|
||||
text,
|
||||
chatType,
|
||||
sessionId,
|
||||
});
|
||||
|
||||
if (node) {
|
||||
log.debug(
|
||||
'AI voice synthesis completed group=%d media=%s polls=%d',
|
||||
groupId,
|
||||
describeAiVoiceFingerprint(node),
|
||||
i + 1,
|
||||
);
|
||||
return node as MediaIndexNode;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish an AI voice and wait for QQ's canonical self-message receipt.
|
||||
*
|
||||
* The 0x929B completion response carries the media node but, on live QQ,
|
||||
* omits the group message sequence. Subscribe before publishing so an echo
|
||||
* that wins the response race is buffered, then correlate by the exact media
|
||||
* UUID. Never guess from content hashes or "the next voice in the group":
|
||||
* concurrent requests can legitimately render byte-identical audio.
|
||||
*/
|
||||
async sendAiVoice(
|
||||
groupId: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AiVoiceChatType | number,
|
||||
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
|
||||
): Promise<AiVoiceSendReceipt> {
|
||||
const candidates: GroupMessageEvent[] = [];
|
||||
let candidatesOverflowed = false;
|
||||
let expectedNode: MediaIndexNode | null = null;
|
||||
let receiptSettled = false;
|
||||
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
|
||||
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
|
||||
resolveReceipt = resolve;
|
||||
});
|
||||
|
||||
const claim = (event: GroupMessageEvent): boolean => {
|
||||
if (receiptSettled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
|
||||
|
||||
if (this.claimedAiVoiceReceiptKeys.has(key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.claimedAiVoiceReceiptKeys.add(key);
|
||||
|
||||
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
|
||||
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
|
||||
|
||||
if (oldest !== undefined) {
|
||||
this.claimedAiVoiceReceiptKeys.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
receiptSettled = true;
|
||||
return true;
|
||||
};
|
||||
|
||||
const accept = (event: GroupMessageEvent): void => {
|
||||
if (event.groupId !== groupId || event.senderUin !== event.selfUin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.elements.some((element) => element.type === 'record')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
|
||||
resolveReceipt?.(event);
|
||||
return;
|
||||
}
|
||||
|
||||
candidates.push(event);
|
||||
|
||||
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
|
||||
candidates.shift();
|
||||
candidatesOverflowed = true;
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = this.ctx.events.on('group_message', accept);
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
try {
|
||||
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
|
||||
expectedNode = node;
|
||||
const fingerprint = describeAiVoiceFingerprint(node);
|
||||
|
||||
if (fingerprint === 'missing') {
|
||||
throw new Error(
|
||||
'AI voice was published but QQ returned no exact media identifier for receipt correlation',
|
||||
);
|
||||
}
|
||||
|
||||
const buffered = candidates.find(
|
||||
(event) => matchesAiVoiceEvent(node, event) && claim(event),
|
||||
);
|
||||
|
||||
if (!buffered && candidatesOverflowed) {
|
||||
throw new Error(
|
||||
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} ` +
|
||||
`unmatched self voice messages (group=${groupId} media=${fingerprint})`,
|
||||
);
|
||||
}
|
||||
|
||||
const event =
|
||||
buffered ??
|
||||
(await Promise.race([
|
||||
receiptPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
reject(
|
||||
new Error(
|
||||
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms ` +
|
||||
`(group=${groupId} media=${fingerprint})`,
|
||||
),
|
||||
);
|
||||
}, receiptTimeoutMs);
|
||||
timeout.unref?.();
|
||||
}),
|
||||
]));
|
||||
|
||||
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
|
||||
throw new Error(
|
||||
`AI voice receipt carried invalid message sequence: ${event.msgSeq}`,
|
||||
);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
|
||||
groupId,
|
||||
fingerprint,
|
||||
event.msgSeq,
|
||||
event.msgId,
|
||||
);
|
||||
return {
|
||||
sequence: event.msgSeq,
|
||||
};
|
||||
} finally {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
|
||||
|
||||
/**
|
||||
* Send ONE `pttTrans.Trans{C2C,Group}PttReq` to trigger transcription and
|
||||
* return the recognised text IF the response carries it inline (the
|
||||
* already-transcribed case). For a freshly-received voice the response is an
|
||||
* empty ack and the text is delivered later via the async Event 0x210
|
||||
* subType-61 push — callers should treat `''` as "pending" and wait for the
|
||||
* `ptt_trans_result` event (correlated by msgId).
|
||||
*/
|
||||
async translatePttToText(input: PttTransInput): Promise<string> {
|
||||
// QQ NT sends the md5 as a 32-char lowercase HEX STRING, not the raw 16
|
||||
// bytes (RE'd from wrapper.linux.node EncodeTroopPtt/EncodeC2CPtt: the md5
|
||||
// field goes through a bytes→hex helper). Sending raw bytes → errCode -1079.
|
||||
const md5 = input.md5Hex.toLowerCase();
|
||||
const req: PttTransReq = input.isGroup
|
||||
? {
|
||||
type: 1,
|
||||
groupItem: {
|
||||
msgId: BigInt(input.msgId),
|
||||
senderUin: BigInt(input.senderUin),
|
||||
groupUin: BigInt(input.peerUin),
|
||||
fileId: input.fileId ?? 0,
|
||||
md5,
|
||||
duration: input.duration,
|
||||
size: input.size,
|
||||
format: input.format,
|
||||
uuid: input.uuid,
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: 2,
|
||||
c2cItem: {
|
||||
msgId: BigInt(input.msgId),
|
||||
senderUin: BigInt(input.senderUin),
|
||||
receiverUin: BigInt(input.peerUin),
|
||||
uuid: input.uuid,
|
||||
duration: input.duration,
|
||||
size: input.size,
|
||||
format: input.format,
|
||||
md5,
|
||||
},
|
||||
};
|
||||
const cmd = input.isGroup ? 'pttTrans.TransGroupPttReq' : 'pttTrans.TransC2CPttReq';
|
||||
|
||||
const result = await this.ctx.sendRawPacket(cmd, protobuf_encode<PttTransReq>(req));
|
||||
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'ptt translate request failed');
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<PttTransResp>(result.responseData);
|
||||
const item = input.isGroup ? resp?.groupResult : resp?.c2cResult;
|
||||
|
||||
if (item?.errCode) {
|
||||
// Diagnostic (#165 备选): correlate QQ's errCode with the request fields we
|
||||
// sourced from cache, to tell a server-side ASR failure apart from our own
|
||||
// missing/zero field (md5/format/uuid). Behaviour unchanged — still throws.
|
||||
log.warn(
|
||||
'ptt translate errCode=%d isGroup=%s md5=%s format=%d uuid=%s dur=%d size=%d',
|
||||
item.errCode,
|
||||
input.isGroup,
|
||||
input.md5Hex ? `${input.md5Hex.length / 2}B` : 'EMPTY',
|
||||
input.format,
|
||||
input.uuid ? 'set' : 'EMPTY',
|
||||
input.duration,
|
||||
input.size,
|
||||
);
|
||||
throw new Error(`ptt translate failed: error=${item.errCode}`);
|
||||
}
|
||||
|
||||
return item?.text ?? ''; // '' = transcribing async; caller awaits the push
|
||||
}
|
||||
|
||||
/**
|
||||
* Transcode a voice record (`get_record out_format`, #165). `source` is a
|
||||
* URL / local path / `base64://…` (the record's download URL in practice);
|
||||
* it is loaded then transcoded to `format` via the bundled SILK-capable
|
||||
* ffmpeg addon. Returns base64 + size. Throws on unsupported format or a
|
||||
* failed conversion.
|
||||
*/
|
||||
async convertRecord(source: string, format: string): Promise<{ base64: string; size: number }> {
|
||||
// Voices are tiny — cap the download well below loadBinarySource's 1 GiB
|
||||
// default so a tampered/oversized source can't be pulled in.
|
||||
const { bytes } = await loadBinarySource(source, 'record', 64 * 1024 * 1024);
|
||||
return convertAudioBytes(bytes, format);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,10 @@ import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-cont
|
||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||
import { GetDoubtBuddyReq, type DoubtBuddyRequest } from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import {
|
||||
GetDoubtBuddyReq,
|
||||
type DoubtBuddyRequest,
|
||||
} from '@snowluma/protocol/oidb-services/friend/get-doubt-buddy-req';
|
||||
import { HandleFriendRequest } from '@snowluma/protocol/oidb-services/friend/handle-friend-request';
|
||||
import { RejectDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/reject-doubt-buddy-req';
|
||||
import { SetFriendRemark } from '@snowluma/protocol/oidb-services/friend/set-friend-remark';
|
||||
@@ -14,96 +17,107 @@ export type { DoubtBuddyRequest };
|
||||
const log = createLogger('Bridge.Friend');
|
||||
|
||||
export class FriendApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact cannot be deleted');
|
||||
/**
|
||||
* Accept or reject an inbound friend request. `uidOrFlag` is either a
|
||||
* pre-resolved UID string or a numeric uin (then resolved on the fly).
|
||||
*/
|
||||
handleRequest(uidOrFlag: string, approve: boolean): Promise<void> {
|
||||
return HandleFriendRequest.invoke(this.ctx, { uidOrFlag, approve });
|
||||
}
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
// The server-side delete has already completed. A refresh failure must be
|
||||
// visible, but throwing here would misreport the delete itself as failed
|
||||
// and encourage callers to repeat a destructive request.
|
||||
try {
|
||||
await this.ctx.apis.contacts.fetchFriendList();
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'friend-list refresh failed after deleting user=%d: %s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async setRemark(userId: number, remark: string): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact does not support remarks');
|
||||
}
|
||||
if (remark === '') {
|
||||
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
return;
|
||||
}
|
||||
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
return Promise.all(list.map(async (item) => {
|
||||
let uid = item.uid;
|
||||
let userId = item.user_id;
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
try {
|
||||
uid = await this.ctx.resolveUserUid(userId);
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'doubt-request uid resolve failed: user=%d err=%s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
async delete(userId: number, block = false): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact cannot be deleted');
|
||||
}
|
||||
}
|
||||
return { ...item, uid: uid || '', user_id: userId };
|
||||
}));
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
log.trace('doubt-request approval: resolving applicant');
|
||||
const uid = await this.resolveDoubtFlag(uidOrFlag);
|
||||
log.trace('doubt-request approval: submitting request');
|
||||
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
log.trace('doubt-request approval: completed');
|
||||
}
|
||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
|
||||
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, {
|
||||
uid: await this.resolveDoubtFlag(uidOrFlag),
|
||||
});
|
||||
}
|
||||
// The server-side delete has already completed. A refresh failure must be
|
||||
// visible, but throwing here would misreport the delete itself as failed
|
||||
// and encourage callers to repeat a destructive request.
|
||||
try {
|
||||
await this.ctx.apis.contacts.fetchFriendList();
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'friend-list refresh failed after deleting user=%d: %s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Digit-only flags are account numbers and must be translated before the
|
||||
* approval/reject packet is built. A raw number in that packet is rejected
|
||||
* by the server. Same rule as inbound friend-request handling.
|
||||
*/
|
||||
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
|
||||
if (!/^\d+$/.test(uidOrFlag)) return Promise.resolve(uidOrFlag);
|
||||
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
async setRemark(userId: number, remark: string): Promise<void> {
|
||||
if (findDatalineDeviceByUin(userId)) {
|
||||
throw new Error('this contact does not support remarks');
|
||||
}
|
||||
|
||||
if (remark === '') {
|
||||
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||
return;
|
||||
}
|
||||
|
||||
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||
}
|
||||
|
||||
/** List doubtful friend-add requests (可能认识的人). */
|
||||
async getDoubtRequests(count: number): Promise<DoubtBuddyRequest[]> {
|
||||
const list = await GetDoubtBuddyReq.invoke(this.ctx, { count });
|
||||
return Promise.all(
|
||||
list.map(async (item) => {
|
||||
let uid = item.uid;
|
||||
let userId = item.user_id;
|
||||
|
||||
if (userId <= 0 && uid) {
|
||||
userId = this.ctx.identity.findUinByUid(uid) ?? 0;
|
||||
}
|
||||
|
||||
// Applicants need not be friends or share a group. Use Identity's
|
||||
// profile lookup when the list only supplies an account number.
|
||||
if (!uid && userId > 0) {
|
||||
try {
|
||||
uid = await this.ctx.resolveUserUid(userId);
|
||||
} catch (err: unknown) {
|
||||
log.warn(
|
||||
'doubt-request uid resolve failed: user=%d err=%s',
|
||||
userId,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { ...item, uid: uid || '', user_id: userId };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Approve a doubtful friend-add request. `uidOrFlag` is the list uid, or a digit-only account number. */
|
||||
async approveDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
log.trace('doubt-request approval: resolving applicant');
|
||||
const uid = await this.resolveDoubtFlag(uidOrFlag);
|
||||
log.trace('doubt-request approval: submitting request');
|
||||
await ApproveDoubtBuddyReq.invoke(this.ctx, { uid });
|
||||
log.trace('doubt-request approval: completed');
|
||||
}
|
||||
|
||||
/** Reject (delete/decline) a doubtful friend-add request. `uidOrFlag` matches `approveDoubtRequest`. */
|
||||
async rejectDoubtRequest(uidOrFlag: string): Promise<void> {
|
||||
return RejectDoubtBuddyReq.invoke(this.ctx, {
|
||||
uid: await this.resolveDoubtFlag(uidOrFlag),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Digit-only flags are account numbers and must be translated before the
|
||||
* approval/reject packet is built. A raw number in that packet is rejected
|
||||
* by the server. Same rule as inbound friend-request handling.
|
||||
*/
|
||||
private resolveDoubtFlag(uidOrFlag: string): Promise<string> {
|
||||
if (!/^\d+$/.test(uidOrFlag)) {
|
||||
return Promise.resolve(uidOrFlag);
|
||||
}
|
||||
|
||||
return this.ctx.resolveUserUid(parseInt(uidOrFlag, 10));
|
||||
}
|
||||
}
|
||||
@@ -13,22 +13,22 @@ import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set
|
||||
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
|
||||
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
|
||||
import {
|
||||
decodeMemberInvitePolicy,
|
||||
MEMBER_INVITE_PRIVILEGE_MASK,
|
||||
mergeMemberInvitePrivilegeFlag,
|
||||
SetMemberInvitePolicy,
|
||||
type GroupMemberInvitePolicy,
|
||||
decodeMemberInvitePolicy,
|
||||
MEMBER_INVITE_PRIVILEGE_MASK,
|
||||
mergeMemberInvitePrivilegeFlag,
|
||||
SetMemberInvitePolicy,
|
||||
type GroupMemberInvitePolicy,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
|
||||
import {
|
||||
decodeGroupHistoryVisibility,
|
||||
SetNewMemberHistoryVisibility,
|
||||
decodeGroupHistoryVisibility,
|
||||
SetNewMemberHistoryVisibility,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
|
||||
import {
|
||||
decodeGroupMemberPermissions,
|
||||
GROUP_MEMBER_PERMISSION_MASKS,
|
||||
mergeGroupMemberPermission,
|
||||
SetMemberPermission,
|
||||
type GroupMemberPermission,
|
||||
decodeGroupMemberPermissions,
|
||||
GROUP_MEMBER_PERMISSION_MASKS,
|
||||
mergeGroupMemberPermission,
|
||||
SetMemberPermission,
|
||||
type GroupMemberPermission,
|
||||
} from '@snowluma/protocol/oidb-services/group-admin/set-member-permission';
|
||||
import { SetSearch } from '@snowluma/protocol/oidb-services/group-admin/set-search';
|
||||
import { GetGroupCategoryTags } from '@snowluma/protocol/oidb-services/group-admin/get-group-category-tags';
|
||||
@@ -41,282 +41,334 @@ import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
/** QQ only accepts this write from the group owner (#411). */
|
||||
export const MEMBER_PERMISSIONS_OWNER_ONLY =
|
||||
'only the group owner can change group member permissions';
|
||||
'only the group owner can change group member permissions';
|
||||
|
||||
export type GroupAdminSettings = {
|
||||
add_type: number;
|
||||
group_question: string;
|
||||
group_answer: string;
|
||||
robot_member_switch: number;
|
||||
robot_member_examine: number;
|
||||
member_invite_policy: GroupMemberInvitePolicy;
|
||||
allow_member_upload_album: boolean;
|
||||
allow_member_temporary_session: boolean;
|
||||
allow_member_create_group: boolean;
|
||||
new_member_history_visible: boolean;
|
||||
no_finger_open: number;
|
||||
no_code_finger_open: number;
|
||||
add_type: number;
|
||||
group_question: string;
|
||||
group_answer: string;
|
||||
robot_member_switch: number;
|
||||
robot_member_examine: number;
|
||||
member_invite_policy: GroupMemberInvitePolicy;
|
||||
allow_member_upload_album: boolean;
|
||||
allow_member_temporary_session: boolean;
|
||||
allow_member_create_group: boolean;
|
||||
new_member_history_visible: boolean;
|
||||
no_finger_open: number;
|
||||
no_code_finger_open: number;
|
||||
};
|
||||
|
||||
export interface GroupMemberPermissions {
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
allowMemberUploadAlbum?: boolean;
|
||||
allowMemberTemporarySession?: boolean;
|
||||
allowMemberCreateGroup?: boolean;
|
||||
}
|
||||
|
||||
export class GroupAdminApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/** Set the group's robot-add option (switch / examine) via group ext-info. */
|
||||
setRobotAddOption(groupId: number, robotMemberSwitch?: number, robotMemberExamine?: number): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
|
||||
}
|
||||
|
||||
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
|
||||
const [detail, robot] = await Promise.all([
|
||||
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
|
||||
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
|
||||
]);
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read group admin settings for group ${groupId}`);
|
||||
}
|
||||
const privilegeFlag = results.privilegeFlag ?? 0;
|
||||
const permissions = decodeGroupMemberPermissions(privilegeFlag);
|
||||
return {
|
||||
add_type: results.addType ?? 0,
|
||||
group_question: results.question ?? '',
|
||||
group_answer: results.answer ?? '',
|
||||
robot_member_switch: robot.robotMemberSwitch,
|
||||
robot_member_examine: robot.robotMemberExamine,
|
||||
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
|
||||
allow_member_upload_album: permissions.allowMemberUploadAlbum,
|
||||
allow_member_temporary_session: permissions.allowMemberTemporarySession,
|
||||
allow_member_create_group: permissions.allowMemberCreateGroup,
|
||||
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
|
||||
no_finger_open: results.noFingerOpen ?? 0,
|
||||
no_code_finger_open: results.noCodeFingerOpen ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
|
||||
setAddOption(
|
||||
groupId: number,
|
||||
addType: number,
|
||||
groupQuestion?: string,
|
||||
groupAnswer?: string,
|
||||
): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
|
||||
}
|
||||
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
listCategoryTags(groupClass: number): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
addCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
removeCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
|
||||
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'before update',
|
||||
);
|
||||
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
|
||||
|
||||
await SetMemberInvitePolicy.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag,
|
||||
policy,
|
||||
});
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'after update',
|
||||
);
|
||||
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
|
||||
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
|
||||
throw new Error(`group member invite policy was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
|
||||
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
|
||||
}
|
||||
|
||||
private async fetchGroupPrivilegeState(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
|
||||
}
|
||||
return {
|
||||
privilegeFlag: results.privilegeFlag ?? 0,
|
||||
ownerUid: results.ownerUid,
|
||||
};
|
||||
}
|
||||
|
||||
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
|
||||
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
|
||||
['upload_album', permissions.allowMemberUploadAlbum],
|
||||
['temporary_session', permissions.allowMemberTemporarySession],
|
||||
['create_group', permissions.allowMemberCreateGroup],
|
||||
];
|
||||
if (!updates.some(([, allow]) => allow !== undefined)) {
|
||||
throw new Error('at least one member permission must be specified');
|
||||
}
|
||||
|
||||
const before = await this.fetchGroupPrivilegeState(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'before update',
|
||||
);
|
||||
const selfUid = this.ctx.identity.selfUid;
|
||||
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
let expectedPrivilegeFlag = before.privilegeFlag;
|
||||
let combinedMask = 0n;
|
||||
|
||||
for (const [permission, allow] of updates) {
|
||||
if (allow === undefined) continue;
|
||||
try {
|
||||
await SetMemberPermission.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag: expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
/** Set the group's robot-add option (switch / examine) via group ext-info. */
|
||||
setRobotAddOption(
|
||||
groupId: number,
|
||||
robotMemberSwitch?: number,
|
||||
robotMemberExamine?: number,
|
||||
): Promise<void> {
|
||||
return ModifyGroupExtInfo.invoke(this.ctx, {
|
||||
groupId,
|
||||
robotMemberSwitch,
|
||||
robotMemberExamine,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError && error.code === 1287) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
|
||||
const [detail, robot] = await Promise.all([
|
||||
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
|
||||
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
|
||||
]);
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read group admin settings for group ${groupId}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(expectedPrivilegeFlag, permission, allow);
|
||||
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
|
||||
|
||||
const privilegeFlag = results.privilegeFlag ?? 0;
|
||||
const permissions = decodeGroupMemberPermissions(privilegeFlag);
|
||||
return {
|
||||
add_type: results.addType ?? 0,
|
||||
group_question: results.question ?? '',
|
||||
group_answer: results.answer ?? '',
|
||||
robot_member_switch: robot.robotMemberSwitch,
|
||||
robot_member_examine: robot.robotMemberExamine,
|
||||
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
|
||||
allow_member_upload_album: permissions.allowMemberUploadAlbum,
|
||||
allow_member_temporary_session: permissions.allowMemberTemporarySession,
|
||||
allow_member_create_group: permissions.allowMemberCreateGroup,
|
||||
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
|
||||
no_finger_open: results.noFingerOpen ?? 0,
|
||||
no_code_finger_open: results.noCodeFingerOpen ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'after update',
|
||||
);
|
||||
if ((BigInt(actualPrivilegeFlag) & combinedMask) !== (BigInt(expectedPrivilegeFlag) & combinedMask)) {
|
||||
throw new Error(`group member permissions were not applied for group ${groupId}`);
|
||||
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
|
||||
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
|
||||
}
|
||||
}
|
||||
|
||||
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
|
||||
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
|
||||
|
||||
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
|
||||
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
|
||||
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
|
||||
muteAll(groupId: number, enable: boolean): Promise<void> {
|
||||
return MuteAll.invoke(this.ctx, { groupId, enable });
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
if (!results) {
|
||||
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
|
||||
setAddOption(
|
||||
groupId: number,
|
||||
addType: number,
|
||||
groupQuestion?: string,
|
||||
groupAnswer?: string,
|
||||
): Promise<void> {
|
||||
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
|
||||
}
|
||||
return results.groupFlagExt4 ?? 0;
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number, sequence: number, eventType: number,
|
||||
approve: boolean, reason = '', filtered = false,
|
||||
operateTransInfo?: Uint8Array,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, {
|
||||
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
|
||||
});
|
||||
}
|
||||
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
|
||||
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
listCategoryTags(
|
||||
groupClass: number,
|
||||
): Promise<{ tags: { id: number; name: string; type: number }[] }> {
|
||||
return GetGroupCategoryTags.invoke(this.ctx, { groupClass });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
addCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return AddGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
async leave(groupId: number): Promise<void> {
|
||||
await LeaveGroup.invoke(this.ctx, { groupId });
|
||||
// The server doesn't push a member-decrease back to the member who left of
|
||||
// its own accord, so synthesize the self group_member_leave here — otherwise
|
||||
// downstream never sees notice.group_decrease and keeps a "zombie" group in
|
||||
// its cache (#133). Also drop the group from our own roster.
|
||||
const selfUin = Number(this.ctx.identity.uin) || 0;
|
||||
const selfUid = this.ctx.identity.selfUid ?? '';
|
||||
await this.ctx.events.emit({
|
||||
kind: 'group_member_leave',
|
||||
time: Math.floor(Date.now() / 1000),
|
||||
selfUin,
|
||||
groupId,
|
||||
userUin: selfUin,
|
||||
operatorUin: selfUin,
|
||||
userUid: selfUid,
|
||||
operatorUid: selfUid,
|
||||
leaveType: 'leave',
|
||||
});
|
||||
this.ctx.identity.forgetGroup(groupId);
|
||||
}
|
||||
removeCategoryTag(groupClass: number, name: string): Promise<void> {
|
||||
return DeleteGroupCategoryTag.invoke(this.ctx, { groupClass, name });
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
async setMemberInvitePolicy(groupId: number, policy: GroupMemberInvitePolicy): Promise<void> {
|
||||
const currentPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'before update',
|
||||
);
|
||||
const expectedPrivilegeFlag = mergeMemberInvitePrivilegeFlag(currentPrivilegeFlag, policy);
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
await SetMemberInvitePolicy.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag,
|
||||
policy,
|
||||
});
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member invite policy',
|
||||
'after update',
|
||||
);
|
||||
const mask = BigInt(MEMBER_INVITE_PRIVILEGE_MASK);
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
if ((BigInt(actualPrivilegeFlag) & mask) !== (BigInt(expectedPrivilegeFlag) & mask)) {
|
||||
throw new Error(`group member invite policy was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
private async fetchGroupPrivilegeFlag(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<number> {
|
||||
return (await this.fetchGroupPrivilegeState(groupId, setting, phase)).privilegeFlag;
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
private async fetchGroupPrivilegeState(
|
||||
groupId: number,
|
||||
setting: string,
|
||||
phase: string,
|
||||
): Promise<{ privilegeFlag: number; ownerUid?: string }> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
|
||||
}
|
||||
|
||||
return {
|
||||
privilegeFlag: results.privilegeFlag ?? 0,
|
||||
ownerUid: results.ownerUid,
|
||||
};
|
||||
}
|
||||
|
||||
async setMemberPermissions(
|
||||
groupId: number,
|
||||
permissions: GroupMemberPermissions,
|
||||
): Promise<void> {
|
||||
const updates: ReadonlyArray<readonly [GroupMemberPermission, boolean | undefined]> = [
|
||||
['upload_album', permissions.allowMemberUploadAlbum],
|
||||
['temporary_session', permissions.allowMemberTemporarySession],
|
||||
['create_group', permissions.allowMemberCreateGroup],
|
||||
];
|
||||
|
||||
if (!updates.some(([, allow]) => allow !== undefined)) {
|
||||
throw new Error('at least one member permission must be specified');
|
||||
}
|
||||
|
||||
const before = await this.fetchGroupPrivilegeState(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'before update',
|
||||
);
|
||||
const selfUid = this.ctx.identity.selfUid;
|
||||
|
||||
if (selfUid && before.ownerUid && selfUid !== before.ownerUid) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
let expectedPrivilegeFlag = before.privilegeFlag;
|
||||
let combinedMask = 0n;
|
||||
|
||||
for (const [permission, allow] of updates) {
|
||||
if (allow === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await SetMemberPermission.invoke(this.ctx, {
|
||||
groupId,
|
||||
currentPrivilegeFlag: expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OidbError && error.code === 1287) {
|
||||
throw new Error(MEMBER_PERMISSIONS_OWNER_ONLY);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
expectedPrivilegeFlag = mergeGroupMemberPermission(
|
||||
expectedPrivilegeFlag,
|
||||
permission,
|
||||
allow,
|
||||
);
|
||||
combinedMask |= BigInt(GROUP_MEMBER_PERMISSION_MASKS[permission]);
|
||||
}
|
||||
|
||||
const actualPrivilegeFlag = await this.fetchGroupPrivilegeFlag(
|
||||
groupId,
|
||||
'group member permissions',
|
||||
'after update',
|
||||
);
|
||||
|
||||
if (
|
||||
(BigInt(actualPrivilegeFlag) & combinedMask) !==
|
||||
(BigInt(expectedPrivilegeFlag) & combinedMask)
|
||||
) {
|
||||
throw new Error(`group member permissions were not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
|
||||
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
|
||||
|
||||
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
|
||||
|
||||
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
|
||||
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
|
||||
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
|
||||
const results = detail.groupInfo?.results;
|
||||
|
||||
if (!results) {
|
||||
throw new Error(
|
||||
`unable to read new-member history visibility ${phase} for group ${groupId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return results.groupFlagExt4 ?? 0;
|
||||
}
|
||||
|
||||
setAddRequest(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
eventType: number,
|
||||
approve: boolean,
|
||||
reason = '',
|
||||
filtered = false,
|
||||
operateTransInfo?: Uint8Array,
|
||||
): Promise<void> {
|
||||
return SetAddRequest.invoke(this.ctx, {
|
||||
groupId,
|
||||
sequence,
|
||||
eventType,
|
||||
approve,
|
||||
reason,
|
||||
filtered,
|
||||
operateTransInfo,
|
||||
});
|
||||
}
|
||||
|
||||
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
|
||||
return KickMember.invoke(this.ctx, { groupId, userId, reject, reason });
|
||||
}
|
||||
|
||||
kickMembers(groupId: number, userIds: number[], reject: boolean): Promise<void> {
|
||||
return KickMembers.invoke(this.ctx, { groupId, userIds, reject });
|
||||
}
|
||||
|
||||
async leave(groupId: number): Promise<void> {
|
||||
await LeaveGroup.invoke(this.ctx, { groupId });
|
||||
// The server doesn't push a member-decrease back to the member who left of
|
||||
// its own accord, so synthesize the self group_member_leave here — otherwise
|
||||
// downstream never sees notice.group_decrease and keeps a "zombie" group in
|
||||
// its cache (#133). Also drop the group from our own roster.
|
||||
const selfUin = Number(this.ctx.identity.uin) || 0;
|
||||
const selfUid = this.ctx.identity.selfUid ?? '';
|
||||
await this.ctx.events.emit({
|
||||
kind: 'group_member_leave',
|
||||
time: Math.floor(Date.now() / 1000),
|
||||
selfUin,
|
||||
groupId,
|
||||
userUin: selfUin,
|
||||
operatorUin: selfUin,
|
||||
userUid: selfUid,
|
||||
operatorUid: selfUid,
|
||||
leaveType: 'leave',
|
||||
});
|
||||
this.ctx.identity.forgetGroup(groupId);
|
||||
}
|
||||
|
||||
setAdmin(groupId: number, userId: number, enable: boolean): Promise<void> {
|
||||
return SetAdmin.invoke(this.ctx, { groupId, userId, enable });
|
||||
}
|
||||
|
||||
setCard(groupId: number, userId: number, card: string): Promise<void> {
|
||||
return SetMemberCard.invoke(this.ctx, { groupId, userId, card });
|
||||
}
|
||||
|
||||
setName(groupId: number, name: string): Promise<void> {
|
||||
return SetGroupName.invoke(this.ctx, { groupId, name });
|
||||
}
|
||||
|
||||
setSpecialTitle(groupId: number, userId: number, title: string): Promise<void> {
|
||||
return SetSpecialTitle.invoke(this.ctx, { groupId, userId, title });
|
||||
}
|
||||
|
||||
/**
|
||||
* The bot's local-only label for a group. Lives here rather than
|
||||
* `FriendApi` because the semantic is "operate on a group" rather
|
||||
* than "operate on a contact list".
|
||||
*/
|
||||
setRemark(groupId: number, remark: string): Promise<void> {
|
||||
return SetGroupRemark.invoke(this.ctx, { groupId, remark });
|
||||
}
|
||||
|
||||
getAtAllRemain(groupId: number): Promise<{
|
||||
can_at_all: boolean;
|
||||
remain_at_all_count_for_group: number;
|
||||
remain_at_all_count_for_uin: number;
|
||||
}> {
|
||||
return GetAtAllRemain.invoke(this.ctx, { groupId });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,11 @@
|
||||
export interface HistoryRequestGateClock {
|
||||
now(): number;
|
||||
sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
||||
now(): number;
|
||||
sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
||||
}
|
||||
|
||||
const SYSTEM_CLOCK: HistoryRequestGateClock = {
|
||||
now: () => Date.now(),
|
||||
sleep: (ms, signal) => abortableSleep(ms, signal),
|
||||
now: () => Date.now(),
|
||||
sleep: (ms, signal) => abortableSleep(ms, signal),
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -16,93 +16,95 @@ const SYSTEM_CLOCK: HistoryRequestGateClock = {
|
||||
* both sides of an automatic history-sync request.
|
||||
*/
|
||||
export class HistoryRequestGate {
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
private lastStartedAt: number | null = null;
|
||||
private nextAllowedAt = 0;
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
private lastStartedAt: number | null = null;
|
||||
private nextAllowedAt = 0;
|
||||
|
||||
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
|
||||
constructor(private readonly clock: HistoryRequestGateClock = SYSTEM_CLOCK) {}
|
||||
|
||||
run<T>(
|
||||
minimumGapMs: number,
|
||||
operation: () => Promise<T>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<T> {
|
||||
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
|
||||
return Promise.reject(new Error(`history request gap is invalid: ${String(minimumGapMs)}`));
|
||||
run<T>(minimumGapMs: number, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (!Number.isSafeInteger(minimumGapMs) || minimumGapMs < 0) {
|
||||
return Promise.reject(
|
||||
new Error(`history request gap is invalid: ${String(minimumGapMs)}`),
|
||||
);
|
||||
}
|
||||
|
||||
let operationStarted = false;
|
||||
const result = this.tail.then(async () => {
|
||||
throwIfAborted(signal);
|
||||
const now = this.clock.now();
|
||||
const requestedBoundary =
|
||||
this.lastStartedAt === null ? now : this.lastStartedAt + minimumGapMs;
|
||||
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
|
||||
|
||||
if (wait > 0) {
|
||||
await this.clock.sleep(wait, signal);
|
||||
}
|
||||
|
||||
throwIfAborted(signal);
|
||||
const startedAt = this.clock.now();
|
||||
this.lastStartedAt = startedAt;
|
||||
this.nextAllowedAt = startedAt + minimumGapMs;
|
||||
operationStarted = true;
|
||||
return operation();
|
||||
});
|
||||
|
||||
this.tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return signal ? rejectWhileQueuedOnAbort(result, signal, () => operationStarted) : result;
|
||||
}
|
||||
|
||||
let operationStarted = false;
|
||||
const result = this.tail.then(async () => {
|
||||
throwIfAborted(signal);
|
||||
const now = this.clock.now();
|
||||
const requestedBoundary = this.lastStartedAt === null
|
||||
? now
|
||||
: this.lastStartedAt + minimumGapMs;
|
||||
const wait = Math.max(this.nextAllowedAt, requestedBoundary) - now;
|
||||
if (wait > 0) await this.clock.sleep(wait, signal);
|
||||
|
||||
throwIfAborted(signal);
|
||||
const startedAt = this.clock.now();
|
||||
this.lastStartedAt = startedAt;
|
||||
this.nextAllowedAt = startedAt + minimumGapMs;
|
||||
operationStarted = true;
|
||||
return operation();
|
||||
});
|
||||
|
||||
this.tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return signal
|
||||
? rejectWhileQueuedOnAbort(result, signal, () => operationStarted)
|
||||
: result;
|
||||
}
|
||||
}
|
||||
|
||||
function throwIfAborted(signal?: AbortSignal): void {
|
||||
if (signal?.aborted) {
|
||||
throw signal.reason ?? new Error('history request aborted');
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
throw signal.reason ?? new Error('history request aborted');
|
||||
}
|
||||
}
|
||||
|
||||
function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
throwIfAborted(signal);
|
||||
if (!signal) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
throwIfAborted(signal);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
if (!signal) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function rejectWhileQueuedOnAbort<T>(
|
||||
result: Promise<T>,
|
||||
signal: AbortSignal,
|
||||
hasStarted: () => boolean,
|
||||
result: Promise<T>,
|
||||
signal: AbortSignal,
|
||||
hasStarted: () => boolean,
|
||||
): Promise<T> {
|
||||
if (signal.aborted && !hasStarted()) {
|
||||
return Promise.reject(signal.reason ?? new Error('history request aborted'));
|
||||
}
|
||||
if (signal.aborted && !hasStarted()) {
|
||||
return Promise.reject(signal.reason ?? new Error('history request aborted'));
|
||||
}
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
if (!hasStarted()) {
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort);
|
||||
result.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
if (!hasStarted()) {
|
||||
reject(signal.reason ?? new Error('history request aborted'));
|
||||
}
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', onAbort);
|
||||
result.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -17,38 +17,38 @@ import { WebApi } from './web';
|
||||
import { SystemFaceApi } from './system-face';
|
||||
|
||||
export interface ApiHub {
|
||||
/** Personal QQ collections: authenticated list retrieval and pagination. */
|
||||
readonly collection: CollectionApi;
|
||||
/** Send/recall/markRead operations across c2c + group + c2c-file. */
|
||||
readonly message: MessageApi;
|
||||
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
|
||||
readonly contacts: ContactsApi;
|
||||
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
|
||||
readonly groupAdmin: GroupAdminApi;
|
||||
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
|
||||
readonly groupFile: GroupFileApi;
|
||||
/** Group photo album: list/upload/comment/like/delete + media listing. */
|
||||
readonly groupAlbum: GroupAlbumApi;
|
||||
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
|
||||
readonly qzone: QzoneApi;
|
||||
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
|
||||
readonly interaction: InteractionApi;
|
||||
/** Friend roster mutations: handleRequest / delete / setRemark. */
|
||||
readonly friend: FriendApi;
|
||||
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
|
||||
readonly profile: ProfileApi;
|
||||
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
|
||||
readonly flashTransfer: FlashTransferApi;
|
||||
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
|
||||
readonly forward: ForwardApi;
|
||||
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
|
||||
readonly misc: MiscApi;
|
||||
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
|
||||
readonly extras: ExtrasApi;
|
||||
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
|
||||
readonly web: WebApi;
|
||||
/** QQ system-face directory: durable catalog, id lookup, and search. */
|
||||
readonly systemFace: SystemFaceApi;
|
||||
/** Personal QQ collections: authenticated list retrieval and pagination. */
|
||||
readonly collection: CollectionApi;
|
||||
/** Send/recall/markRead operations across c2c + group + c2c-file. */
|
||||
readonly message: MessageApi;
|
||||
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
|
||||
readonly contacts: ContactsApi;
|
||||
/** Group moderation: mute/kick/admin/card/name/title/leave + join-policy. */
|
||||
readonly groupAdmin: GroupAdminApi;
|
||||
/** Group file CRUD + private (c2c) file upload + media URL resolvers. */
|
||||
readonly groupFile: GroupFileApi;
|
||||
/** Group photo album: list/upload/comment/like/delete + media listing. */
|
||||
readonly groupAlbum: GroupAlbumApi;
|
||||
/** Personal QQ-Zone (个人空间): 说说 list + (future) publish/like/comment. */
|
||||
readonly qzone: QzoneApi;
|
||||
/** Interactive engagement: poke / like / reaction / essence / emoji-like-list. */
|
||||
readonly interaction: InteractionApi;
|
||||
/** Friend roster mutations: handleRequest / delete / setRemark. */
|
||||
readonly friend: FriendApi;
|
||||
/** Personal profile: status / avatar / nickname / likes / custom-faces. */
|
||||
readonly profile: ProfileApi;
|
||||
/** QQ 闪传(fileset 文件集): 上传/查询/分享/发送/删除/重命名。 */
|
||||
readonly flashTransfer: FlashTransferApi;
|
||||
/** Long-message (forward / 聊天记录) upload + retrieval with NapCat piggyback. */
|
||||
readonly forward: ForwardApi;
|
||||
/** Odds & ends: translate / mini-app ARK / inline-keyboard / group sign. */
|
||||
readonly misc: MiscApi;
|
||||
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
|
||||
readonly extras: ExtrasApi;
|
||||
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
|
||||
readonly web: WebApi;
|
||||
/** QQ system-face directory: durable catalog, id lookup, and search. */
|
||||
readonly systemFace: SystemFaceApi;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,24 +60,24 @@ export interface ApiHub {
|
||||
* complexity for ~13 small classes.
|
||||
*/
|
||||
export function buildApiHub(ctx: BridgeContext): ApiHub {
|
||||
return {
|
||||
collection: new CollectionApi(ctx),
|
||||
message: new MessageApi(ctx),
|
||||
contacts: new ContactsApi(ctx),
|
||||
groupAdmin: new GroupAdminApi(ctx),
|
||||
groupFile: new GroupFileApi(ctx),
|
||||
groupAlbum: new GroupAlbumApi(ctx),
|
||||
qzone: new QzoneApi(ctx),
|
||||
interaction: new InteractionApi(ctx),
|
||||
friend: new FriendApi(ctx),
|
||||
profile: new ProfileApi(ctx),
|
||||
flashTransfer: new FlashTransferApi(ctx),
|
||||
forward: new ForwardApi(ctx),
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
web: new WebApi(ctx),
|
||||
systemFace: new SystemFaceApi(ctx),
|
||||
};
|
||||
return {
|
||||
collection: new CollectionApi(ctx),
|
||||
message: new MessageApi(ctx),
|
||||
contacts: new ContactsApi(ctx),
|
||||
groupAdmin: new GroupAdminApi(ctx),
|
||||
groupFile: new GroupFileApi(ctx),
|
||||
groupAlbum: new GroupAlbumApi(ctx),
|
||||
qzone: new QzoneApi(ctx),
|
||||
interaction: new InteractionApi(ctx),
|
||||
friend: new FriendApi(ctx),
|
||||
profile: new ProfileApi(ctx),
|
||||
flashTransfer: new FlashTransferApi(ctx),
|
||||
forward: new ForwardApi(ctx),
|
||||
misc: new MiscApi(ctx),
|
||||
extras: new ExtrasApi(ctx),
|
||||
web: new WebApi(ctx),
|
||||
systemFace: new SystemFaceApi(ctx),
|
||||
};
|
||||
}
|
||||
|
||||
// Re-export the Api classes themselves so callers can write
|
||||
@@ -93,12 +93,12 @@ export { GroupAlbumApi } from './group-album';
|
||||
export { GroupFileApi } from './group-file';
|
||||
export { InteractionApi } from './interaction';
|
||||
export {
|
||||
MessageApi,
|
||||
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
|
||||
type GroupHistorySyncState,
|
||||
type HistorySyncPrivateTarget,
|
||||
type HistorySyncState,
|
||||
type PrivateHistorySyncState,
|
||||
MessageApi,
|
||||
LOGIN_HISTORY_SYNC_PROTOCOL_LIMITS,
|
||||
type GroupHistorySyncState,
|
||||
type HistorySyncPrivateTarget,
|
||||
type HistorySyncState,
|
||||
type PrivateHistorySyncState,
|
||||
} from './message';
|
||||
export { MiscApi } from './misc';
|
||||
export { ProfileApi } from './profile';
|
||||
|
||||
@@ -15,47 +15,56 @@ import { SetReaction } from '@snowluma/protocol/oidb-services/reaction/set-react
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
export class InteractionApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
|
||||
}
|
||||
|
||||
sendLike(userId: number, count: number): Promise<void> {
|
||||
return SendLike.invoke(this.ctx, { userId, count });
|
||||
}
|
||||
|
||||
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
|
||||
}
|
||||
|
||||
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
|
||||
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
|
||||
}
|
||||
|
||||
/** Fetch the reactor list for one emoji on a group message. */
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType = 1,
|
||||
count = 10,
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
try {
|
||||
return await GetEmojiLikes.invoke(this.ctx, { groupId, sequence, emojiId, emojiType, count, cookie });
|
||||
} catch {
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
sendPoke(isGroup: boolean, peerUin: number, targetUin?: number): Promise<void> {
|
||||
return SendPoke.invoke(this.ctx, { isGroup, peerUin, targetUin });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
|
||||
*/
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>> {
|
||||
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
|
||||
}
|
||||
sendLike(userId: number, count: number): Promise<void> {
|
||||
return SendLike.invoke(this.ctx, { userId, count });
|
||||
}
|
||||
|
||||
setReaction(groupId: number, sequence: number, code: string, isSet: boolean): Promise<void> {
|
||||
return SetReaction.invoke(this.ctx, { groupId, sequence, code, isSet });
|
||||
}
|
||||
|
||||
setEssence(groupId: number, sequence: number, random: number, enable: boolean): Promise<void> {
|
||||
return SetEssence.invoke(this.ctx, { groupId, sequence, random, enable });
|
||||
}
|
||||
|
||||
/** Fetch the reactor list for one emoji on a group message. */
|
||||
async getEmojiLikes(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
emojiId: string,
|
||||
emojiType = 1,
|
||||
count = 10,
|
||||
cookie = '',
|
||||
): Promise<{ users: Array<{ uin: number }>; cookie: string; isLast: boolean }> {
|
||||
try {
|
||||
return await GetEmojiLikes.invoke(this.ctx, {
|
||||
groupId,
|
||||
sequence,
|
||||
emojiId,
|
||||
emojiType,
|
||||
count,
|
||||
cookie,
|
||||
});
|
||||
} catch {
|
||||
return { users: [], cookie: '', isLast: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recent-used emoji catalog (0x9084_1). Not a per-message reaction list.
|
||||
*/
|
||||
fetchReactionSummary(
|
||||
groupId: number,
|
||||
sequence: number,
|
||||
): Promise<
|
||||
Array<{ emojiId: string; emojiType: number; count: number; lastReactionTime: number }>
|
||||
> {
|
||||
return FetchReactionSummary.invoke(this.ctx, { groupId, sequence });
|
||||
}
|
||||
}
|
||||
+1527
-1260
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,5 @@
|
||||
import type { JsonObject, JsonValue } from '@snowluma/common/json';
|
||||
import type {
|
||||
MiniAppShareReq,
|
||||
MiniAppShareResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import type { MiniAppShareReq, MiniAppShareResp } from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
// Migrated OIDB cmds — facade methods are one-line forwarders.
|
||||
@@ -13,83 +10,108 @@ import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decr
|
||||
import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
ocrImage(imageUrl: string): Promise<OcrResult> {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl = 'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
translateEn2Zh(words: string[]): Promise<string[]> {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
const request = protobuf_encode<MiniAppShareReq>({
|
||||
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
|
||||
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket('LightAppSvc.mini_app_share.AdaptShareInfo', request);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
ocrImage(imageUrl: string): Promise<OcrResult> {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
|
||||
const jsonStr = decoded?.body?.jsonStr;
|
||||
async getMiniAppArk(
|
||||
type: string,
|
||||
title: string,
|
||||
desc: string,
|
||||
picUrl: string,
|
||||
jumpUrl: string,
|
||||
): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl =
|
||||
'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
if (!jsonStr) {
|
||||
throw new Error('mini app share json empty');
|
||||
if (type === 'weibo') {
|
||||
appid = '1109224783';
|
||||
iconUrl =
|
||||
'http://miniapp.gtimg.cn/public/appicon/35bbb44dc68e65194cfacfb206b8f1f7_200.jpg';
|
||||
} else if (type !== 'bili') {
|
||||
throw new Error(`unsupported type: ${type}, only support bili and weibo`);
|
||||
}
|
||||
|
||||
const request = protobuf_encode<MiniAppShareReq>({
|
||||
sdkVersion: 'V1_PC_MINISDK_99.99.99_1_APP_A',
|
||||
body: { appid, title, desc, picUrl, jumpUrl, iconUrl },
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'LightAppSvc.mini_app_share.AdaptShareInfo',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'get mini app ark failed');
|
||||
}
|
||||
|
||||
const decoded = protobuf_decode<MiniAppShareResp>(result.responseData);
|
||||
const jsonStr = decoded?.body?.jsonStr;
|
||||
|
||||
if (!jsonStr) {
|
||||
throw new Error('mini app share json empty');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr) as Record<
|
||||
string,
|
||||
JsonObject | string | number | boolean | null
|
||||
>;
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr) as Record<string, JsonObject | string | number | boolean | null>;
|
||||
|
||||
return {
|
||||
data: {
|
||||
ver: parsed.ver,
|
||||
prompt: parsed.prompt,
|
||||
config: parsed.config,
|
||||
app: parsed.appName,
|
||||
view: parsed.appView,
|
||||
meta: parsed.metaData,
|
||||
miniappShareOrigin: 3,
|
||||
miniappOpenRefer: '10002',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
clickInlineKeyboardButton(
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<JsonValue> {
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, { groupId, botAppid, buttonId, callbackData, msgSeq });
|
||||
}
|
||||
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`);
|
||||
clickInlineKeyboardButton(
|
||||
groupId: number,
|
||||
botAppid: number,
|
||||
buttonId: string,
|
||||
callbackData: string,
|
||||
msgSeq: number,
|
||||
): Promise<JsonValue> {
|
||||
return ClickInlineKeyboardButton.invoke(this.ctx, {
|
||||
groupId,
|
||||
botAppid,
|
||||
buttonId,
|
||||
callbackData,
|
||||
msgSeq,
|
||||
});
|
||||
}
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
|
||||
sendGroupSign(groupId: number): Promise<void> {
|
||||
return SendGroupSign.invoke(this.ctx, { groupId });
|
||||
}
|
||||
|
||||
async getDecryptKey(dbSalt: string): Promise<string> {
|
||||
const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt });
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!result.dbKey) {
|
||||
throw new Error('Decrypt key is empty');
|
||||
}
|
||||
|
||||
return result.dbKey;
|
||||
}
|
||||
return result.dbKey;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import type {
|
||||
GroupAvatarExtra,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
GroupAvatarExtra,
|
||||
SetStatusReq,
|
||||
SetStatusResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { AddCustomFace } from '@snowluma/protocol/oidb-services/custom-face/add-custom-face';
|
||||
import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/delete-custom-face';
|
||||
@@ -10,10 +10,17 @@ import { FetchCustomFaceList } from '@snowluma/protocol/oidb-services/custom-fac
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import {
|
||||
BufferChunkSource,
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
} from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import {
|
||||
GetUnidirectionalFriendList,
|
||||
type UnidirectionalFriendEntry,
|
||||
} from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
import { SetInputStatus } from '@snowluma/protocol/oidb-services/profile/set-input-status';
|
||||
import { SetProfile } from '@snowluma/protocol/oidb-services/profile/set-profile';
|
||||
import { SetSelfLongNick } from '@snowluma/protocol/oidb-services/profile/set-self-long-nick';
|
||||
@@ -21,226 +28,273 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
export interface CustomFaceDetail {
|
||||
emojiId: string;
|
||||
url: string;
|
||||
md5: string;
|
||||
desc: string;
|
||||
emojiId: string;
|
||||
url: string;
|
||||
md5: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export class ProfileApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
// ─────────────── status / profile setters ───────────────
|
||||
// ─────────────── status / profile setters ───────────────
|
||||
|
||||
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
|
||||
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
|
||||
}
|
||||
|
||||
/**
|
||||
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
|
||||
* — the values QQ associates with "I have a custom status string" —
|
||||
* and threads the faceId / wording / faceType through the customExt
|
||||
* sub-message of the same SetStatus wire call.
|
||||
*/
|
||||
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
|
||||
await this.dispatchSetStatus({
|
||||
status: 10,
|
||||
extStatus: 2000,
|
||||
batteryStatus: 0,
|
||||
customExt: { faceId, text: wording, faceType },
|
||||
});
|
||||
}
|
||||
|
||||
private async dispatchSetStatus(value: {
|
||||
status: number;
|
||||
extStatus: number;
|
||||
batteryStatus: number;
|
||||
customExt?: { faceId: number; text: string; faceType: number };
|
||||
}): Promise<void> {
|
||||
const request = protobuf_encode<SetStatusReq>(value);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
|
||||
request,
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
async setOnlineStatus(status: number, extStatus = 0, batteryStatus = 100): Promise<void> {
|
||||
await this.dispatchSetStatus({ status, extStatus, batteryStatus });
|
||||
}
|
||||
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protobuf_decode<SetStatusResp>(result.responseData);
|
||||
if (!resp) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
const message = resp.errMsg ?? '';
|
||||
if (message !== '' && message !== 'set status success') {
|
||||
throw new Error(message);
|
||||
}
|
||||
/**
|
||||
* DIY (custom) online status. napcat fixes status=10 / extStatus=2000
|
||||
* — the values QQ associates with "I have a custom status string" —
|
||||
* and threads the faceId / wording / faceType through the customExt
|
||||
* sub-message of the same SetStatus wire call.
|
||||
*/
|
||||
async setDiyOnlineStatus(faceId: number, wording: string, faceType: number): Promise<void> {
|
||||
await this.dispatchSetStatus({
|
||||
status: 10,
|
||||
extStatus: 2000,
|
||||
batteryStatus: 0,
|
||||
customExt: { faceId, text: wording, faceType },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
|
||||
}
|
||||
private async dispatchSetStatus(value: {
|
||||
status: number;
|
||||
extStatus: number;
|
||||
batteryStatus: number;
|
||||
customExt?: { faceId: number; text: string; faceType: number };
|
||||
}): Promise<void> {
|
||||
const request = protobuf_encode<SetStatusReq>(value);
|
||||
const result = await this.ctx.sendRawPacket(
|
||||
'trpc.qq_new_tech.status_svc.StatusService.SetStatus',
|
||||
request,
|
||||
);
|
||||
|
||||
setSelfLongNick(longNick: string): Promise<void> {
|
||||
return SetSelfLongNick.invoke(this.ctx, { longNick });
|
||||
}
|
||||
if (!result.success) {
|
||||
throw new Error(result.errorMessage || 'set online status failed (network/timeout)');
|
||||
}
|
||||
|
||||
setInputStatus(userId: number, eventType: number): Promise<void> {
|
||||
return SetInputStatus.invoke(this.ctx, { userId, eventType });
|
||||
}
|
||||
if (result.responseData && result.responseData.length > 0) {
|
||||
const resp = protobuf_decode<SetStatusResp>(result.responseData);
|
||||
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
if (!loaded.bytes.length) throw new Error('avatar file is empty');
|
||||
if (!resp) {
|
||||
throw new Error(
|
||||
result.errorMessage || 'set online status failed (network/timeout)',
|
||||
);
|
||||
}
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
|
||||
}
|
||||
const message = resp.errMsg ?? '';
|
||||
|
||||
/**
|
||||
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
|
||||
* - same highway HTTP upload as personal avatar
|
||||
* - cmdId 3000 (instead of 90)
|
||||
* - GroupAvatarExtra proto carried as the `extend` blob, with the
|
||||
* four protocol-prescribed constants (type=101, field5=3, field6=1,
|
||||
* field3.field1=1) and the target groupUin.
|
||||
*
|
||||
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
|
||||
*/
|
||||
async setGroupAvatar(groupId: number, source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'group-avatar');
|
||||
if (!loaded.bytes.length) throw new Error('group avatar file is empty');
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const extra = protobuf_encode<GroupAvatarExtra>({
|
||||
type: 101,
|
||||
groupUin: groupId,
|
||||
field3: { field1: 1 },
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
|
||||
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
|
||||
return GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
}
|
||||
|
||||
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
|
||||
return GetUnidirectionalFriendList.invoke(this.ctx);
|
||||
}
|
||||
|
||||
async fetchCustomFace(count = 10): Promise<string[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
return faceIds.map((id) => this.customFaceUrl(id));
|
||||
}
|
||||
|
||||
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
if (faceIds.length === 0) return [];
|
||||
|
||||
const emojis = faceIds.map((emojiId) => ({
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
}));
|
||||
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
|
||||
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
|
||||
|
||||
return emojis.map(({ emojiId, md5 }) => ({
|
||||
emojiId,
|
||||
url: this.customFaceUrl(emojiId),
|
||||
md5,
|
||||
// The detail response may omit entries which have never had a remark.
|
||||
desc: descriptions.get(emojiId) ?? '',
|
||||
}));
|
||||
}
|
||||
|
||||
async fetchCustomFaceIds(count = 10): Promise<string[]> {
|
||||
if (!Number.isInteger(count) || count < 0) {
|
||||
throw new Error('custom face count must be a non-negative integer');
|
||||
if (message !== '' && message !== 'set status success') {
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count === 0) return [];
|
||||
|
||||
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
return faceIds.slice(0, count);
|
||||
}
|
||||
setProfile(nickname?: string, personalNote?: string, sex?: number): Promise<void> {
|
||||
return SetProfile.invoke(this.ctx, { nickname, personalNote, sex });
|
||||
}
|
||||
|
||||
private customFaceUrl(emojiId: string): string {
|
||||
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
|
||||
}
|
||||
setSelfLongNick(longNick: string): Promise<void> {
|
||||
return SetSelfLongNick.invoke(this.ctx, { longNick });
|
||||
}
|
||||
|
||||
/** Resolve an existing saved sticker by its resource id or content MD5. */
|
||||
async resolveCustomFace(identifier: string): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
const wanted = identifier.trim();
|
||||
if (!wanted) throw new Error('custom face identifier is empty');
|
||||
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
|
||||
const emojiId = ids.find((id) => byMd5
|
||||
? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase()
|
||||
: id === wanted);
|
||||
if (!emojiId) throw new Error('custom face is not in the saved sticker list');
|
||||
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
|
||||
}
|
||||
setInputStatus(userId: number, eventType: number): Promise<void> {
|
||||
return SetInputStatus.invoke(this.ctx, { userId, eventType });
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
}
|
||||
async setAvatar(source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'avatar');
|
||||
|
||||
/**
|
||||
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
|
||||
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
|
||||
*/
|
||||
async addCustomFace(imageSource: string): Promise<string> {
|
||||
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
|
||||
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
|
||||
}
|
||||
if (!loaded.bytes.length) {
|
||||
throw new Error('avatar file is empty');
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
|
||||
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
|
||||
*/
|
||||
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
|
||||
return ModifyCustomFace.invoke(this.ctx, {
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
desc,
|
||||
});
|
||||
}
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
session,
|
||||
90,
|
||||
new BufferChunkSource(loaded.bytes),
|
||||
hashes.md5,
|
||||
new Uint8Array(0),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
|
||||
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
|
||||
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
|
||||
* 两步都发才生效。
|
||||
*/
|
||||
async moveCustomFaceToFront(emojiId: string): Promise<void> {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const ids = await this.fetchCustomFaceIds(1000);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
if (idx < 0) throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
const reordered = ids.slice();
|
||||
reordered.splice(idx, 1);
|
||||
reordered.unshift(emojiId);
|
||||
// 2. 0x902f 移动指令(f3=1 = 移到最前)
|
||||
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
|
||||
// 3. 0x902e opType=2 上传新顺序
|
||||
await MoveCustomFace.invoke(this.ctx, {
|
||||
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Set group avatar. Mirrors Lagrange.Core's GroupSetAvatar:
|
||||
* - same highway HTTP upload as personal avatar
|
||||
* - cmdId 3000 (instead of 90)
|
||||
* - GroupAvatarExtra proto carried as the `extend` blob, with the
|
||||
* four protocol-prescribed constants (type=101, field5=3, field6=1,
|
||||
* field3.field1=1) and the target groupUin.
|
||||
*
|
||||
* Source ref: Lagrange.Core/Internal/Context/Logic/Implementation/OperationLogic.cs#GroupSetAvatar.
|
||||
*/
|
||||
async setGroupAvatar(groupId: number, source: string): Promise<void> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const loaded = await loadBinarySource(source, 'group-avatar');
|
||||
|
||||
if (!loaded.bytes.length) {
|
||||
throw new Error('group avatar file is empty');
|
||||
}
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
const extra = protobuf_encode<GroupAvatarExtra>({
|
||||
type: 101,
|
||||
groupUin: groupId,
|
||||
field3: { field1: 1 },
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
session,
|
||||
3000,
|
||||
new BufferChunkSource(loaded.bytes),
|
||||
hashes.md5,
|
||||
extra,
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
|
||||
getLike(userId?: number, start = 0, limit = 10): Promise<LikeInfo> {
|
||||
return GetLike.invoke(this.ctx, { userId, start, limit });
|
||||
}
|
||||
|
||||
getUnidirectionalFriendList(): Promise<UnidirectionalFriendEntry[]> {
|
||||
return GetUnidirectionalFriendList.invoke(this.ctx);
|
||||
}
|
||||
|
||||
async fetchCustomFace(count = 10): Promise<string[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
return faceIds.map((id) => this.customFaceUrl(id));
|
||||
}
|
||||
|
||||
async fetchCustomFaceDetails(count = 10): Promise<CustomFaceDetail[]> {
|
||||
const faceIds = await this.fetchCustomFaceIds(count);
|
||||
|
||||
if (faceIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const emojis = faceIds.map((emojiId) => ({
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
}));
|
||||
const details = await FetchCustomFaceDetail.invoke(this.ctx, { emojis });
|
||||
const descriptions = new Map(details.map((detail) => [detail.emojiId, detail.desc]));
|
||||
|
||||
return emojis.map(({ emojiId, md5 }) => ({
|
||||
emojiId,
|
||||
url: this.customFaceUrl(emojiId),
|
||||
md5,
|
||||
// The detail response may omit entries which have never had a remark.
|
||||
desc: descriptions.get(emojiId) ?? '',
|
||||
}));
|
||||
}
|
||||
|
||||
async fetchCustomFaceIds(count = 10): Promise<string[]> {
|
||||
if (!Number.isInteger(count) || count < 0) {
|
||||
throw new Error('custom face count must be a non-negative integer');
|
||||
}
|
||||
|
||||
if (count === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const faceIds = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
return faceIds.slice(0, count);
|
||||
}
|
||||
|
||||
private customFaceUrl(emojiId: string): string {
|
||||
return `https://p.qpic.cn/qq_expression/${this.ctx.identity.uin}/${emojiId}/0`;
|
||||
}
|
||||
|
||||
/** Resolve an existing saved sticker by its resource id or content MD5. */
|
||||
async resolveCustomFace(
|
||||
identifier: string,
|
||||
): Promise<Pick<CustomFaceDetail, 'emojiId' | 'url' | 'md5'>> {
|
||||
const wanted = identifier.trim();
|
||||
|
||||
if (!wanted) {
|
||||
throw new Error('custom face identifier is empty');
|
||||
}
|
||||
|
||||
const ids = await FetchCustomFaceList.invoke(this.ctx, { uin: this.ctx.identity.uin });
|
||||
const byMd5 = /^[a-fA-F0-9]{32}$/.test(wanted);
|
||||
const emojiId = ids.find((id) =>
|
||||
byMd5 ? md5FromEmojiId(id).toLowerCase() === wanted.toLowerCase() : id === wanted,
|
||||
);
|
||||
|
||||
if (!emojiId) {
|
||||
throw new Error('custom face is not in the saved sticker list');
|
||||
}
|
||||
|
||||
return { emojiId, url: this.customFaceUrl(emojiId), md5: md5FromEmojiId(emojiId) };
|
||||
}
|
||||
|
||||
/** 删除一个收藏表情(custom face)。emoji_id 来自收藏列表。 */
|
||||
deleteCustomFace(emojiId: string): Promise<void> {
|
||||
return DeleteCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, emojiId });
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加收藏表情(custom face)。imageSource 支持 file:///、base64://、http(s)://
|
||||
* (复用 highway utils 的 loadBinarySource)。返回新 emoji_id。
|
||||
*/
|
||||
async addCustomFace(imageSource: string): Promise<string> {
|
||||
const { bytes } = await loadBinarySource(imageSource, 'custom-face');
|
||||
return AddCustomFace.invoke(this.ctx, { uin: this.ctx.identity.uin, imageBytes: bytes });
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改收藏表情(custom face)备注。emoji_id 来自收藏列表;md5 从 emoji_id
|
||||
* 中段解析,无需调用方单独提供。desc 为空串则清空备注。
|
||||
*/
|
||||
modifyCustomFace(emojiId: string, desc: string): Promise<void> {
|
||||
return ModifyCustomFace.invoke(this.ctx, {
|
||||
emojiId,
|
||||
md5: md5FromEmojiId(emojiId),
|
||||
desc,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 收藏表情(custom face)移到最前。QQ 客户端只有"移动到最前",协议层
|
||||
* (0x902f 的 f3=1)也只支持最前,不支持移到其他位置。两步流程:先 0x902f
|
||||
* 移动指令,再 0x902e opType=2 上传新顺序(fetch 当前列表把目标挪到第一)。
|
||||
* 两步都发才生效。
|
||||
*/
|
||||
async moveCustomFaceToFront(emojiId: string): Promise<void> {
|
||||
// 1. fetch 当前完整列表(fetch 顺序即可,不需要 DB 显示顺序)
|
||||
const ids = await this.fetchCustomFaceIds(1000);
|
||||
const idx = ids.indexOf(emojiId);
|
||||
|
||||
if (idx < 0) {
|
||||
throw new Error(`emoji_id not in list: ${emojiId}`);
|
||||
}
|
||||
|
||||
// 新顺序:目标挪到第一,其余按原顺序
|
||||
const reordered = ids.slice();
|
||||
reordered.splice(idx, 1);
|
||||
reordered.unshift(emojiId);
|
||||
// 2. 0x902f 移动指令(f3=1 = 移到最前)
|
||||
await OrderCustomFace.invoke(this.ctx, { emojiId, position: 1 });
|
||||
// 3. 0x902e opType=2 上传新顺序
|
||||
await MoveCustomFace.invoke(this.ctx, {
|
||||
emojis: reordered.map((id) => ({ emojiId: id, md5: md5FromEmojiId(id) })),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,11 +303,13 @@ export class ProfileApi {
|
||||
* 传空串让服务端拒绝更早定位问题。
|
||||
*/
|
||||
function md5FromEmojiId(emojiId: string): string {
|
||||
const parts = emojiId.split('_');
|
||||
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
|
||||
const md5 = parts[4];
|
||||
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
|
||||
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
|
||||
}
|
||||
return md5.toUpperCase();
|
||||
const parts = emojiId.split('_');
|
||||
// 期望形如 `<uin>_0_0_0_<md5>_0_0`,共 7 段,md5 在 index 4。
|
||||
const md5 = parts[4];
|
||||
|
||||
if (!md5 || md5.length !== 32 || !/^[0-9a-fA-F]{32}$/.test(md5)) {
|
||||
throw new Error(`invalid emoji_id (cannot extract md5): ${emojiId}`);
|
||||
}
|
||||
|
||||
return md5.toUpperCase();
|
||||
}
|
||||
@@ -1,19 +1,19 @@
|
||||
import {
|
||||
commentQzoneMsg,
|
||||
deleteQzoneMsg,
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneBlack,
|
||||
setQzoneLike,
|
||||
updateQzoneMsgRight,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
type QzoneUpdateRightResult,
|
||||
type QzoneUploadImageResult,
|
||||
commentQzoneMsg,
|
||||
deleteQzoneMsg,
|
||||
getQzoneFeeds,
|
||||
getQzoneMsgList,
|
||||
publishQzoneMsg,
|
||||
setQzoneBlack,
|
||||
setQzoneLike,
|
||||
updateQzoneMsgRight,
|
||||
uploadQzoneImageFromSource,
|
||||
type QzoneCommentResult,
|
||||
type QzoneFeedsResult,
|
||||
type QzoneMsgListResult,
|
||||
type QzonePublishResult,
|
||||
type QzoneUpdateRightResult,
|
||||
type QzoneUploadImageResult,
|
||||
} from '@snowluma/protocol/web/qzone';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
@@ -24,105 +24,122 @@ import type { BridgeContext } from '../bridge-context';
|
||||
* Distinct from the group-album surface, which lives on GroupAlbumApi.
|
||||
*/
|
||||
export class QzoneApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
/**
|
||||
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
|
||||
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
|
||||
*/
|
||||
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
|
||||
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneMsgList(cookieObject, uin, pos, num);
|
||||
}
|
||||
/**
|
||||
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
|
||||
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
|
||||
*/
|
||||
async getMsgList(targetUin?: number, pos = 0, num = 20): Promise<QzoneMsgListResult> {
|
||||
const uin = targetUin && targetUin > 0 ? targetUin.toString() : this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneMsgList(cookieObject, uin, pos, num);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
|
||||
* 始终以机器人自己的身份拉取好友动态。
|
||||
*/
|
||||
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
/**
|
||||
* 获取好友动态(feed)。`pageNum` 为 1 起的页码,`count` 为本页数量。
|
||||
* 始终以机器人自己的身份拉取好友动态。
|
||||
*/
|
||||
async getFeeds(pageNum = 1, count = 10): Promise<QzoneFeedsResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从来源上传图片到 QQ 空间。
|
||||
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
|
||||
*/
|
||||
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
|
||||
}
|
||||
/**
|
||||
* 从来源上传图片到 QQ 空间。
|
||||
* `source` 支持: file:// 本地路径 | http(s):// URL | base64:// base64数据
|
||||
*/
|
||||
async uploadImageFromSource(source: string): Promise<QzoneUploadImageResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return uploadQzoneImageFromSource(cookieObject, this.ctx.identity.uin, source);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
|
||||
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
|
||||
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
|
||||
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
|
||||
*/
|
||||
async publish(
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
ugcRight = 1,
|
||||
targetUins?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins);
|
||||
}
|
||||
/**
|
||||
* 发表说说,返回新说说的 tid。始终发到机器人自己的空间。
|
||||
* `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串
|
||||
* (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。
|
||||
* `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。
|
||||
*/
|
||||
async publish(
|
||||
content: string,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
ugcRight = 1,
|
||||
targetUins?: string,
|
||||
): Promise<QzonePublishResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return publishQzoneMsg(
|
||||
cookieObject,
|
||||
this.ctx.identity.uin,
|
||||
content,
|
||||
richType,
|
||||
richval,
|
||||
ugcRight,
|
||||
targetUins,
|
||||
);
|
||||
}
|
||||
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
async delete(tid: string): Promise<void> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
|
||||
}
|
||||
/** 删除机器人自己空间的一条说说(按 tid)。 */
|
||||
async delete(tid: string): Promise<void> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
|
||||
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
|
||||
*/
|
||||
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
|
||||
}
|
||||
/**
|
||||
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
|
||||
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
|
||||
*/
|
||||
async updateRight(
|
||||
tid: string,
|
||||
ugcRight: number,
|
||||
targetUins?: string,
|
||||
): Promise<QzoneUpdateRightResult> {
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
*/
|
||||
async like(tid: string, targetUin: number | undefined, like: boolean, abstime = 0): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
|
||||
}
|
||||
/**
|
||||
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
|
||||
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
|
||||
*/
|
||||
async like(
|
||||
tid: string,
|
||||
targetUin: number | undefined,
|
||||
like: boolean,
|
||||
abstime = 0,
|
||||
): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneLike(cookieObject, selfUin, owner, tid, like, abstime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
*/
|
||||
async comment(
|
||||
tid: string,
|
||||
content: string,
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
/**
|
||||
* 评论一条说说。`targetUin` 为说说所属 QQ 号(省略=机器人自己空间);
|
||||
* 始终以机器人身份发表评论。返回新评论 id(尽力而为)。
|
||||
* `richType` / `richval`: 带图评论时传 richType=1 和图片直链 URL
|
||||
* (从 uploadImageFromSource 的 url 字段获取)。
|
||||
*/
|
||||
async comment(
|
||||
tid: string,
|
||||
content: string,
|
||||
targetUin: number | undefined,
|
||||
richType?: number,
|
||||
richval?: string,
|
||||
): Promise<QzoneCommentResult> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const owner = targetUin && targetUin > 0 ? targetUin.toString() : selfUin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
return commentQzoneMsg(cookieObject, selfUin, owner, tid, content, richType, richval);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
|
||||
* `ban=true` 拉黑,`ban=false` 解除拉黑。
|
||||
*/
|
||||
async setBlack(targetUin: number, ban: boolean): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
|
||||
}
|
||||
/**
|
||||
* 拉黑或解除拉黑某人(修改机器人自身 QQ 空间黑名单)。
|
||||
* `ban=true` 拉黑,`ban=false` 解除拉黑。
|
||||
*/
|
||||
async setBlack(targetUin: number, ban: boolean): Promise<void> {
|
||||
const selfUin = this.ctx.identity.uin;
|
||||
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
|
||||
await setQzoneBlack(cookieObject, selfUin, targetUin.toString(), ban);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,19 @@
|
||||
export function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'bigint') {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
return 0;
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'bigint') {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol
|
||||
@@ -22,25 +27,25 @@ export { resolveSelfUid } from '@snowluma/protocol/self-uid';
|
||||
* fetchers in group-file.ts.
|
||||
*/
|
||||
export interface MediaIndexNode {
|
||||
info?: {
|
||||
fileSize?: number;
|
||||
fileHash?: string;
|
||||
fileSha1?: string;
|
||||
fileName?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
time?: number;
|
||||
original?: number;
|
||||
type?: {
|
||||
type?: number;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
info?: {
|
||||
fileSize?: number;
|
||||
fileHash?: string;
|
||||
fileSha1?: string;
|
||||
fileName?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
time?: number;
|
||||
original?: number;
|
||||
type?: {
|
||||
type?: number;
|
||||
picFormat?: number;
|
||||
videoFormat?: number;
|
||||
voiceFormat?: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
fileUuid?: string;
|
||||
storeId?: number;
|
||||
uploadTime?: number;
|
||||
ttl?: number;
|
||||
subType?: number;
|
||||
fileUuid?: string;
|
||||
storeId?: number;
|
||||
uploadTime?: number;
|
||||
ttl?: number;
|
||||
subType?: number;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
sysFaceStore,
|
||||
type SysFaceEntry,
|
||||
type SysFacePackEntry,
|
||||
sysFaceStore,
|
||||
type SysFaceEntry,
|
||||
type SysFacePackEntry,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
@@ -9,27 +9,28 @@ import type { BridgeContext } from '../bridge-context';
|
||||
/** QQ's account-independent system-face directory. The shared store owns
|
||||
* persistence and refresh coalescing; this API binds it to one live sender. */
|
||||
export class SystemFaceApi {
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
|
||||
return sysFaceStore.getCatalog(this.ctx, refresh);
|
||||
}
|
||||
|
||||
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
|
||||
if (refresh) {
|
||||
await sysFaceStore.refresh(this.ctx);
|
||||
return sysFaceStore.lookup(faceId);
|
||||
fetchCatalog(refresh = false): Promise<SysFacePackEntry[]> {
|
||||
return sysFaceStore.getCatalog(this.ctx, refresh);
|
||||
}
|
||||
return sysFaceStore.resolve(this.ctx, faceId);
|
||||
}
|
||||
|
||||
async search(query: string): Promise<SysFaceEntry[]> {
|
||||
await sysFaceStore.ensureReady(this.ctx);
|
||||
return sysFaceStore.search(query);
|
||||
}
|
||||
async fetchFace(faceId: number, refresh = false): Promise<SysFaceEntry | null> {
|
||||
if (refresh) {
|
||||
await sysFaceStore.refresh(this.ctx);
|
||||
return sysFaceStore.lookup(faceId);
|
||||
}
|
||||
|
||||
async isSuper(faceId: number, refresh = false): Promise<boolean> {
|
||||
const face = await this.fetchFace(faceId, refresh);
|
||||
return face !== null && isSuperFaceEntry(face);
|
||||
}
|
||||
return sysFaceStore.resolve(this.ctx, faceId);
|
||||
}
|
||||
|
||||
async search(query: string): Promise<SysFaceEntry[]> {
|
||||
await sysFaceStore.ensureReady(this.ctx);
|
||||
return sysFaceStore.search(query);
|
||||
}
|
||||
|
||||
async isSuper(faceId: number, refresh = false): Promise<boolean> {
|
||||
const face = await this.fetchFace(faceId, refresh);
|
||||
return face !== null && isSuperFaceEntry(face);
|
||||
}
|
||||
}
|
||||
@@ -1,226 +1,288 @@
|
||||
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import {
|
||||
ForceFetchClientKey,
|
||||
type ClientKeyInfo as NamespaceClientKeyInfo,
|
||||
} from '@snowluma/protocol/oidb-services/web/force-fetch-client-key';
|
||||
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
|
||||
import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence';
|
||||
import {
|
||||
getGroupEssenceMsg,
|
||||
getGroupEssenceMsgAll,
|
||||
type GroupEssenceMsgRet,
|
||||
} from '@snowluma/protocol/web/group-essence';
|
||||
import { getFriendDressWebAPI, type WebFriendDress } from '@snowluma/protocol/web/friend-dress';
|
||||
import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/protocol/web/group-honor';
|
||||
import {
|
||||
getHonorListWebAPI,
|
||||
WebHonorType,
|
||||
type WebHonorItem,
|
||||
} from '@snowluma/protocol/web/group-honor';
|
||||
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
||||
import {
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
GROUP_NOTICE_TYPE_NORMAL,
|
||||
getGroupNoticeWebAPI,
|
||||
groupNoticeImageUrl,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
type WebApiGroupNoticeCollection,
|
||||
type WebApiGroupNoticeFeed,
|
||||
type WebApiGroupNoticeRet,
|
||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
GROUP_NOTICE_TYPE_NORMAL,
|
||||
getGroupNoticeWebAPI,
|
||||
groupNoticeImageUrl,
|
||||
setGroupNoticeWebAPI,
|
||||
uploadGroupNoticeImage,
|
||||
type SetNoticeRetSuccess,
|
||||
type WebApiGroupNoticeCollection,
|
||||
type WebApiGroupNoticeFeed,
|
||||
type WebApiGroupNoticeRet,
|
||||
} from '@snowluma/protocol/web/group-notice';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
import type { Bridge } from '../bridge';
|
||||
import type { BridgeContext } from '../bridge-context';
|
||||
|
||||
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
|
||||
function asBridge(ctx: BridgeContext): Bridge {
|
||||
return ctx as unknown as Bridge;
|
||||
}
|
||||
|
||||
export type ClientKeyInfo = NamespaceClientKeyInfo;
|
||||
|
||||
export interface WebHonorInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
group_id: number;
|
||||
current_talkative: WebHonorItem | null;
|
||||
talkative_list: WebHonorItem[];
|
||||
performer_list: WebHonorItem[];
|
||||
legend_list: WebHonorItem[];
|
||||
emotion_list: WebHonorItem[];
|
||||
strong_newbie_list: WebHonorItem[];
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
group_id: number;
|
||||
current_talkative: WebHonorItem | null;
|
||||
talkative_list: WebHonorItem[];
|
||||
performer_list: WebHonorItem[];
|
||||
legend_list: WebHonorItem[];
|
||||
emotion_list: WebHonorItem[];
|
||||
strong_newbie_list: WebHonorItem[];
|
||||
}
|
||||
|
||||
export interface WebNoticeInfo {
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
notice_id: string;
|
||||
sender_id: number;
|
||||
publish_time: number;
|
||||
message: {
|
||||
text: string;
|
||||
image: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
/** Server response type. Regular notices are commonly returned as 6. */
|
||||
type: number;
|
||||
pinned: number;
|
||||
send_to_new_members: boolean;
|
||||
[key: string]: import('@snowluma/common/json').JsonValue;
|
||||
notice_id: string;
|
||||
sender_id: number;
|
||||
publish_time: number;
|
||||
message: {
|
||||
text: string;
|
||||
image: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
images: Array<{ id: string; url: string; height: number; width: number }>;
|
||||
};
|
||||
settings: import('@snowluma/common/json').JsonValue;
|
||||
read_num: number;
|
||||
/** Server response type. Regular notices are commonly returned as 6. */
|
||||
type: number;
|
||||
pinned: number;
|
||||
send_to_new_members: boolean;
|
||||
}
|
||||
|
||||
export interface SendNoticeOptions {
|
||||
image?: string;
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
sendToNewMembers?: boolean;
|
||||
isShowEditCard?: number;
|
||||
tipWindowType?: number;
|
||||
confirmRequired?: number;
|
||||
image?: string;
|
||||
pinned?: number;
|
||||
type?: number;
|
||||
sendToNewMembers?: boolean;
|
||||
isShowEditCard?: number;
|
||||
tipWindowType?: number;
|
||||
confirmRequired?: number;
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown, field: string): number {
|
||||
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
|
||||
if (!Number.isFinite(parsed)) {
|
||||
throw new Error(`invalid group notice response: ${field} must be a finite number`);
|
||||
}
|
||||
return parsed;
|
||||
const parsed =
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: typeof value === 'string' && value.trim() !== ''
|
||||
? Number(value)
|
||||
: Number.NaN;
|
||||
|
||||
if (!Number.isFinite(parsed)) {
|
||||
throw new Error(`invalid group notice response: ${field} must be a finite number`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function collectionValues(
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
field: 'feeds' | 'inst',
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
field: 'feeds' | 'inst',
|
||||
): WebApiGroupNoticeFeed[] {
|
||||
if (collection === undefined) return [];
|
||||
if (Array.isArray(collection)) return collection;
|
||||
if (collection === null || typeof collection !== 'object') {
|
||||
throw new Error(`invalid group notice response: ${field} must be an array or object`);
|
||||
}
|
||||
return Object.values(collection);
|
||||
if (collection === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (Array.isArray(collection)) {
|
||||
return collection;
|
||||
}
|
||||
|
||||
if (collection === null || typeof collection !== 'object') {
|
||||
throw new Error(`invalid group notice response: ${field} must be an array or object`);
|
||||
}
|
||||
|
||||
return Object.values(collection);
|
||||
}
|
||||
|
||||
function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo {
|
||||
if (!feed || typeof feed !== 'object') {
|
||||
throw new Error('invalid group notice response: feed must be an object');
|
||||
}
|
||||
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
|
||||
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
|
||||
}
|
||||
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
|
||||
}
|
||||
if (feed.settings === undefined) {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
|
||||
}
|
||||
|
||||
const image = (feed.msg.pics ?? []).map((pic, index) => {
|
||||
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
|
||||
if (!feed || typeof feed !== 'object') {
|
||||
throw new Error('invalid group notice response: feed must be an object');
|
||||
}
|
||||
return {
|
||||
id: pic.id,
|
||||
url: groupNoticeImageUrl(pic.id),
|
||||
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
|
||||
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||
};
|
||||
});
|
||||
const responseType = feed.type === undefined
|
||||
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
|
||||
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
|
||||
|
||||
return {
|
||||
notice_id: feed.fid,
|
||||
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
|
||||
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
|
||||
message: {
|
||||
text: feed.msg.text,
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
|
||||
type: responseType,
|
||||
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
};
|
||||
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
|
||||
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
|
||||
}
|
||||
|
||||
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
|
||||
}
|
||||
|
||||
if (feed.settings === undefined) {
|
||||
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
|
||||
}
|
||||
|
||||
const image = (feed.msg.pics ?? []).map((pic, index) => {
|
||||
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
|
||||
throw new Error(
|
||||
`invalid group notice response: feed ${feed.fid} image ${index} is malformed`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
id: pic.id,
|
||||
url: groupNoticeImageUrl(pic.id),
|
||||
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
|
||||
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||
};
|
||||
});
|
||||
const responseType =
|
||||
feed.type === undefined
|
||||
? sendToNewMembers
|
||||
? GROUP_NOTICE_TYPE_NEW_MEMBERS
|
||||
: GROUP_NOTICE_TYPE_NORMAL
|
||||
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
|
||||
|
||||
return {
|
||||
notice_id: feed.fid,
|
||||
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
|
||||
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
|
||||
message: {
|
||||
text: feed.msg.text,
|
||||
image,
|
||||
images: image,
|
||||
},
|
||||
settings: feed.settings,
|
||||
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
|
||||
type: responseType,
|
||||
pinned:
|
||||
feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||
};
|
||||
}
|
||||
|
||||
/** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */
|
||||
export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] {
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
|
||||
}
|
||||
|
||||
const notices: WebNoticeInfo[] = [];
|
||||
const indexByNoticeId = new Map<string, number>();
|
||||
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
|
||||
for (const feed of collectionValues(collection, field)) {
|
||||
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
|
||||
const existingIndex = indexByNoticeId.get(mapped.notice_id);
|
||||
if (existingIndex === undefined) {
|
||||
indexByNoticeId.set(mapped.notice_id, notices.length);
|
||||
notices.push(mapped);
|
||||
} else if (sendToNewMembers) {
|
||||
// If QQ returns the same item in both collections, `inst` is the
|
||||
// authoritative signal that it targets new members.
|
||||
notices[existingIndex] = mapped;
|
||||
}
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
|
||||
}
|
||||
};
|
||||
|
||||
append(ret.feeds, false, 'feeds');
|
||||
append(ret.inst, true, 'inst');
|
||||
return notices;
|
||||
const notices: WebNoticeInfo[] = [];
|
||||
const indexByNoticeId = new Map<string, number>();
|
||||
|
||||
const append = (
|
||||
collection: WebApiGroupNoticeCollection | undefined,
|
||||
sendToNewMembers: boolean,
|
||||
field: 'feeds' | 'inst',
|
||||
) => {
|
||||
for (const feed of collectionValues(collection, field)) {
|
||||
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
|
||||
const existingIndex = indexByNoticeId.get(mapped.notice_id);
|
||||
|
||||
if (existingIndex === undefined) {
|
||||
indexByNoticeId.set(mapped.notice_id, notices.length);
|
||||
notices.push(mapped);
|
||||
} else if (sendToNewMembers) {
|
||||
// If QQ returns the same item in both collections, `inst` is the
|
||||
// authoritative signal that it targets new members.
|
||||
notices[existingIndex] = mapped;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
append(ret.feeds, false, 'feeds');
|
||||
append(ret.inst, true, 'inst');
|
||||
return notices;
|
||||
}
|
||||
|
||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||
|
||||
function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
return ForceFetchClientKey.invoke(bridge);
|
||||
}
|
||||
|
||||
function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
function getPSkey(
|
||||
bridge: Bridge,
|
||||
domainList: string[],
|
||||
): Promise<{ domainPskeyMap: Map<string, string> }> {
|
||||
return GetPskey.invoke(bridge, { domainList });
|
||||
}
|
||||
|
||||
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
|
||||
// Build the ptlogin2 jump URL: this is the canonical way for the
|
||||
// bot to swap its clientKey for cookie-jar entries on a given
|
||||
// qq.com subdomain.
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
|
||||
// Build the ptlogin2 jump URL: this is the canonical way for the
|
||||
// bot to swap its clientKey for cookie-jar entries on a given
|
||||
// qq.com subdomain.
|
||||
const requestUrl =
|
||||
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' +
|
||||
bridge.identity.uin +
|
||||
'&clientkey=' +
|
||||
ClientKeyData.clientKey +
|
||||
'&u1=https%3A%2F%2F' +
|
||||
domain +
|
||||
'%2F' +
|
||||
bridge.identity.uin +
|
||||
'%2Finfocenter&keyindex=' +
|
||||
ClientKeyData.keyIndex;
|
||||
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const data = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
|
||||
// for the same domain. Errors are swallowed so the caller can
|
||||
// still proceed with whatever cookies it did get.
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
if (!data['p_skey'] || data['p_skey'].length === 0) {
|
||||
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
|
||||
// for the same domain. Errors are swallowed so the caller can
|
||||
// still proceed with whatever cookies it did get.
|
||||
try {
|
||||
const pskeyData = await getPSkey(bridge, [domain]);
|
||||
const pskey = pskeyData.domainPskeyMap.get(domain);
|
||||
|
||||
if (pskey) {
|
||||
data['p_skey'] = pskey;
|
||||
}
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getSKey(bridge: Bridge): Promise<string> {
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
const ClientKeyData = await forceFetchClientKeyInner(bridge);
|
||||
|
||||
if (!ClientKeyData.clientKey) {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
if (!ClientKeyData.clientKey) {
|
||||
throw new Error('getClientKey Error: clientKey is empty');
|
||||
}
|
||||
|
||||
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' + bridge.identity.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey +
|
||||
'&u1=' + u1 +
|
||||
'&keyindex=' + ClientKeyData.keyIndex;
|
||||
const u1 = encodeURIComponent(
|
||||
'https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0',
|
||||
);
|
||||
const requestUrl =
|
||||
'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
|
||||
'&clientuin=' +
|
||||
bridge.identity.uin +
|
||||
'&clientkey=' +
|
||||
ClientKeyData.clientKey +
|
||||
'&u1=' +
|
||||
u1 +
|
||||
'&keyindex=' +
|
||||
ClientKeyData.keyIndex;
|
||||
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const skey = cookies['skey'];
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return skey;
|
||||
return skey;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,207 +290,213 @@ async function getSKey(bridge: Bridge): Promise<string> {
|
||||
* skey or p_skey. djb2 hash truncated to 31 bits.
|
||||
*/
|
||||
function getBknFromSKey(skey: string): number {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
return hash & 2147483647;
|
||||
let hash = 5381;
|
||||
|
||||
for (let i = 0; i < skey.length; i++) {
|
||||
hash += (hash << 5) + skey.charCodeAt(i);
|
||||
}
|
||||
|
||||
return hash & 2147483647;
|
||||
}
|
||||
|
||||
export class WebApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
constructor(private readonly ctx: BridgeContext) {}
|
||||
|
||||
// ─────────────── cookie / token primitives ───────────────
|
||||
// ─────────────── cookie / token primitives ───────────────
|
||||
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> {
|
||||
return forceFetchClientKeyInner(asBridge(this.ctx));
|
||||
}
|
||||
|
||||
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
|
||||
* (qzone.qq.com) and by every other web helper here. */
|
||||
async getCookies(domain: string): Promise<Record<string, string>> {
|
||||
return getCookies(asBridge(this.ctx), domain);
|
||||
}
|
||||
|
||||
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
|
||||
async getCookiesStr(domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(asBridge(this.ctx), domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
async getCsrfToken(): Promise<number> {
|
||||
const skey = await getSKey(asBridge(this.ctx));
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
|
||||
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
|
||||
const cookieObject = await getCookies(asBridge(this.ctx), domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
return {
|
||||
cookies: cookiesStr,
|
||||
token,
|
||||
csrf_token: token,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────── group essence ───────────────
|
||||
|
||||
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
|
||||
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
|
||||
}
|
||||
|
||||
/** Walks every page and returns the concatenated result. */
|
||||
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
}
|
||||
|
||||
// ─────────────── group honor ───────────────
|
||||
|
||||
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const honorInfo: WebHonorInfo = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
async forceFetchClientKey(): Promise<ClientKeyInfo> {
|
||||
return forceFetchClientKeyInner(asBridge(this.ctx));
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
|
||||
* (qzone.qq.com) and by every other web helper here. */
|
||||
async getCookies(domain: string): Promise<Record<string, string>> {
|
||||
return getCookies(asBridge(this.ctx), domain);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
|
||||
async getCookiesStr(domain: string): Promise<string> {
|
||||
const cookieObject = await getCookies(asBridge(this.ctx), domain);
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
|
||||
async getCsrfToken(): Promise<number> {
|
||||
const skey = await getSKey(asBridge(this.ctx));
|
||||
|
||||
if (!skey) {
|
||||
throw new Error('SKey is Empty');
|
||||
}
|
||||
|
||||
return getBknFromSKey(skey);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
|
||||
async getCredentials(
|
||||
domain: string,
|
||||
): Promise<{ cookies: string; token: number; csrf_token: number }> {
|
||||
const cookieObject = await getCookies(asBridge(this.ctx), domain);
|
||||
const cookiesStr = Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
|
||||
// ─────────────── group sign-in (打卡) ───────────────
|
||||
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
|
||||
const token = skey ? getBknFromSKey(skey) : 0;
|
||||
|
||||
/** Today's group sign-in list via qun.qq.com. [] when the group has no
|
||||
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
|
||||
async getSignedList(groupId: number): Promise<SignedListMember[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return getDaySignedListWebAPI(cookieObject, groupId.toString(), bridge.identity.uin.toString());
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: SendNoticeOptions,
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
return {
|
||||
cookies: cookiesStr,
|
||||
token,
|
||||
csrf_token: token,
|
||||
};
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(
|
||||
cookieObject,
|
||||
groupCode,
|
||||
content,
|
||||
{
|
||||
pinned: options?.pinned,
|
||||
type: options?.type,
|
||||
sendToNewMembers: options?.sendToNewMembers,
|
||||
isShowEditCard: options?.isShowEditCard,
|
||||
tipWindowType: options?.tipWindowType,
|
||||
confirmRequired: options?.confirmRequired,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
},
|
||||
);
|
||||
// ─────────────── group essence ───────────────
|
||||
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
|
||||
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
|
||||
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<GroupEssenceMsgRet> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
|
||||
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
/** Walks every page and returns the concatenated result. */
|
||||
async getEssenceAll(groupId: number): Promise<GroupEssenceMsgRet[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await getGroupEssenceMsgAll(cookieObject, groupCode);
|
||||
}
|
||||
|
||||
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
// ─────────────── group honor ───────────────
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
return mapGroupNoticeResponse(ret);
|
||||
}
|
||||
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<WebHonorInfo> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
|
||||
}
|
||||
const honorInfo: WebHonorInfo = {
|
||||
group_id: groupId,
|
||||
current_talkative: null,
|
||||
talkative_list: [],
|
||||
performer_list: [],
|
||||
legend_list: [],
|
||||
emotion_list: [],
|
||||
strong_newbie_list: [],
|
||||
};
|
||||
|
||||
// ─────────────── friend dress (好友装扮) ───────────────
|
||||
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
|
||||
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
|
||||
|
||||
/** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域,
|
||||
* 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/
|
||||
* 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */
|
||||
async getFriendDress(targetUin: number): Promise<WebFriendDress> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'vip.qq.com');
|
||||
return getFriendDressWebAPI(cookieObject, targetUin.toString());
|
||||
}
|
||||
if (talkativeList.length > 0) {
|
||||
honorInfo.current_talkative = talkativeList[0];
|
||||
honorInfo.talkative_list = talkativeList;
|
||||
}
|
||||
}
|
||||
|
||||
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
|
||||
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
|
||||
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
|
||||
}
|
||||
|
||||
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
|
||||
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
|
||||
}
|
||||
|
||||
return honorInfo;
|
||||
}
|
||||
|
||||
// ─────────────── group sign-in (打卡) ───────────────
|
||||
|
||||
/** Today's group sign-in list via qun.qq.com. [] when the group has no
|
||||
* sign-ins; THROWS on transport / auth failure (caller maps to failed). */
|
||||
async getSignedList(groupId: number): Promise<SignedListMember[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return getDaySignedListWebAPI(
|
||||
cookieObject,
|
||||
groupId.toString(),
|
||||
bridge.identity.uin.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── group notice ───────────────
|
||||
|
||||
async sendNotice(
|
||||
groupId: number,
|
||||
content: string,
|
||||
options?: SendNoticeOptions,
|
||||
): Promise<SetNoticeRetSuccess> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
let picId = '';
|
||||
let imgWidth = 540;
|
||||
let imgHeight = 300;
|
||||
|
||||
if (options?.image) {
|
||||
// Route through loadBinarySource so the group-notice image download
|
||||
// gets the same browser-UA + Referer-retry hardening as every other
|
||||
// media fetch — and http/file/base64 source handling for free.
|
||||
const loaded = await loadBinarySource(options.image, 'group-notice image');
|
||||
const imageBuffer = Buffer.from(loaded.bytes);
|
||||
|
||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||
picId = picInfo.id;
|
||||
imgWidth = picInfo.width;
|
||||
imgHeight = picInfo.height;
|
||||
}
|
||||
|
||||
const ret = await setGroupNoticeWebAPI(cookieObject, groupCode, content, {
|
||||
pinned: options?.pinned,
|
||||
type: options?.type,
|
||||
sendToNewMembers: options?.sendToNewMembers,
|
||||
isShowEditCard: options?.isShowEditCard,
|
||||
tipWindowType: options?.tipWindowType,
|
||||
confirmRequired: options?.confirmRequired,
|
||||
picId,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
});
|
||||
|
||||
if (ret.ec !== 0) {
|
||||
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
async getNotice(groupId: number): Promise<WebNoticeInfo[]> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
|
||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||
return mapGroupNoticeResponse(ret);
|
||||
}
|
||||
|
||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const groupCode = groupId.toString();
|
||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
|
||||
}
|
||||
|
||||
// ─────────────── friend dress (好友装扮) ───────────────
|
||||
|
||||
/** 查某人正在用的好友装扮(挂件/名片/来电/输入状态等)。走 vip.qq.com 域,
|
||||
* 纯 cookie 鉴权、抓 SSR HTML。「查到但没装扮」返回空 items;网络/未登录态/
|
||||
* 风控/页面改版/串号数据抛 FriendDressError(kind 区分具体环节)。 */
|
||||
async getFriendDress(targetUin: number): Promise<WebFriendDress> {
|
||||
const bridge = asBridge(this.ctx);
|
||||
const cookieObject = await getCookies(bridge, 'vip.qq.com');
|
||||
return getFriendDressWebAPI(cookieObject, targetUin.toString());
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import type { BridgeContext as BaseBridgeContext } from '@snowluma/protocol/brid
|
||||
import type { ApiHub } from './apis';
|
||||
|
||||
export interface BridgeContext extends BaseBridgeContext {
|
||||
readonly apis: ApiHub;
|
||||
readonly apis: ApiHub;
|
||||
}
|
||||
export type { UploadedFileMeta } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
@@ -2,18 +2,18 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
|
||||
import type { BridgeContext } from './bridge-context';
|
||||
|
||||
export interface RosterWarmupResult {
|
||||
friendsLoaded: boolean;
|
||||
groupsLoaded: boolean;
|
||||
friendsLoaded: boolean;
|
||||
groupsLoaded: boolean;
|
||||
}
|
||||
|
||||
export interface BridgeInterface extends BridgeContext {
|
||||
readonly activePid: number | null;
|
||||
/** Settles once for this Bridge session after first-login roster fetch. */
|
||||
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
|
||||
/** False only when every attached QQ process has a confirmed receive or
|
||||
* request-path failure. An unarmed watchdog remains true for compatibility. */
|
||||
readonly receiveHealthy: boolean;
|
||||
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
|
||||
* QQ has not emitted its cache notification since SnowLuma attached. */
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
|
||||
readonly activePid: number | null;
|
||||
/** Settles once for this Bridge session after first-login roster fetch. */
|
||||
whenRosterWarmupSettled(): Promise<RosterWarmupResult>;
|
||||
/** False only when every attached QQ process has a confirmed receive or
|
||||
* request-path failure. An unarmed watchdog remains true for compatibility. */
|
||||
readonly receiveHealthy: boolean;
|
||||
/** Latest device snapshot observed on this Bridge lifecycle. `null` means
|
||||
* QQ has not emitted its cache notification since SnowLuma attached. */
|
||||
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
|
||||
}
|
||||
+640
-484
File diff suppressed because it is too large.
Load diff
+357
-334
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { isRealUin } from '@snowluma/common/uin';
|
||||
@@ -13,7 +9,7 @@ export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
|
||||
export type SessionClosedCallback = (uin: string, bridge: Bridge) => void;
|
||||
|
||||
interface QQSession {
|
||||
bridge: Bridge;
|
||||
bridge: Bridge;
|
||||
}
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
@@ -21,366 +17,393 @@ const packetLog = createLogger('Bridge.Packet');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge now carries the bridge too, since callers read the last
|
||||
* nickname before it is disposed. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
}
|
||||
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-started listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
/** Additive subscription: every observer (OneBotManager, NotificationManager,
|
||||
* …) receives every session edge. (Was a single `set*Callback` setter —
|
||||
* converted to N listeners so a second observer can't clobber the first.)
|
||||
* The close edge now carries the bridge too, since callers read the last
|
||||
* nickname before it is disposed. */
|
||||
addSessionStartedListener(cb: SessionStartedCallback): void {
|
||||
this.sessionStartedListeners_.push(cb);
|
||||
}
|
||||
}
|
||||
|
||||
private fireSessionClosed(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn('session-closed listener threw: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
addSessionClosedListener(cb: SessionClosedCallback): void {
|
||||
this.sessionClosedListeners_.push(cb);
|
||||
}
|
||||
}
|
||||
|
||||
onPidDisconnected(pid: number): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_start pid=%d uin=%j',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
try {
|
||||
const closed = this.detachPidFromSession(pid, uin);
|
||||
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
|
||||
if (closed) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
private fireSessionStarted(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionStartedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'session-started listener threw: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
closed ? 'session_closed' : 'pid_detached',
|
||||
activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) {
|
||||
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session || !session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
private fireSessionClosed(uin: string, bridge: Bridge): void {
|
||||
for (const cb of this.sessionClosedListeners_) {
|
||||
try {
|
||||
cb(uin, bridge);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'session-closed listener threw: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
session.bridge.setPidReceiveHealthy(pid, healthy);
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!isRealUin(uin)) return;
|
||||
onPidDisconnected(pid: number): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const previousUin = this.pidToUin_.get(pid) ?? null;
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
if (!uin) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace('bridge_detach_start pid=%d uin=%j', pid, uin);
|
||||
|
||||
try {
|
||||
const closed = this.detachPidFromSession(pid, uin);
|
||||
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
|
||||
|
||||
if (closed) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
closed ? 'session_closed' : 'pid_detached',
|
||||
activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
|
||||
if (!uin) {
|
||||
const message = `BridgeManager invariant violated: receive health for unmapped PID=${pid}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
if (!session || !session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
session.bridge.setPidReceiveHealthy(pid, healthy);
|
||||
}
|
||||
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!isRealUin(uin)) {
|
||||
return;
|
||||
}
|
||||
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const previousUin = this.pidToUin_.get(pid) ?? null;
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
|
||||
try {
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
|
||||
if (previousUin && previousUin !== uin) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
const previousSession = this.sessions_.get(previousUin);
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousSession ? 'previous_session_retained' : 'previous_session_closed',
|
||||
previousUin,
|
||||
previousSession?.bridge.activePid ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
if (created) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=session_created',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
previousUin && previousUin !== uin ? 'rebound' : 'bound',
|
||||
created,
|
||||
session.bridge.activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
runWithTraceRequest(() => this.onPacketInContext(pkt));
|
||||
}
|
||||
|
||||
private onPacketInContext(pkt: PacketInfo): void {
|
||||
const startedAt = Date.now();
|
||||
packetLog.trace(() => [
|
||||
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
pkt.retCode,
|
||||
pkt.fromClient,
|
||||
pkt.pid,
|
||||
pkt.uin,
|
||||
pkt.body.byteLength,
|
||||
renderTraceBytes(pkt.body),
|
||||
]);
|
||||
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
const uin = pkt.uin;
|
||||
|
||||
let completion: Promise<void>;
|
||||
let handedToPipeline = false;
|
||||
|
||||
try {
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
// PID can never remain attached to two Bridges.
|
||||
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||
const { session, created } = client
|
||||
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||
: this.ensureSession(uin);
|
||||
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
|
||||
// dispatch; its promise only marks completion of any async enrichment.
|
||||
handedToPipeline = true;
|
||||
completion = session.bridge.onPacket(pkt);
|
||||
} catch (error) {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
handedToPipeline ? 'pipeline_failed' : 'routing_failed',
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
void completion.catch((error) => {
|
||||
this.tracePacketFailure(pkt, startedAt, 'pipeline_failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
private tracePacketFailure(
|
||||
pkt: PacketInfo,
|
||||
startedAt: number,
|
||||
reason: 'routing_failed' | 'pipeline_failed',
|
||||
error: unknown,
|
||||
): void {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
log.error(
|
||||
'packet %s failed for %s: %s',
|
||||
reason === 'routing_failed' ? 'routing' : 'pipeline',
|
||||
pkt.serviceCmd,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
/** Bind PID + sender as one state transition. If the PID changed accounts,
|
||||
* the old Bridge is fully detached (and, when empty, closed) before the new
|
||||
* Bridge is created. */
|
||||
private bindPid(
|
||||
pid: number,
|
||||
uin: string,
|
||||
packetClient: PacketSender,
|
||||
source: 'login' | 'packet',
|
||||
): { session: QQSession; created: boolean } {
|
||||
const previousUin = this.pidToUin_.get(pid);
|
||||
|
||||
try {
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
if (previousUin && previousUin !== uin) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
const previousSession = this.sessions_.get(previousUin);
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousSession ? 'previous_session_retained' : 'previous_session_closed',
|
||||
previousUin,
|
||||
previousSession?.bridge.activePid ?? null,
|
||||
);
|
||||
log.warn(
|
||||
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
|
||||
pid,
|
||||
previousUin,
|
||||
uin,
|
||||
source,
|
||||
);
|
||||
this.detachPidFromSession(pid, previousUin);
|
||||
}
|
||||
|
||||
if (created) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=session_created',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
const result = this.ensureSession(uin);
|
||||
result.session.bridge.bindPid(pid, packetClient);
|
||||
this.pidToUin_.set(pid, uin);
|
||||
return result;
|
||||
}
|
||||
|
||||
private packetClientForPid(pid: number): PacketSender | null {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
|
||||
if (!uin) {
|
||||
return null;
|
||||
}
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
previousUin && previousUin !== uin ? 'rebound' : 'bound',
|
||||
created,
|
||||
session.bridge.activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
runWithTraceRequest(() => this.onPacketInContext(pkt));
|
||||
}
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
private onPacketInContext(pkt: PacketInfo): void {
|
||||
const startedAt = Date.now();
|
||||
packetLog.trace(() => [
|
||||
'packet_push serviceCmd=%j seqId=%d retCode=%d fromClient=%s pid=%d uin=%j length=%d body=%s',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
pkt.retCode,
|
||||
pkt.fromClient,
|
||||
pkt.pid,
|
||||
pkt.uin,
|
||||
pkt.body.byteLength,
|
||||
renderTraceBytes(pkt.body),
|
||||
]);
|
||||
if (!pkt.uin || !isRealUin(pkt.uin)) {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=dropped reason=invalid_uin events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
const uin = pkt.uin;
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
let completion: Promise<void>;
|
||||
let handedToPipeline = false;
|
||||
try {
|
||||
// A packet may be the first trustworthy observation that a live PID moved
|
||||
// to another UIN. Apply the exact same ownership transition as login so a
|
||||
// PID can never remain attached to two Bridges.
|
||||
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||
const { session, created } = client
|
||||
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||
: this.ensureSession(uin);
|
||||
const packetClient = session.bridge.packetClientForPid(pid);
|
||||
|
||||
// Notify session started on first real packet
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
if (packetClient) {
|
||||
return packetClient;
|
||||
}
|
||||
|
||||
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
|
||||
// dispatch; its promise only marks completion of any async enrichment.
|
||||
handedToPipeline = true;
|
||||
completion = session.bridge.onPacket(pkt);
|
||||
} catch (error) {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
handedToPipeline
|
||||
? 'pipeline_failed'
|
||||
: 'routing_failed',
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
void completion.catch((error) => {
|
||||
this.tracePacketFailure(
|
||||
pkt,
|
||||
startedAt,
|
||||
'pipeline_failed',
|
||||
error,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private tracePacketFailure(
|
||||
pkt: PacketInfo,
|
||||
startedAt: number,
|
||||
reason: 'routing_failed' | 'pipeline_failed',
|
||||
error: unknown,
|
||||
): void {
|
||||
packetLog.trace(() => [
|
||||
'packet_terminal serviceCmd=%j seqId=%d outcome=failed reason=%s error=%j events=0 dispatched=0 elapsedMs=%d',
|
||||
pkt.serviceCmd,
|
||||
pkt.seqId,
|
||||
reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
log.error(
|
||||
'packet %s failed for %s: %s',
|
||||
reason === 'routing_failed'
|
||||
? 'routing'
|
||||
: 'pipeline',
|
||||
pkt.serviceCmd,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
/** Bind PID + sender as one state transition. If the PID changed accounts,
|
||||
* the old Bridge is fully detached (and, when empty, closed) before the new
|
||||
* Bridge is created. */
|
||||
private bindPid(
|
||||
pid: number,
|
||||
uin: string,
|
||||
packetClient: PacketSender,
|
||||
source: 'login' | 'packet',
|
||||
): { session: QQSession; created: boolean } {
|
||||
const previousUin = this.pidToUin_.get(pid);
|
||||
if (previousUin && previousUin !== uin) {
|
||||
log.warn(
|
||||
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
|
||||
pid,
|
||||
previousUin,
|
||||
uin,
|
||||
source,
|
||||
);
|
||||
this.detachPidFromSession(pid, previousUin);
|
||||
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const result = this.ensureSession(uin);
|
||||
result.session.bridge.bindPid(pid, packetClient);
|
||||
this.pidToUin_.set(pid, uin);
|
||||
return result;
|
||||
}
|
||||
private detachPidFromSession(pid: number, uin: string): boolean {
|
||||
const mappedUin = this.pidToUin_.get(pid);
|
||||
|
||||
private packetClientForPid(pid: number): PacketSender | null {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return null;
|
||||
if (mappedUin !== uin) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
const session = this.sessions_.get(uin);
|
||||
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
if (!session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
if (!session.bridge.packetClientForPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
// Validation is complete. Mutate both sides only after the ownership
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
session.bridge.detachPid(pid);
|
||||
|
||||
if (!session.bridge.empty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
return true;
|
||||
}
|
||||
|
||||
const packetClient = session.bridge.packetClientForPid(pid);
|
||||
if (packetClient) return packetClient;
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
let session = this.sessions_.get(uin);
|
||||
|
||||
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (session) {
|
||||
return { session, created: false };
|
||||
}
|
||||
|
||||
private detachPidFromSession(pid: number, uin: string): boolean {
|
||||
const mappedUin = this.pidToUin_.get(pid);
|
||||
if (mappedUin !== uin) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
// `bridge.events` directly via the per-kind bus — there is no longer a
|
||||
// generic firehose to wire here.
|
||||
return { session, created: true };
|
||||
}
|
||||
|
||||
const session = this.sessions_.get(uin);
|
||||
if (!session) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
getSession(uin: string): QQSession | null {
|
||||
return this.sessions_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
if (!session.bridge.hasPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
get sessions(): Map<string, { bridge: Bridge }> {
|
||||
return this.sessions_;
|
||||
}
|
||||
if (!session.bridge.packetClientForPid(pid)) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
|
||||
log.error(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
// Validation is complete. Mutate both sides only after the ownership
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
session.bridge.detachPid(pid);
|
||||
if (!session.bridge.empty) return false;
|
||||
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
return true;
|
||||
}
|
||||
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
let session = this.sessions_.get(uin);
|
||||
if (session) return { session, created: false };
|
||||
|
||||
const bridge = new Bridge(IdentityService.openForUin(uin));
|
||||
session = { bridge };
|
||||
this.sessions_.set(uin, session);
|
||||
|
||||
// Each downstream consumer (e.g. OneBotInstance) subscribes to
|
||||
// `bridge.events` directly via the per-kind bus — there is no longer a
|
||||
// generic firehose to wire here.
|
||||
return { session, created: true };
|
||||
}
|
||||
|
||||
getSession(uin: string): QQSession | null {
|
||||
return this.sessions_.get(uin) ?? null;
|
||||
}
|
||||
|
||||
get sessions(): Map<string, { bridge: Bridge }> {
|
||||
return this.sessions_;
|
||||
}
|
||||
}
|
||||
+197
-139
@@ -2,17 +2,17 @@ import { HookManager } from '@snowluma/bridge';
|
||||
import { configureFileTransport } from '@snowluma/common/log-file-transport';
|
||||
import { closeLogger, createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
DEFAULT_LOG_PER_UIN,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
loadRuntimeConfig,
|
||||
DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
DEFAULT_LOG_PER_UIN,
|
||||
DEFAULT_LOG_RETAIN_DAYS,
|
||||
loadRuntimeConfig,
|
||||
} from '@snowluma/common/runtime';
|
||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
|
||||
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
|
||||
import {
|
||||
isMessageStoreMigrationWorkerData,
|
||||
runMessageStoreMigrationWorker,
|
||||
isMessageStoreMigrationWorkerData,
|
||||
runMessageStoreMigrationWorker,
|
||||
} from '@snowluma/onebot/message-store-migration-worker';
|
||||
import { workerData } from 'node:worker_threads';
|
||||
import { BridgeManager } from './bridge/manager';
|
||||
@@ -24,155 +24,213 @@ import { readAppVersion, startNativeStageSync, tempStagePath } from './native-st
|
||||
const log = createLogger('App');
|
||||
|
||||
function installProcessGuards(): void {
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
// can drop at any moment, and a stray rejection on a detached callback (or a
|
||||
// throw that escapes one) must NOT take the whole process down — otherwise
|
||||
// Docker restarts it (dropping every session) and a bare Windows run just dies
|
||||
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
|
||||
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error('unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason));
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
});
|
||||
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
|
||||
// can drop at any moment, and a stray rejection on a detached callback (or a
|
||||
// throw that escapes one) must NOT take the whole process down — otherwise
|
||||
// Docker restarts it (dropping every session) and a bare Windows run just dies
|
||||
// ("connection pipe closed", bot offline). Log and keep serving; the bridge's
|
||||
// own watcher reconnects the dropped pipe. Targeted handlers still cover the
|
||||
// known paths (e.g. the hook-client send deferreds) — these only catch what
|
||||
// slips through, and surface its stack so the real source can be fixed.
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
log.error(
|
||||
'unhandledRejection (kept alive): %s',
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason),
|
||||
);
|
||||
});
|
||||
process.on('uncaughtException', (error) => {
|
||||
log.error('uncaughtException (kept alive): %s', error.stack ?? error.message);
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
await configureFileTransport({
|
||||
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
|
||||
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
|
||||
});
|
||||
log.info('SnowLuma starting');
|
||||
const stopNativeStageSync = startNativeStageSync({
|
||||
version: readAppVersion(import.meta.url),
|
||||
dataDir: 'data',
|
||||
tempPath: tempStagePath(),
|
||||
});
|
||||
const runtimeConfig = loadRuntimeConfig();
|
||||
await configureFileTransport({
|
||||
maxTotalMb: runtimeConfig.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
|
||||
retainDays: runtimeConfig.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
|
||||
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
|
||||
});
|
||||
log.info('SnowLuma starting');
|
||||
const stopNativeStageSync = startNativeStageSync({
|
||||
version: readAppVersion(import.meta.url),
|
||||
dataDir: 'data',
|
||||
tempPath: tempStagePath(),
|
||||
});
|
||||
|
||||
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
|
||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||
migrateGlobalSettings();
|
||||
// One-shot: lift a legacy per-UIN musicSignUrl into the global store before
|
||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||
migrateGlobalSettings();
|
||||
|
||||
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
|
||||
// native hook may have created with a timestamp-shaped UIN (issue #162).
|
||||
cleanupInvalidPerUinConfigs();
|
||||
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
|
||||
// native hook may have created with a timestamp-shaped UIN (issue #162).
|
||||
cleanupInvalidPerUinConfigs();
|
||||
|
||||
const bridgeManager = new BridgeManager();
|
||||
bindSystemFaceCatalog(bridgeManager);
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const bridgeManager = new BridgeManager();
|
||||
bindSystemFaceCatalog(bridgeManager);
|
||||
const oneBotManager = new OneBotManager();
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
|
||||
// WebUI state-push wiring: HookManager + BridgeManager edges publish
|
||||
// `processes` / `qq-list` / `connections` invalidations into a bus the
|
||||
// /api/state/stream SSE handler subscribes to (no REST polling required).
|
||||
const stateWiring = createStateWiring();
|
||||
const hookManager = new HookManager({
|
||||
bridgeManager,
|
||||
autoLoadOnDiscovery,
|
||||
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||
});
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
// WebUI state-push wiring: HookManager + BridgeManager edges publish
|
||||
// `processes` / `qq-list` / `connections` invalidations into a bus the
|
||||
// /api/state/stream SSE handler subscribes to (no REST polling required).
|
||||
const stateWiring = createStateWiring();
|
||||
const hookManager = new HookManager({
|
||||
bridgeManager,
|
||||
autoLoadOnDiscovery,
|
||||
onSessionsChanged: stateWiring.onSessionsChanged,
|
||||
});
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
stateWiring.bindBridgeManager(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
let stopWebUI: (() => Promise<void>) | undefined;
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
const started = await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
});
|
||||
stopWebUI = started.stop;
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
let shutdownStarted = false;
|
||||
const shutdown = (signal: string) => async () => {
|
||||
if (shutdownStarted) return;
|
||||
shutdownStarted = true;
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
let exitCode = 0;
|
||||
try {
|
||||
await oneBotManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
oneBotManager.bind(bridgeManager);
|
||||
stateWiring.bindBridgeManager(bridgeManager);
|
||||
|
||||
// Global notification subsystem (account up/down → webhook). Bound AFTER
|
||||
// OneBotManager so the nickname fallback is already populated when it observes.
|
||||
const notificationManager = createNotificationManager();
|
||||
notificationManager.bind(bridgeManager);
|
||||
|
||||
let stopWebUI: (() => Promise<void>) | undefined;
|
||||
|
||||
if (
|
||||
(typeof __BUILD_WEBUI__ !== 'undefined' && __BUILD_WEBUI__) ||
|
||||
process.env.SNOWLUMA_DEV_WEBUI === '1'
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
const started = await initWebUI(
|
||||
runtimeConfig.webuiPort || 5099,
|
||||
oneBotManager,
|
||||
hookManager,
|
||||
notificationManager,
|
||||
{
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
stateBus: stateWiring.bus,
|
||||
},
|
||||
);
|
||||
stopWebUI = started.stop;
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
}
|
||||
try { notificationManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try {
|
||||
if (stopWebUI) await stopWebUI();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('WebUI shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
// Observers go deaf before Hook teardown. Hook dispose then emits the
|
||||
// same disconnected → PID detach → Bridge closed path as a live drop;
|
||||
// those closed edges must not look like a runtime offline.
|
||||
try { stateWiring.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
try { stopNativeStageSync.stop(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('stage sync shutdown failed: %s', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
try { hookManager.dispose(); } catch (error) {
|
||||
exitCode = 1;
|
||||
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
}
|
||||
await closeLogger();
|
||||
process.exit(exitCode);
|
||||
};
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
|
||||
// Graceful shutdown: dispose managers, await log flush, then exit.
|
||||
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
|
||||
let shutdownStarted = false;
|
||||
|
||||
const shutdown = (signal: string) => async () => {
|
||||
if (shutdownStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
shutdownStarted = true;
|
||||
log.warn(`Shutting down (${signal})...`);
|
||||
let exitCode = 0;
|
||||
|
||||
try {
|
||||
await oneBotManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'OneBot shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
notificationManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'notification shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
if (stopWebUI) {
|
||||
await stopWebUI();
|
||||
}
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'WebUI shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
// Observers go deaf before Hook teardown. Hook dispose then emits the
|
||||
// same disconnected → PID detach → Bridge closed path as a live drop;
|
||||
// those closed edges must not look like a runtime offline.
|
||||
try {
|
||||
stateWiring.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'state wiring shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
stopNativeStageSync.stop();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'stage sync shutdown failed: %s',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
hookManager.dispose();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
log.error(
|
||||
'hook shutdown failed: %s',
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
await closeLogger();
|
||||
process.exit(exitCode);
|
||||
};
|
||||
|
||||
process.on('SIGINT', shutdown('SIGINT'));
|
||||
process.on('SIGTERM', shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
|
||||
if (typeof envRaw === 'string' && envRaw.trim()) {
|
||||
const v = envRaw.trim().toLowerCase();
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
|
||||
}
|
||||
return fromConfig === true;
|
||||
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
|
||||
|
||||
if (typeof envRaw === 'string' && envRaw.trim()) {
|
||||
const v = envRaw.trim().toLowerCase();
|
||||
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
if (isMessageStoreMigrationWorkerData(workerData)) {
|
||||
runMessageStoreMigrationWorker(workerData).catch(() => {
|
||||
process.exitCode = 1;
|
||||
});
|
||||
runMessageStoreMigrationWorker(workerData).catch(() => {
|
||||
process.exitCode = 1;
|
||||
});
|
||||
} else {
|
||||
installProcessGuards();
|
||||
main().catch(async (error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
await closeLogger();
|
||||
process.exit(1);
|
||||
});
|
||||
installProcessGuards();
|
||||
main().catch(async (error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
await closeLogger();
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync, statSync, openSync, readSync, closeSync, fstatSync } from 'node:fs';
|
||||
import {
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
mkdirSync,
|
||||
statSync,
|
||||
openSync,
|
||||
readSync,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
} from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
@@ -9,260 +18,349 @@ export const MIRROR_LIMIT_BYTES = 1024 * 1024;
|
||||
const VERSION_HEADER = /^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
|
||||
|
||||
export function isVersionHeader(line: string): boolean {
|
||||
return VERSION_HEADER.test(line);
|
||||
return VERSION_HEADER.test(line);
|
||||
}
|
||||
|
||||
export function lineSeverity(line: string): 'info' | 'error' {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
|
||||
const parts = line.trim().split(/\s+/);
|
||||
return parts.length >= 4 && parts[3] === '1' ? 'error' : 'info';
|
||||
}
|
||||
|
||||
export function publicLine(version: string, raw: string): string {
|
||||
return `${version} ${raw.trim()}`;
|
||||
return `${version} ${raw.trim()}`;
|
||||
}
|
||||
|
||||
function byteSize(lines: readonly string[]): number {
|
||||
if (lines.length === 0) return 0;
|
||||
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
|
||||
if (lines.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Buffer.byteLength(`${lines.join('\n')}\n`, 'utf8');
|
||||
}
|
||||
|
||||
export function trimMirror(text: string, limit = MIRROR_LIMIT_BYTES): string {
|
||||
const lines = text.split('\n').filter((line) => line.length > 0);
|
||||
const size = () => byteSize(lines);
|
||||
while (lines.length > 0 && size() > limit) {
|
||||
const body = lines.findIndex((line) => !isVersionHeader(line));
|
||||
if (body >= 0) {
|
||||
lines.splice(body, 1);
|
||||
continue;
|
||||
const lines = text.split('\n').filter((line) => line.length > 0);
|
||||
const size = () => byteSize(lines);
|
||||
|
||||
while (lines.length > 0 && size() > limit) {
|
||||
const body = lines.findIndex((line) => !isVersionHeader(line));
|
||||
|
||||
if (body >= 0) {
|
||||
lines.splice(body, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length <= 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
lines.shift();
|
||||
}
|
||||
if (lines.length <= 1) break;
|
||||
lines.shift();
|
||||
}
|
||||
if (lines.length === 0) return '';
|
||||
return `${lines.join('\n')}\n`;
|
||||
|
||||
if (lines.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export function appendEvents(
|
||||
mirror: string,
|
||||
version: string,
|
||||
events: readonly string[],
|
||||
limit = MIRROR_LIMIT_BYTES,
|
||||
mirror: string,
|
||||
version: string,
|
||||
events: readonly string[],
|
||||
limit = MIRROR_LIMIT_BYTES,
|
||||
): string {
|
||||
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
if (fresh.length === 0) return mirror;
|
||||
const header = `v${version}`;
|
||||
const lines = mirror.split('\n').filter((line) => line.length > 0);
|
||||
let lastHeader = '';
|
||||
for (const line of lines) {
|
||||
if (isVersionHeader(line)) lastHeader = line;
|
||||
}
|
||||
const next = [...lines];
|
||||
if (lastHeader !== header) next.push(header);
|
||||
next.push(...fresh);
|
||||
return trimMirror(`${next.join('\n')}\n`, limit);
|
||||
const fresh = events.map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
|
||||
if (fresh.length === 0) {
|
||||
return mirror;
|
||||
}
|
||||
|
||||
const header = `v${version}`;
|
||||
const lines = mirror.split('\n').filter((line) => line.length > 0);
|
||||
let lastHeader = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (isVersionHeader(line)) {
|
||||
lastHeader = line;
|
||||
}
|
||||
}
|
||||
|
||||
const next = [...lines];
|
||||
|
||||
if (lastHeader !== header) {
|
||||
next.push(header);
|
||||
}
|
||||
|
||||
next.push(...fresh);
|
||||
return trimMirror(`${next.join('\n')}\n`, limit);
|
||||
}
|
||||
|
||||
export function tempStagePath(
|
||||
platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): string {
|
||||
if (platform === 'win32') {
|
||||
const base = env.TMP || env.TEMP || os.tmpdir();
|
||||
return path.join(base, STAGE_FILE_NAME);
|
||||
}
|
||||
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
|
||||
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
|
||||
if (platform === 'win32') {
|
||||
const base = env.TMP || env.TEMP || os.tmpdir();
|
||||
return path.join(base, STAGE_FILE_NAME);
|
||||
}
|
||||
|
||||
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
|
||||
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
|
||||
}
|
||||
|
||||
export function readAppVersion(moduleUrl: string | URL = import.meta.url): string {
|
||||
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) return __APP_VERSION__;
|
||||
try {
|
||||
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
|
||||
const version = JSON.parse(raw).version;
|
||||
if (typeof version === 'string' && version.trim()) return version.trim();
|
||||
} catch {
|
||||
// Built layouts that do not sit next to a package manifest keep the fallback.
|
||||
}
|
||||
return '0.0.0';
|
||||
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) {
|
||||
return __APP_VERSION__;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
|
||||
const version = JSON.parse(raw).version;
|
||||
|
||||
if (typeof version === 'string' && version.trim()) {
|
||||
return version.trim();
|
||||
}
|
||||
} catch {
|
||||
// Built layouts that do not sit next to a package manifest keep the fallback.
|
||||
}
|
||||
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
export function errorCode(error: unknown): string {
|
||||
if (error && typeof error === 'object' && 'code' in error) {
|
||||
const code = (error as { code?: unknown }).code;
|
||||
if (typeof code === 'string' && code) return code;
|
||||
}
|
||||
return 'ERR';
|
||||
if (error && typeof error === 'object' && 'code' in error) {
|
||||
const code = (error as { code?: unknown }).code;
|
||||
|
||||
if (typeof code === 'string' && code) {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
return 'ERR';
|
||||
}
|
||||
|
||||
export interface StageSyncOptions {
|
||||
version: string;
|
||||
dataDir: string;
|
||||
tempPath: string;
|
||||
log?: Logger;
|
||||
intervalMs?: number;
|
||||
version: string;
|
||||
dataDir: string;
|
||||
tempPath: string;
|
||||
log?: Logger;
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
interface IngestResult {
|
||||
mirror: string;
|
||||
offset: number;
|
||||
lines: string[];
|
||||
missing: boolean;
|
||||
errorCode?: string;
|
||||
mirror: string;
|
||||
offset: number;
|
||||
lines: string[];
|
||||
missing: boolean;
|
||||
errorCode?: string;
|
||||
}
|
||||
|
||||
export function ingestTemp(args: {
|
||||
tempText: string;
|
||||
offset: number;
|
||||
mirror: string;
|
||||
version: string;
|
||||
missing?: boolean;
|
||||
errorCode?: string;
|
||||
tempText: string;
|
||||
offset: number;
|
||||
mirror: string;
|
||||
version: string;
|
||||
missing?: boolean;
|
||||
errorCode?: string;
|
||||
}): IngestResult {
|
||||
if (args.missing) {
|
||||
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
|
||||
}
|
||||
if (args.errorCode) {
|
||||
if (args.missing) {
|
||||
return { mirror: args.mirror, offset: args.offset, lines: [], missing: true };
|
||||
}
|
||||
|
||||
if (args.errorCode) {
|
||||
return {
|
||||
mirror: args.mirror,
|
||||
offset: args.offset,
|
||||
lines: [],
|
||||
missing: false,
|
||||
errorCode: args.errorCode,
|
||||
};
|
||||
}
|
||||
|
||||
const start = args.offset > args.tempText.length ? 0 : args.offset;
|
||||
const chunk = args.tempText.slice(start);
|
||||
const newline = chunk.lastIndexOf('\n');
|
||||
|
||||
if (newline < 0) {
|
||||
return { mirror: args.mirror, offset: start, lines: [], missing: false };
|
||||
}
|
||||
|
||||
const complete = chunk.slice(0, newline + 1);
|
||||
const lines = complete
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
return {
|
||||
mirror: args.mirror,
|
||||
offset: args.offset,
|
||||
lines: [],
|
||||
missing: false,
|
||||
errorCode: args.errorCode,
|
||||
mirror: appendEvents(args.mirror, args.version, lines),
|
||||
offset: start + newline + 1,
|
||||
lines,
|
||||
missing: false,
|
||||
};
|
||||
}
|
||||
const start = args.offset > args.tempText.length ? 0 : args.offset;
|
||||
const chunk = args.tempText.slice(start);
|
||||
const newline = chunk.lastIndexOf('\n');
|
||||
if (newline < 0) {
|
||||
return { mirror: args.mirror, offset: start, lines: [], missing: false };
|
||||
}
|
||||
const complete = chunk.slice(0, newline + 1);
|
||||
const lines = complete.split('\n').map((line) => line.trim()).filter((line) => line.length > 0);
|
||||
return {
|
||||
mirror: appendEvents(args.mirror, args.version, lines),
|
||||
offset: start + newline + 1,
|
||||
lines,
|
||||
missing: false,
|
||||
};
|
||||
}
|
||||
|
||||
function readOffset(file: string): number {
|
||||
try {
|
||||
const raw = readFileSync(file, 'utf8').trim();
|
||||
const value = Number(raw);
|
||||
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
const raw = readFileSync(file, 'utf8').trim();
|
||||
const value = Number(raw);
|
||||
return Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function readTemp(file: string): { text: string; missing: boolean; errorCode?: string } {
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
fd = openSync(file, 'r');
|
||||
const info = fstatSync(fd);
|
||||
const size = info.size;
|
||||
if (size > 8 * 1024 * 1024) {
|
||||
return { text: '', missing: false, errorCode: 'E2BIG' };
|
||||
let fd: number | undefined;
|
||||
|
||||
try {
|
||||
fd = openSync(file, 'r');
|
||||
const info = fstatSync(fd);
|
||||
const size = info.size;
|
||||
|
||||
if (size > 8 * 1024 * 1024) {
|
||||
return { text: '', missing: false, errorCode: 'E2BIG' };
|
||||
}
|
||||
|
||||
const buf = Buffer.alloc(size);
|
||||
let got = 0;
|
||||
|
||||
while (got < size) {
|
||||
const n = readSync(fd, buf, got, size - got, got);
|
||||
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
got += n;
|
||||
}
|
||||
|
||||
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return { text: '', missing: true };
|
||||
}
|
||||
|
||||
return { text: '', missing: false, errorCode: code };
|
||||
} finally {
|
||||
if (fd !== undefined) {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
const buf = Buffer.alloc(size);
|
||||
let got = 0;
|
||||
while (got < size) {
|
||||
const n = readSync(fd, buf, got, size - got, got);
|
||||
if (n <= 0) break;
|
||||
got += n;
|
||||
}
|
||||
return { text: buf.subarray(0, got).toString('utf8'), missing: false };
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
if (code === 'ENOENT') return { text: '', missing: true };
|
||||
return { text: '', missing: false, errorCode: code };
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
export function startNativeStageSync(options: StageSyncOptions): { stop: () => void } {
|
||||
const log = options.log ?? createLogger('native');
|
||||
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
|
||||
const offsetPath = path.join(options.dataDir, 's7.off');
|
||||
let offset = readOffset(offsetPath);
|
||||
let failed = false;
|
||||
let stopped = false;
|
||||
const log = options.log ?? createLogger('native');
|
||||
const mirrorPath = path.join(options.dataDir, STAGE_FILE_NAME);
|
||||
const offsetPath = path.join(options.dataDir, 's7.off');
|
||||
let offset = readOffset(offsetPath);
|
||||
let failed = false;
|
||||
let stopped = false;
|
||||
|
||||
const tick = () => {
|
||||
if (stopped) return;
|
||||
let tempSize = 0;
|
||||
try {
|
||||
tempSize = statSync(options.tempPath).size;
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
if (code === 'ENOENT') return;
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', code);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (tempSize < offset) offset = 0;
|
||||
const temp = readTemp(options.tempPath);
|
||||
if (temp.missing) return;
|
||||
if (temp.errorCode) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', temp.errorCode);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mirror = '';
|
||||
try {
|
||||
mirror = readFileSync(mirrorPath, 'utf8');
|
||||
} catch (error) {
|
||||
if (errorCode(error) !== 'ENOENT') {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
const tick = () => {
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
const ingested = ingestTemp({
|
||||
tempText: temp.text,
|
||||
offset,
|
||||
mirror,
|
||||
version: options.version,
|
||||
});
|
||||
if (ingested.lines.length === 0 && ingested.offset === offset) {
|
||||
failed = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
mkdirSync(options.dataDir, { recursive: true });
|
||||
writeFileSync(mirrorPath, ingested.mirror);
|
||||
writeFileSync(offsetPath, `${ingested.offset}\n`);
|
||||
offset = ingested.offset;
|
||||
failed = false;
|
||||
} catch (error) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const line of ingested.lines) {
|
||||
const text = publicLine(options.version, line);
|
||||
if (lineSeverity(line) === 'error') log.error('%s', text);
|
||||
else log.info('%s', text);
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const timer = setInterval(tick, options.intervalMs ?? 500);
|
||||
timer.unref?.();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
let tempSize = 0;
|
||||
|
||||
try {
|
||||
tempSize = statSync(options.tempPath).size;
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
|
||||
if (code === 'ENOENT') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', code);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (tempSize < offset) {
|
||||
offset = 0;
|
||||
}
|
||||
|
||||
const temp = readTemp(options.tempPath);
|
||||
|
||||
if (temp.missing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (temp.errorCode) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', temp.errorCode);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let mirror = '';
|
||||
|
||||
try {
|
||||
mirror = readFileSync(mirrorPath, 'utf8');
|
||||
} catch (error) {
|
||||
if (errorCode(error) !== 'ENOENT') {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const ingested = ingestTemp({
|
||||
tempText: temp.text,
|
||||
offset,
|
||||
mirror,
|
||||
version: options.version,
|
||||
});
|
||||
|
||||
if (ingested.lines.length === 0 && ingested.offset === offset) {
|
||||
failed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(options.dataDir, { recursive: true });
|
||||
writeFileSync(mirrorPath, ingested.mirror);
|
||||
writeFileSync(offsetPath, `${ingested.offset}\n`);
|
||||
offset = ingested.offset;
|
||||
failed = false;
|
||||
} catch (error) {
|
||||
if (!failed) {
|
||||
failed = true;
|
||||
log.error('sync failed %s', errorCode(error));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
for (const line of ingested.lines) {
|
||||
const text = publicLine(options.version, line);
|
||||
|
||||
if (lineSeverity(line) === 'error') {
|
||||
log.error('%s', text);
|
||||
} else {
|
||||
log.info('%s', text);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const timer = setInterval(tick, options.intervalMs ?? 500);
|
||||
timer.unref?.();
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -43,40 +43,40 @@ export type NotificationEvent = 'offline' | 'online';
|
||||
export type NotificationChannelType = 'webhook' | 'email';
|
||||
|
||||
export interface NotificationChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
type: NotificationChannelType;
|
||||
/** http(s) webhook target. Empty on email channels. */
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
/** Extra outbound request headers (Authorization, etc.). Webhook only. */
|
||||
headers?: Record<string, string>;
|
||||
smtpHost?: string;
|
||||
smtpPort?: number;
|
||||
smtpSecure?: boolean;
|
||||
smtpUser?: string;
|
||||
smtpPass?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
subjectTemplate?: string;
|
||||
id: string;
|
||||
name: string;
|
||||
type: NotificationChannelType;
|
||||
/** http(s) webhook target. Empty on email channels. */
|
||||
url: string;
|
||||
bodyTemplate: string;
|
||||
enabled: boolean;
|
||||
/** Extra outbound request headers (Authorization, etc.). Webhook only. */
|
||||
headers?: Record<string, string>;
|
||||
smtpHost?: string;
|
||||
smtpPort?: number;
|
||||
smtpSecure?: boolean;
|
||||
smtpUser?: string;
|
||||
smtpPass?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
subjectTemplate?: string;
|
||||
}
|
||||
|
||||
export function isEmailChannel(ch: NotificationChannel): ch is NotificationChannel & {
|
||||
smtpHost: string;
|
||||
smtpPort: number;
|
||||
smtpSecure: boolean;
|
||||
from: string;
|
||||
to: string;
|
||||
subjectTemplate: string;
|
||||
smtpHost: string;
|
||||
smtpPort: number;
|
||||
smtpSecure: boolean;
|
||||
from: string;
|
||||
to: string;
|
||||
subjectTemplate: string;
|
||||
} {
|
||||
return ch.type === 'email';
|
||||
return ch.type === 'email';
|
||||
}
|
||||
|
||||
export interface NotificationsConfig {
|
||||
version: typeof NOTIFICATIONS_CONFIG_VERSION;
|
||||
debounceSeconds: number;
|
||||
channels: NotificationChannel[];
|
||||
version: typeof NOTIFICATIONS_CONFIG_VERSION;
|
||||
debounceSeconds: number;
|
||||
channels: NotificationChannel[];
|
||||
}
|
||||
|
||||
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
|
||||
@@ -105,11 +105,11 @@ const SMTP_PORT_MIN = 1;
|
||||
const SMTP_PORT_MAX = 65535;
|
||||
|
||||
export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: DEFAULT_DEBOUNCE_SECONDS,
|
||||
channels: [],
|
||||
};
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: DEFAULT_DEBOUNCE_SECONDS,
|
||||
channels: [],
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Template renderer ──────────────────────────────────────────────────────
|
||||
@@ -125,19 +125,27 @@ export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
* become `\\` and double-quotes become `\"`.
|
||||
*/
|
||||
export function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
if (typeof template !== 'string') return '';
|
||||
let isJson = false;
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) return match;
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
if (typeof template !== 'string') {
|
||||
return '';
|
||||
}
|
||||
|
||||
let isJson = false;
|
||||
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) {
|
||||
return match;
|
||||
}
|
||||
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Normalization helpers ──────────────────────────────────────────────────
|
||||
@@ -145,235 +153,351 @@ export function renderTemplate(template: string, vars: Record<string, string>):
|
||||
// notifications-only (string truncation to maxLen), so it stays here.
|
||||
|
||||
function strOr(value: unknown, fallback: string, maxLen: number): string {
|
||||
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
|
||||
return typeof value === 'string' ? value.slice(0, maxLen) : fallback;
|
||||
}
|
||||
|
||||
function normalizeChannelId(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) return null;
|
||||
if (!CHANNEL_ID_RE.test(v)) return null;
|
||||
return v;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim();
|
||||
|
||||
if (v.length === 0 || v.length > CHANNEL_ID_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CHANNEL_ID_RE.test(v)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
function isHttpUrl(value: string): boolean {
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHeaders(value: unknown): Record<string, string> | undefined {
|
||||
if (!isObject(value)) return undefined;
|
||||
const out: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const [rawName, rawValue] of Object.entries(value)) {
|
||||
if (Object.keys(out).length >= HEADERS_MAX) break;
|
||||
if (typeof rawValue !== 'string') continue;
|
||||
const name = rawName.trim();
|
||||
if (name.length === 0 || name.length > HEADER_NAME_MAX) continue;
|
||||
if (!HEADER_NAME_RE.test(name)) continue;
|
||||
const folded = name.toLowerCase();
|
||||
if (seen.has(folded)) continue;
|
||||
const headerValue = rawValue.trim();
|
||||
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) continue;
|
||||
if (headerValue.includes('\r') || headerValue.includes('\n')) continue;
|
||||
seen.add(folded);
|
||||
out[name] = headerValue;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
if (!isObject(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const out: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const [rawName, rawValue] of Object.entries(value)) {
|
||||
if (Object.keys(out).length >= HEADERS_MAX) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (typeof rawValue !== 'string') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = rawName.trim();
|
||||
|
||||
if (name.length === 0 || name.length > HEADER_NAME_MAX) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!HEADER_NAME_RE.test(name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const folded = name.toLowerCase();
|
||||
|
||||
if (seen.has(folded)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const headerValue = rawValue.trim();
|
||||
|
||||
if (headerValue.length === 0 || headerValue.length > HEADER_VALUE_MAX) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (headerValue.includes('\r') || headerValue.includes('\n')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(folded);
|
||||
out[name] = headerValue;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
|
||||
function normalizeSmtpHost(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim();
|
||||
if (!v || v.length > SMTP_HOST_MAX) return null;
|
||||
if (/\s/.test(v) || v.includes('/') || v.includes('://')) return null;
|
||||
return v;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim();
|
||||
|
||||
if (!v || v.length > SMTP_HOST_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (/\s/.test(v) || v.includes('/') || v.includes('://')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeFrom(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
|
||||
return extractAddress(v) ? v : null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value.trim().slice(0, EMAIL_FIELD_MAX);
|
||||
return extractAddress(v) ? v : null;
|
||||
}
|
||||
|
||||
function normalizeTo(value: unknown): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
|
||||
return addrs.length > 0 ? addrs.join(', ') : null;
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const addrs = parseRecipients(value.trim().slice(0, EMAIL_FIELD_MAX));
|
||||
return addrs.length > 0 ? addrs.join(', ') : null;
|
||||
}
|
||||
|
||||
function normalizeChannelType(value: unknown): NotificationChannelType | null {
|
||||
if (value === 'email') return 'email';
|
||||
if (value === 'webhook' || value === undefined || value === '') return 'webhook';
|
||||
return null;
|
||||
if (value === 'email') {
|
||||
return 'email';
|
||||
}
|
||||
|
||||
if (value === 'webhook' || value === undefined || value === '') {
|
||||
return 'webhook';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeEmailChannel(
|
||||
raw: Record<string, unknown>,
|
||||
id: string,
|
||||
name: string,
|
||||
raw: Record<string, unknown>,
|
||||
id: string,
|
||||
name: string,
|
||||
): NotificationChannel | null {
|
||||
const smtpHost = normalizeSmtpHost(raw.smtpHost);
|
||||
const from = normalizeFrom(raw.from);
|
||||
const to = normalizeTo(raw.to);
|
||||
if (!smtpHost || !from || !to) return null;
|
||||
const smtpHost = normalizeSmtpHost(raw.smtpHost);
|
||||
const from = normalizeFrom(raw.from);
|
||||
const to = normalizeTo(raw.to);
|
||||
|
||||
const portRaw = raw.smtpPort;
|
||||
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
|
||||
const secureProvided = typeof raw.smtpSecure === 'boolean';
|
||||
const port = portProvided
|
||||
? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0)
|
||||
: 0;
|
||||
if (portProvided && port === 0) return null;
|
||||
if (!smtpHost || !from || !to) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
|
||||
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
|
||||
const portRaw = raw.smtpPort;
|
||||
const portProvided = portRaw !== undefined && portRaw !== null && portRaw !== '';
|
||||
const secureProvided = typeof raw.smtpSecure === 'boolean';
|
||||
const port = portProvided ? clampInt(portRaw, SMTP_PORT_MIN, SMTP_PORT_MAX, 0) : 0;
|
||||
|
||||
const smtpUser = typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
|
||||
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
|
||||
if (portProvided && port === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
smtpHost,
|
||||
smtpPort,
|
||||
smtpSecure,
|
||||
...(smtpUser ? { smtpUser } : {}),
|
||||
...(smtpPass ? { smtpPass } : {}),
|
||||
from,
|
||||
to,
|
||||
subjectTemplate: strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) || DEFAULT_SUBJECT_TEMPLATE,
|
||||
};
|
||||
const smtpSecure = secureProvided ? Boolean(raw.smtpSecure) : port === 465 || port === 0;
|
||||
const smtpPort = port === 0 ? (smtpSecure ? 465 : 587) : port;
|
||||
|
||||
const smtpUser =
|
||||
typeof raw.smtpUser === 'string' ? raw.smtpUser.trim().slice(0, SMTP_USER_MAX) : '';
|
||||
const smtpPass = typeof raw.smtpPass === 'string' ? raw.smtpPass.slice(0, SMTP_PASS_MAX) : '';
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'email',
|
||||
url: '',
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_EMAIL_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
smtpHost,
|
||||
smtpPort,
|
||||
smtpSecure,
|
||||
...(smtpUser ? { smtpUser } : {}),
|
||||
...(smtpPass ? { smtpPass } : {}),
|
||||
from,
|
||||
to,
|
||||
subjectTemplate:
|
||||
strOr(raw.subjectTemplate, DEFAULT_SUBJECT_TEMPLATE, SUBJECT_TEMPLATE_MAX) ||
|
||||
DEFAULT_SUBJECT_TEMPLATE,
|
||||
};
|
||||
}
|
||||
|
||||
/** A channel is usable only with a valid id AND a deliverable target —
|
||||
* http(s) URL for webhooks, SMTP host + from/to for email. Anything else
|
||||
* is dropped (total normalize). */
|
||||
function normalizeChannel(raw: unknown): NotificationChannel | null {
|
||||
if (!isObject(raw)) return null;
|
||||
const id = normalizeChannelId(raw.id);
|
||||
if (!id) return null;
|
||||
const type = normalizeChannelType(raw.type);
|
||||
if (!type) return null;
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
if (type === 'email') return normalizeEmailChannel(raw, id, name);
|
||||
if (!isObject(raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
if (!isHttpUrl(url)) return null;
|
||||
const headers = normalizeHeaders(raw.headers);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'webhook',
|
||||
url,
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
...(headers ? { headers } : {}),
|
||||
};
|
||||
const id = normalizeChannelId(raw.id);
|
||||
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const type = normalizeChannelType(raw.type);
|
||||
|
||||
if (!type) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const name = strOr(raw.name, id, CHANNEL_NAME_MAX).trim() || id;
|
||||
|
||||
if (type === 'email') {
|
||||
return normalizeEmailChannel(raw, id, name);
|
||||
}
|
||||
|
||||
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
||||
|
||||
if (!isHttpUrl(url)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const headers = normalizeHeaders(raw.headers);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: 'webhook',
|
||||
url,
|
||||
bodyTemplate: strOr(raw.bodyTemplate, DEFAULT_BODY_TEMPLATE, BODY_TEMPLATE_MAX),
|
||||
enabled: boolOr(raw.enabled, true),
|
||||
...(headers ? { headers } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeChannels(value: unknown): NotificationChannel[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const seen = new Set<string>();
|
||||
const out: NotificationChannel[] = [];
|
||||
for (const raw of value) {
|
||||
const ch = normalizeChannel(raw);
|
||||
if (!ch) continue;
|
||||
if (seen.has(ch.id)) continue; // dedupe by id — first occurrence wins
|
||||
seen.add(ch.id);
|
||||
out.push(ch);
|
||||
}
|
||||
return out;
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const out: NotificationChannel[] = [];
|
||||
|
||||
for (const raw of value) {
|
||||
const ch = normalizeChannel(raw);
|
||||
|
||||
if (!ch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seen.has(ch.id)) {
|
||||
continue;
|
||||
} // dedupe by id — first occurrence wins
|
||||
|
||||
seen.add(ch.id);
|
||||
out.push(ch);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeNotificationsConfig(value: unknown): NotificationsConfig {
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
),
|
||||
channels: normalizeChannels(v.channels),
|
||||
};
|
||||
const v = isObject(value) ? value : {};
|
||||
return {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds: clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
),
|
||||
channels: normalizeChannels(v.channels),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Persistence (atomic write + module-level cache) ────────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
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);
|
||||
// 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), {
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
});
|
||||
enforceSensitiveFileMode(tmp);
|
||||
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
|
||||
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
|
||||
ensureConfigDir();
|
||||
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
|
||||
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;
|
||||
|
||||
/** Load + normalize the channel store, creating it from defaults if absent. */
|
||||
export function loadNotificationsConfig(): NotificationsConfig {
|
||||
if (cached) return cached;
|
||||
ensureConfigDir();
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
ensureConfigDir();
|
||||
|
||||
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
|
||||
const fresh = defaultNotificationsConfig();
|
||||
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to write initial notifications.json: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
cached = fresh;
|
||||
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);
|
||||
|
||||
if (!fs.existsSync(NOTIFICATIONS_CONFIG_PATH)) {
|
||||
const fresh = defaultNotificationsConfig();
|
||||
try {
|
||||
atomicWrite(fresh);
|
||||
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const normalized = normalizeNotificationsConfig(parsed);
|
||||
|
||||
// Self-heal on disk only if normalization changed something (corrupt/old).
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to normalize notifications.json on disk: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('failed to write initial notifications.json: %s', err instanceof Error ? err.message : String(err));
|
||||
log.warn(
|
||||
'notifications.json unreadable; using defaults: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
const fresh = defaultNotificationsConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
cached = fresh;
|
||||
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;
|
||||
const normalized = normalizeNotificationsConfig(parsed);
|
||||
// Self-heal on disk only if normalization changed something (corrupt/old).
|
||||
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
|
||||
try {
|
||||
atomicWrite(normalized);
|
||||
} catch (err) {
|
||||
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
cached = normalized;
|
||||
return normalized;
|
||||
} catch (err) {
|
||||
log.warn('notifications.json unreadable; using defaults: %s', err instanceof Error ? err.message : String(err));
|
||||
const fresh = defaultNotificationsConfig();
|
||||
cached = fresh;
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -382,17 +506,22 @@ export function loadNotificationsConfig(): NotificationsConfig {
|
||||
* as `saveUiConfig`. Returns the stored, normalized config.
|
||||
*/
|
||||
export function saveNotificationsConfig(incoming: unknown): NotificationsConfig {
|
||||
const current = loadNotificationsConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
const next: NotificationsConfig = {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds:
|
||||
v.debounceSeconds !== undefined
|
||||
? clampInt(v.debounceSeconds, DEBOUNCE_SECONDS_MIN, DEBOUNCE_SECONDS_MAX, DEFAULT_DEBOUNCE_SECONDS)
|
||||
: current.debounceSeconds,
|
||||
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
const current = loadNotificationsConfig();
|
||||
const v = isObject(incoming) ? incoming : {};
|
||||
const next: NotificationsConfig = {
|
||||
version: NOTIFICATIONS_CONFIG_VERSION,
|
||||
debounceSeconds:
|
||||
v.debounceSeconds !== undefined
|
||||
? clampInt(
|
||||
v.debounceSeconds,
|
||||
DEBOUNCE_SECONDS_MIN,
|
||||
DEBOUNCE_SECONDS_MAX,
|
||||
DEFAULT_DEBOUNCE_SECONDS,
|
||||
)
|
||||
: current.debounceSeconds,
|
||||
channels: Array.isArray(v.channels) ? normalizeChannels(v.channels) : current.channels,
|
||||
};
|
||||
atomicWrite(next);
|
||||
cached = next;
|
||||
return next;
|
||||
}
|
||||
@@ -12,71 +12,85 @@
|
||||
import type { NotificationEvent } from './config';
|
||||
|
||||
export type DebounceDecision =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'schedule'; delayMs: number }
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'emit'; event: NotificationEvent };
|
||||
| { kind: 'none' }
|
||||
| { kind: 'schedule'; delayMs: number }
|
||||
| { kind: 'cancel' }
|
||||
| { kind: 'emit'; event: NotificationEvent };
|
||||
|
||||
interface UinState {
|
||||
/** An offline debounce timer is armed but has not yet fired. */
|
||||
pending: boolean;
|
||||
/** An "offline" notification has fired and is awaiting its recovery. */
|
||||
firedOffline: boolean;
|
||||
/** An offline debounce timer is armed but has not yet fired. */
|
||||
pending: boolean;
|
||||
/** An "offline" notification has fired and is awaiting its recovery. */
|
||||
firedOffline: boolean;
|
||||
}
|
||||
|
||||
export class DebounceMachine {
|
||||
private readonly states = new Map<string, UinState>();
|
||||
private readonly states = new Map<string, UinState>();
|
||||
|
||||
private state(uin: string): UinState {
|
||||
let s = this.states.get(uin);
|
||||
if (!s) {
|
||||
s = { pending: false, firedOffline: false };
|
||||
this.states.set(uin, s);
|
||||
private state(uin: string): UinState {
|
||||
let s = this.states.get(uin);
|
||||
|
||||
if (!s) {
|
||||
s = { pending: false, firedOffline: false };
|
||||
this.states.set(uin, s);
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Account went offline. `debounceSeconds` is read fresh from config so a
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.firedOffline || s.pending) return { kind: 'none' }; // already down / already counting
|
||||
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
|
||||
// never schedule a setTimeout(NaN|Infinity). Production config always
|
||||
// clamps to a finite [0,3600]; this only hardens direct callers.
|
||||
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
/** Account went offline. `debounceSeconds` is read fresh from config so a
|
||||
* reload takes effect on the next transition. */
|
||||
onOffline(uin: string, debounceSeconds: number): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
|
||||
if (s.firedOffline || s.pending) {
|
||||
return { kind: 'none' };
|
||||
} // already down / already counting
|
||||
|
||||
// Non-finite / non-positive → no debounce, fire immediately. Stays total:
|
||||
// never schedule a setTimeout(NaN|Infinity). Production config always
|
||||
// clamps to a finite [0,3600]; this only hardens direct callers.
|
||||
if (!Number.isFinite(debounceSeconds) || debounceSeconds <= 0) {
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
s.pending = true;
|
||||
return { kind: 'schedule', delayMs: debounceSeconds * 1000 };
|
||||
}
|
||||
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
/** Account came online. */
|
||||
onOnline(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
|
||||
if (s.pending) {
|
||||
s.pending = false;
|
||||
return { kind: 'cancel' }; // self-heal within the debounce window — nothing fired
|
||||
}
|
||||
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
}
|
||||
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
if (s.firedOffline) {
|
||||
s.firedOffline = false;
|
||||
return { kind: 'emit', event: 'online' }; // recovery, paired with the fired offline
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
|
||||
if (!s.pending) {
|
||||
return { kind: 'none' };
|
||||
} // cancelled before firing
|
||||
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
return { kind: 'none' }; // cold online / already up
|
||||
}
|
||||
|
||||
/** The offline debounce window elapsed (the armed timer fired). */
|
||||
onTimerElapsed(uin: string): DebounceDecision {
|
||||
const s = this.state(uin);
|
||||
if (!s.pending) return { kind: 'none' }; // cancelled before firing
|
||||
s.pending = false;
|
||||
s.firedOffline = true;
|
||||
return { kind: 'emit', event: 'offline' };
|
||||
}
|
||||
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
/** Drop a UIN's state (e.g. on dispose). */
|
||||
forget(uin: string): void {
|
||||
this.states.delete(uin);
|
||||
}
|
||||
}
|
||||
@@ -13,12 +13,12 @@ import { createLogger } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import {
|
||||
isEmailChannel,
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
type NotificationEvent,
|
||||
type NotificationsConfig,
|
||||
isEmailChannel,
|
||||
loadNotificationsConfig,
|
||||
renderTemplate,
|
||||
type NotificationChannel,
|
||||
type NotificationEvent,
|
||||
type NotificationsConfig,
|
||||
} from './config';
|
||||
import { DebounceMachine, type DebounceDecision } from './debounce';
|
||||
import { formatSmtpError, parseRecipients, sendSmtpMail } from './smtp';
|
||||
@@ -31,287 +31,360 @@ const FALLBACK_DEBOUNCE_SECONDS = 30;
|
||||
|
||||
/** One delivery attempt; kept only in memory (the plan forbids persistence). */
|
||||
export interface DeliveryRecord {
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEvent;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
time: number;
|
||||
uin: string;
|
||||
event: NotificationEvent;
|
||||
channelId: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PostResult {
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
ok: boolean;
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface MailPayload {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface NotificationManagerDeps {
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
|
||||
/** SMTP delivery — optional so webhook-only tests stay lean. */
|
||||
sendMail?: (mail: MailPayload) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
/** Global channel store (channels + debounceSeconds). */
|
||||
loadConfig: () => NotificationsConfig;
|
||||
/** The channel ids a UIN has opted into. */
|
||||
loadChannelIds: (uin: string) => string[];
|
||||
/** Webhook delivery — never throws; failures come back as `{ ok: false }`. */
|
||||
post: (url: string, body: string, headers?: Record<string, string>) => Promise<PostResult>;
|
||||
/** SMTP delivery — optional so webhook-only tests stay lean. */
|
||||
sendMail?: (mail: MailPayload) => Promise<PostResult>;
|
||||
now: () => number;
|
||||
historyLimit?: number;
|
||||
}
|
||||
|
||||
function errMsg(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure: the channels a UIN should be notified through — globally enabled AND
|
||||
* opted into by the UIN — preserving config order. Exported for unit tests.
|
||||
*/
|
||||
export function selectChannels(channels: NotificationChannel[], enabledIds: string[]): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
export function selectChannels(
|
||||
channels: NotificationChannel[],
|
||||
enabledIds: string[],
|
||||
): NotificationChannel[] {
|
||||
const wanted = new Set(enabledIds);
|
||||
return channels.filter((c) => c.enabled && wanted.has(c.id));
|
||||
}
|
||||
|
||||
export class NotificationManager {
|
||||
private readonly deps: NotificationManagerDeps;
|
||||
private readonly machine = new DebounceMachine();
|
||||
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
private disposed = false;
|
||||
private readonly deps: NotificationManagerDeps;
|
||||
private readonly machine = new DebounceMachine();
|
||||
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
private readonly nicknames = new Map<string, string>();
|
||||
private readonly history: DeliveryRecord[] = [];
|
||||
private readonly historyLimit: number;
|
||||
private disposed = false;
|
||||
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
}
|
||||
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => this.handleOnline(uin, bridge.identity.nickname));
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) => this.handleOffline(uin, bridge.identity.nickname));
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) return;
|
||||
if (nickname) this.nicknames.set(uin, nickname);
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
constructor(deps: NotificationManagerDeps) {
|
||||
this.deps = deps;
|
||||
this.historyLimit = deps.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
private apply(uin: string, decision: DebounceDecision): void {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
if (existing) clearTimeout(existing);
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
/** Subscribe to the global session online/offline edges. Register AFTER
|
||||
* OneBotManager so the nickname fallback is already populated. */
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) =>
|
||||
this.handleOnline(uin, bridge.identity.nickname),
|
||||
);
|
||||
bridgeManager.addSessionClosedListener((uin, bridge) =>
|
||||
this.handleOffline(uin, bridge.identity.nickname),
|
||||
);
|
||||
}
|
||||
|
||||
handleOnline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
|
||||
this.apply(uin, this.machine.onOnline(uin));
|
||||
}
|
||||
}
|
||||
|
||||
/** Render + deliver a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
try {
|
||||
const cfg = this.deps.loadConfig();
|
||||
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
|
||||
} catch (err) {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
handleOffline(uin: string, nickname?: string): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname) {
|
||||
this.nicknames.set(uin, nickname);
|
||||
}
|
||||
|
||||
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
|
||||
}
|
||||
if (channels.length === 0) return;
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
uin,
|
||||
nickname,
|
||||
event,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const result = await this.deliver(ch, vars);
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
event,
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok ? undefined : (result.error ?? (result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
if (!result.ok) {
|
||||
log.warn('notify %s→%s channel=%s failed: %s', uin, event, ch.id, result.error ?? `HTTP ${result.status ?? '?'}`);
|
||||
}
|
||||
private debounceSeconds(): number {
|
||||
try {
|
||||
return this.deps.loadConfig().debounceSeconds;
|
||||
} catch {
|
||||
return FALLBACK_DEBOUNCE_SECONDS;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async deliver(ch: NotificationChannel, vars: Record<string, string>): Promise<PostResult> {
|
||||
try {
|
||||
if (isEmailChannel(ch)) {
|
||||
const send = this.deps.sendMail;
|
||||
if (!send) return { ok: false, error: 'email delivery is not configured' };
|
||||
return await send({
|
||||
host: ch.smtpHost,
|
||||
port: ch.smtpPort,
|
||||
secure: ch.smtpSecure,
|
||||
user: ch.smtpUser,
|
||||
pass: ch.smtpPass,
|
||||
from: ch.from,
|
||||
to: ch.to,
|
||||
subject: renderTemplate(ch.subjectTemplate, vars),
|
||||
text: renderTemplate(ch.bodyTemplate, vars),
|
||||
});
|
||||
}
|
||||
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
|
||||
} catch (err) {
|
||||
// Injected collaborators are contracted not to throw, but guard anyway.
|
||||
return { ok: false, error: errMsg(err) };
|
||||
private apply(uin: string, decision: DebounceDecision): void {
|
||||
switch (decision.kind) {
|
||||
case 'schedule': {
|
||||
const existing = this.timers.get(uin);
|
||||
|
||||
if (existing) {
|
||||
clearTimeout(existing);
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this.timers.delete(uin);
|
||||
this.apply(uin, this.machine.onTimerElapsed(uin));
|
||||
}, decision.delayMs);
|
||||
|
||||
// Don't let a pending notification timer keep the process alive.
|
||||
if (typeof (timer as { unref?: () => void }).unref === 'function') {
|
||||
(timer as { unref: () => void }).unref();
|
||||
}
|
||||
|
||||
this.timers.set(uin, timer);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'cancel': {
|
||||
const timer = this.timers.get(uin);
|
||||
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.timers.delete(uin);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 'emit':
|
||||
void this.notify(uin, decision.event);
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Send a one-off test to a single channel by id — ignores `enabled` and the
|
||||
* per-UIN opt-in (you test a channel before wiring it up), with sample
|
||||
* variables. Reuses the real render+deliver path; NOT recorded to history.
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
try {
|
||||
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
|
||||
} catch (err) {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
/** Render + deliver a transition to every opted-in, enabled channel and record
|
||||
* the outcome. Never throws (a bad channel can't break the others). */
|
||||
async notify(uin: string, event: NotificationEvent): Promise<void> {
|
||||
let channels: NotificationChannel[];
|
||||
|
||||
try {
|
||||
const cfg = this.deps.loadConfig();
|
||||
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
|
||||
} catch (err) {
|
||||
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
|
||||
return;
|
||||
}
|
||||
|
||||
if (channels.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nickname = this.nicknames.get(uin) || uin;
|
||||
const vars: Record<string, string> = {
|
||||
uin,
|
||||
nickname,
|
||||
event,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
|
||||
for (const ch of channels) {
|
||||
const result = await this.deliver(ch, vars);
|
||||
this.record({
|
||||
time: this.deps.now(),
|
||||
uin,
|
||||
event,
|
||||
channelId: ch.id,
|
||||
ok: result.ok,
|
||||
status: result.status,
|
||||
error: result.ok
|
||||
? undefined
|
||||
: (result.error ??
|
||||
(result.status ? `HTTP ${result.status}` : 'delivery failed')),
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
log.warn(
|
||||
'notify %s→%s channel=%s failed: %s',
|
||||
uin,
|
||||
event,
|
||||
ch.id,
|
||||
result.error ?? `HTTP ${result.status ?? '?'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!channel) return { ok: false, found: false };
|
||||
const vars = {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
event: 'offline' as const,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
return { ...(await this.deliver(channel, vars)), found: true };
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
private async deliver(
|
||||
ch: NotificationChannel,
|
||||
vars: Record<string, string>,
|
||||
): Promise<PostResult> {
|
||||
try {
|
||||
if (isEmailChannel(ch)) {
|
||||
const send = this.deps.sendMail;
|
||||
|
||||
if (!send) {
|
||||
return { ok: false, error: 'email delivery is not configured' };
|
||||
}
|
||||
|
||||
return await send({
|
||||
host: ch.smtpHost,
|
||||
port: ch.smtpPort,
|
||||
secure: ch.smtpSecure,
|
||||
user: ch.smtpUser,
|
||||
pass: ch.smtpPass,
|
||||
from: ch.from,
|
||||
to: ch.to,
|
||||
subject: renderTemplate(ch.subjectTemplate, vars),
|
||||
text: renderTemplate(ch.bodyTemplate, vars),
|
||||
});
|
||||
}
|
||||
|
||||
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
|
||||
} catch (err) {
|
||||
// Injected collaborators are contracted not to throw, but guard anyway.
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Most-recent-first delivery history (capped at the buffer size). */
|
||||
getRecent(limit = this.historyLimit): DeliveryRecord[] {
|
||||
const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length));
|
||||
return this.history.slice(this.history.length - n).reverse();
|
||||
}
|
||||
/** Send a one-off test to a single channel by id — ignores `enabled` and the
|
||||
* per-UIN opt-in (you test a channel before wiring it up), with sample
|
||||
* variables. Reuses the real render+deliver path; NOT recorded to history.
|
||||
* `found:false` means the channel id is unknown. */
|
||||
async testSend(channelId: string): Promise<PostResult & { found: boolean }> {
|
||||
let channel: NotificationChannel | undefined;
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
for (const timer of this.timers.values()) clearTimeout(timer);
|
||||
this.timers.clear();
|
||||
}
|
||||
try {
|
||||
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
|
||||
} catch (err) {
|
||||
return { ok: false, found: false, error: errMsg(err) };
|
||||
}
|
||||
|
||||
if (!channel) {
|
||||
return { ok: false, found: false };
|
||||
}
|
||||
|
||||
const vars = {
|
||||
uin: '10000',
|
||||
nickname: '测试账号',
|
||||
event: 'offline' as const,
|
||||
time: new Date(this.deps.now()).toISOString(),
|
||||
};
|
||||
return { ...(await this.deliver(channel, vars)), found: true };
|
||||
}
|
||||
|
||||
private record(rec: DeliveryRecord): void {
|
||||
this.history.push(rec);
|
||||
|
||||
if (this.history.length > this.historyLimit) {
|
||||
this.history.splice(0, this.history.length - this.historyLimit);
|
||||
}
|
||||
}
|
||||
|
||||
/** Most-recent-first delivery history (capped at the buffer size). */
|
||||
getRecent(limit = this.historyLimit): DeliveryRecord[] {
|
||||
const n = Math.max(0, Math.min(Math.trunc(limit) || 0, this.history.length));
|
||||
return this.history.slice(this.history.length - n).reverse();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
|
||||
for (const timer of this.timers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
this.timers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Default outbound POST: a single attempt with a timeout, JSON content-type
|
||||
* (the common case for 钉钉/Discord/飞书). Never throws. */
|
||||
export function createDefaultPost(
|
||||
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
|
||||
timeoutMs = positiveIntEnv('SNOWLUMA_NOTIFICATION_HTTP_TIMEOUT_MS', DEFAULT_POST_TIMEOUT_MS),
|
||||
): NotificationManagerDeps['post'] {
|
||||
return async (url, body, headers) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return { ok: res.ok, status: res.status, error: res.ok ? undefined : `HTTP ${res.status}` };
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
return async (url, body, headers) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...headers },
|
||||
body,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
return {
|
||||
ok: res.ok,
|
||||
status: res.status,
|
||||
error: res.ok ? undefined : `HTTP ${res.status}`,
|
||||
};
|
||||
} catch (err) {
|
||||
return { ok: false, error: errMsg(err) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_SMTP_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** Default SMTP send. Never throws. */
|
||||
export function createDefaultSendMail(timeoutMs = DEFAULT_SMTP_TIMEOUT_MS): NonNullable<NotificationManagerDeps['sendMail']> {
|
||||
return async (mail) => {
|
||||
try {
|
||||
await sendSmtpMail({
|
||||
host: mail.host,
|
||||
port: mail.port,
|
||||
secure: mail.secure,
|
||||
user: mail.user,
|
||||
pass: mail.pass,
|
||||
from: mail.from,
|
||||
to: parseRecipients(mail.to),
|
||||
subject: mail.subject,
|
||||
body: mail.text,
|
||||
}, { timeoutMs });
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
|
||||
}
|
||||
};
|
||||
export function createDefaultSendMail(
|
||||
timeoutMs = DEFAULT_SMTP_TIMEOUT_MS,
|
||||
): NonNullable<NotificationManagerDeps['sendMail']> {
|
||||
return async (mail) => {
|
||||
try {
|
||||
await sendSmtpMail(
|
||||
{
|
||||
host: mail.host,
|
||||
port: mail.port,
|
||||
secure: mail.secure,
|
||||
user: mail.user,
|
||||
pass: mail.pass,
|
||||
from: mail.from,
|
||||
to: parseRecipients(mail.to),
|
||||
subject: mail.subject,
|
||||
body: mail.text,
|
||||
},
|
||||
{ timeoutMs },
|
||||
);
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: formatSmtpError(err, mail.host, mail.port) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The real, fully-wired singleton. */
|
||||
export function createNotificationManager(): NotificationManager {
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
sendMail: createDefaultSendMail(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
return new NotificationManager({
|
||||
loadConfig: loadNotificationsConfig,
|
||||
loadChannelIds: (uin) => loadOneBotConfig(uin).notifications?.channelIds ?? [],
|
||||
post: createDefaultPost(),
|
||||
sendMail: createDefaultSendMail(),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -9,375 +9,474 @@ const CRLF = '\r\n';
|
||||
const DEFAULT_TIMEOUT_MS = 15_000;
|
||||
|
||||
export class SmtpError extends Error {
|
||||
readonly responseCode?: number;
|
||||
readonly code?: string;
|
||||
readonly responseCode?: number;
|
||||
readonly code?: string;
|
||||
|
||||
constructor(message: string, opts?: { responseCode?: number; code?: string }) {
|
||||
super(message);
|
||||
this.name = 'SmtpError';
|
||||
this.responseCode = opts?.responseCode;
|
||||
this.code = opts?.code;
|
||||
}
|
||||
constructor(message: string, opts?: { responseCode?: number; code?: string }) {
|
||||
super(message);
|
||||
this.name = 'SmtpError';
|
||||
this.responseCode = opts?.responseCode;
|
||||
this.code = opts?.code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SmtpMail {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string[];
|
||||
subject: string;
|
||||
body: string;
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
from: string;
|
||||
to: string[];
|
||||
subject: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface SendSmtpOptions {
|
||||
timeoutMs?: number;
|
||||
/** Defaults true. Tests against a self-signed mock pass false. */
|
||||
rejectUnauthorized?: boolean;
|
||||
timeoutMs?: number;
|
||||
/** Defaults true. Tests against a self-signed mock pass false. */
|
||||
rejectUnauthorized?: boolean;
|
||||
}
|
||||
|
||||
export function looksLikeEmail(value: string): boolean {
|
||||
return /^[^\s<>@]+@[^\s<>@]+$/.test(value);
|
||||
return /^[^\s<>@]+@[^\s<>@]+$/.test(value);
|
||||
}
|
||||
|
||||
/** Address from `Name <user@host>` or a bare addr; null if neither is usable. */
|
||||
export function extractAddress(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const angled = /<([^<>]+)>/.exec(trimmed);
|
||||
const addr = (angled ? angled[1] : trimmed).trim();
|
||||
return looksLikeEmail(addr) ? addr : null;
|
||||
const trimmed = value.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const angled = /<([^<>]+)>/.exec(trimmed);
|
||||
const addr = (angled ? angled[1] : trimmed).trim();
|
||||
return looksLikeEmail(addr) ? addr : null;
|
||||
}
|
||||
|
||||
/** Split a comma / semicolon / newline list and keep unique addresses. */
|
||||
export function parseRecipients(value: string): string[] {
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const part of value.split(/[,;\n]+/)) {
|
||||
const addr = extractAddress(part);
|
||||
if (!addr) continue;
|
||||
const key = addr.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(addr);
|
||||
}
|
||||
return out;
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
|
||||
for (const part of value.split(/[,;\n]+/)) {
|
||||
const addr = extractAddress(part);
|
||||
|
||||
if (!addr) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = addr.toLowerCase();
|
||||
|
||||
if (seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(key);
|
||||
out.push(addr);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function encodeHeader(value: string): string {
|
||||
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) return value;
|
||||
return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`;
|
||||
if (/^[\x20-\x7E]*$/.test(value) && !/[\r\n]/.test(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return `=?UTF-8?B?${Buffer.from(value, 'utf8').toString('base64')}?=`;
|
||||
}
|
||||
|
||||
function rfc5322Date(d: Date): string {
|
||||
return d.toUTCString().replace(/GMT$/, '+0000');
|
||||
return d.toUTCString().replace(/GMT$/, '+0000');
|
||||
}
|
||||
|
||||
function wrap76(b64: string): string {
|
||||
return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd();
|
||||
return b64.replace(/.{1,76}/g, (line) => `${line}\r\n`).trimEnd();
|
||||
}
|
||||
|
||||
function isHtmlBody(body: string): boolean {
|
||||
return /^\s*</.test(body);
|
||||
return /^\s*</.test(body);
|
||||
}
|
||||
|
||||
function dotStuff(payload: string): string {
|
||||
return payload.replace(/^\./gm, '..');
|
||||
return payload.replace(/^\./gm, '..');
|
||||
}
|
||||
|
||||
/** Build a single-part MIME message (plain or HTML). Exported for tests. */
|
||||
export function buildMimeMessage(mail: SmtpMail, now = new Date()): string {
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
const toHeader = mail.to.join(', ');
|
||||
const html = isHtmlBody(mail.body);
|
||||
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`;
|
||||
const headers = [
|
||||
`From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`,
|
||||
`To: ${toHeader}`,
|
||||
`Subject: ${encodeHeader(mail.subject)}`,
|
||||
`Date: ${rfc5322Date(now)}`,
|
||||
`Message-ID: ${id}`,
|
||||
'MIME-Version: 1.0',
|
||||
`Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`,
|
||||
'Content-Transfer-Encoding: base64',
|
||||
];
|
||||
const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64'));
|
||||
return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`;
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
const toHeader = mail.to.join(', ');
|
||||
const html = isHtmlBody(mail.body);
|
||||
const id = `<${now.getTime()}.${Math.random().toString(36).slice(2, 10)}@snowluma>`;
|
||||
const headers = [
|
||||
`From: ${mail.from.trim() || (fromAddr ? `<${fromAddr}>` : '')}`,
|
||||
`To: ${toHeader}`,
|
||||
`Subject: ${encodeHeader(mail.subject)}`,
|
||||
`Date: ${rfc5322Date(now)}`,
|
||||
`Message-ID: ${id}`,
|
||||
'MIME-Version: 1.0',
|
||||
`Content-Type: ${html ? 'text/html' : 'text/plain'}; charset=UTF-8`,
|
||||
'Content-Transfer-Encoding: base64',
|
||||
];
|
||||
const body = wrap76(Buffer.from(mail.body, 'utf8').toString('base64'));
|
||||
return `${headers.join(CRLF)}${CRLF}${CRLF}${body}${CRLF}`;
|
||||
}
|
||||
|
||||
interface SmtpReply {
|
||||
code: number;
|
||||
lines: string[];
|
||||
text: string;
|
||||
code: number;
|
||||
lines: string[];
|
||||
text: string;
|
||||
}
|
||||
|
||||
function consumeReply(buf: string): { reply: SmtpReply; rest: string } | null {
|
||||
let offset = 0;
|
||||
const lines: string[] = [];
|
||||
let code = 0;
|
||||
while (offset < buf.length) {
|
||||
const nl = buf.indexOf('\n', offset);
|
||||
if (nl === -1) return null;
|
||||
const line = buf.slice(offset, nl).replace(/\r$/, '');
|
||||
offset = nl + 1;
|
||||
const m = /^(\d{3})([ -])(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
code = Number(m[1]);
|
||||
lines.push(m[3]);
|
||||
if (m[2] === ' ') {
|
||||
return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) };
|
||||
let offset = 0;
|
||||
const lines: string[] = [];
|
||||
let code = 0;
|
||||
|
||||
while (offset < buf.length) {
|
||||
const nl = buf.indexOf('\n', offset);
|
||||
|
||||
if (nl === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const line = buf.slice(offset, nl).replace(/\r$/, '');
|
||||
offset = nl + 1;
|
||||
const m = /^(\d{3})([ -])(.*)$/.exec(line);
|
||||
|
||||
if (!m) {
|
||||
continue;
|
||||
}
|
||||
|
||||
code = Number(m[1]);
|
||||
lines.push(m[3]);
|
||||
|
||||
if (m[2] === ' ') {
|
||||
return { reply: { code, lines, text: lines.join('\n') }, rest: buf.slice(offset) };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
type SmtpSock = net.Socket | tls.TLSSocket;
|
||||
|
||||
function parseCapabilities(reply: SmtpReply): { starttls: boolean; auth: Set<string> } {
|
||||
const auth = new Set<string>();
|
||||
let starttls = false;
|
||||
for (const line of reply.lines) {
|
||||
const u = line.toUpperCase();
|
||||
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) starttls = true;
|
||||
if (u.startsWith('AUTH ')) {
|
||||
for (const mech of u.slice(5).split(/\s+/)) {
|
||||
if (mech) auth.add(mech);
|
||||
}
|
||||
const auth = new Set<string>();
|
||||
let starttls = false;
|
||||
|
||||
for (const line of reply.lines) {
|
||||
const u = line.toUpperCase();
|
||||
|
||||
if (u === 'STARTTLS' || u.startsWith('STARTTLS ')) {
|
||||
starttls = true;
|
||||
}
|
||||
|
||||
if (u.startsWith('AUTH ')) {
|
||||
for (const mech of u.slice(5).split(/\s+/)) {
|
||||
if (mech) {
|
||||
auth.add(mech);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { starttls, auth };
|
||||
|
||||
return { starttls, auth };
|
||||
}
|
||||
|
||||
function connectSocket(
|
||||
host: string,
|
||||
port: number,
|
||||
secure: boolean,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
host: string,
|
||||
port: number,
|
||||
secure: boolean,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
): Promise<SmtpSock> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock: SmtpSock = secure
|
||||
? tls.connect({
|
||||
host,
|
||||
port,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
})
|
||||
: net.connect({ host, port });
|
||||
const fail = (err: Error) => {
|
||||
sock.destroy();
|
||||
reject(err);
|
||||
};
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.once('timeout', () => fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })));
|
||||
sock.once('error', fail);
|
||||
sock.once(secure ? 'secureConnect' : 'connect', () => {
|
||||
sock.removeAllListeners('timeout');
|
||||
sock.removeAllListeners('error');
|
||||
resolve(sock);
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock: SmtpSock = secure
|
||||
? tls.connect({
|
||||
host,
|
||||
port,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
})
|
||||
: net.connect({ host, port });
|
||||
|
||||
const fail = (err: Error) => {
|
||||
sock.destroy();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.once('timeout', () =>
|
||||
fail(new SmtpError('SMTP connection timed out', { code: 'ETIMEDOUT' })),
|
||||
);
|
||||
sock.once('error', fail);
|
||||
sock.once(secure ? 'secureConnect' : 'connect', () => {
|
||||
sock.removeAllListeners('timeout');
|
||||
sock.removeAllListeners('error');
|
||||
resolve(sock);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function upgradeTls(
|
||||
socket: net.Socket,
|
||||
host: string,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
socket: net.Socket,
|
||||
host: string,
|
||||
timeoutMs: number,
|
||||
rejectUnauthorized: boolean,
|
||||
): Promise<tls.TLSSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tlsSocket = tls.connect({
|
||||
socket,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
}, () => resolve(tlsSocket));
|
||||
tlsSocket.setTimeout(timeoutMs);
|
||||
tlsSocket.once('timeout', () => {
|
||||
tlsSocket.destroy();
|
||||
reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' }));
|
||||
return new Promise((resolve, reject) => {
|
||||
const tlsSocket = tls.connect(
|
||||
{
|
||||
socket,
|
||||
servername: net.isIP(host) === 0 ? host : undefined,
|
||||
rejectUnauthorized,
|
||||
},
|
||||
() => resolve(tlsSocket),
|
||||
);
|
||||
tlsSocket.setTimeout(timeoutMs);
|
||||
tlsSocket.once('timeout', () => {
|
||||
tlsSocket.destroy();
|
||||
reject(new SmtpError('SMTP STARTTLS timed out', { code: 'ETIMEDOUT' }));
|
||||
});
|
||||
tlsSocket.once('error', reject);
|
||||
});
|
||||
tlsSocket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
class SmtpSession {
|
||||
private buf = '';
|
||||
private buf = '';
|
||||
|
||||
constructor(private socket: SmtpSock) {}
|
||||
constructor(private socket: SmtpSock) {}
|
||||
|
||||
destroy(): void {
|
||||
this.socket.destroy();
|
||||
}
|
||||
|
||||
attachTimeout(timeoutMs: number, onTimeout: () => void): void {
|
||||
this.socket.setTimeout(timeoutMs);
|
||||
this.socket.once('timeout', onTimeout);
|
||||
}
|
||||
|
||||
async read(): Promise<SmtpReply> {
|
||||
const ready = consumeReply(this.buf);
|
||||
if (ready) {
|
||||
this.buf = ready.rest;
|
||||
return ready.reply;
|
||||
destroy(): void {
|
||||
this.socket.destroy();
|
||||
}
|
||||
return new Promise<SmtpReply>((resolve, reject) => {
|
||||
const onData = (chunk: Buffer) => {
|
||||
this.buf += chunk.toString('utf8');
|
||||
const got = consumeReply(this.buf);
|
||||
if (!got) return;
|
||||
this.buf = got.rest;
|
||||
cleanup();
|
||||
resolve(got.reply);
|
||||
};
|
||||
const onError = (err: Error) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
};
|
||||
const onClose = () => {
|
||||
cleanup();
|
||||
reject(new SmtpError('SMTP connection closed'));
|
||||
};
|
||||
const cleanup = () => {
|
||||
this.socket.removeListener('data', onData);
|
||||
this.socket.removeListener('error', onError);
|
||||
this.socket.removeListener('close', onClose);
|
||||
};
|
||||
this.socket.on('data', onData);
|
||||
this.socket.once('error', onError);
|
||||
this.socket.once('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
write(data: string): void {
|
||||
this.socket.write(data);
|
||||
}
|
||||
|
||||
async command(line: string, ok: (code: number) => boolean, label?: string): Promise<SmtpReply> {
|
||||
this.write(line + CRLF);
|
||||
const reply = await this.read();
|
||||
if (!ok(reply.code)) {
|
||||
const name = label ?? line.split(' ')[0] ?? 'SMTP';
|
||||
throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), {
|
||||
responseCode: reply.code,
|
||||
});
|
||||
attachTimeout(timeoutMs: number, onTimeout: () => void): void {
|
||||
this.socket.setTimeout(timeoutMs);
|
||||
this.socket.once('timeout', onTimeout);
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
replaceSocket(next: SmtpSock): void {
|
||||
this.socket = next;
|
||||
this.buf = '';
|
||||
}
|
||||
async read(): Promise<SmtpReply> {
|
||||
const ready = consumeReply(this.buf);
|
||||
|
||||
if (ready) {
|
||||
this.buf = ready.rest;
|
||||
return ready.reply;
|
||||
}
|
||||
|
||||
return new Promise<SmtpReply>((resolve, reject) => {
|
||||
const onData = (chunk: Buffer) => {
|
||||
this.buf += chunk.toString('utf8');
|
||||
const got = consumeReply(this.buf);
|
||||
|
||||
if (!got) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.buf = got.rest;
|
||||
cleanup();
|
||||
resolve(got.reply);
|
||||
};
|
||||
|
||||
const onError = (err: Error) => {
|
||||
cleanup();
|
||||
reject(err);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
cleanup();
|
||||
reject(new SmtpError('SMTP connection closed'));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
this.socket.removeListener('data', onData);
|
||||
this.socket.removeListener('error', onError);
|
||||
this.socket.removeListener('close', onClose);
|
||||
};
|
||||
|
||||
this.socket.on('data', onData);
|
||||
this.socket.once('error', onError);
|
||||
this.socket.once('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
write(data: string): void {
|
||||
this.socket.write(data);
|
||||
}
|
||||
|
||||
async command(line: string, ok: (code: number) => boolean, label?: string): Promise<SmtpReply> {
|
||||
this.write(line + CRLF);
|
||||
const reply = await this.read();
|
||||
|
||||
if (!ok(reply.code)) {
|
||||
const name = label ?? line.split(' ')[0] ?? 'SMTP';
|
||||
throw new SmtpError(`${name} failed: ${reply.code} ${reply.text}`.trim(), {
|
||||
responseCode: reply.code,
|
||||
});
|
||||
}
|
||||
|
||||
return reply;
|
||||
}
|
||||
|
||||
replaceSocket(next: SmtpSock): void {
|
||||
this.socket = next;
|
||||
this.buf = '';
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSmtpError(err: unknown, host: string, port: number): string {
|
||||
if (err instanceof SmtpError) {
|
||||
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
if (err instanceof SmtpError) {
|
||||
if (err.code === 'ECONNREFUSED' || err.code === 'ENOTFOUND' || err.code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
|
||||
if (err.responseCode === 535) {
|
||||
return 'SMTP 认证失败';
|
||||
}
|
||||
|
||||
return err.message;
|
||||
}
|
||||
if (err.responseCode === 535) return 'SMTP 认证失败';
|
||||
return err.message;
|
||||
}
|
||||
if (err instanceof Error) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
|
||||
if (err instanceof Error) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
|
||||
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'ETIMEDOUT') {
|
||||
return `无法连接 SMTP:${host}:${port}`;
|
||||
}
|
||||
|
||||
if (/self-signed|unable to verify/i.test(err.message)) {
|
||||
return `SMTP 证书不受信任:${host}`;
|
||||
}
|
||||
|
||||
return err.message || '邮件发送失败';
|
||||
}
|
||||
if (/self-signed|unable to verify/i.test(err.message)) {
|
||||
return `SMTP 证书不受信任:${host}`;
|
||||
}
|
||||
return err.message || '邮件发送失败';
|
||||
}
|
||||
return '邮件发送失败';
|
||||
|
||||
return '邮件发送失败';
|
||||
}
|
||||
|
||||
export async function sendSmtpMail(mail: SmtpMail, opts: SendSmtpOptions = {}): Promise<void> {
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const rejectUnauthorized = opts.rejectUnauthorized ?? true;
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
if (!fromAddr) throw new SmtpError('invalid from address');
|
||||
if (mail.to.length === 0) throw new SmtpError('no recipients');
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const rejectUnauthorized = opts.rejectUnauthorized ?? true;
|
||||
const fromAddr = extractAddress(mail.from);
|
||||
|
||||
let sock = await connectSocket(mail.host, mail.port, mail.secure, timeoutMs, rejectUnauthorized);
|
||||
const session = new SmtpSession(sock);
|
||||
let finished = false;
|
||||
const failTimeout = () => {
|
||||
if (finished) return;
|
||||
session.destroy();
|
||||
};
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
|
||||
try {
|
||||
const greeting = await session.read();
|
||||
if (greeting.code !== 220) {
|
||||
throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), {
|
||||
responseCode: greeting.code,
|
||||
});
|
||||
if (!fromAddr) {
|
||||
throw new SmtpError('invalid from address');
|
||||
}
|
||||
|
||||
const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250);
|
||||
let caps = parseCapabilities(await ehlo());
|
||||
|
||||
if (!mail.secure && caps.starttls) {
|
||||
await session.command('STARTTLS', (c) => c === 220);
|
||||
const upgraded = await upgradeTls(sock as net.Socket, mail.host, timeoutMs, rejectUnauthorized);
|
||||
session.replaceSocket(upgraded);
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
sock = upgraded;
|
||||
caps = parseCapabilities(await ehlo());
|
||||
if (mail.to.length === 0) {
|
||||
throw new SmtpError('no recipients');
|
||||
}
|
||||
|
||||
const user = mail.user?.trim() ?? '';
|
||||
if (user) {
|
||||
await authenticate(session, caps.auth, user, mail.pass ?? '');
|
||||
}
|
||||
let sock = await connectSocket(
|
||||
mail.host,
|
||||
mail.port,
|
||||
mail.secure,
|
||||
timeoutMs,
|
||||
rejectUnauthorized,
|
||||
);
|
||||
const session = new SmtpSession(sock);
|
||||
let finished = false;
|
||||
|
||||
const failTimeout = () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
|
||||
session.destroy();
|
||||
};
|
||||
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
|
||||
await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250);
|
||||
for (const rcpt of mail.to) {
|
||||
await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251);
|
||||
}
|
||||
await session.command('DATA', (c) => c === 354);
|
||||
session.write(dotStuff(buildMimeMessage(mail)));
|
||||
await session.command('.', (c) => c === 250, 'DATA');
|
||||
try {
|
||||
await session.command('QUIT', (c) => c === 221);
|
||||
} catch {
|
||||
// Some relays drop the socket after 250; delivery already succeeded.
|
||||
const greeting = await session.read();
|
||||
|
||||
if (greeting.code !== 220) {
|
||||
throw new SmtpError(`SMTP greeting failed: ${greeting.code} ${greeting.text}`.trim(), {
|
||||
responseCode: greeting.code,
|
||||
});
|
||||
}
|
||||
|
||||
const ehlo = async () => session.command('EHLO [127.0.0.1]', (c) => c === 250);
|
||||
let caps = parseCapabilities(await ehlo());
|
||||
|
||||
if (!mail.secure && caps.starttls) {
|
||||
await session.command('STARTTLS', (c) => c === 220);
|
||||
const upgraded = await upgradeTls(
|
||||
sock as net.Socket,
|
||||
mail.host,
|
||||
timeoutMs,
|
||||
rejectUnauthorized,
|
||||
);
|
||||
session.replaceSocket(upgraded);
|
||||
session.attachTimeout(timeoutMs, failTimeout);
|
||||
sock = upgraded;
|
||||
caps = parseCapabilities(await ehlo());
|
||||
}
|
||||
|
||||
const user = mail.user?.trim() ?? '';
|
||||
|
||||
if (user) {
|
||||
await authenticate(session, caps.auth, user, mail.pass ?? '');
|
||||
}
|
||||
|
||||
await session.command(`MAIL FROM:<${fromAddr}>`, (c) => c === 250);
|
||||
|
||||
for (const rcpt of mail.to) {
|
||||
await session.command(`RCPT TO:<${rcpt}>`, (c) => c === 250 || c === 251);
|
||||
}
|
||||
|
||||
await session.command('DATA', (c) => c === 354);
|
||||
session.write(dotStuff(buildMimeMessage(mail)));
|
||||
await session.command('.', (c) => c === 250, 'DATA');
|
||||
|
||||
try {
|
||||
await session.command('QUIT', (c) => c === 221);
|
||||
} catch {
|
||||
// Some relays drop the socket after 250; delivery already succeeded.
|
||||
}
|
||||
|
||||
finished = true;
|
||||
} catch (err) {
|
||||
finished = true;
|
||||
throw err;
|
||||
} finally {
|
||||
session.destroy();
|
||||
}
|
||||
finished = true;
|
||||
} catch (err) {
|
||||
finished = true;
|
||||
throw err;
|
||||
} finally {
|
||||
session.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
session: SmtpSession,
|
||||
mechs: Set<string>,
|
||||
user: string,
|
||||
pass: string,
|
||||
session: SmtpSession,
|
||||
mechs: Set<string>,
|
||||
user: string,
|
||||
pass: string,
|
||||
): Promise<void> {
|
||||
const hasPlain = mechs.has('PLAIN');
|
||||
const hasLogin = mechs.has('LOGIN');
|
||||
if (hasPlain || !hasLogin) {
|
||||
try {
|
||||
const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64');
|
||||
await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH');
|
||||
return;
|
||||
} catch (err) {
|
||||
if (hasPlain && !hasLogin) throw err;
|
||||
if (err instanceof SmtpError && err.responseCode === 535) throw err;
|
||||
const hasPlain = mechs.has('PLAIN');
|
||||
const hasLogin = mechs.has('LOGIN');
|
||||
|
||||
if (hasPlain || !hasLogin) {
|
||||
try {
|
||||
const token = Buffer.from(`\0${user}\0${pass}`, 'utf8').toString('base64');
|
||||
await session.command(`AUTH PLAIN ${token}`, (c) => c === 235, 'AUTH');
|
||||
return;
|
||||
} catch (err) {
|
||||
if (hasPlain && !hasLogin) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (err instanceof SmtpError && err.responseCode === 535) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await loginAuth(session, user, pass);
|
||||
|
||||
await loginAuth(session, user, pass);
|
||||
}
|
||||
|
||||
async function loginAuth(session: SmtpSession, user: string, pass: string): Promise<void> {
|
||||
await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH');
|
||||
await session.command('AUTH LOGIN', (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(user, 'utf8').toString('base64'), (c) => c === 334, 'AUTH');
|
||||
await session.command(Buffer.from(pass, 'utf8').toString('base64'), (c) => c === 235, 'AUTH');
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import path from 'node:path';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
SysFaceStore,
|
||||
sysFaceStore,
|
||||
type SysFaceCatalogStorage,
|
||||
SysFaceStore,
|
||||
sysFaceStore,
|
||||
type SysFaceCatalogStorage,
|
||||
} from '@snowluma/protocol/sys-face-store';
|
||||
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
|
||||
import type { BridgeManager } from './bridge/manager';
|
||||
@@ -11,30 +11,32 @@ import type { BridgeManager } from './bridge/manager';
|
||||
const log = createLogger('SysFace');
|
||||
|
||||
export interface SystemFaceCatalogBindingOptions {
|
||||
store?: SysFaceStore;
|
||||
storage?: SysFaceCatalogStorage;
|
||||
dataRoot?: string;
|
||||
store?: SysFaceStore;
|
||||
storage?: SysFaceCatalogStorage;
|
||||
dataRoot?: string;
|
||||
}
|
||||
|
||||
/** Attach the shared system-face catalog to Bridge login edges. The first
|
||||
* account restores + refreshes it; later accounts reuse the same result. */
|
||||
export function bindSystemFaceCatalog(
|
||||
manager: BridgeManager,
|
||||
options: SystemFaceCatalogBindingOptions = {},
|
||||
manager: BridgeManager,
|
||||
options: SystemFaceCatalogBindingOptions = {},
|
||||
): void {
|
||||
const store = options.store ?? sysFaceStore;
|
||||
const storage = options.storage ?? new JsonSysFaceCatalogStorage(
|
||||
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
|
||||
);
|
||||
store.configureStorage(storage);
|
||||
const store = options.store ?? sysFaceStore;
|
||||
const storage =
|
||||
options.storage ??
|
||||
new JsonSysFaceCatalogStorage(
|
||||
path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'),
|
||||
);
|
||||
store.configureStorage(storage);
|
||||
|
||||
manager.addSessionStartedListener((uin, bridge) => {
|
||||
void store.prewarm(bridge).catch((error) => {
|
||||
log.error(
|
||||
'system face catalog login prewarm failed: uin=%s error=%s',
|
||||
uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
manager.addSessionStartedListener((uin, bridge) => {
|
||||
void store.prewarm(bridge).catch((error) => {
|
||||
log.error(
|
||||
'system face catalog login prewarm failed: uin=%s error=%s',
|
||||
uin,
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
+332
-256
@@ -3,10 +3,10 @@ import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
parseTotpStateLenient,
|
||||
prepareTotpStateForRestore,
|
||||
rewrapTotpSecret,
|
||||
type TotpPersistedState,
|
||||
parseTotpStateLenient,
|
||||
prepareTotpStateForRestore,
|
||||
rewrapTotpSecret,
|
||||
type TotpPersistedState,
|
||||
} from './totp';
|
||||
|
||||
const log = createLogger('WebUI.Auth');
|
||||
@@ -22,53 +22,62 @@ const SCRYPT_P = 1;
|
||||
const DEV_PASSWORD = 'snowluma-dev';
|
||||
|
||||
export function isDevAuthMode(): boolean {
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
}
|
||||
|
||||
function envBootstrapPassword(): string | null {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
if (!raw || typeof raw !== 'string') return null;
|
||||
if (raw.length < 8) return null;
|
||||
return raw;
|
||||
const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD;
|
||||
|
||||
if (!raw || typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (raw.length < 8) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return raw;
|
||||
}
|
||||
|
||||
export interface WebuiAuthState {
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
totp?: TotpPersistedState;
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
mustChangePassword: boolean;
|
||||
generatedAt: string;
|
||||
updatedAt: string;
|
||||
totp?: TotpPersistedState;
|
||||
}
|
||||
|
||||
export interface PasswordRule {
|
||||
id: string;
|
||||
label: string;
|
||||
test: (pwd: string) => boolean;
|
||||
id: string;
|
||||
label: string;
|
||||
test: (pwd: string) => boolean;
|
||||
}
|
||||
|
||||
export const PASSWORD_RULES: PasswordRule[] = [
|
||||
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
|
||||
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
|
||||
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
|
||||
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
{ id: 'length', label: '长度不少于 10 位', test: (p) => p.length >= 10 },
|
||||
{ id: 'lower', label: '包含小写字母', test: (p) => /[a-z]/.test(p) },
|
||||
{ id: 'upper', label: '包含大写字母', test: (p) => /[A-Z]/.test(p) },
|
||||
{ id: 'special', label: '包含特殊符号 (!@#$%…)', test: (p) => /[^A-Za-z0-9\s]/.test(p) },
|
||||
{ id: 'no-space', label: '不包含空格', test: (p) => !/\s/.test(p) && p.length > 0 },
|
||||
];
|
||||
|
||||
export function evaluatePasswordRules(password: string): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
export function evaluatePasswordRules(
|
||||
password: string,
|
||||
): { id: string; label: string; ok: boolean }[] {
|
||||
return PASSWORD_RULES.map((r) => ({ id: r.id, label: r.label, ok: r.test(password) }));
|
||||
}
|
||||
|
||||
export function isStrongPassword(password: string): boolean {
|
||||
return PASSWORD_RULES.every((r) => r.test(password));
|
||||
return PASSWORD_RULES.every((r) => r.test(password));
|
||||
}
|
||||
|
||||
function hashPassword(password: string, salt: Buffer): Buffer {
|
||||
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
return scryptSync(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
|
||||
}
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,265 +88,332 @@ function ensureConfigDir(): void {
|
||||
* operator would be locked out after a restore.
|
||||
*/
|
||||
export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt', 'totp']);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
if (unknown) throw new Error(`unknown field $.${unknown}`);
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('credential state must be an object');
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
|
||||
if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) {
|
||||
throw new Error('passwordHash must be exactly 128 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) {
|
||||
throw new Error('passwordSalt must be exactly 32 hexadecimal characters');
|
||||
}
|
||||
|
||||
if (typeof v.mustChangePassword !== 'boolean') {
|
||||
throw new Error('mustChangePassword must be a boolean');
|
||||
}
|
||||
|
||||
if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) {
|
||||
throw new Error('generatedAt must be a valid timestamp');
|
||||
}
|
||||
|
||||
if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) {
|
||||
throw new Error('updatedAt must be a valid timestamp');
|
||||
}
|
||||
|
||||
const allowed = new Set([
|
||||
'passwordHash',
|
||||
'passwordSalt',
|
||||
'mustChangePassword',
|
||||
'generatedAt',
|
||||
'updatedAt',
|
||||
'totp',
|
||||
]);
|
||||
const unknown = Object.keys(v).find((key) => !allowed.has(key));
|
||||
|
||||
if (unknown) {
|
||||
throw new Error(`unknown field $.${unknown}`);
|
||||
}
|
||||
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: v.passwordHash,
|
||||
passwordSalt: v.passwordSalt,
|
||||
mustChangePassword: v.mustChangePassword,
|
||||
generatedAt: v.generatedAt,
|
||||
updatedAt: v.updatedAt,
|
||||
};
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(v, 'totp') || v.totp === undefined) {
|
||||
return state;
|
||||
}
|
||||
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
state.totp = prepareTotpStateForRestore(v.totp);
|
||||
return state;
|
||||
}
|
||||
|
||||
function parseLiveAuthState(value: unknown): WebuiAuthState | null {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
try {
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp')
|
||||
? withoutTotp
|
||||
: value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn('webui.json totp field is invalid and will be ignored; password credentials are unchanged');
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
const totpValue = v.totp;
|
||||
const withoutTotp = { ...v };
|
||||
delete withoutTotp.totp;
|
||||
|
||||
try {
|
||||
const state = prepareWebuiAuthStateForRestore(
|
||||
Object.prototype.hasOwnProperty.call(v, 'totp') ? withoutTotp : value,
|
||||
);
|
||||
const totp = parseTotpStateLenient(totpValue);
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(v, 'totp') && totpValue !== undefined && !totp) {
|
||||
log.warn(
|
||||
'webui.json totp field is invalid and will be ignored; password credentials are unchanged',
|
||||
);
|
||||
}
|
||||
|
||||
if (totp) {
|
||||
state.totp = totp;
|
||||
}
|
||||
|
||||
return state;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (totp) state.totp = totp;
|
||||
return state;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function generateInitialState(initialPassword: string): WebuiAuthState {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(initialPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: true,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(initialPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: true,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
function backupCorruptConfig(): void {
|
||||
try {
|
||||
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
try {
|
||||
const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`;
|
||||
fs.renameSync(WEBUI_CONFIG_PATH, dest);
|
||||
log.warn('previous webui.json moved to %s', dest);
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to back up corrupt webui.json: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(state: WebuiAuthState): void {
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
ensureConfigDir();
|
||||
const tmp = WEBUI_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
|
||||
|
||||
try {
|
||||
fs.chmodSync(tmp, 0o600);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
fs.renameSync(tmp, WEBUI_CONFIG_PATH);
|
||||
}
|
||||
|
||||
export class WebuiAuth {
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
ensureConfigDir();
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const live = parseLiveAuthState(parsed);
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
// be lost), so rotate to a fresh CSPRNG password they can see.
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn('previous bootstrap password was never rotated; regenerated a new one');
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
return new WebuiAuth(live, null, false);
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
}
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
log.error(
|
||||
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
backupCorruptConfig();
|
||||
}
|
||||
|
||||
ensureConfigDir();
|
||||
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
const live = parseLiveAuthState(parsed);
|
||||
|
||||
if (live) {
|
||||
if (live.mustChangePassword) {
|
||||
// Previous start generated a bootstrap password but the operator
|
||||
// never completed the forced-change flow. The plaintext is gone
|
||||
// (only the hash is on disk, and the log line from last run may
|
||||
// be lost), so rotate to a fresh CSPRNG password they can see.
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
log.warn(
|
||||
'previous bootstrap password was never rotated; regenerated a new one',
|
||||
);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
return new WebuiAuth(live, null, false);
|
||||
}
|
||||
|
||||
log.error('webui.json schema invalid; backing up and regenerating credentials');
|
||||
backupCorruptConfig();
|
||||
} catch (err) {
|
||||
log.error(
|
||||
'webui.json is corrupt and will be regenerated; the previous file is backed up: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
backupCorruptConfig();
|
||||
}
|
||||
}
|
||||
|
||||
const envPassword = envBootstrapPassword();
|
||||
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
atomicWrite(state);
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
}
|
||||
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
const envPassword = envBootstrapPassword();
|
||||
if (envPassword !== null) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(envPassword, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
atomicWrite(state);
|
||||
log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD');
|
||||
return new WebuiAuth(state, null, false);
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
takeInitialPassword(): string | null {
|
||||
const p = this.initialPlain;
|
||||
this.initialPlain = null;
|
||||
return p;
|
||||
}
|
||||
|
||||
mustChangePassword(): boolean {
|
||||
return this.state.mustChangePassword;
|
||||
}
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) return false;
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
if (got.length !== expected.length) return false;
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
}
|
||||
|
||||
setPassword(newPassword: string, currentPassword?: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
takeInitialPassword(): string | null {
|
||||
const p = this.initialPlain;
|
||||
this.initialPlain = null;
|
||||
return p;
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
|
||||
mustChangePassword(): boolean {
|
||||
return this.state.mustChangePassword;
|
||||
}
|
||||
let totp = this.state.totp;
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
|
||||
verify(password: string): boolean {
|
||||
if (typeof password !== 'string' || password.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const salt = Buffer.from(this.state.passwordSalt, 'hex');
|
||||
const expected = Buffer.from(this.state.passwordHash, 'hex');
|
||||
const got = hashPassword(password, salt);
|
||||
|
||||
if (got.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return timingSafeEqual(got, expected);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
...(totp ? { totp } : {}),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
totpEnabled(): boolean {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
setPassword(newPassword: string, currentPassword?: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
|
||||
totpStatus(): { enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
if (!totp) return { enabled: false };
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
label: totp.label,
|
||||
};
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
|
||||
totpState(): TotpPersistedState | undefined {
|
||||
return this.state.totp;
|
||||
}
|
||||
let totp = this.state.totp;
|
||||
|
||||
persistTotp(totp: TotpPersistedState | undefined): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
if (totp) {
|
||||
if (typeof currentPassword !== 'string' || currentPassword.length === 0) {
|
||||
throw new Error('修改密码需要当前密码以重新保护 2FA 密钥');
|
||||
}
|
||||
|
||||
totp = rewrapTotpSecret(currentPassword, newPassword, totp);
|
||||
}
|
||||
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(newPassword, salt);
|
||||
const next: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: this.state.generatedAt,
|
||||
updatedAt: new Date().toISOString(),
|
||||
...(totp ? { totp } : {}),
|
||||
};
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
|
||||
totpEnabled(): boolean {
|
||||
return this.state.totp !== undefined;
|
||||
}
|
||||
|
||||
totpStatus():
|
||||
{ enabled: false } | { enabled: true; remainingRecoveryCodes: number; label: string } {
|
||||
const totp = this.state.totp;
|
||||
|
||||
if (!totp) {
|
||||
return { enabled: false };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: true,
|
||||
remainingRecoveryCodes: totp.recoveryCodeHashes.length,
|
||||
label: totp.label,
|
||||
};
|
||||
}
|
||||
|
||||
totpState(): TotpPersistedState | undefined {
|
||||
return this.state.totp;
|
||||
}
|
||||
|
||||
persistTotp(totp: TotpPersistedState | undefined): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用 2FA');
|
||||
}
|
||||
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
|
||||
if (totp) {
|
||||
next.totp = totp;
|
||||
} else {
|
||||
delete next.totp;
|
||||
}
|
||||
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
const next: WebuiAuthState = { ...this.state, updatedAt: new Date().toISOString() };
|
||||
if (totp) next.totp = totp;
|
||||
else delete next.totp;
|
||||
atomicWrite(next);
|
||||
this.state = next;
|
||||
}
|
||||
}
|
||||
+649
-381
File diff suppressed because it is too large.
Load diff
@@ -2,88 +2,131 @@ import { getConnInfo } from '@hono/node-server/conninfo';
|
||||
import type { Context } from 'hono';
|
||||
|
||||
export type TrustProxyMode =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'loopback' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'ip-list'; ips: Set<string> };
|
||||
| { kind: 'none' }
|
||||
| { kind: 'loopback' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'ip-list'; ips: Set<string> };
|
||||
|
||||
export function parseTrustProxy(raw: string | undefined): TrustProxyMode {
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
if (!value) return { kind: 'none' };
|
||||
if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' };
|
||||
if (value === 'loopback') return { kind: 'loopback' };
|
||||
const ips = new Set(
|
||||
value.split(',').map((s) => s.trim()).filter(Boolean),
|
||||
);
|
||||
if (ips.size === 0) return { kind: 'none' };
|
||||
return { kind: 'ip-list', ips };
|
||||
const value = raw?.trim().toLowerCase() ?? '';
|
||||
|
||||
if (!value) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
if (value === '1' || value === 'true' || value === 'all') {
|
||||
return { kind: 'all' };
|
||||
}
|
||||
|
||||
if (value === 'loopback') {
|
||||
return { kind: 'loopback' };
|
||||
}
|
||||
|
||||
const ips = new Set(
|
||||
value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
);
|
||||
|
||||
if (ips.size === 0) {
|
||||
return { kind: 'none' };
|
||||
}
|
||||
|
||||
return { kind: 'ip-list', ips };
|
||||
}
|
||||
|
||||
export function describeTrustProxy(mode: TrustProxyMode): string {
|
||||
switch (mode.kind) {
|
||||
case 'none': return 'socket peer (default)';
|
||||
case 'all': return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
switch (mode.kind) {
|
||||
case 'none':
|
||||
return 'socket peer (default)';
|
||||
case 'all':
|
||||
return 'X-Real-IP / X-Forwarded-For from any peer';
|
||||
case 'loopback':
|
||||
return 'X-Real-IP / X-Forwarded-For when socket peer is loopback';
|
||||
case 'ip-list':
|
||||
return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
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 isLoopbackClientIp(socketIp);
|
||||
case 'ip-list': return mode.ips.has(socketIp);
|
||||
}
|
||||
switch (mode.kind) {
|
||||
case 'none':
|
||||
return false;
|
||||
case 'all':
|
||||
return true;
|
||||
case 'loopback':
|
||||
return isLoopbackClientIp(socketIp);
|
||||
case 'ip-list':
|
||||
return mode.ips.has(socketIp);
|
||||
}
|
||||
}
|
||||
|
||||
export function pickClientIp(
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
fallbackIp = '127.0.0.1',
|
||||
c: Pick<Context, 'req'>,
|
||||
mode: TrustProxyMode,
|
||||
getSocketIp: () => string,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): string {
|
||||
let socketIp: string;
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
if (!socketIp) return fallbackIp;
|
||||
let socketIp: string;
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) return socketIp;
|
||||
try {
|
||||
socketIp = getSocketIp();
|
||||
} catch {
|
||||
return fallbackIp;
|
||||
}
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
if (realIp) return realIp;
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return socketIp;
|
||||
if (!socketIp) {
|
||||
return fallbackIp;
|
||||
}
|
||||
|
||||
if (!shouldTrustHeaders(mode, socketIp)) {
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
const realIp = c.req.header('x-real-ip')?.trim();
|
||||
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
const xff = c.req.header('x-forwarded-for');
|
||||
|
||||
if (xff) {
|
||||
const first = xff.split(',')[0].trim();
|
||||
|
||||
if (first) {
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
return socketIp;
|
||||
}
|
||||
|
||||
/** Convenience binding for the live server: read socket via getConnInfo. */
|
||||
export function makeClientIpResolver(
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
mode: TrustProxyMode,
|
||||
fallbackIp = '127.0.0.1',
|
||||
): (c: Context) => string {
|
||||
return (c) => pickClientIp(
|
||||
c,
|
||||
mode,
|
||||
() => getConnInfo(c).remote.address ?? fallbackIp,
|
||||
fallbackIp,
|
||||
);
|
||||
return (c) =>
|
||||
pickClientIp(c, mode, () => getConnInfo(c).remote.address ?? fallbackIp, fallbackIp);
|
||||
}
|
||||
@@ -11,138 +11,149 @@
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { createLogger, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
const log = createLogger('WebUI.Connections');
|
||||
|
||||
export interface ConnectionDiffLoopOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
getSnapshot: () => unknown;
|
||||
/** Optional projector — return the "comparable" subset of the snapshot.
|
||||
* The full snapshot is what the SSE handler ships to the WebUI; this
|
||||
* projection is what the diff loop compares between ticks. Use it to
|
||||
* strip volatile fields (e.g. HH:MM:SS timestamps embedded in adapter
|
||||
* `detail` strings) that would otherwise produce a publish every tick
|
||||
* under any active webhook — defeating the loop's whole purpose.
|
||||
* Default: identity. */
|
||||
pickComparable?: (snapshot: unknown) => unknown;
|
||||
/** Poll cadence in milliseconds; default 500. */
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
export interface ConnectionDiffLoopHandle {
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
/** Stop the loop. Subsequent snapshot mutations produce nothing. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedSnapshotThrew = false;
|
||||
let warnedProjectorThrew = false;
|
||||
const intervalMs = opts.intervalMs ?? 500;
|
||||
let lastSerialized = '';
|
||||
let haveBaseline = false;
|
||||
let disposed = false;
|
||||
// One-shot diagnostic latch: a projector that starts throwing only after
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedSnapshotThrew = false;
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
if (disposed) return;
|
||||
let snap: unknown;
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch (err) {
|
||||
if (!warnedSnapshotThrew) {
|
||||
warnedSnapshotThrew = true;
|
||||
const tick = (): void => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
let snap: unknown;
|
||||
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch (err) {
|
||||
if (!warnedSnapshotThrew) {
|
||||
warnedSnapshotThrew = true;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace('connection_diff_start phase=snapshot_read');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
|
||||
let comparable: unknown;
|
||||
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
log.error(
|
||||
'connection snapshot projector failed; updates may be stale: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start phase=project snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = JSON.stringify(comparable);
|
||||
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (serialized === lastSerialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSerialized = serialized;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace('connection_diff_start phase=snapshot_read');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => ['connection_diff_start snapshot=%s', renderParamsVerbose(snap)]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
return;
|
||||
}
|
||||
let comparable: unknown;
|
||||
try {
|
||||
comparable = opts.pickComparable ? opts.pickComparable(snap) : snap;
|
||||
} catch (err) {
|
||||
// A buggy projector must not crash the diff loop or wedge baseline.
|
||||
// But silent wedge is its own bug class — log the FIRST occurrence
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
log.error(
|
||||
'connection snapshot projector failed; updates may be stale: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start phase=project snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const serialized = JSON.stringify(comparable);
|
||||
if (!haveBaseline) {
|
||||
// First successful observation. The SSE handler's sendAllInitial
|
||||
// already shipped a `connections` frame to every connected client
|
||||
// on connect, so the baseline is what they already have — emitting
|
||||
// it again would be a duplicate. Just store it.
|
||||
lastSerialized = serialized;
|
||||
haveBaseline = true;
|
||||
return;
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
lastSerialized = serialized;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
// Don't pin the Node event loop: the loop is permanent for the server
|
||||
// lifetime by design, but tests / a future hot-reload scenario must be
|
||||
// able to exit cleanly without an outstanding interval ref. Mirrors the
|
||||
// tokenJanitor pattern in server.ts.
|
||||
timer.unref?.();
|
||||
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
return {
|
||||
dispose(): void {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
clearInterval(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,28 +1,31 @@
|
||||
import type { AccountConnections } from '@snowluma/onebot/manager';
|
||||
|
||||
export function comparableConnectionSnapshot(snapshot: unknown): unknown {
|
||||
if (!Array.isArray(snapshot)) return snapshot;
|
||||
return (snapshot as AccountConnections[]).map((account) => ({
|
||||
uin: account.uin,
|
||||
nickname: account.nickname,
|
||||
adapters: Array.isArray(account.adapters)
|
||||
? account.adapters.map((adapter) => ({
|
||||
name: adapter.name,
|
||||
kind: adapter.kind,
|
||||
status: adapter.status,
|
||||
lastErrorAt: adapter.lastErrorAt,
|
||||
}))
|
||||
: [],
|
||||
databaseMigration: account.databaseMigration
|
||||
? {
|
||||
phase: account.databaseMigration.phase,
|
||||
usable: account.databaseMigration.usable,
|
||||
processed: account.databaseMigration.processed,
|
||||
total: account.databaseMigration.total,
|
||||
progress: account.databaseMigration.progress,
|
||||
estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds,
|
||||
error: account.databaseMigration.error,
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
if (!Array.isArray(snapshot)) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
return (snapshot as AccountConnections[]).map((account) => ({
|
||||
uin: account.uin,
|
||||
nickname: account.nickname,
|
||||
adapters: Array.isArray(account.adapters)
|
||||
? account.adapters.map((adapter) => ({
|
||||
name: adapter.name,
|
||||
kind: adapter.kind,
|
||||
status: adapter.status,
|
||||
lastErrorAt: adapter.lastErrorAt,
|
||||
}))
|
||||
: [],
|
||||
databaseMigration: account.databaseMigration
|
||||
? {
|
||||
phase: account.databaseMigration.phase,
|
||||
usable: account.databaseMigration.usable,
|
||||
processed: account.databaseMigration.processed,
|
||||
total: account.databaseMigration.total,
|
||||
progress: account.databaseMigration.progress,
|
||||
estimatedRemainingSeconds: account.databaseMigration.estimatedRemainingSeconds,
|
||||
error: account.databaseMigration.error,
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
+165
-118
@@ -14,8 +14,8 @@ const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json');
|
||||
// repo-root markdown; the build copies them next to the bundle (dist/) so the
|
||||
// same lookup works in a packaged deploy. See vite.config.ts cp targets.
|
||||
const AGREEMENT_FILES = [
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
];
|
||||
|
||||
export const EULA_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_EULA';
|
||||
@@ -24,54 +24,60 @@ export const PRIVACY_ACCEPT_ENV = 'SNOWLUMA_ACCEPT_PRIVACY';
|
||||
type ConsentEnvironment = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
export interface EnvironmentConsent {
|
||||
eulaAccepted: boolean;
|
||||
privacyAccepted: boolean;
|
||||
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
|
||||
accepted: boolean;
|
||||
eulaAccepted: boolean;
|
||||
privacyAccepted: boolean;
|
||||
/** Both documents must be accepted; a partial opt-in never unlocks the gate. */
|
||||
accepted: boolean;
|
||||
}
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsentRecord {
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text,
|
||||
* environment consent is incomplete, AND the stored consent version differs
|
||||
* from the current one. A missing or unreadable agreement set fails OPEN (no
|
||||
* gate) so a broken bundle can never lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text,
|
||||
* environment consent is incomplete, AND the stored consent version differs
|
||||
* from the current one. A missing or unreadable agreement set fails OPEN (no
|
||||
* gate) so a broken bundle can never lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
function parseEnvironmentAcceptance(name: string, raw: string | undefined): boolean {
|
||||
if (raw === undefined || raw.trim() === '') return false;
|
||||
if (raw === undefined || raw.trim() === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
if (normalized === '1' || normalized === 'true') return true;
|
||||
if (normalized === '0' || normalized === 'false') return false;
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
|
||||
throw new Error(
|
||||
`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`,
|
||||
);
|
||||
if (normalized === '1' || normalized === 'true') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (normalized === '0' || normalized === 'false') {
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error(`${name} must be one of: 1, true, 0, false; received ${JSON.stringify(raw)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,15 +86,15 @@ function parseEnvironmentAcceptance(name: string, raw: string | undefined): bool
|
||||
* versioned consent gate instead of silently writing a permanent record.
|
||||
*/
|
||||
export function resolveEnvironmentConsent(
|
||||
env: ConsentEnvironment = process.env,
|
||||
env: ConsentEnvironment = process.env,
|
||||
): EnvironmentConsent {
|
||||
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
|
||||
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
|
||||
return {
|
||||
eulaAccepted,
|
||||
privacyAccepted,
|
||||
accepted: eulaAccepted && privacyAccepted,
|
||||
};
|
||||
const eulaAccepted = parseEnvironmentAcceptance(EULA_ACCEPT_ENV, env[EULA_ACCEPT_ENV]);
|
||||
const privacyAccepted = parseEnvironmentAcceptance(PRIVACY_ACCEPT_ENV, env[PRIVACY_ACCEPT_ENV]);
|
||||
return {
|
||||
eulaAccepted,
|
||||
privacyAccepted,
|
||||
accepted: eulaAccepted && privacyAccepted,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
|
||||
@@ -101,35 +107,39 @@ export function resolveEnvironmentConsent(
|
||||
* root or dist/), so we probe a handful of candidates and take the first hit.
|
||||
*/
|
||||
function resolveAgreementFile(file: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract title / declared version / effective date from a doc body. */
|
||||
export function parseAgreementMeta(text: string): {
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
} {
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,89 +149,126 @@ export function parseAgreementMeta(text: string): {
|
||||
* and changes the moment any agreement's TEXT changes (forcing re-consent).
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
const hash = createHash('sha256');
|
||||
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'failed to read %s: %s',
|
||||
file,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log.warn(
|
||||
'agreement file not found (looked for %s near the bundle and repo root)',
|
||||
file,
|
||||
);
|
||||
}
|
||||
|
||||
const meta = parseAgreementMeta(text);
|
||||
return {
|
||||
id,
|
||||
title: meta.title,
|
||||
declaredVersion: meta.declaredVersion,
|
||||
effectiveDate: meta.effectiveDate,
|
||||
text,
|
||||
};
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
// ── Consent persistence (config/consent.json, atomic) ───────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const v = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'consent.json unreadable, treating as no consent: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(record: ConsentRecord): void {
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
/** Persist that the operator accepted `version`. Returns the stored record. */
|
||||
export function recordConsent(version: string): ConsentRecord {
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** True when neither environment nor stored consent covers the current agreements. */
|
||||
export function isConsentRequired(env: ConsentEnvironment = process.env): boolean {
|
||||
if (resolveEnvironmentConsent(env).accepted) return false;
|
||||
if (resolveEnvironmentConsent(env).accepted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
return loadConsentRecord()?.version !== version;
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
|
||||
if (!hasContent) {
|
||||
return false;
|
||||
} // fail open: never brick the panel on a broken bundle
|
||||
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
/** Public payload for GET /api/agreements (texts + version + consentRequired). */
|
||||
export function getAgreementsPayload(): AgreementsPayload {
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
}
|
||||
@@ -5,24 +5,33 @@
|
||||
// handler so this (easy-to-get-wrong) logic is unit-tested.
|
||||
|
||||
export interface FramePusherOptions {
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
}
|
||||
|
||||
/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
dropped = 0;
|
||||
}
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
|
||||
if (d !== null && d <= 0) {
|
||||
dropped += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(
|
||||
encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`),
|
||||
);
|
||||
dropped = 0;
|
||||
}
|
||||
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -35,27 +35,29 @@ const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
* with no path separators or traversal. The client path is NEVER trusted for
|
||||
* placement — this is only used to keep the stored name human-readable. */
|
||||
export function safeUploadName(raw: string | undefined): string {
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
// Treat both separators as path delimiters, then take the basename so any
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
}
|
||||
|
||||
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
|
||||
* Throws if the composed path would escape the dir (defence in depth — it
|
||||
* can't, given the random id + basename, but we assert anyway). */
|
||||
export function uploadDestPath(safeName: string): string {
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
return dest;
|
||||
const id = randomBytes(12).toString('hex');
|
||||
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
|
||||
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
|
||||
|
||||
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||
throw new Error('invalid upload path');
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
|
||||
@@ -63,84 +65,126 @@ export function uploadDestPath(safeName: string): string {
|
||||
* error the partial file is removed and the call rejects. Never buffers the
|
||||
* whole body. */
|
||||
export async function streamUploadToDisk(
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
body: ReadableStream<Uint8Array> | null,
|
||||
filename: string | undefined,
|
||||
opts: { maxBytes?: number } = {},
|
||||
): Promise<{ path: string; size: number }> {
|
||||
if (!body) throw new Error('empty body');
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
|
||||
let size = 0;
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
if (!body) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
|
||||
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
|
||||
void sweepOldUploads(); // fire-and-forget TTL cleanup
|
||||
|
||||
const dest = uploadDestPath(safeUploadName(filename));
|
||||
const out = createWriteStream(dest, { mode: 0o600 });
|
||||
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
|
||||
// background flush — typically while we're parked at reader.read() or waiting
|
||||
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
|
||||
// backpressured error would leave 'drain' to never fire (a forever-hung await
|
||||
// + leaked fd). So turn it into a rejection and race it into every await; the
|
||||
// catch below then destroys + unlinks the partial.
|
||||
const errored = new Promise<never>((_, rej) => out.once('error', rej));
|
||||
errored.catch(() => {
|
||||
/* swallow a late error after success (still raced below) */
|
||||
});
|
||||
let size = 0;
|
||||
|
||||
try {
|
||||
const reader = body.getReader();
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (!value || value.byteLength === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
|
||||
if (size > maxBytes) {
|
||||
throw new Error('上传超出大小上限');
|
||||
}
|
||||
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.race([
|
||||
errored,
|
||||
new Promise<void>((res, rej) =>
|
||||
out.end((err?: Error | null) => (err ? rej(err) : res())),
|
||||
),
|
||||
]);
|
||||
|
||||
if (size === 0) {
|
||||
throw new Error('empty body');
|
||||
}
|
||||
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
|
||||
if (!out.closed) {
|
||||
await new Promise<void>((res) => out.once('close', () => res()));
|
||||
}
|
||||
|
||||
await rm(dest, { force: true }).catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
|
||||
if (size === 0) throw new Error('empty body');
|
||||
return { path: dest, size };
|
||||
} catch (err) {
|
||||
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
|
||||
// opens the fd asynchronously, so a fast failure can reach `rm` before the
|
||||
// file even exists on disk — then the late open would re-create it and leak
|
||||
// the partial. 'close' guarantees the fd is settled and no more writes land.
|
||||
out.destroy();
|
||||
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
|
||||
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
|
||||
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
try {
|
||||
const s = await stat(p);
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* racing cleanup / vanished file */ }
|
||||
}),
|
||||
);
|
||||
} catch { /* dir absent yet */ }
|
||||
return removed;
|
||||
let removed = 0;
|
||||
|
||||
try {
|
||||
const names = await readdir(DEBUG_UPLOAD_DIR);
|
||||
await Promise.all(
|
||||
names.map(async (n) => {
|
||||
const p = path.join(DEBUG_UPLOAD_DIR, n);
|
||||
|
||||
try {
|
||||
const s = await stat(p);
|
||||
|
||||
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
|
||||
await rm(p, { force: true, recursive: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch {
|
||||
/* racing cleanup / vanished file */
|
||||
}
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* dir absent yet */
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Drives a stream-capable action and relays its frames. The driver is the
|
||||
* instance's `invokeStream` (which itself handles non-stream actions by emitting
|
||||
* a single frame). */
|
||||
export type StreamInvokeDriver = (
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
rawRequest: string,
|
||||
emit: (json: string) => Promise<void>,
|
||||
isAlive: () => boolean,
|
||||
) => Promise<void>;
|
||||
|
||||
/** How long emit() will wait for a backed-up consumer to drain before it gives
|
||||
@@ -154,47 +198,75 @@ const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
|
||||
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
|
||||
* delivery. `delay` is injectable for tests. */
|
||||
export function buildStreamInvokeResponse(
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
driver: StreamInvokeDriver,
|
||||
rawRequest: string,
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
): Response {
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
const onAbort = () => { closed = true; };
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
if (!isAlive()) throw new Error('stream transport closed');
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
const onAbort = () => {
|
||||
closed = true;
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
try {
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
|
||||
} catch { /* controller already torn down */ }
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
try { controller.close(); } catch { /* already closed */ }
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
|
||||
try {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
/* controller already torn down */
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,27 +1,40 @@
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
export type ListenerExposureCheck =
|
||||
| { ok: true }
|
||||
| { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
{ ok: true } | { ok: false; code: 'invalid-bind-host' | 'tls-pair-required' };
|
||||
|
||||
/** TCP bind-host accepted by WebUI Listener Exposure (settings, restore, boot). */
|
||||
export function isValidBindHost(value: string): boolean {
|
||||
const host = value.trim();
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false;
|
||||
if (host.includes(':')) return isIP(host) === 6;
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
const host = value.trim();
|
||||
|
||||
if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (host.includes(':')) {
|
||||
return isIP(host) === 6;
|
||||
}
|
||||
|
||||
if (/^[\d.]+$/.test(host)) {
|
||||
return isIP(host) === 4;
|
||||
}
|
||||
|
||||
const normalized = host.endsWith('.') ? host.slice(0, -1) : host;
|
||||
return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/.test(label));
|
||||
}
|
||||
|
||||
export function checkListenerExposure(input: {
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
pairOk: boolean;
|
||||
}): ListenerExposureCheck {
|
||||
if (!isValidBindHost(input.webuiHost)) return { ok: false, code: 'invalid-bind-host' };
|
||||
if (input.tlsEnabled && !input.pairOk) return { ok: false, code: 'tls-pair-required' };
|
||||
return { ok: true };
|
||||
if (!isValidBindHost(input.webuiHost)) {
|
||||
return { ok: false, code: 'invalid-bind-host' };
|
||||
}
|
||||
|
||||
if (input.tlsEnabled && !input.pairOk) {
|
||||
return { ok: false, code: 'tls-pair-required' };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -1,69 +1,68 @@
|
||||
import type { LogEntry } from '@snowluma/common/logger';
|
||||
|
||||
export interface FullTraceExportMetadata {
|
||||
version: string;
|
||||
operatingSystem: string;
|
||||
architecture: string;
|
||||
nodeVersion: string;
|
||||
logLevel: LogEntry['level'];
|
||||
exportedAt: string;
|
||||
version: string;
|
||||
operatingSystem: string;
|
||||
architecture: string;
|
||||
nodeVersion: string;
|
||||
logLevel: LogEntry['level'];
|
||||
exportedAt: string;
|
||||
}
|
||||
|
||||
const PRIVACY_WARNING = 'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
const PRIVACY_WARNING =
|
||||
'WARNING: This export may contain unredacted private data and credentials. Sanitize it before submission.';
|
||||
|
||||
export interface FullTraceDownload {
|
||||
body: string;
|
||||
headers: {
|
||||
'Content-Type': string;
|
||||
'Content-Disposition': string;
|
||||
'Cache-Control': string;
|
||||
};
|
||||
body: string;
|
||||
headers: {
|
||||
'Content-Type': string;
|
||||
'Content-Disposition': string;
|
||||
'Cache-Control': string;
|
||||
};
|
||||
}
|
||||
|
||||
export function buildFullTraceDownload(
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
): FullTraceDownload {
|
||||
const timestamp = metadata.exportedAt
|
||||
.slice(0, 19)
|
||||
.replace(/[:.]/g, '-');
|
||||
return {
|
||||
body: formatFullTraceExport(entries, metadata),
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="snowluma-trace-${timestamp}.log"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
};
|
||||
const timestamp = metadata.exportedAt.slice(0, 19).replace(/[:.]/g, '-');
|
||||
return {
|
||||
body: formatFullTraceExport(entries, metadata),
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="snowluma-trace-${timestamp}.log"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFullTraceExport(
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
entries: readonly LogEntry[],
|
||||
metadata: FullTraceExportMetadata,
|
||||
): string {
|
||||
const lines = [
|
||||
'SnowLuma full TRACE export',
|
||||
'==========================',
|
||||
`SnowLuma version: ${metadata.version}`,
|
||||
`Operating system: ${metadata.operatingSystem}`,
|
||||
`Architecture: ${metadata.architecture}`,
|
||||
`Node.js version: ${metadata.nodeVersion}`,
|
||||
`Current log level: ${metadata.logLevel.toUpperCase()}`,
|
||||
`Export time: ${metadata.exportedAt}`,
|
||||
`Retained records: ${entries.length}`,
|
||||
'',
|
||||
PRIVACY_WARNING,
|
||||
'This is a snapshot of the normal and TRACE records still retained in memory; records already evicted cannot be recovered.',
|
||||
'',
|
||||
'Logs',
|
||||
'----',
|
||||
];
|
||||
const lines = [
|
||||
'SnowLuma full TRACE export',
|
||||
'==========================',
|
||||
`SnowLuma version: ${metadata.version}`,
|
||||
`Operating system: ${metadata.operatingSystem}`,
|
||||
`Architecture: ${metadata.architecture}`,
|
||||
`Node.js version: ${metadata.nodeVersion}`,
|
||||
`Current log level: ${metadata.logLevel.toUpperCase()}`,
|
||||
`Export time: ${metadata.exportedAt}`,
|
||||
`Retained records: ${entries.length}`,
|
||||
'',
|
||||
PRIVACY_WARNING,
|
||||
'This is a snapshot of the normal and TRACE records still retained in memory; records already evicted cannot be recovered.',
|
||||
'',
|
||||
'Logs',
|
||||
'----',
|
||||
];
|
||||
|
||||
if (entries.length === 0) {
|
||||
lines.push('(No log records are currently retained.)');
|
||||
} else {
|
||||
lines.push(...entries.map((entry) => entry.line));
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
lines.push('(No log records are currently retained.)');
|
||||
} else {
|
||||
lines.push(...entries.map((entry) => entry.line));
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
Loaded 100 of 977 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user