This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+18 -18
View File
@@ -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
+372 -281
View File
@@ -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
+100 -86
View File
@@ -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));
}
}
+314 -262
View File
@@ -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);
});
});
});
}
+56 -56
View File
@@ -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';
+49 -40
View File
@@ -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 });
}
}
File diff suppressed because it is too large. Load diff
+95 -73
View File
@@ -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;
}
}
+264 -208
View File
@@ -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();
}
+124 -107
View File
@@ -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);
}
}
+35 -30
View File
@@ -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;
}
+23 -22
View File
@@ -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);
}
}
+408 -340
View File
@@ -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());
}
}
+1 -2
View File
@@ -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';
+11 -11
View File
@@ -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;
}
File diff suppressed because it is too large. Load diff
+357 -334
View File
@@ -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
View File
@@ -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);
});
}
+303 -205
View File
@@ -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);
},
};
}
+353 -224
View File
@@ -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;
}
+68 -54
View File
@@ -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);
}
}
+308 -235
View File
@@ -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(),
});
}
+377 -278
View File
@@ -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');
}
+23 -21
View File
@@ -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
View File
@@ -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;
}
}
File diff suppressed because it is too large. Load diff
+105 -62
View File
@@ -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);
}
+128 -117
View File
@@ -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);
},
};
}
+27 -24
View File
@@ -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
View File
@@ -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 };
}
+25 -16
View File
@@ -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`));
};
}
+193 -121
View File
@@ -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',
},
});
}
+29 -16
View File
@@ -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 };
}
+50 -51
View File
@@ -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`;
}
+296 -237
View File
@@ -1,11 +1,11 @@
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import {
createLogger,
currentRequestId,
getLogLevel,
renderTraceBytes,
runWithRequestId,
runWithTraceRequest,
createLogger,
currentRequestId,
getLogLevel,
renderTraceBytes,
runWithRequestId,
runWithTraceRequest,
} from '@snowluma/common/logger';
const log = createLogger('WebUI.Mutation');
@@ -14,284 +14,343 @@ const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']);
const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']);
// This route can disable TRACE while its own operation is in flight; its
// existing WebUI info record is the authoritative result.
const TRACE_EXCLUDED_PATHS = new Set([
'/api/auth/check-strength',
'/api/logs/level',
]);
const TRACE_EXCLUDED_PATHS = new Set(['/api/auth/check-strength', '/api/logs/level']);
interface CapturedBody {
bytes: Uint8Array;
text: string;
bytes: Uint8Array;
text: string;
}
function shouldTraceMutation(request: Request): boolean {
if (getLogLevel() !== 'trace') return false;
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false;
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
if (getLogLevel() !== 'trace') {
return false;
}
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) {
return false;
}
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
}
async function captureBody(message: Request | Response): Promise<CapturedBody> {
const bytes = new Uint8Array(await message.arrayBuffer());
return {
bytes,
text: new TextDecoder().decode(bytes),
};
const bytes = new Uint8Array(await message.arrayBuffer());
return {
bytes,
text: new TextDecoder().decode(bytes),
};
}
function traceBody(
branch: 'request_body' | 'response',
body: CapturedBody,
response?: Response,
branch: 'request_body' | 'response',
body: CapturedBody,
response?: Response,
): void {
log.trace(() => [
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
branch,
response
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
: '',
body.bytes.byteLength,
body.text,
renderTraceBytes(body.bytes),
]);
log.trace(() => [
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
branch,
response
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
: '',
body.bytes.byteLength,
body.text,
renderTraceBytes(body.bytes),
]);
}
function traceStreamChunk(
branch: 'request_body_chunk' | 'response_chunk',
chunk: Uint8Array,
offset: number,
branch: 'request_body_chunk' | 'response_chunk',
chunk: Uint8Array,
offset: number,
): void {
log.trace(() => [
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
branch,
offset,
chunk.byteLength,
renderTraceBytes(chunk),
]);
log.trace(() => [
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
branch,
offset,
chunk.byteLength,
renderTraceBytes(chunk),
]);
}
export function traceWebuiMutationRequestChunk(chunk: Uint8Array, offset: number): void {
traceStreamChunk('request_body_chunk', chunk, offset);
traceStreamChunk('request_body_chunk', chunk, offset);
}
function traceStreamedResponse(
response: Response,
requestBody: Promise<CapturedBody> | null,
startedAt: number,
response: Response,
requestBody: Promise<CapturedBody> | null,
startedAt: number,
): Response {
if (!response.body) {
void settleMutation(
requestBody,
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
response,
startedAt,
false,
);
return response;
}
if (!response.body) {
void settleMutation(
requestBody,
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
response,
startedAt,
false,
);
return response;
}
const reader = response.body.getReader();
const requestId = currentRequestId();
const inContext = <T>(fn: () => T): T => requestId === undefined
? fn()
: runWithRequestId(requestId, fn);
let offset = 0;
let settled = false;
const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => {
if (settled) return;
settled = true;
void inContext(() => traceRequestBody(requestBody)).then(() => {
inContext(() => log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
outcome,
reason,
response.status,
error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
Date.now() - startedAt,
));
});
};
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const result = await reader.read();
if (result.done) {
terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status');
controller.close();
return;
const reader = response.body.getReader();
const requestId = currentRequestId();
const inContext = <T>(fn: () => T): T =>
requestId === undefined ? fn() : runWithRequestId(requestId, fn);
let offset = 0;
let settled = false;
const terminal = (
outcome: 'completed' | 'failed' | 'cancelled',
reason: string,
error?: unknown,
) => {
if (settled) {
return;
}
const chunk = result.value;
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
offset += chunk.byteLength;
controller.enqueue(chunk);
} catch (error) {
terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error);
controller.error(error);
}
},
async cancel(reason) {
terminal('cancelled', 'body_cancelled', reason);
await reader.cancel(reason);
},
}, { highWaterMark: 0 });
return new Response(body, response);
settled = true;
void inContext(() => traceRequestBody(requestBody)).then(() => {
inContext(() =>
log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
outcome,
reason,
response.status,
error === undefined
? ''
: ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
Date.now() - startedAt,
),
);
});
};
const body = new ReadableStream<Uint8Array>(
{
async pull(controller) {
try {
const result = await reader.read();
if (result.done) {
terminal(
response.ok ? 'completed' : 'failed',
response.ok ? 'response_completed' : 'http_status',
);
controller.close();
return;
}
const chunk = result.value;
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
offset += chunk.byteLength;
controller.enqueue(chunk);
} catch (error) {
terminal(
error instanceof Error && error.name === 'AbortError'
? 'cancelled'
: 'failed',
error instanceof Error && error.name === 'AbortError'
? 'body_cancelled'
: 'body_read_failed',
error,
);
controller.error(error);
}
},
async cancel(reason) {
terminal('cancelled', 'body_cancelled', reason);
await reader.cancel(reason);
},
},
{ highWaterMark: 0 },
);
return new Response(body, response);
}
async function traceRequestBody(requestBody: Promise<CapturedBody> | null): Promise<void> {
if (!requestBody) return;
try {
traceBody('request_body', await requestBody);
} catch (error) {
log.trace(
'webui_mutation_branch branch=request_body_failed error=%j',
error instanceof Error ? error.message : String(error),
);
}
if (!requestBody) {
return;
}
try {
traceBody('request_body', await requestBody);
} catch (error) {
log.trace(
'webui_mutation_branch branch=request_body_failed error=%j',
error instanceof Error ? error.message : String(error),
);
}
}
async function settleMutation(
requestBody: Promise<CapturedBody> | null,
responseBody: Promise<CapturedBody>,
response: Response,
startedAt: number,
requestCancelled: boolean,
requestBody: Promise<CapturedBody> | null,
responseBody: Promise<CapturedBody>,
response: Response,
startedAt: number,
requestCancelled: boolean,
): Promise<void> {
const results = await Promise.allSettled([
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
responseBody,
]);
const [requestResult, responseResult] = results;
if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value);
if (requestBody && requestResult.status === 'rejected') {
log.trace('webui_mutation_branch branch=request_body_failed error=%j',
requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason));
}
if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response);
else {
log.trace(() => [
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
response.status,
response.statusText,
renderParamsVerbose([...response.headers.entries()]),
responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason),
const results = await Promise.allSettled([
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
responseBody,
]);
}
const error = responseResult.status === 'rejected'
? responseResult.reason
: requestResult.status === 'rejected'
? requestResult.reason
: undefined;
if (error === undefined) {
if (requestCancelled) {
log.trace(
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
response.status,
Date.now() - startedAt,
);
return;
const [requestResult, responseResult] = results;
if (requestBody && requestResult.status === 'fulfilled') {
traceBody('request_body', requestResult.value);
}
if (requestBody && requestResult.status === 'rejected') {
log.trace(
'webui_mutation_branch branch=request_body_failed error=%j',
requestResult.reason instanceof Error
? requestResult.reason.message
: String(requestResult.reason),
);
}
if (responseResult.status === 'fulfilled') {
traceBody('response', responseResult.value, response);
} else {
log.trace(() => [
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
response.status,
response.statusText,
renderParamsVerbose([...response.headers.entries()]),
responseResult.reason instanceof Error
? responseResult.reason.message
: String(responseResult.reason),
]);
}
const error =
responseResult.status === 'rejected'
? responseResult.reason
: requestResult.status === 'rejected'
? requestResult.reason
: undefined;
if (error === undefined) {
if (requestCancelled) {
log.trace(
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
response.status,
Date.now() - startedAt,
);
return;
}
log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
response.ok ? 'completed' : 'failed',
response.ok ? 'response_completed' : 'http_status',
response.status,
Date.now() - startedAt,
);
return;
}
log.trace(
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
response.ok ? 'completed' : 'failed',
response.ok ? 'response_completed' : 'http_status',
response.status,
Date.now() - startedAt,
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
error instanceof Error && error.name === 'AbortError'
? 'body_cancelled'
: 'body_read_failed',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
return;
}
log.trace(
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
}
function failureOutcome(error: unknown): {
outcome: 'failed' | 'timeout' | 'cancelled';
reason: string;
outcome: 'failed' | 'timeout' | 'cancelled';
reason: string;
} {
if (error instanceof Error && error.name === 'TimeoutError') {
return { outcome: 'timeout', reason: 'handler_timeout' };
}
if (error instanceof Error && error.name === 'AbortError') {
return { outcome: 'cancelled', reason: 'handler_cancelled' };
}
return { outcome: 'failed', reason: 'handler_threw' };
if (error instanceof Error && error.name === 'TimeoutError') {
return { outcome: 'timeout', reason: 'handler_timeout' };
}
if (error instanceof Error && error.name === 'AbortError') {
return { outcome: 'cancelled', reason: 'handler_cancelled' };
}
return { outcome: 'failed', reason: 'handler_threw' };
}
/** Trace one authenticated WebUI write without consuming its live streams. */
export function traceAuthenticatedWebuiMutation(
request: Request,
next: () => Promise<Response>,
request: Request,
next: () => Promise<Response>,
): Promise<Response> {
if (!shouldTraceMutation(request)) return next();
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const requestHeaders = [...request.headers.entries()];
const pathname = new URL(request.url).pathname;
let requestBody: Promise<CapturedBody> | null = null;
log.trace(() => [
'webui_mutation_start method=%j url=%j headers=%s',
request.method,
request.url,
renderParamsVerbose(requestHeaders),
]);
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
try {
requestBody = captureBody(request.clone());
} catch (error) {
log.trace(
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
if (!shouldTraceMutation(request)) {
return next();
}
}
try {
const response = await next();
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
return traceStreamedResponse(response, requestBody, startedAt);
}
let responseBody: Promise<CapturedBody>;
try {
responseBody = captureBody(response.clone());
} catch (error) {
void traceRequestBody(requestBody).then(() => {
log.trace(
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
});
return response;
}
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const requestHeaders = [...request.headers.entries()];
const pathname = new URL(request.url).pathname;
let requestBody: Promise<CapturedBody> | null = null;
void settleMutation(
requestBody,
responseBody,
response,
startedAt,
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
);
return response;
} catch (error) {
await traceRequestBody(requestBody);
const failure = failureOutcome(error);
log.trace(
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
failure.outcome,
failure.reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
log.trace(() => [
'webui_mutation_start method=%j url=%j headers=%s',
request.method,
request.url,
renderParamsVerbose(requestHeaders),
]);
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
try {
requestBody = captureBody(request.clone());
} catch (error) {
log.trace(
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
return next();
}
}
try {
const response = await next();
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
return traceStreamedResponse(response, requestBody, startedAt);
}
let responseBody: Promise<CapturedBody>;
try {
responseBody = captureBody(response.clone());
} catch (error) {
void traceRequestBody(requestBody).then(() => {
log.trace(
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
});
return response;
}
void settleMutation(
requestBody,
responseBody,
response,
startedAt,
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
);
return response;
} catch (error) {
await traceRequestBody(requestBody);
const failure = failureOutcome(error);
log.trace(
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
failure.outcome,
failure.reason,
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
);
throw error;
}
});
}
+87 -61
View File
@@ -3,22 +3,34 @@ import type { OneBotConfig } from '@snowluma/onebot/types';
import { isLoopbackClientIp } from './client-ip';
function isLoopbackBindHost(host: string | undefined): boolean {
const value = host?.trim().toLowerCase().replace(/^\[|\]$/gu, '').replace(/\.$/u, '') ?? '';
if (!value) return false;
if (value === 'localhost' || value.endsWith('.localhost')) return true;
return isLoopbackClientIp(value);
const value =
host
?.trim()
.toLowerCase()
.replace(/^\[|\]$/gu, '')
.replace(/\.$/u, '') ?? '';
if (!value) {
return false;
}
if (value === 'localhost' || value.endsWith('.localhost')) {
return true;
}
return isLoopbackClientIp(value);
}
export class OneBotAccessTokenPolicyError extends Error {
constructor(message: string) {
super(message);
this.name = 'OneBotAccessTokenPolicyError';
}
constructor(message: string) {
super(message);
this.name = 'OneBotAccessTokenPolicyError';
}
}
export interface OneBotAccessTokenPolicyOptions {
clientIp: string;
uin: string;
clientIp: string;
uin: string;
}
type InboundKind = 'httpServers' | 'wsServers';
@@ -26,63 +38,77 @@ type InboundKind = 'httpServers' | 'wsServers';
const INBOUND_KINDS: readonly InboundKind[] = ['httpServers', 'wsServers'];
function sameTokenAtPreviousIdentity(
previous: OneBotConfig['networks'][InboundKind],
next: OneBotConfig['networks'][InboundKind],
nextName: string,
nextToken: string,
index: number,
previous: OneBotConfig['networks'][InboundKind],
next: OneBotConfig['networks'][InboundKind],
nextName: string,
nextToken: string,
index: number,
): boolean {
const named = previous.find((adapter) => adapter.name === nextName);
if (named && (named.accessToken ?? '') === nextToken) return true;
// Preserve a legacy token when the operator only renames the same list item.
// Reordering keeps names stable and is covered by the lookup above.
const sameIndex = previous[index];
return sameIndex !== undefined
&& !next.some((adapter) => adapter.name === sameIndex.name)
&& (sameIndex.accessToken ?? '') === nextToken;
const named = previous.find((adapter) => adapter.name === nextName);
if (named && (named.accessToken ?? '') === nextToken) {
return true;
}
// Preserve a legacy token when the operator only renames the same list item.
// Reordering keeps names stable and is covered by the lookup above.
const sameIndex = previous[index];
return (
sameIndex !== undefined &&
!next.some((adapter) => adapter.name === sameIndex.name) &&
(sameIndex.accessToken ?? '') === nextToken
);
}
export function validateOneBotAccessTokenChanges(
previous: OneBotConfig | null,
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
previous: OneBotConfig | null,
next: OneBotConfig,
options: OneBotAccessTokenPolicyOptions,
): void {
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
for (let index = 0; index < nextList.length; index += 1) {
const adapter = nextList[index];
const token = adapter.accessToken ?? '';
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) continue;
const allowEmptyFromClient = isLoopbackClientIp(options.clientIp);
if (!token) {
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
);
for (const kind of INBOUND_KINDS) {
const previousList = previous?.networks[kind] ?? [];
const nextList = next.networks[kind];
for (let index = 0; index < nextList.length; index += 1) {
const adapter = nextList[index];
const token = adapter.accessToken ?? '';
if (sameTokenAtPreviousIdentity(previousList, nextList, adapter.name, token, index)) {
continue;
}
if (!token) {
if (!allowEmptyFromClient && !isLoopbackBindHost(adapter.host)) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”未绑定本机地址,远程保存必须填写令牌;请生成令牌或将主机改为 127.0.0.1。`,
);
}
continue;
}
const host = adapter.host ?? '0.0.0.0';
const assessment = assessAccessToken(token, [
options.uin,
adapter.name,
kind,
host,
adapter.port,
]);
if (assessment.reason === 'too-short') {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
);
}
if (!assessment.acceptable) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
);
}
}
continue;
}
const host = adapter.host ?? '0.0.0.0';
const assessment = assessAccessToken(token, [
options.uin,
adapter.name,
kind,
host,
adapter.port,
]);
if (assessment.reason === 'too-short') {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌至少需要 16 个字符;请重新生成或继续补充。`,
);
}
if (!assessment.acceptable) {
throw new OneBotAccessTokenPolicyError(
`节点“${adapter.name}”的令牌容易被猜中;请重新生成随机令牌。`,
);
}
}
}
}
+45 -30
View File
@@ -1,26 +1,33 @@
import net from 'net';
function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
const finalize = (ok: boolean) => {
if (settled) return;
settled = true;
try {
server.close(() => resolve(ok));
} catch {
resolve(ok);
}
};
server.once('error', () => finalize(false));
server.once('listening', () => finalize(true));
try {
server.listen(port, host);
} catch {
finalize(false);
}
});
return new Promise((resolve) => {
const server = net.createServer();
let settled = false;
const finalize = (ok: boolean) => {
if (settled) {
return;
}
settled = true;
try {
server.close(() => resolve(ok));
} catch {
resolve(ok);
}
};
server.once('error', () => finalize(false));
server.once('listening', () => finalize(true));
try {
server.listen(port, host);
} catch {
finalize(false);
}
});
}
/**
@@ -28,15 +35,23 @@ function isPortAvailable(port: number, host = '127.0.0.1'): Promise<boolean> {
* Skips reserved/invalid port numbers.
*/
export async function findAvailablePort(
start: number,
options: { maxTries?: number; host?: string } = {},
start: number,
options: { maxTries?: number; host?: string } = {},
): Promise<number> {
const { maxTries = 50, host = '127.0.0.1' } = options;
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) break;
if (await isPortAvailable(port, host)) return port;
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
const { maxTries = 50, host = '127.0.0.1' } = options;
let port = Math.max(1, Math.min(65535, Math.trunc(start)));
for (let i = 0; i < maxTries; i++) {
if (port > 65535) {
break;
}
if (await isPortAvailable(port, host)) {
return port;
}
port += 1;
}
throw new Error(`No available TCP port found near ${start}`);
}
+36 -32
View File
@@ -7,59 +7,63 @@ const AVATAR_SESSION_COOKIE = 'snowluma_avatar_session';
const AVATAR_SESSION_MAX_AGE_SECONDS = 24 * 60 * 60;
function isJsonMediaType(value: string | undefined): boolean {
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
return mediaType === 'application/json' || mediaType.endsWith('+json');
const mediaType = value?.split(';', 1)[0]?.trim().toLowerCase() ?? '';
return mediaType === 'application/json' || mediaType.endsWith('+json');
}
/** Install guards before the login route is registered. */
export function registerLoginRequestSecurity(app: Hono): void {
app.use('/api/login', bodyLimit({
maxSize: LOGIN_BODY_LIMIT_BYTES,
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
}));
app.use('/api/login', async (c, next) => {
if (!isJsonMediaType(c.req.header('content-type'))) {
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
}
return next();
});
app.use(
'/api/login',
bodyLimit({
maxSize: LOGIN_BODY_LIMIT_BYTES,
onError: (c) => c.json({ success: false, message: '请求体过大' }, 413),
}),
);
app.use('/api/login', async (c, next) => {
if (!isJsonMediaType(c.req.header('content-type'))) {
return c.json({ success: false, message: 'Content-Type 必须为 application/json' }, 415);
}
return next();
});
}
/** Minimal response policy that does not restrict the current script/style bundle. */
export const webuiSecurityHeaders: MiddlewareHandler = async (c, next) => {
await next();
c.res.headers.set('X-Frame-Options', 'DENY');
c.res.headers.set('X-Content-Type-Options', 'nosniff');
c.res.headers.set('Referrer-Policy', 'no-referrer');
c.res.headers.set(
'Content-Security-Policy',
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
);
await next();
c.res.headers.set('X-Frame-Options', 'DENY');
c.res.headers.set('X-Content-Type-Options', 'nosniff');
c.res.headers.set('Referrer-Policy', 'no-referrer');
c.res.headers.set(
'Content-Security-Policy',
"frame-ancestors 'none'; base-uri 'self'; object-src 'none'",
);
};
export function extractBearerToken(request: Request): string {
const authorization = request.headers.get('authorization');
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
const authorization = request.headers.get('authorization');
return authorization?.startsWith('Bearer ') ? authorization.slice(7) : '';
}
const avatarCookieOptions = (secure: boolean) => ({
httpOnly: true,
sameSite: 'Strict' as const,
secure,
path: '/avatar',
httpOnly: true,
sameSite: 'Strict' as const,
secure,
path: '/avatar',
});
export function setAvatarSessionCookie(c: Context, token: string, secure: boolean): void {
setCookie(c, AVATAR_SESSION_COOKIE, token, {
...avatarCookieOptions(secure),
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
});
setCookie(c, AVATAR_SESSION_COOKIE, token, {
...avatarCookieOptions(secure),
maxAge: AVATAR_SESSION_MAX_AGE_SECONDS,
});
}
export function clearAvatarSessionCookie(c: Context, secure: boolean): void {
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
deleteCookie(c, AVATAR_SESSION_COOKIE, avatarCookieOptions(secure));
}
export function readAvatarSessionToken(c: Context): string {
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
return getCookie(c, AVATAR_SESSION_COOKIE) ?? '';
}
+374 -320
View File
@@ -2,78 +2,74 @@ import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import {
prepareRestorePlan,
RestorePreflightError,
type RestoreMigration,
} from './backup';
import { prepareRestorePlan, RestorePreflightError, type RestoreMigration } from './backup';
const log = createLogger('WebUI.Restore');
export type RestorePhase = 'preflight' | 'snapshot' | 'stage' | 'commit' | 'rollback' | 'cleanup';
export interface RestoreOperation {
phase: Exclude<RestorePhase, 'preflight'>;
operation:
| 'copy-current'
| 'write-staged'
| 'chmod-staged'
| 'rename-staged'
| 'restore-current'
| 'remove-created'
| 'remove-transaction';
file?: string;
phase: Exclude<RestorePhase, 'preflight'>;
operation:
| 'copy-current'
| 'write-staged'
| 'chmod-staged'
| 'rename-staged'
| 'restore-current'
| 'remove-created'
| 'remove-transaction';
file?: string;
}
export interface RestoreBackupOptions {
configDir: string;
restoreCredentials: boolean;
/** Deterministic id for tests/diagnostics; production normally omits it. */
transactionId?: string;
/** Filesystem-boundary fault hook used by the transaction fault matrix. */
beforeOperation?: (operation: RestoreOperation) => void;
configDir: string;
restoreCredentials: boolean;
/** Deterministic id for tests/diagnostics; production normally omits it. */
transactionId?: string;
/** Filesystem-boundary fault hook used by the transaction fault matrix. */
beforeOperation?: (operation: RestoreOperation) => void;
}
export interface RestoreBackupResult {
transactionId: string;
restored: string[];
skipped: string[];
migrated: RestoreMigration[];
restartRequiredToApply: boolean;
transactionId: string;
restored: string[];
skipped: string[];
migrated: RestoreMigration[];
restartRequiredToApply: boolean;
}
export class RestoreTransactionError extends Error {
readonly phase: RestorePhase;
readonly transactionId: string;
readonly rollbackSucceeded?: boolean;
readonly snapshotDir?: string;
readonly committed: boolean;
readonly failedFiles: string[];
readonly phase: RestorePhase;
readonly transactionId: string;
readonly rollbackSucceeded?: boolean;
readonly snapshotDir?: string;
readonly committed: boolean;
readonly failedFiles: string[];
constructor(options: {
phase: RestorePhase;
transactionId: string;
message: string;
cause: unknown;
rollbackSucceeded?: boolean;
snapshotDir?: string;
committed?: boolean;
failedFiles?: string[];
}) {
super(options.message, { cause: options.cause });
this.name = 'RestoreTransactionError';
this.phase = options.phase;
this.transactionId = options.transactionId;
this.rollbackSucceeded = options.rollbackSucceeded;
this.snapshotDir = options.snapshotDir;
this.committed = options.committed ?? false;
this.failedFiles = options.failedFiles ?? [];
}
constructor(options: {
phase: RestorePhase;
transactionId: string;
message: string;
cause: unknown;
rollbackSucceeded?: boolean;
snapshotDir?: string;
committed?: boolean;
failedFiles?: string[];
}) {
super(options.message, { cause: options.cause });
this.name = 'RestoreTransactionError';
this.phase = options.phase;
this.transactionId = options.transactionId;
this.rollbackSucceeded = options.rollbackSucceeded;
this.snapshotDir = options.snapshotDir;
this.committed = options.committed ?? false;
this.failedFiles = options.failedFiles ?? [];
}
}
interface CommittedFile {
name: string;
existed: boolean;
name: string;
existed: boolean;
}
/**
@@ -85,307 +81,365 @@ interface CommittedFile {
* rollback retains the transaction directory and reports its recovery path.
*/
export function restoreBackup(parsed: unknown, options: RestoreBackupOptions): RestoreBackupResult {
const transactionId = options.transactionId ?? randomUUID();
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
}
const configDir = path.resolve(options.configDir);
const readCurrent = (name: string): Buffer | null => {
const file = path.join(configDir, name);
try {
return fs.readFileSync(file);
} catch (error) {
if (isMissingPathError(error)) return null;
throw error;
}
};
const listCurrentOneBotNames = (): string[] => {
try {
return fs.readdirSync(configDir);
} catch (error) {
if (isMissingPathError(error)) return [];
throw error;
}
};
const transactionId = options.transactionId ?? randomUUID();
log.info('restore transaction=%s phase=preflight', transactionId);
let prepared: ReturnType<typeof prepareRestorePlan>;
try {
prepared = prepareRestorePlan(parsed, {
restoreCredentials: options.restoreCredentials,
readCurrent,
listCurrentOneBotNames,
});
} catch (error) {
const file = error instanceof RestorePreflightError ? error.file : undefined;
log.warn(
'restore transaction=%s phase=preflight file=%s failed error=%s',
transactionId,
file ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase: 'preflight',
transactionId,
message: `restore preflight failed: ${errorMessage(error)}`,
cause: error,
failedFiles: file ? [file] : [],
});
}
const names = prepared.restore.map((file) => file.name);
log.info('restore transaction=%s phase=preflight-complete files=%s', transactionId, names.join(','));
if (!/^[A-Za-z0-9_-]+$/.test(transactionId)) {
throw new Error('restore transactionId must contain only letters, numbers, _ or -');
}
if (prepared.restore.length === 0) {
return {
transactionId,
restored: [],
skipped: prepared.skipped,
migrated: prepared.migrated,
restartRequiredToApply: false,
const configDir = path.resolve(options.configDir);
const readCurrent = (name: string): Buffer | null => {
const file = path.join(configDir, name);
try {
return fs.readFileSync(file);
} catch (error) {
if (isMissingPathError(error)) {
return null;
}
throw error;
}
};
}
const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`);
const snapshotRoot = path.join(transactionDir, 'snapshot');
const stagedRoot = path.join(transactionDir, 'staged');
const rollbackRoot = path.join(transactionDir, 'rollback');
const existed = new Map<string, boolean>();
const committed: CommittedFile[] = [];
let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot';
let activeFile: string | undefined;
let transactionCreated = false;
const listCurrentOneBotNames = (): string[] => {
try {
return fs.readdirSync(configDir);
} catch (error) {
if (isMissingPathError(error)) {
return [];
}
try {
fs.mkdirSync(configDir, { recursive: true });
fs.mkdirSync(transactionDir, { mode: 0o700 });
transactionCreated = true;
fs.chmodSync(transactionDir, 0o700);
throw error;
}
};
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const live = path.join(configDir, file.name);
let wasPresent: boolean;
try {
fs.lstatSync(live);
wasPresent = true;
} catch (error) {
if (!isMissingPathError(error)) throw error;
wasPresent = false;
}
existed.set(file.name, wasPresent);
if (!wasPresent) continue;
const snapshot = path.join(snapshotRoot, file.name);
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
fs.copyFileSync(live, snapshot);
}
log.info('restore transaction=%s phase=preflight', transactionId);
let prepared: ReturnType<typeof prepareRestorePlan>;
phase = 'stage';
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const staged = path.join(stagedRoot, file.name);
fs.mkdirSync(path.dirname(staged), { recursive: true });
invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name });
fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode });
invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name });
fs.chmodSync(staged, file.mode);
}
phase = 'commit';
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const staged = path.join(stagedRoot, file.name);
const live = path.join(configDir, file.name);
fs.mkdirSync(path.dirname(live), { recursive: true });
invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name });
fs.renameSync(staged, live);
committed.push({ name: file.name, existed: existed.get(file.name) === true });
}
activeFile = undefined;
} catch (error) {
if (phase !== 'commit') {
const cleanupError = transactionCreated ? removeTransaction(options, transactionDir) : null;
if (cleanupError) {
log.error(
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
transactionId,
phase,
activeFile ?? '-',
errorMessage(error),
errorMessage(cleanupError),
try {
prepared = prepareRestorePlan(parsed, {
restoreCredentials: options.restoreCredentials,
readCurrent,
listCurrentOneBotNames,
});
} catch (error) {
const file = error instanceof RestorePreflightError ? error.file : undefined;
log.warn(
'restore transaction=%s phase=preflight file=%s failed error=%s',
transactionId,
file ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message: `restore ${phase} failed and transaction cleanup also failed`,
cause: new AggregateError([error, cleanupError], `restore ${phase} and cleanup both failed`),
snapshotDir: transactionDir,
failedFiles: activeFile ? [activeFile] : [],
phase: 'preflight',
transactionId,
message: `restore preflight failed: ${errorMessage(error)}`,
cause: error,
failedFiles: file ? [file] : [],
});
}
log.warn(
'restore transaction=%s phase=%s file=%s failed error=%s',
transactionId,
phase,
activeFile ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase,
transactionId,
message: `restore ${phase} failed before live commit`,
cause: error,
failedFiles: activeFile ? [activeFile] : [],
});
}
const rollbackErrors = rollbackCommitted(options, configDir, snapshotRoot, rollbackRoot, committed);
if (rollbackErrors.length > 0) {
const failedFiles = rollbackErrors.map((entry) => entry.name);
const rollbackDetails = rollbackErrors
.map((entry) => `${entry.name}:${errorMessage(entry.error)}`)
.join(';');
log.error(
'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s',
const names = prepared.restore.map((file) => file.name);
log.info(
'restore transaction=%s phase=preflight-complete files=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
rollbackDetails,
transactionDir,
);
throw new RestoreTransactionError({
phase: 'rollback',
transactionId,
message: 'restore commit failed and rollback was incomplete',
cause: new AggregateError(
[error, ...rollbackErrors.map((entry) => entry.error)],
'restore commit and rollback both failed',
),
rollbackSucceeded: false,
snapshotDir: transactionDir,
committed: committed.length > 0,
failedFiles,
});
names.join(','),
);
if (prepared.restore.length === 0) {
return {
transactionId,
restored: [],
skipped: prepared.skipped,
migrated: prepared.migrated,
restartRequiredToApply: false,
};
}
const transactionDir = path.join(configDir, `.restore-transaction-${transactionId}`);
const snapshotRoot = path.join(transactionDir, 'snapshot');
const stagedRoot = path.join(transactionDir, 'staged');
const rollbackRoot = path.join(transactionDir, 'rollback');
const existed = new Map<string, boolean>();
const committed: CommittedFile[] = [];
let phase: 'snapshot' | 'stage' | 'commit' = 'snapshot';
let activeFile: string | undefined;
let transactionCreated = false;
try {
fs.mkdirSync(configDir, { recursive: true });
fs.mkdirSync(transactionDir, { mode: 0o700 });
transactionCreated = true;
fs.chmodSync(transactionDir, 0o700);
log.info('restore transaction=%s phase=snapshot files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const live = path.join(configDir, file.name);
let wasPresent: boolean;
try {
fs.lstatSync(live);
wasPresent = true;
} catch (error) {
if (!isMissingPathError(error)) {
throw error;
}
wasPresent = false;
}
existed.set(file.name, wasPresent);
if (!wasPresent) {
continue;
}
const snapshot = path.join(snapshotRoot, file.name);
fs.mkdirSync(path.dirname(snapshot), { recursive: true });
invoke(options, { phase: 'snapshot', operation: 'copy-current', file: file.name });
fs.copyFileSync(live, snapshot);
}
phase = 'stage';
log.info('restore transaction=%s phase=stage files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const staged = path.join(stagedRoot, file.name);
fs.mkdirSync(path.dirname(staged), { recursive: true });
invoke(options, { phase: 'stage', operation: 'write-staged', file: file.name });
fs.writeFileSync(staged, file.data, { flag: 'wx', mode: file.mode });
invoke(options, { phase: 'stage', operation: 'chmod-staged', file: file.name });
fs.chmodSync(staged, file.mode);
}
phase = 'commit';
log.info('restore transaction=%s phase=commit files=%s', transactionId, names.join(','));
for (const file of prepared.restore) {
activeFile = file.name;
const staged = path.join(stagedRoot, file.name);
const live = path.join(configDir, file.name);
fs.mkdirSync(path.dirname(live), { recursive: true });
invoke(options, { phase: 'commit', operation: 'rename-staged', file: file.name });
fs.renameSync(staged, live);
committed.push({ name: file.name, existed: existed.get(file.name) === true });
}
activeFile = undefined;
} catch (error) {
if (phase !== 'commit') {
const cleanupError = transactionCreated
? removeTransaction(options, transactionDir)
: null;
if (cleanupError) {
log.error(
'restore transaction=%s phase=cleanup failed-after=%s file=%s original-error=%s cleanup-error=%s',
transactionId,
phase,
activeFile ?? '-',
errorMessage(error),
errorMessage(cleanupError),
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message: `restore ${phase} failed and transaction cleanup also failed`,
cause: new AggregateError(
[error, cleanupError],
`restore ${phase} and cleanup both failed`,
),
snapshotDir: transactionDir,
failedFiles: activeFile ? [activeFile] : [],
});
}
log.warn(
'restore transaction=%s phase=%s file=%s failed error=%s',
transactionId,
phase,
activeFile ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase,
transactionId,
message: `restore ${phase} failed before live commit`,
cause: error,
failedFiles: activeFile ? [activeFile] : [],
});
}
const rollbackErrors = rollbackCommitted(
options,
configDir,
snapshotRoot,
rollbackRoot,
committed,
);
if (rollbackErrors.length > 0) {
const failedFiles = rollbackErrors.map((entry) => entry.name);
const rollbackDetails = rollbackErrors
.map((entry) => `${entry.name}:${errorMessage(entry.error)}`)
.join(';');
log.error(
'restore transaction=%s phase=rollback commit-file=%s commit-error=%s failed=%s snapshot=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
rollbackDetails,
transactionDir,
);
throw new RestoreTransactionError({
phase: 'rollback',
transactionId,
message: 'restore commit failed and rollback was incomplete',
cause: new AggregateError(
[error, ...rollbackErrors.map((entry) => entry.error)],
'restore commit and rollback both failed',
),
rollbackSucceeded: false,
snapshotDir: transactionDir,
committed: committed.length > 0,
failedFiles,
});
}
const cleanupError = removeTransaction(options, transactionDir);
if (cleanupError) {
log.error(
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
errorMessage(cleanupError),
transactionDir,
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message:
'restore commit failed, rollback succeeded, but transaction cleanup failed',
cause: new AggregateError(
[error, cleanupError],
'restore commit and post-rollback cleanup both failed',
),
rollbackSucceeded: true,
snapshotDir: transactionDir,
failedFiles: activeFile ? [activeFile] : [],
});
}
log.warn(
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase: 'commit',
transactionId,
message: 'restore commit failed; every committed file was rolled back',
cause: error,
rollbackSucceeded: true,
failedFiles: activeFile ? [activeFile] : [],
});
}
const cleanupError = removeTransaction(options, transactionDir);
if (cleanupError) {
log.error(
'restore transaction=%s phase=cleanup failed-after=rollback commit-file=%s commit-error=%s cleanup-error=%s snapshot=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
errorMessage(cleanupError),
transactionDir,
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message: 'restore commit failed, rollback succeeded, but transaction cleanup failed',
cause: new AggregateError([error, cleanupError], 'restore commit and post-rollback cleanup both failed'),
rollbackSucceeded: true,
snapshotDir: transactionDir,
failedFiles: activeFile ? [activeFile] : [],
});
log.error(
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
transactionId,
errorMessage(cleanupError),
transactionDir,
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message: 'restore committed successfully, but transaction cleanup failed',
cause: cleanupError,
snapshotDir: transactionDir,
committed: true,
});
}
log.warn(
'restore transaction=%s phase=commit file=%s failed rollback=complete error=%s',
transactionId,
activeFile ?? '-',
errorMessage(error),
);
throw new RestoreTransactionError({
phase: 'commit',
transactionId,
message: 'restore commit failed; every committed file was rolled back',
cause: error,
rollbackSucceeded: true,
failedFiles: activeFile ? [activeFile] : [],
});
}
const cleanupError = removeTransaction(options, transactionDir);
if (cleanupError) {
log.error(
'restore transaction=%s phase=cleanup failed-after=commit cleanup-error=%s snapshot=%s',
transactionId,
errorMessage(cleanupError),
transactionDir,
);
throw new RestoreTransactionError({
phase: 'cleanup',
transactionId,
message: 'restore committed successfully, but transaction cleanup failed',
cause: cleanupError,
snapshotDir: transactionDir,
committed: true,
});
}
log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(','));
return {
transactionId,
restored: names,
skipped: prepared.skipped,
migrated: prepared.migrated,
restartRequiredToApply: true,
};
log.info('restore transaction=%s phase=complete files=%s', transactionId, names.join(','));
return {
transactionId,
restored: names,
skipped: prepared.skipped,
migrated: prepared.migrated,
restartRequiredToApply: true,
};
}
function rollbackCommitted(
options: RestoreBackupOptions,
configDir: string,
snapshotRoot: string,
rollbackRoot: string,
committed: readonly CommittedFile[],
options: RestoreBackupOptions,
configDir: string,
snapshotRoot: string,
rollbackRoot: string,
committed: readonly CommittedFile[],
): Array<{ name: string; error: unknown }> {
const errors: Array<{ name: string; error: unknown }> = [];
for (const file of [...committed].reverse()) {
const live = path.join(configDir, file.name);
try {
if (!file.existed) {
invoke(options, { phase: 'rollback', operation: 'remove-created', file: file.name });
fs.rmSync(live, { force: true });
continue;
}
const snapshot = path.join(snapshotRoot, file.name);
const rollback = path.join(rollbackRoot, file.name);
fs.mkdirSync(path.dirname(rollback), { recursive: true });
invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name });
fs.copyFileSync(snapshot, rollback);
fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777);
fs.renameSync(rollback, live);
} catch (error) {
errors.push({ name: file.name, error });
const errors: Array<{ name: string; error: unknown }> = [];
for (const file of [...committed].reverse()) {
const live = path.join(configDir, file.name);
try {
if (!file.existed) {
invoke(options, {
phase: 'rollback',
operation: 'remove-created',
file: file.name,
});
fs.rmSync(live, { force: true });
continue;
}
const snapshot = path.join(snapshotRoot, file.name);
const rollback = path.join(rollbackRoot, file.name);
fs.mkdirSync(path.dirname(rollback), { recursive: true });
invoke(options, { phase: 'rollback', operation: 'restore-current', file: file.name });
fs.copyFileSync(snapshot, rollback);
fs.chmodSync(rollback, fs.statSync(snapshot).mode & 0o777);
fs.renameSync(rollback, live);
} catch (error) {
errors.push({ name: file.name, error });
}
}
}
return errors;
return errors;
}
function removeTransaction(options: RestoreBackupOptions, transactionDir: string): unknown | null {
try {
invoke(options, { phase: 'cleanup', operation: 'remove-transaction' });
fs.rmSync(transactionDir, { recursive: true, force: true });
return null;
} catch (error) {
return error;
}
try {
invoke(options, { phase: 'cleanup', operation: 'remove-transaction' });
fs.rmSync(transactionDir, { recursive: true, force: true });
return null;
} catch (error) {
return error;
}
}
function invoke(options: RestoreBackupOptions, operation: RestoreOperation): void {
options.beforeOperation?.(operation);
options.beforeOperation?.(operation);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
function isMissingPathError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& 'code' in error
&& error.code === 'ENOENT';
return (
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
);
}
File diff suppressed because it is too large. Load diff
+79 -45
View File
@@ -6,18 +6,18 @@ import { type Context } from 'hono';
* transport lifecycle (heartbeat / teardown / abort / headers).
*/
export interface SseChannel {
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
}
/**
@@ -33,37 +33,71 @@ export interface SseChannel {
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
if (closed) return;
closed = true;
if (heartbeat) clearInterval(heartbeat);
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
try { controller.close(); } catch { /* ignore */ }
};
const raw = (chunk: Uint8Array) => {
if (closed) return;
try { controller.enqueue(chunk); } catch { teardown(); }
};
const ch: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => { cleanups.push(fn); },
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
if (closed) {
return;
}
closed = true;
if (heartbeat) {
clearInterval(heartbeat);
}
for (const fn of cleanups) {
try {
fn();
} catch {
/* ignore */
}
}
try {
controller.close();
} catch {
/* ignore */
}
};
const raw = (chunk: Uint8Array) => {
if (closed) {
return;
}
try {
controller.enqueue(chunk);
} catch {
teardown();
}
};
const ch: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => {
cleanups.push(fn);
},
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
}
+49 -38
View File
@@ -22,46 +22,57 @@ export type StateResource = 'processes' | 'qq-list' | 'connections';
export type StateListener = (resource: StateResource) => void;
export class StateBus {
private readonly listeners = new Set<StateListener>();
private disposed = false;
private readonly listeners = new Set<StateListener>();
private disposed = false;
/** Subscribe to every publish; returns an unsubscribe handle. Calling
* the handle more than once is a no-op. */
subscribe(listener: StateListener): () => void {
if (this.disposed) return () => undefined;
this.listeners.add(listener);
let active = true;
return () => {
if (!active) return;
active = false;
this.listeners.delete(listener);
};
}
/** Subscribe to every publish; returns an unsubscribe handle. Calling
* the handle more than once is a no-op. */
subscribe(listener: StateListener): () => void {
if (this.disposed) {
return () => undefined;
}
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
* Iterates a frozen snapshot of the subscriber set so add/remove during
* the emit don't change which listeners see THIS publish; subscriber
* exceptions are isolated and do not abort the fan-out. */
publish(resource: StateResource): void {
if (this.disposed) return;
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
}
this.listeners.add(listener);
let active = true;
return () => {
if (!active) {
return;
}
active = false;
this.listeners.delete(listener);
};
}
}
/** Drop every subscriber and refuse future subscribes / publishes. */
dispose(): void {
this.disposed = true;
this.listeners.clear();
}
/** Notify every CURRENTLY-subscribed listener that `resource` is stale.
* Iterates a frozen snapshot of the subscriber set so add/remove during
* the emit don't change which listeners see THIS publish; subscriber
* exceptions are isolated and do not abort the fan-out. */
publish(resource: StateResource): void {
if (this.disposed) {
return;
}
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
}
}
}
/** Drop every subscriber and refuse future subscribes / publishes. */
dispose(): void {
this.disposed = true;
this.listeners.clear();
}
}
+121 -93
View File
@@ -17,112 +17,140 @@
import type { StateBus, StateResource } from './state-bus';
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
resource: StateResource;
data: unknown;
}
export interface BindStateStreamOptions {
bus: StateBus;
/** Read the current snapshot for one resource. May be sync or async. */
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
/** Receive a fresh frame; called once per debounced publish.
* Exceptions are caught — a dead controller must not abort the bus
* subscription or break sibling resources. */
send: (frame: StateStreamFrame) => void;
/** Coalesce window in milliseconds; default 50. */
debounceMs?: number;
bus: StateBus;
/** Read the current snapshot for one resource. May be sync or async. */
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
/** Receive a fresh frame; called once per debounced publish.
* Exceptions are caught — a dead controller must not abort the bus
* subscription or break sibling resources. */
send: (frame: StateStreamFrame) => void;
/** Coalesce window in milliseconds; default 50. */
debounceMs?: number;
}
export interface StateStreamHandle {
/** Emit one frame per resource using the current snapshot. Use on connect. */
sendAllInitial(): Promise<void>;
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
* produce nothing through this binding. */
dispose(): void;
/** Emit one frame per resource using the current snapshot. Use on connect. */
sendAllInitial(): Promise<void>;
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
* produce nothing through this binding. */
dispose(): void;
}
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) return;
inFlight.add(resource);
try {
let data: unknown;
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
}
if (disposed) return;
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
}
};
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) {
return;
}
const schedule = (resource: StateResource): void => {
if (disposed) return;
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) clearTimeout(existing);
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
inFlight.add(resource);
const unsubscribe = opts.bus.subscribe(schedule);
try {
let data: unknown;
return {
async sendAllInitial(): Promise<void> {
if (disposed) return;
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
},
dispose(): void {
if (disposed) return;
disposed = true;
unsubscribe();
for (const t of timers.values()) clearTimeout(t);
timers.clear();
pending.clear();
},
};
try {
data = await opts.snapshot(resource);
} catch {
// Per-resource snapshot failure (e.g. listProcesses threw): skip
// this frame so siblings keep flowing. The next publish for the
// same resource gets a fresh attempt.
return;
}
if (disposed) {
return;
}
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
}
};
const schedule = (resource: StateResource): void => {
if (disposed) {
return;
}
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
return;
}
const existing = timers.get(resource);
if (existing) {
clearTimeout(existing);
}
const t = setTimeout(() => {
timers.delete(resource);
void flush(resource);
}, debounceMs);
timers.set(resource, t);
};
const unsubscribe = opts.bus.subscribe(schedule);
return {
async sendAllInitial(): Promise<void> {
if (disposed) {
return;
}
// Fire all three in parallel. Each resource's snapshot is independent
// so a slow listProcesses() doesn't gate qq-list/connections. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
},
dispose(): void {
if (disposed) {
return;
}
disposed = true;
unsubscribe();
for (const t of timers.values()) {
clearTimeout(t);
}
timers.clear();
pending.clear();
},
};
}
+49 -43
View File
@@ -23,52 +23,58 @@ import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
dispose(): void;
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
dispose(): void;
}
export function createStateWiring(): StateWiring {
const bus = new StateBus();
let disposed = false;
const bus = new StateBus();
let disposed = false;
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) return;
bus.publish(resource);
};
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) {
return;
}
return {
bus,
onSessionsChanged: () => publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
dispose(): void {
if (disposed) return;
disposed = true;
bus.dispose();
},
};
bus.publish(resource);
};
return {
bus,
onSessionsChanged: () => publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
dispose(): void {
if (disposed) {
return;
}
disposed = true;
bus.dispose();
},
};
}
+309 -255
View File
@@ -1,333 +1,387 @@
import fs from 'node:fs';
import path from 'node:path';
import type {
LogCleanupResult,
LogStorageStatus,
} from '@snowluma/common/log-file-transport';
import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport';
import { isRealUin } from '@snowluma/common/uin';
export interface TemporaryStorageSnapshot {
totalBytes: number;
fileCount: number;
activeItemCount: number;
totalBytes: number;
fileCount: number;
activeItemCount: number;
}
export interface TemporaryCleanupResult {
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
deletedFiles: number;
freedBytes: number;
skippedActiveItems: number;
failures: Array<{ item: string; message: string }>;
}
export interface TemporaryStorageAdapter {
snapshot(): TemporaryStorageSnapshot;
clearInactive(): TemporaryCleanupResult;
snapshot(): TemporaryStorageSnapshot;
clearInactive(): TemporaryCleanupResult;
}
export interface OnlineStorageAccount {
uin: string;
nickname: string;
uin: string;
nickname: string;
}
export interface AccountStorageSnapshot {
uin: string;
nickname?: string;
online: boolean;
messagesBytes: number;
mediaBytes: number;
reactionsBytes: number;
totalBytes: number;
uin: string;
nickname?: string;
online: boolean;
messagesBytes: number;
mediaBytes: number;
reactionsBytes: number;
totalBytes: number;
}
export type PublicLogStorageStatus = Omit<LogStorageStatus, 'directory'>;
export function publicLogStorageStatus(status: LogStorageStatus): PublicLogStorageStatus {
const { directory, ...publicStatus } = status;
if (!publicStatus.lastError) return publicStatus;
return {
...publicStatus,
lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'),
};
const { directory, ...publicStatus } = status;
if (!publicStatus.lastError) {
return publicStatus;
}
return {
...publicStatus,
lastError: redactFilesystemPath(publicStatus.lastError, directory, '[日志目录]'),
};
}
export interface PublicLogCleanupResult extends Omit<LogCleanupResult, 'status'> {
status: PublicLogStorageStatus;
status: PublicLogStorageStatus;
}
export interface StorageSnapshot {
logs: PublicLogStorageStatus;
temporary: TemporaryStorageSnapshot;
accounts: AccountStorageSnapshot[];
totals: {
logsBytes: number;
temporaryBytes: number;
accountDataBytes: number;
managedBytes: number;
};
logs: PublicLogStorageStatus;
temporary: TemporaryStorageSnapshot;
accounts: AccountStorageSnapshot[];
totals: {
logsBytes: number;
temporaryBytes: number;
accountDataBytes: number;
managedBytes: number;
};
}
export type AccountStorageCategory = 'messages' | 'media' | 'reactions';
export interface AccountDataCleanupResult {
category: AccountStorageCategory;
uins: string[];
deletedFiles: number;
freedBytes: number;
failures: Array<{ uin: string; file: string; message: string }>;
category: AccountStorageCategory;
uins: string[];
deletedFiles: number;
freedBytes: number;
failures: Array<{ uin: string; file: string; message: string }>;
}
export class StorageManagementInputError extends Error {
constructor(message: string) {
super(message);
this.name = 'StorageManagementInputError';
}
constructor(message: string) {
super(message);
this.name = 'StorageManagementInputError';
}
}
export class StorageAccountOnlineError extends Error {
constructor(readonly uins: string[]) {
super(`account data cleanup requires offline accounts: ${uins.join(', ')}`);
this.name = 'StorageAccountOnlineError';
}
constructor(readonly uins: string[]) {
super(`account data cleanup requires offline accounts: ${uins.join(', ')}`);
this.name = 'StorageAccountOnlineError';
}
}
export interface StorageManagementDependencies {
dataDir: string;
getLogStatus(): LogStorageStatus;
clearLogs(): Promise<LogCleanupResult>;
temporary: TemporaryStorageAdapter;
listOnlineAccounts(): OnlineStorageAccount[];
dataDir: string;
getLogStatus(): LogStorageStatus;
clearLogs(): Promise<LogCleanupResult>;
temporary: TemporaryStorageAdapter;
listOnlineAccounts(): OnlineStorageAccount[];
}
const DATABASE_FILES = {
messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'],
media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'],
reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'],
messages: ['messages.db', 'messages.db-wal', 'messages.db-shm', 'messages.db-journal'],
media: ['media.db', 'media.db-wal', 'media.db-shm', 'media.db-journal'],
reactions: ['reactions.db', 'reactions.db-wal', 'reactions.db-shm', 'reactions.db-journal'],
} as const;
export class StorageManagementService {
constructor(private readonly deps: StorageManagementDependencies) {}
constructor(private readonly deps: StorageManagementDependencies) {}
snapshot(): StorageSnapshot {
const logStatus = this.deps.getLogStatus();
const logs = publicLogStorageStatus(logStatus);
const temporary = this.deps.temporary.snapshot();
const accounts = this.accountSnapshots();
const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0);
return {
logs,
temporary,
accounts,
totals: {
logsBytes: logs.totalBytes,
temporaryBytes: temporary.totalBytes,
accountDataBytes,
managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes,
},
};
}
async clearLogs(): Promise<PublicLogCleanupResult> {
const result = await this.deps.clearLogs();
return {
...result,
failures: result.failures.map((failure) => ({
...failure,
message: redactFilesystemPath(
failure.message,
result.status.directory,
'[日志目录]',
),
})),
status: publicLogStorageStatus(result.status),
};
}
clearTemporary(): TemporaryCleanupResult {
return this.deps.temporary.clearInactive();
}
clearAccountData(category: string, uin: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
if (!isRealUin(uin)) {
throw new StorageManagementInputError(`invalid UIN: ${uin}`);
}
return this.clearAccountDataForUins(validatedCategory, [uin]);
}
clearAllAccountData(category: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
const uins = listDirectoryNames(this.deps.dataDir)
.filter((name) => isRealUin(name))
.sort((a, b) => Number(a) - Number(b));
return this.clearAccountDataForUins(validatedCategory, uins);
}
private clearAccountDataForUins(
category: AccountStorageCategory,
uins: string[],
): AccountDataCleanupResult {
const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir);
const onlineUins = new Set(
this.deps.listOnlineAccounts()
.map((account) => account.uin)
.filter((uin) => isRealUin(uin)),
);
const blockedUins = uins.filter((uin) => onlineUins.has(uin));
if (blockedUins.length > 0) throw new StorageAccountOnlineError(blockedUins);
const failures: AccountDataCleanupResult['failures'] = [];
let deletedFiles = 0;
let freedBytes = 0;
if (!hasManagedRoot) {
return { category, uins, deletedFiles, freedBytes, failures };
}
for (const uin of uins) {
const dir = path.join(this.deps.dataDir, uin);
if (!isManagedDirectory(dir)) continue;
for (const name of DATABASE_FILES[category]) {
const filePath = path.join(dir, name);
let bytes: number;
try {
const stat = fs.lstatSync(filePath);
if (!stat.isFile()) continue;
bytes = stat.size;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
continue;
}
try {
fs.unlinkSync(filePath);
deletedFiles += 1;
freedBytes += bytes;
} catch (error) {
if (isMissing(error)) continue;
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
}
}
}
return { category, uins, deletedFiles, freedBytes, failures };
}
private accountSnapshots(): AccountStorageSnapshot[] {
const online = new Map(
this.deps.listOnlineAccounts()
.filter((account) => isRealUin(account.uin))
.map((account) => [account.uin, account.nickname]),
);
const uins = new Set(online.keys());
for (const name of listDirectoryNames(this.deps.dataDir)) {
if (isRealUin(name)) uins.add(name);
}
return [...uins]
.sort((a, b) => Number(a) - Number(b))
.map((uin) => {
const dir = path.join(this.deps.dataDir, uin);
const managedDirectory = isManagedDirectory(dir);
const messagesBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.messages)
: 0;
const mediaBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.media)
: 0;
const reactionsBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.reactions)
: 0;
const nickname = online.get(uin);
snapshot(): StorageSnapshot {
const logStatus = this.deps.getLogStatus();
const logs = publicLogStorageStatus(logStatus);
const temporary = this.deps.temporary.snapshot();
const accounts = this.accountSnapshots();
const accountDataBytes = accounts.reduce((sum, account) => sum + account.totalBytes, 0);
return {
uin,
...(nickname ? { nickname } : {}),
online: online.has(uin),
messagesBytes,
mediaBytes,
reactionsBytes,
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
logs,
temporary,
accounts,
totals: {
logsBytes: logs.totalBytes,
temporaryBytes: temporary.totalBytes,
accountDataBytes,
managedBytes: logs.totalBytes + temporary.totalBytes + accountDataBytes,
},
};
});
}
}
async clearLogs(): Promise<PublicLogCleanupResult> {
const result = await this.deps.clearLogs();
return {
...result,
failures: result.failures.map((failure) => ({
...failure,
message: redactFilesystemPath(
failure.message,
result.status.directory,
'[日志目录]',
),
})),
status: publicLogStorageStatus(result.status),
};
}
clearTemporary(): TemporaryCleanupResult {
return this.deps.temporary.clearInactive();
}
clearAccountData(category: string, uin: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
if (!isRealUin(uin)) {
throw new StorageManagementInputError(`invalid UIN: ${uin}`);
}
return this.clearAccountDataForUins(validatedCategory, [uin]);
}
clearAllAccountData(category: string): AccountDataCleanupResult {
const validatedCategory = validateAccountStorageCategory(category);
const uins = listDirectoryNames(this.deps.dataDir)
.filter((name) => isRealUin(name))
.sort((a, b) => Number(a) - Number(b));
return this.clearAccountDataForUins(validatedCategory, uins);
}
private clearAccountDataForUins(
category: AccountStorageCategory,
uins: string[],
): AccountDataCleanupResult {
const hasManagedRoot = assertManagedDataRootOrMissing(this.deps.dataDir);
const onlineUins = new Set(
this.deps
.listOnlineAccounts()
.map((account) => account.uin)
.filter((uin) => isRealUin(uin)),
);
const blockedUins = uins.filter((uin) => onlineUins.has(uin));
if (blockedUins.length > 0) {
throw new StorageAccountOnlineError(blockedUins);
}
const failures: AccountDataCleanupResult['failures'] = [];
let deletedFiles = 0;
let freedBytes = 0;
if (!hasManagedRoot) {
return { category, uins, deletedFiles, freedBytes, failures };
}
for (const uin of uins) {
const dir = path.join(this.deps.dataDir, uin);
if (!isManagedDirectory(dir)) {
continue;
}
for (const name of DATABASE_FILES[category]) {
const filePath = path.join(dir, name);
let bytes: number;
try {
const stat = fs.lstatSync(filePath);
if (!stat.isFile()) {
continue;
}
bytes = stat.size;
} catch (error) {
if (isMissing(error)) {
continue;
}
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
continue;
}
try {
fs.unlinkSync(filePath);
deletedFiles += 1;
freedBytes += bytes;
} catch (error) {
if (isMissing(error)) {
continue;
}
failures.push({
uin,
file: name,
message: redactFilesystemPath(
errorMessage(error),
filePath,
'[账号数据库]',
),
});
}
}
}
return { category, uins, deletedFiles, freedBytes, failures };
}
private accountSnapshots(): AccountStorageSnapshot[] {
const online = new Map(
this.deps
.listOnlineAccounts()
.filter((account) => isRealUin(account.uin))
.map((account) => [account.uin, account.nickname]),
);
const uins = new Set(online.keys());
for (const name of listDirectoryNames(this.deps.dataDir)) {
if (isRealUin(name)) {
uins.add(name);
}
}
return [...uins]
.sort((a, b) => Number(a) - Number(b))
.map((uin) => {
const dir = path.join(this.deps.dataDir, uin);
const managedDirectory = isManagedDirectory(dir);
const messagesBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.messages)
: 0;
const mediaBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.media)
: 0;
const reactionsBytes = managedDirectory
? sumAllowlistedFiles(dir, DATABASE_FILES.reactions)
: 0;
const nickname = online.get(uin);
return {
uin,
...(nickname ? { nickname } : {}),
online: online.has(uin),
messagesBytes,
mediaBytes,
reactionsBytes,
totalBytes: messagesBytes + mediaBytes + reactionsBytes,
};
});
}
}
function listDirectoryNames(dir: string): string[] {
if (!assertManagedDataRootOrMissing(dir)) return [];
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
} catch (error) {
if (isMissing(error)) return [];
throw error;
}
if (!assertManagedDataRootOrMissing(dir)) {
return [];
}
try {
return fs
.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
} catch (error) {
if (isMissing(error)) {
return [];
}
throw error;
}
}
function assertManagedDataRootOrMissing(dir: string): boolean {
try {
const stat = fs.lstatSync(dir);
if (!stat.isDirectory()) {
throw new Error('managed data root must be a real directory');
try {
const stat = fs.lstatSync(dir);
if (!stat.isDirectory()) {
throw new Error('managed data root must be a real directory');
}
return true;
} catch (error) {
if (isMissing(error)) {
return false;
}
throw error;
}
return true;
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
}
function sumAllowlistedFiles(dir: string, names: readonly string[]): number {
let total = 0;
for (const name of names) {
const filePath = path.join(dir, name);
try {
const stat = fs.lstatSync(filePath);
if (stat.isFile()) total += stat.size;
} catch (error) {
if (!isMissing(error)) throw error;
let total = 0;
for (const name of names) {
const filePath = path.join(dir, name);
try {
const stat = fs.lstatSync(filePath);
if (stat.isFile()) {
total += stat.size;
}
} catch (error) {
if (!isMissing(error)) {
throw error;
}
}
}
}
return total;
return total;
}
function isMissing(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
}
function isManagedDirectory(dir: string): boolean {
try {
return fs.lstatSync(dir).isDirectory();
} catch (error) {
if (isMissing(error)) return false;
throw error;
}
try {
return fs.lstatSync(dir).isDirectory();
} catch (error) {
if (isMissing(error)) {
return false;
}
throw error;
}
}
function validateAccountStorageCategory(value: string): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
if (value === 'messages' || value === 'media' || value === 'reactions') {
return value;
}
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message
.split(absolute).join(label)
.split(filePath).join(label);
const absolute = path.resolve(filePath);
return message.split(absolute).join(label).split(filePath).join(label);
}
+320 -264
View File
@@ -1,317 +1,373 @@
import { isRealUin } from '@snowluma/common/uin';
import type { Hono } from 'hono';
import {
StorageAccountOnlineError,
StorageManagementInputError,
type AccountDataCleanupResult,
type AccountStorageCategory,
type PublicLogCleanupResult,
type StorageManagementService,
type StorageSnapshot,
type TemporaryCleanupResult,
StorageAccountOnlineError,
StorageManagementInputError,
type AccountDataCleanupResult,
type AccountStorageCategory,
type PublicLogCleanupResult,
type StorageManagementService,
type StorageSnapshot,
type TemporaryCleanupResult,
} from './storage-management';
import {
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
type LogStorageSettingsManager,
StorageSettingsInputError,
StorageSettingsLockedError,
StorageSettingsTransactionError,
type LogStorageSettingsManager,
} from './storage-settings';
export const ALL_ACCOUNTS_CONFIRMATION = '清理全部账号';
type StorageCleanupRequest =
| { scope: 'logs' }
| { scope: 'temporary' }
| { scope: 'account'; category: AccountStorageCategory; uin: string }
| {
scope: 'allAccounts';
category: AccountStorageCategory;
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
};
| { scope: 'logs' }
| { scope: 'temporary' }
| { scope: 'account'; category: AccountStorageCategory; uin: string }
| {
scope: 'allAccounts';
category: AccountStorageCategory;
confirmation: typeof ALL_ACCOUNTS_CONFIRMATION;
};
type StorageCleanupResult =
| PublicLogCleanupResult
| TemporaryCleanupResult
| AccountDataCleanupResult;
PublicLogCleanupResult | TemporaryCleanupResult | AccountDataCleanupResult;
export interface StorageCleanupAuditEvent {
scope: StorageCleanupRequest['scope'];
accountScope: 'global' | 'single' | 'all';
category?: AccountStorageCategory;
uin?: string;
deletedFiles: number;
freedBytes: number;
failureCount: number;
scope: StorageCleanupRequest['scope'];
accountScope: 'global' | 'single' | 'all';
category?: AccountStorageCategory;
uin?: string;
deletedFiles: number;
freedBytes: number;
failureCount: number;
}
export interface LastStorageCleanup extends StorageCleanupAuditEvent {
at: string;
skippedActiveItems?: number;
failures: Array<{ item: string; message: string }>;
at: string;
skippedActiveItems?: number;
failures: Array<{ item: string; message: string }>;
}
export interface StorageRouteDependencies {
storage: Pick<
StorageManagementService,
'snapshot'
| 'clearLogs'
| 'clearTemporary'
| 'clearAccountData'
| 'clearAllAccountData'
>;
settings: Pick<LogStorageSettingsManager, 'read' | 'update'>;
audit(event: StorageCleanupAuditEvent): void;
reportError(operation: string, error: unknown): void;
now?: () => Date;
storage: Pick<
StorageManagementService,
'snapshot' | 'clearLogs' | 'clearTemporary' | 'clearAccountData' | 'clearAllAccountData'
>;
settings: Pick<LogStorageSettingsManager, 'read' | 'update'>;
audit(event: StorageCleanupAuditEvent): void;
reportError(operation: string, error: unknown): void;
now?: () => Date;
}
export function registerStorageRoutes(app: Hono, deps: StorageRouteDependencies): void {
let lastCleanup: LastStorageCleanup | null = null;
let mutationQueue: Promise<void> = Promise.resolve();
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
const result = mutationQueue.then(operation);
mutationQueue = result.then(
() => undefined,
() => undefined,
);
return result;
};
let lastCleanup: LastStorageCleanup | null = null;
let mutationQueue: Promise<void> = Promise.resolve();
app.get('/api/system/storage', (c) => {
try {
return c.json({
settings: deps.settings.read(),
snapshot: deps.storage.snapshot(),
lastCleanup,
});
} catch (error) {
deps.reportError('read storage snapshot', error);
return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500);
}
});
app.post('/api/system/storage/settings', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let result: Awaited<ReturnType<LogStorageSettingsManager['update']>>;
try {
result = await serializeMutation(() => deps.settings.update(body));
} catch (error) {
if (error instanceof StorageSettingsInputError) {
return c.json({ success: false, message: error.message }, 400);
}
if (error instanceof StorageSettingsLockedError) {
return c.json({
success: false,
message: '这些设置已由环境变量锁定',
lockedFields: error.fields,
}, 409);
}
deps.reportError('update log storage settings', error);
if (error instanceof StorageSettingsTransactionError) {
deps.reportError('update log storage settings operation', error.operationError);
error.rollbackErrors.forEach((rollbackError, index) => {
deps.reportError(
`rollback log storage settings step=${String(index + 1)}`,
rollbackError,
);
});
return c.json({
success: false,
message: error.rollbackErrors.length > 0
? '保存失败且回滚不完整,请立即检查服务器日志'
: '保存失败,原设置已恢复',
}, 500);
}
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
try {
return c.json({
success: true,
settings: result.settings,
status: result.status,
snapshot: deps.storage.snapshot(),
});
} catch (error) {
deps.reportError('refresh storage snapshot after settings update', error);
return c.json({
success: false,
message: '设置已生效,但刷新存储统计失败,请检查服务器日志',
settings: result.settings,
status: result.status,
}, 500);
}
});
app.post('/api/system/storage/cleanup', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let request: StorageCleanupRequest;
try {
request = parseCleanupRequest(body);
} catch (error) {
const message = error instanceof Error ? error.message : '请求格式错误';
return c.json({ success: false, message }, 400);
}
let cleanup: StorageCleanupResult;
try {
cleanup = await serializeMutation(() => executeCleanup(deps.storage, request));
} catch (error) {
if (error instanceof StorageAccountOnlineError) {
return c.json({
success: false,
message: '账号在线,必须先下线后才能清理数据库',
onlineUins: error.uins,
}, 409);
}
if (error instanceof StorageManagementInputError) {
return c.json({ success: false, message: error.message }, 400);
}
deps.reportError(`clean storage scope=${request.scope}`, error);
return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500);
}
const auditEvent: StorageCleanupAuditEvent = {
scope: request.scope,
accountScope: accountScope(request),
...('category' in request ? { category: request.category } : {}),
...(request.scope === 'account' ? { uin: request.uin } : {}),
deletedFiles: cleanup.deletedFiles,
freedBytes: cleanup.freedBytes,
failureCount: cleanup.failures.length,
};
deps.audit(auditEvent);
for (const failure of cleanup.failures) {
deps.reportError(
`clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`,
new Error(failure.message),
);
}
lastCleanup = {
at: (deps.now?.() ?? new Date()).toISOString(),
...auditEvent,
...('skippedActiveItems' in cleanup
? { skippedActiveItems: cleanup.skippedActiveItems }
: {}),
failures: cleanup.failures.map((failure) => ({
item: cleanupFailureItem(failure),
message: failure.message,
})),
const serializeMutation = <T>(operation: () => Promise<T>): Promise<T> => {
const result = mutationQueue.then(operation);
mutationQueue = result.then(
() => undefined,
() => undefined,
);
return result;
};
let snapshot: StorageSnapshot;
try {
snapshot = deps.storage.snapshot();
} catch (error) {
deps.reportError(`refresh storage snapshot after cleanup scope=${request.scope}`, error);
return c.json({
success: false,
message: '清理已执行,但刷新存储统计失败,请检查服务器日志',
scope: request.scope,
cleanup,
lastCleanup,
}, 500);
}
app.get('/api/system/storage', (c) => {
try {
return c.json({
settings: deps.settings.read(),
snapshot: deps.storage.snapshot(),
lastCleanup,
});
} catch (error) {
deps.reportError('read storage snapshot', error);
return c.json({ success: false, message: '读取存储信息失败,请检查服务器日志' }, 500);
}
});
const success = cleanup.failures.length === 0;
return c.json({
success,
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
scope: request.scope,
cleanup,
snapshot,
lastCleanup,
}, success ? 200 : 500);
});
app.post('/api/system/storage/settings', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let result: Awaited<ReturnType<LogStorageSettingsManager['update']>>;
try {
result = await serializeMutation(() => deps.settings.update(body));
} catch (error) {
if (error instanceof StorageSettingsInputError) {
return c.json({ success: false, message: error.message }, 400);
}
if (error instanceof StorageSettingsLockedError) {
return c.json(
{
success: false,
message: '这些设置已由环境变量锁定',
lockedFields: error.fields,
},
409,
);
}
deps.reportError('update log storage settings', error);
if (error instanceof StorageSettingsTransactionError) {
deps.reportError('update log storage settings operation', error.operationError);
error.rollbackErrors.forEach((rollbackError, index) => {
deps.reportError(
`rollback log storage settings step=${String(index + 1)}`,
rollbackError,
);
});
return c.json(
{
success: false,
message:
error.rollbackErrors.length > 0
? '保存失败且回滚不完整,请立即检查服务器日志'
: '保存失败,原设置已恢复',
},
500,
);
}
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
}
try {
return c.json({
success: true,
settings: result.settings,
status: result.status,
snapshot: deps.storage.snapshot(),
});
} catch (error) {
deps.reportError('refresh storage snapshot after settings update', error);
return c.json(
{
success: false,
message: '设置已生效,但刷新存储统计失败,请检查服务器日志',
settings: result.settings,
status: result.status,
},
500,
);
}
});
app.post('/api/system/storage/cleanup', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, message: '请求格式错误' }, 400);
}
let request: StorageCleanupRequest;
try {
request = parseCleanupRequest(body);
} catch (error) {
const message = error instanceof Error ? error.message : '请求格式错误';
return c.json({ success: false, message }, 400);
}
let cleanup: StorageCleanupResult;
try {
cleanup = await serializeMutation(() => executeCleanup(deps.storage, request));
} catch (error) {
if (error instanceof StorageAccountOnlineError) {
return c.json(
{
success: false,
message: '账号在线,必须先下线后才能清理数据库',
onlineUins: error.uins,
},
409,
);
}
if (error instanceof StorageManagementInputError) {
return c.json({ success: false, message: error.message }, 400);
}
deps.reportError(`clean storage scope=${request.scope}`, error);
return c.json({ success: false, message: '清理失败,请检查服务器日志' }, 500);
}
const auditEvent: StorageCleanupAuditEvent = {
scope: request.scope,
accountScope: accountScope(request),
...('category' in request ? { category: request.category } : {}),
...(request.scope === 'account' ? { uin: request.uin } : {}),
deletedFiles: cleanup.deletedFiles,
freedBytes: cleanup.freedBytes,
failureCount: cleanup.failures.length,
};
deps.audit(auditEvent);
for (const failure of cleanup.failures) {
deps.reportError(
`clean storage scope=${request.scope} item=${cleanupFailureItem(failure)}`,
new Error(failure.message),
);
}
lastCleanup = {
at: (deps.now?.() ?? new Date()).toISOString(),
...auditEvent,
...('skippedActiveItems' in cleanup
? { skippedActiveItems: cleanup.skippedActiveItems }
: {}),
failures: cleanup.failures.map((failure) => ({
item: cleanupFailureItem(failure),
message: failure.message,
})),
};
let snapshot: StorageSnapshot;
try {
snapshot = deps.storage.snapshot();
} catch (error) {
deps.reportError(
`refresh storage snapshot after cleanup scope=${request.scope}`,
error,
);
return c.json(
{
success: false,
message: '清理已执行,但刷新存储统计失败,请检查服务器日志',
scope: request.scope,
cleanup,
lastCleanup,
},
500,
);
}
const success = cleanup.failures.length === 0;
return c.json(
{
success,
...(success ? {} : { message: '部分文件清理失败,请检查失败明细' }),
scope: request.scope,
cleanup,
snapshot,
lastCleanup,
},
success ? 200 : 500,
);
});
}
function parseCleanupRequest(body: unknown): StorageCleanupRequest {
if (!isObject(body) || typeof body.scope !== 'string') {
throw new StorageManagementInputError('scope is required');
}
if (body.scope === 'logs' || body.scope === 'temporary') {
assertExactKeys(body, ['scope']);
return { scope: body.scope };
}
if (body.scope === 'account') {
assertExactKeys(body, ['scope', 'category', 'uin']);
const category = parseCategory(body.category);
if (typeof body.uin !== 'string' || !isRealUin(body.uin)) {
throw new StorageManagementInputError('invalid UIN');
if (!isObject(body) || typeof body.scope !== 'string') {
throw new StorageManagementInputError('scope is required');
}
return { scope: 'account', category, uin: body.uin };
}
if (body.scope === 'allAccounts') {
assertExactKeys(body, ['scope', 'category', 'confirmation']);
const category = parseCategory(body.category);
if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) {
throw new StorageManagementInputError('all-account cleanup requires confirmation');
if (body.scope === 'logs' || body.scope === 'temporary') {
assertExactKeys(body, ['scope']);
return { scope: body.scope };
}
return {
scope: 'allAccounts',
category,
confirmation: ALL_ACCOUNTS_CONFIRMATION,
};
}
throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`);
if (body.scope === 'account') {
assertExactKeys(body, ['scope', 'category', 'uin']);
const category = parseCategory(body.category);
if (typeof body.uin !== 'string' || !isRealUin(body.uin)) {
throw new StorageManagementInputError('invalid UIN');
}
return { scope: 'account', category, uin: body.uin };
}
if (body.scope === 'allAccounts') {
assertExactKeys(body, ['scope', 'category', 'confirmation']);
const category = parseCategory(body.category);
if (body.confirmation !== ALL_ACCOUNTS_CONFIRMATION) {
throw new StorageManagementInputError('all-account cleanup requires confirmation');
}
return {
scope: 'allAccounts',
category,
confirmation: ALL_ACCOUNTS_CONFIRMATION,
};
}
throw new StorageManagementInputError(`unsupported cleanup scope: ${body.scope}`);
}
async function executeCleanup(
storage: StorageRouteDependencies['storage'],
request: StorageCleanupRequest,
storage: StorageRouteDependencies['storage'],
request: StorageCleanupRequest,
): Promise<StorageCleanupResult> {
if (request.scope === 'logs') return storage.clearLogs();
if (request.scope === 'temporary') return storage.clearTemporary();
if (request.scope === 'account') {
return storage.clearAccountData(request.category, request.uin);
}
return storage.clearAllAccountData(request.category);
if (request.scope === 'logs') {
return storage.clearLogs();
}
if (request.scope === 'temporary') {
return storage.clearTemporary();
}
if (request.scope === 'account') {
return storage.clearAccountData(request.category, request.uin);
}
return storage.clearAllAccountData(request.category);
}
function parseCategory(value: unknown): AccountStorageCategory {
if (value === 'messages' || value === 'media' || value === 'reactions') return value;
throw new StorageManagementInputError('unsupported account storage category');
if (value === 'messages' || value === 'media' || value === 'reactions') {
return value;
}
throw new StorageManagementInputError('unsupported account storage category');
}
function assertExactKeys(body: Record<string, unknown>, allowed: string[]): void {
const allowedSet = new Set(allowed);
const unknown = Object.keys(body).filter((key) => !allowedSet.has(key));
const missing = allowed.filter((key) => !(key in body));
if (unknown.length > 0 || missing.length > 0) {
throw new StorageManagementInputError('cleanup request has unexpected or missing fields');
}
const allowedSet = new Set(allowed);
const unknown = Object.keys(body).filter((key) => !allowedSet.has(key));
const missing = allowed.filter((key) => !(key in body));
if (unknown.length > 0 || missing.length > 0) {
throw new StorageManagementInputError('cleanup request has unexpected or missing fields');
}
}
function accountScope(request: StorageCleanupRequest): StorageCleanupAuditEvent['accountScope'] {
if (request.scope === 'account') return 'single';
if (request.scope === 'allAccounts') return 'all';
return 'global';
if (request.scope === 'account') {
return 'single';
}
if (request.scope === 'allAccounts') {
return 'all';
}
return 'global';
}
function cleanupFailureItem(
failure: StorageCleanupResult['failures'][number],
): string {
if ('uin' in failure) return `${failure.uin}/${failure.file}`;
if ('file' in failure) return failure.file;
return failure.item;
function cleanupFailureItem(failure: StorageCleanupResult['failures'][number]): string {
if ('uin' in failure) {
return `${failure.uin}/${failure.file}`;
}
if ('file' in failure) {
return failure.file;
}
return failure.item;
}
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);
}
+259 -243
View File
@@ -1,312 +1,328 @@
import type {
LogStoragePolicy,
LogStorageStatus,
} from '@snowluma/common/log-file-transport';
import type { LogStoragePolicy, LogStorageStatus } from '@snowluma/common/log-file-transport';
import {
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
MAX_LOG_RETAIN_DAYS,
MAX_LOG_TOTAL_MB,
type RuntimeConfig,
DEFAULT_LOG_MAX_TOTAL_MB,
DEFAULT_LOG_PER_UIN,
DEFAULT_LOG_RETAIN_DAYS,
MAX_LOG_RETAIN_DAYS,
MAX_LOG_TOTAL_MB,
type RuntimeConfig,
} from '@snowluma/common/runtime';
import {
publicLogStorageStatus,
type PublicLogStorageStatus,
} from './storage-management';
import { publicLogStorageStatus, type PublicLogStorageStatus } from './storage-management';
export type LogStorageSettingsField =
| 'logMaxTotalMb'
| 'logRetainDays'
| 'logPerUin';
export type LogStorageSettingsField = 'logMaxTotalMb' | 'logRetainDays' | 'logPerUin';
export interface LogStorageSettings {
logMaxTotalMb: number;
logRetainDays: number;
logPerUin: boolean;
logMaxTotalMb: number;
logRetainDays: number;
logPerUin: boolean;
}
export interface LogStorageSettingsState {
saved: LogStorageSettings;
effective: LogStorageSettings;
envOverrides: LogStorageSettingsField[];
saved: LogStorageSettings;
effective: LogStorageSettings;
envOverrides: LogStorageSettingsField[];
}
export interface LogStorageSettingsUpdateResult {
settings: LogStorageSettingsState;
status: PublicLogStorageStatus;
settings: LogStorageSettingsState;
status: PublicLogStorageStatus;
}
export class StorageSettingsInputError extends Error {
constructor(message: string) {
super(message);
this.name = 'StorageSettingsInputError';
}
constructor(message: string) {
super(message);
this.name = 'StorageSettingsInputError';
}
}
export class StorageSettingsLockedError extends Error {
constructor(readonly fields: LogStorageSettingsField[]) {
super(`settings are locked by environment variables: ${fields.join(', ')}`);
this.name = 'StorageSettingsLockedError';
}
constructor(readonly fields: LogStorageSettingsField[]) {
super(`settings are locked by environment variables: ${fields.join(', ')}`);
this.name = 'StorageSettingsLockedError';
}
}
export class StorageSettingsTransactionError extends Error {
constructor(
message: string,
readonly operationError: unknown,
readonly rollbackErrors: unknown[],
) {
super(message, { cause: operationError });
this.name = 'StorageSettingsTransactionError';
}
constructor(
message: string,
readonly operationError: unknown,
readonly rollbackErrors: unknown[],
) {
super(message, { cause: operationError });
this.name = 'StorageSettingsTransactionError';
}
}
export interface LogStorageSettingsDependencies {
readPersisted(): RuntimeConfig;
readEnvOverrides(): Partial<RuntimeConfig>;
readEffective(): LogStorageStatus;
persist(patch: Partial<RuntimeConfig>): RuntimeConfig;
apply(policy: LogStoragePolicy): Promise<LogStorageStatus>;
readPersisted(): RuntimeConfig;
readEnvOverrides(): Partial<RuntimeConfig>;
readEffective(): LogStorageStatus;
persist(patch: Partial<RuntimeConfig>): RuntimeConfig;
apply(policy: LogStoragePolicy): Promise<LogStorageStatus>;
}
const SETTINGS_FIELDS: LogStorageSettingsField[] = [
'logMaxTotalMb',
'logRetainDays',
'logPerUin',
];
const SETTINGS_FIELDS: LogStorageSettingsField[] = ['logMaxTotalMb', 'logRetainDays', 'logPerUin'];
const SETTINGS_FIELD_SET = new Set<string>(SETTINGS_FIELDS);
export class LogStorageSettingsManager {
private updateQueue: Promise<void> = Promise.resolve();
private updateQueue: Promise<void> = Promise.resolve();
constructor(private readonly deps: LogStorageSettingsDependencies) {}
constructor(private readonly deps: LogStorageSettingsDependencies) {}
read(): LogStorageSettingsState {
return settingsState(
this.deps.readPersisted(),
this.deps.readEnvOverrides(),
settingsFromStatus(this.deps.readEffective()),
);
}
update(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const operation = this.updateQueue.then(() => this.performUpdate(body));
this.updateQueue = operation.then(
() => undefined,
() => undefined,
);
return operation;
}
private async performUpdate(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const patch = coerceLogStorageSettingsPatch(body);
const previousRuntime = this.deps.readPersisted();
const envOverrides = this.deps.readEnvOverrides();
const previous = settingsState(
previousRuntime,
envOverrides,
settingsFromStatus(this.deps.readEffective()),
);
const locked = SETTINGS_FIELDS.filter(
(field) => field in patch && field in envOverrides,
);
if (locked.length > 0) throw new StorageSettingsLockedError(locked);
const nextSaved = { ...previous.saved, ...patch };
const nextEffective = { ...previous.effective, ...patch };
const previousPolicy = toPolicy(previous.effective);
const nextPolicy = toPolicy(nextEffective);
let status: LogStorageStatus;
try {
status = await this.deps.apply(nextPolicy);
assertApplied(status, nextPolicy);
} catch (error) {
const rollbackErrors = await this.rollbackRuntime(previousPolicy);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to apply log settings and runtime rollback was incomplete'
: 'failed to apply log settings; runtime state was rolled back',
error,
rollbackErrors,
);
read(): LogStorageSettingsState {
return settingsState(
this.deps.readPersisted(),
this.deps.readEnvOverrides(),
settingsFromStatus(this.deps.readEffective()),
);
}
let persistedRuntime: RuntimeConfig;
try {
persistedRuntime = this.deps.persist(patch);
assertPersistedSettings(persistedRuntime, nextSaved);
} catch (error) {
const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to persist log settings and rollback was incomplete'
: 'failed to persist log settings; previous settings were restored',
error,
rollbackErrors,
);
update(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const operation = this.updateQueue.then(() => this.performUpdate(body));
this.updateQueue = operation.then(
() => undefined,
() => undefined,
);
return operation;
}
return {
settings: settingsState(
persistedRuntime,
envOverrides,
settingsFromStatus(status),
),
status: publicLogStorageStatus(status),
};
}
private async performUpdate(body: unknown): Promise<LogStorageSettingsUpdateResult> {
const patch = coerceLogStorageSettingsPatch(body);
const previousRuntime = this.deps.readPersisted();
const envOverrides = this.deps.readEnvOverrides();
const previous = settingsState(
previousRuntime,
envOverrides,
settingsFromStatus(this.deps.readEffective()),
);
const locked = SETTINGS_FIELDS.filter((field) => field in patch && field in envOverrides);
private async rollbackRuntime(policy: LogStoragePolicy): Promise<unknown[]> {
try {
const status = await this.deps.apply(policy);
assertApplied(status, policy);
return [];
} catch (error) {
return [error];
}
}
if (locked.length > 0) {
throw new StorageSettingsLockedError(locked);
}
private async rollbackAll(
policy: LogStoragePolicy,
runtime: RuntimeConfig,
): Promise<unknown[]> {
const errors = await this.rollbackRuntime(policy);
try {
this.deps.persist(runtime);
} catch (error) {
errors.push(error);
const nextSaved = { ...previous.saved, ...patch };
const nextEffective = { ...previous.effective, ...patch };
const previousPolicy = toPolicy(previous.effective);
const nextPolicy = toPolicy(nextEffective);
let status: LogStorageStatus;
try {
status = await this.deps.apply(nextPolicy);
assertApplied(status, nextPolicy);
} catch (error) {
const rollbackErrors = await this.rollbackRuntime(previousPolicy);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to apply log settings and runtime rollback was incomplete'
: 'failed to apply log settings; runtime state was rolled back',
error,
rollbackErrors,
);
}
let persistedRuntime: RuntimeConfig;
try {
persistedRuntime = this.deps.persist(patch);
assertPersistedSettings(persistedRuntime, nextSaved);
} catch (error) {
const rollbackErrors = await this.rollbackAll(previousPolicy, previousRuntime);
throw new StorageSettingsTransactionError(
rollbackErrors.length > 0
? 'failed to persist log settings and rollback was incomplete'
: 'failed to persist log settings; previous settings were restored',
error,
rollbackErrors,
);
}
return {
settings: settingsState(persistedRuntime, envOverrides, settingsFromStatus(status)),
status: publicLogStorageStatus(status),
};
}
private async rollbackRuntime(policy: LogStoragePolicy): Promise<unknown[]> {
try {
const status = await this.deps.apply(policy);
assertApplied(status, policy);
return [];
} catch (error) {
return [error];
}
}
private async rollbackAll(
policy: LogStoragePolicy,
runtime: RuntimeConfig,
): Promise<unknown[]> {
const errors = await this.rollbackRuntime(policy);
try {
this.deps.persist(runtime);
} catch (error) {
errors.push(error);
}
return errors;
}
return errors;
}
}
function coerceLogStorageSettingsPatch(body: unknown): Partial<LogStorageSettings> {
if (!isObject(body)) throw new StorageSettingsInputError('body must be an object');
const keys = Object.keys(body);
if (keys.length === 0) throw new StorageSettingsInputError('at least one setting is required');
const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key));
if (unknown.length > 0) {
throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`);
}
if (!isObject(body)) {
throw new StorageSettingsInputError('body must be an object');
}
const patch: Partial<LogStorageSettings> = {};
if ('logMaxTotalMb' in body) {
const value = body.logMaxTotalMb;
if (
typeof value !== 'number'
|| !Number.isSafeInteger(value)
|| value < 1
|| value > MAX_LOG_TOTAL_MB
) {
throw new StorageSettingsInputError(
`logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`,
);
const keys = Object.keys(body);
if (keys.length === 0) {
throw new StorageSettingsInputError('at least one setting is required');
}
patch.logMaxTotalMb = value;
}
if ('logRetainDays' in body) {
const value = body.logRetainDays;
if (
typeof value !== 'number'
|| !Number.isSafeInteger(value)
|| value < 0
|| value > MAX_LOG_RETAIN_DAYS
) {
throw new StorageSettingsInputError(
`logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`,
);
const unknown = keys.filter((key) => !SETTINGS_FIELD_SET.has(key));
if (unknown.length > 0) {
throw new StorageSettingsInputError(`unknown setting: ${unknown.join(', ')}`);
}
patch.logRetainDays = value;
}
if ('logPerUin' in body) {
if (typeof body.logPerUin !== 'boolean') {
throw new StorageSettingsInputError('logPerUin must be a boolean');
const patch: Partial<LogStorageSettings> = {};
if ('logMaxTotalMb' in body) {
const value = body.logMaxTotalMb;
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 1 ||
value > MAX_LOG_TOTAL_MB
) {
throw new StorageSettingsInputError(
`logMaxTotalMb must be an integer in 1..${MAX_LOG_TOTAL_MB}`,
);
}
patch.logMaxTotalMb = value;
}
patch.logPerUin = body.logPerUin;
}
return patch;
if ('logRetainDays' in body) {
const value = body.logRetainDays;
if (
typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < 0 ||
value > MAX_LOG_RETAIN_DAYS
) {
throw new StorageSettingsInputError(
`logRetainDays must be an integer in 0..${MAX_LOG_RETAIN_DAYS}`,
);
}
patch.logRetainDays = value;
}
if ('logPerUin' in body) {
if (typeof body.logPerUin !== 'boolean') {
throw new StorageSettingsInputError('logPerUin must be a boolean');
}
patch.logPerUin = body.logPerUin;
}
return patch;
}
function settingsState(
runtime: RuntimeConfig,
envOverrides: Partial<RuntimeConfig>,
liveEffective?: LogStorageSettings,
runtime: RuntimeConfig,
envOverrides: Partial<RuntimeConfig>,
liveEffective?: LogStorageSettings,
): LogStorageSettingsState {
const saved = settingsFromRuntime(runtime);
const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides);
const effective = liveEffective ?? {
...saved,
...settingsPatchFromRuntime(envOverrides),
};
return { saved, effective, envOverrides: envOverridesList };
const saved = settingsFromRuntime(runtime);
const envOverridesList = SETTINGS_FIELDS.filter((field) => field in envOverrides);
const effective = liveEffective ?? {
...saved,
...settingsPatchFromRuntime(envOverrides),
};
return { saved, effective, envOverrides: envOverridesList };
}
function settingsFromStatus(status: LogStorageStatus): LogStorageSettings {
const maxTotalMb = status.maxTotalBytes / (1024 * 1024);
if (!Number.isSafeInteger(maxTotalMb)) {
throw new Error('live log storage limit is not an integer number of megabytes');
}
return {
logMaxTotalMb: maxTotalMb,
logRetainDays: status.retainDays,
logPerUin: status.perUinEnabled,
};
const maxTotalMb = status.maxTotalBytes / (1024 * 1024);
if (!Number.isSafeInteger(maxTotalMb)) {
throw new Error('live log storage limit is not an integer number of megabytes');
}
return {
logMaxTotalMb: maxTotalMb,
logRetainDays: status.retainDays,
logPerUin: status.perUinEnabled,
};
}
function settingsFromRuntime(runtime: RuntimeConfig): LogStorageSettings {
return {
logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN,
};
return {
logMaxTotalMb: runtime.logMaxTotalMb ?? DEFAULT_LOG_MAX_TOTAL_MB,
logRetainDays: runtime.logRetainDays ?? DEFAULT_LOG_RETAIN_DAYS,
logPerUin: runtime.logPerUin ?? DEFAULT_LOG_PER_UIN,
};
}
function settingsPatchFromRuntime(runtime: Partial<RuntimeConfig>): Partial<LogStorageSettings> {
const patch: Partial<LogStorageSettings> = {};
if (runtime.logMaxTotalMb !== undefined) patch.logMaxTotalMb = runtime.logMaxTotalMb;
if (runtime.logRetainDays !== undefined) patch.logRetainDays = runtime.logRetainDays;
if (runtime.logPerUin !== undefined) patch.logPerUin = runtime.logPerUin;
return patch;
const patch: Partial<LogStorageSettings> = {};
if (runtime.logMaxTotalMb !== undefined) {
patch.logMaxTotalMb = runtime.logMaxTotalMb;
}
if (runtime.logRetainDays !== undefined) {
patch.logRetainDays = runtime.logRetainDays;
}
if (runtime.logPerUin !== undefined) {
patch.logPerUin = runtime.logPerUin;
}
return patch;
}
function toPolicy(settings: LogStorageSettings): LogStoragePolicy {
return {
maxTotalMb: settings.logMaxTotalMb,
retainDays: settings.logRetainDays,
perUinEnabled: settings.logPerUin,
};
return {
maxTotalMb: settings.logMaxTotalMb,
retainDays: settings.logRetainDays,
perUinEnabled: settings.logPerUin,
};
}
function assertApplied(status: LogStorageStatus, policy: LogStoragePolicy): void {
const expectedBytes = policy.maxTotalMb * 1024 * 1024;
if (
status.state === 'warning'
|| status.state === 'degraded'
|| status.lastError !== undefined
|| status.maxTotalBytes !== expectedBytes
|| status.retainDays !== policy.retainDays
|| status.perUinEnabled !== policy.perUinEnabled
) {
throw new Error(status.lastError ?? 'log storage policy did not become effective');
}
const expectedBytes = policy.maxTotalMb * 1024 * 1024;
if (
status.state === 'warning' ||
status.state === 'degraded' ||
status.lastError !== undefined ||
status.maxTotalBytes !== expectedBytes ||
status.retainDays !== policy.retainDays ||
status.perUinEnabled !== policy.perUinEnabled
) {
throw new Error(status.lastError ?? 'log storage policy did not become effective');
}
}
function assertPersistedSettings(
runtime: RuntimeConfig,
expected: LogStorageSettings,
): void {
const actual = settingsFromRuntime(runtime);
if (
actual.logMaxTotalMb !== expected.logMaxTotalMb
|| actual.logRetainDays !== expected.logRetainDays
|| actual.logPerUin !== expected.logPerUin
) {
throw new Error('persisted log storage settings do not match the requested values');
}
function assertPersistedSettings(runtime: RuntimeConfig, expected: LogStorageSettings): void {
const actual = settingsFromRuntime(runtime);
if (
actual.logMaxTotalMb !== expected.logMaxTotalMb ||
actual.logRetainDays !== expected.logRetainDays ||
actual.logPerUin !== expected.logPerUin
) {
throw new Error('persisted log storage settings do not match the requested values');
}
}
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);
}
+53 -41
View File
@@ -6,70 +6,82 @@
import type { RuntimeConfig } from '@snowluma/common/runtime';
import { checkListenerExposure } from './listener-exposure';
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
export type SettingsPatch = Partial<
Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>
>;
export type CoerceResult =
| { ok: true; patch: SettingsPatch }
| { ok: false; error: string };
export type CoerceResult = { ok: true; patch: SettingsPatch } | { ok: false; error: string };
function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
return typeof v === 'object' && v !== null && !Array.isArray(v);
}
export function coerceSettingsPatch(body: unknown): CoerceResult {
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
const patch: SettingsPatch = {};
if ('webuiPort' in body) {
const p = body.webuiPort;
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
if (!isObject(body)) {
return { ok: false, error: 'body must be an object' };
}
patch.webuiPort = p;
}
if ('webuiHost' in body) {
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
return { ok: false, error: 'webuiHost must be a non-empty string' };
const patch: SettingsPatch = {};
if ('webuiPort' in body) {
const p = body.webuiPort;
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
}
patch.webuiPort = p;
}
patch.webuiHost = body.webuiHost.trim();
}
if ('tlsEnabled' in body) {
if (typeof body.tlsEnabled !== 'boolean') {
return { ok: false, error: 'tlsEnabled must be a boolean' };
if ('webuiHost' in body) {
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
return { ok: false, error: 'webuiHost must be a non-empty string' };
}
patch.webuiHost = body.webuiHost.trim();
}
patch.webuiTls = { enabled: body.tlsEnabled };
}
if ('trustProxy' in body) {
if (typeof body.trustProxy !== 'string') {
return { ok: false, error: 'trustProxy must be a string' };
if ('tlsEnabled' in body) {
if (typeof body.tlsEnabled !== 'boolean') {
return { ok: false, error: 'tlsEnabled must be a boolean' };
}
patch.webuiTls = { enabled: body.tlsEnabled };
}
patch.trustProxy = body.trustProxy;
}
return { ok: true, patch };
if ('trustProxy' in body) {
if (typeof body.trustProxy !== 'string') {
return { ok: false, error: 'trustProxy must be a string' };
}
patch.trustProxy = body.trustProxy;
}
return { ok: true, patch };
}
const SETTINGS_ERRORS: Record<'invalid-bind-host' | 'tls-pair-required', string> = {
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
'invalid-bind-host': '绑定地址不是有效的 TCP 地址',
'tls-pair-required': '启用 TLS 前请先上传有效的证书与私钥',
};
/** Validate the listener that would be persisted after applying `patch` to `current`. */
export function evaluateSettingsSave(
current: RuntimeConfig,
patch: SettingsPatch,
pairOk: boolean,
current: RuntimeConfig,
patch: SettingsPatch,
pairOk: boolean,
): CoerceResult {
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
if (!check.ok) return { ok: false, error: SETTINGS_ERRORS[check.code] };
return { ok: true, patch };
const webuiHost = patch.webuiHost ?? current.webuiHost ?? '127.0.0.1';
const tlsEnabled = patch.webuiTls?.enabled ?? current.webuiTls?.enabled ?? false;
const check = checkListenerExposure({ webuiHost, tlsEnabled, pairOk });
if (!check.ok) {
return { ok: false, error: SETTINGS_ERRORS[check.code] };
}
return { ok: true, patch };
}
export function tlsCertDeletionBlocked(tlsEnabled: boolean): boolean {
return tlsEnabled;
return tlsEnabled;
}
+56 -38
View File
@@ -9,63 +9,81 @@ import path from 'path';
import tls from 'tls';
export interface TlsValidation {
ok: boolean;
reason?: string;
ok: boolean;
reason?: string;
}
export interface TlsResolution {
ok: boolean;
cert?: Buffer;
key?: Buffer;
reason?: string;
ok: boolean;
cert?: Buffer;
key?: Buffer;
reason?: string;
}
export interface RequiredTlsContext {
cert: Buffer;
key: Buffer;
cert: Buffer;
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
return e instanceof Error ? e.message : String(e);
}
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' };
if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' };
try {
tls.createSecureContext({ cert, key });
return { ok: true };
} catch (e) {
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
}
if (!cert || !cert.toString().trim()) {
return { ok: false, reason: 'certificate is empty' };
}
if (!key || !key.toString().trim()) {
return { ok: false, reason: 'private key is empty' };
}
try {
tls.createSecureContext({ cert, key });
return { ok: true };
} catch (e) {
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
}
}
/** Load + validate config/cert.pem + config/key.pem from `configDir`. */
export function resolveTlsContext(configDir: string): TlsResolution {
const certPath = path.join(configDir, 'cert.pem');
const keyPath = path.join(configDir, 'key.pem');
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
}
let cert: Buffer;
let key: Buffer;
try {
cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath);
} catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
}
const valid = validateTlsPair(cert, key);
if (!valid.ok) return { ok: false, reason: valid.reason };
return { ok: true, cert, key };
const certPath = path.join(configDir, 'cert.pem');
const keyPath = path.join(configDir, 'key.pem');
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
}
let cert: Buffer;
let key: Buffer;
try {
cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath);
} catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
}
const valid = validateTlsPair(cert, key);
if (!valid.ok) {
return { ok: false, reason: valid.reason };
}
return { ok: true, cert, key };
}
/** Resolve the configured pair for an enabled listener or abort startup. */
export function requireTlsContext(configDir: string): RequiredTlsContext {
const resolved = resolveTlsContext(configDir);
if (!resolved.ok || !resolved.cert || !resolved.key) {
throw new Error(`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`);
}
return { cert: resolved.cert, key: resolved.key };
const resolved = resolveTlsContext(configDir);
if (!resolved.ok || !resolved.cert || !resolved.key) {
throw new Error(
`TLS listener cannot start: ${resolved.reason ?? 'certificate pair is unusable'}`,
);
}
return { cert: resolved.cert, key: resolved.key };
}
+355 -241
View File
@@ -1,4 +1,11 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import {
createCipheriv,
createDecipheriv,
createHash,
randomBytes,
scryptSync,
timingSafeEqual,
} from 'node:crypto';
import * as OTPAuth from 'otpauth';
const TOTP_PERIOD_SECONDS = 30;
@@ -14,324 +21,431 @@ const SCRYPT_R = 8;
const SCRYPT_P = 1;
export interface WrappedTotpSecret {
wrapSalt: string;
iv: string;
ciphertext: string;
authTag: string;
wrapSalt: string;
iv: string;
ciphertext: string;
authTag: string;
}
export interface TotpPersistedState extends WrappedTotpSecret {
recoveryCodeHashes: string[];
lastUsedStep: number;
label: string;
recoveryCodeHashes: string[];
lastUsedStep: number;
label: string;
}
export interface TotpEnrollment {
secret: string;
otpauthUrl: string;
issuer: string;
accountName: string;
secret: string;
otpauthUrl: string;
issuer: string;
accountName: string;
}
function totpFromSecret(secretBase32: string, issuer = '', accountName = 'admin'): OTPAuth.TOTP {
return new OTPAuth.TOTP({
issuer,
label: accountName,
algorithm: 'SHA1',
digits: TOTP_DIGITS,
period: TOTP_PERIOD_SECONDS,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
return new OTPAuth.TOTP({
issuer,
label: accountName,
algorithm: 'SHA1',
digits: TOTP_DIGITS,
period: TOTP_PERIOD_SECONDS,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
}
export function verifyTotpCode(
secretBase32: string,
code: string,
atMs: number,
lastUsedStep?: number,
secretBase32: string,
code: string,
atMs: number,
lastUsedStep?: number,
): { ok: true; step: number } | { ok: false } {
const token = code.replace(/\s/g, '');
if (!/^\d{6}$/.test(token)) return { ok: false };
const token = code.replace(/\s/g, '');
let totp: OTPAuth.TOTP;
try {
totp = totpFromSecret(secretBase32);
} catch {
return { ok: false };
}
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
if (delta === null) return { ok: false };
if (!/^\d{6}$/.test(token)) {
return { ok: false };
}
const step = totp.counter({ timestamp: atMs }) + delta;
if (lastUsedStep !== undefined && step === lastUsedStep) return { ok: false };
return { ok: true, step };
let totp: OTPAuth.TOTP;
try {
totp = totpFromSecret(secretBase32);
} catch {
return { ok: false };
}
const delta = totp.validate({ token, timestamp: atMs, window: TOTP_WINDOW });
if (delta === null) {
return { ok: false };
}
const step = totp.counter({ timestamp: atMs }) + delta;
if (lastUsedStep !== undefined && step === lastUsedStep) {
return { ok: false };
}
return { ok: true, step };
}
function deriveWrapKey(password: string, salt: Buffer): Buffer {
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
return scryptSync(password, salt, WRAP_KEY_BYTES, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P });
}
export function wrapTotpSecret(password: string, secret: string): WrappedTotpSecret {
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
const iv = randomBytes(WRAP_IV_BYTES);
const key = deriveWrapKey(password, wrapSalt);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
return {
wrapSalt: wrapSalt.toString('hex'),
iv: iv.toString('hex'),
ciphertext: ciphertext.toString('hex'),
authTag: cipher.getAuthTag().toString('hex'),
};
const wrapSalt = randomBytes(WRAP_SALT_BYTES);
const iv = randomBytes(WRAP_IV_BYTES);
const key = deriveWrapKey(password, wrapSalt);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
return {
wrapSalt: wrapSalt.toString('hex'),
iv: iv.toString('hex'),
ciphertext: ciphertext.toString('hex'),
authTag: cipher.getAuthTag().toString('hex'),
};
}
export function unwrapTotpSecret(password: string, wrapped: WrappedTotpSecret): string | null {
try {
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
const iv = Buffer.from(wrapped.iv, 'hex');
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
const authTag = Buffer.from(wrapped.authTag, 'hex');
if (wrapSalt.length !== WRAP_SALT_BYTES || iv.length !== WRAP_IV_BYTES || authTag.length !== 16) {
return null;
try {
const wrapSalt = Buffer.from(wrapped.wrapSalt, 'hex');
const iv = Buffer.from(wrapped.iv, 'hex');
const ciphertext = Buffer.from(wrapped.ciphertext, 'hex');
const authTag = Buffer.from(wrapped.authTag, 'hex');
if (
wrapSalt.length !== WRAP_SALT_BYTES ||
iv.length !== WRAP_IV_BYTES ||
authTag.length !== 16
) {
return null;
}
const key = deriveWrapKey(password, wrapSalt);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
} catch {
return null;
}
const key = deriveWrapKey(password, wrapSalt);
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
} catch {
return null;
}
}
function randomRecoveryChunk(): string {
const bytes = randomBytes(4);
let chunk = '';
for (let i = 0; i < 4; i++) {
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
}
return chunk;
const bytes = randomBytes(4);
let chunk = '';
for (let i = 0; i < 4; i++) {
chunk += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length];
}
return chunk;
}
export function generateRecoveryCodes(): string[] {
const codes = new Set<string>();
while (codes.size < RECOVERY_CODE_COUNT) {
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
}
return [...codes];
const codes = new Set<string>();
while (codes.size < RECOVERY_CODE_COUNT) {
codes.add(`${randomRecoveryChunk()}-${randomRecoveryChunk()}`);
}
return [...codes];
}
export function normalizeRecoveryCode(code: string): string {
return code.replace(/[-\s]/g, '').toUpperCase();
return code.replace(/[-\s]/g, '').toUpperCase();
}
export function hashRecoveryCode(code: string): string {
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
return createHash('sha256').update(normalizeRecoveryCode(code), 'utf8').digest('hex');
}
function hashesEqual(left: string, right: string): boolean {
const a = Buffer.from(left, 'hex');
const b = Buffer.from(right, 'hex');
if (a.length !== b.length || a.length === 0) return false;
return timingSafeEqual(a, b);
const a = Buffer.from(left, 'hex');
const b = Buffer.from(right, 'hex');
if (a.length !== b.length || a.length === 0) {
return false;
}
return timingSafeEqual(a, b);
}
export function consumeRecoveryCode(
code: string,
hashes: readonly string[],
code: string,
hashes: readonly string[],
): { ok: true; remainingHashes: string[] } | { ok: false } {
const candidate = hashRecoveryCode(code);
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
if (index < 0) return { ok: false };
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
const candidate = hashRecoveryCode(code);
const index = hashes.findIndex((hash) => hashesEqual(hash, candidate));
if (index < 0) {
return { ok: false };
}
return { ok: true, remainingHashes: hashes.filter((_, i) => i !== index) };
}
export function beginTotpEnrollment(options: {
issuer: string;
accountName: string;
secret?: string;
issuer: string;
accountName: string;
secret?: string;
}): TotpEnrollment {
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
const totp = totpFromSecret(secret, options.issuer, options.accountName);
return {
secret,
otpauthUrl: totp.toString(),
issuer: options.issuer,
accountName: options.accountName,
};
const secret = options.secret ?? new OTPAuth.Secret({ size: 20 }).base32;
const totp = totpFromSecret(secret, options.issuer, options.accountName);
return {
secret,
otpauthUrl: totp.toString(),
issuer: options.issuer,
accountName: options.accountName,
};
}
export function confirmTotpEnrollment(options: {
password: string;
secret: string;
code: string;
label: string;
atMs: number;
password: string;
secret: string;
code: string;
label: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...wrapTotpSecret(options.password, options.secret),
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
lastUsedStep: verified.step,
label: options.label,
},
};
const verified = verifyTotpCode(options.secret, options.code, options.atMs);
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...wrapTotpSecret(options.password, options.secret),
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
lastUsedStep: verified.step,
label: options.label,
},
};
}
export function verifySecondFactor(options: {
password: string;
state: TotpPersistedState;
atMs: number;
totp?: string;
recoveryCode?: string;
password: string;
state: TotpPersistedState;
atMs: number;
totp?: string;
recoveryCode?: string;
}): { ok: true; state: TotpPersistedState } | { ok: false } {
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
const consumed = consumeRecoveryCode(options.recoveryCode, options.state.recoveryCodeHashes);
if (!consumed.ok) return { ok: false };
return { ok: true, state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes } };
}
if (typeof options.totp !== 'string') return { ok: false };
const secret = unwrapTotpSecret(options.password, options.state);
if (secret === null) return { ok: false };
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
if (!checked.ok) return { ok: false };
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
if (typeof options.recoveryCode === 'string' && options.recoveryCode.length > 0) {
const consumed = consumeRecoveryCode(
options.recoveryCode,
options.state.recoveryCodeHashes,
);
if (!consumed.ok) {
return { ok: false };
}
return {
ok: true,
state: { ...options.state, recoveryCodeHashes: consumed.remainingHashes },
};
}
if (typeof options.totp !== 'string') {
return { ok: false };
}
const secret = unwrapTotpSecret(options.password, options.state);
if (secret === null) {
return { ok: false };
}
const checked = verifyTotpCode(secret, options.totp, options.atMs, options.state.lastUsedStep);
if (!checked.ok) {
return { ok: false };
}
return { ok: true, state: { ...options.state, lastUsedStep: checked.step } };
}
export type SecondFactorDecision =
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; state?: TotpPersistedState };
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; state?: TotpPersistedState };
export function decideSecondFactorLogin(options: {
totpEnabled: boolean;
state?: TotpPersistedState;
password: string;
totp?: string;
recoveryCode?: string;
atMs: number;
totpEnabled: boolean;
state?: TotpPersistedState;
password: string;
totp?: string;
recoveryCode?: string;
atMs: number;
}): SecondFactorDecision {
if (!options.totpEnabled) return { kind: 'ok' };
if (!options.state) return { kind: 'bad-second-factor' };
const totp = typeof options.totp === 'string' && options.totp.trim().length > 0
? options.totp.trim()
: undefined;
const recoveryCode = typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
? options.recoveryCode.trim()
: undefined;
if (!totp && !recoveryCode) return { kind: 'needs-totp' };
const result = verifySecondFactor({
password: options.password,
state: options.state,
atMs: options.atMs,
totp,
recoveryCode,
});
if (!result.ok) return { kind: 'bad-second-factor' };
return { kind: 'ok', state: result.state };
if (!options.totpEnabled) {
return { kind: 'ok' };
}
if (!options.state) {
return { kind: 'bad-second-factor' };
}
const totp =
typeof options.totp === 'string' && options.totp.trim().length > 0
? options.totp.trim()
: undefined;
const recoveryCode =
typeof options.recoveryCode === 'string' && options.recoveryCode.trim().length > 0
? options.recoveryCode.trim()
: undefined;
if (!totp && !recoveryCode) {
return { kind: 'needs-totp' };
}
const result = verifySecondFactor({
password: options.password,
state: options.state,
atMs: options.atMs,
totp,
recoveryCode,
});
if (!result.ok) {
return { kind: 'bad-second-factor' };
}
return { kind: 'ok', state: result.state };
}
export function regenerateRecoveryCodes(options: {
password: string;
state: TotpPersistedState;
totp: string;
atMs: number;
password: string;
state: TotpPersistedState;
totp: string;
atMs: number;
}): { state: TotpPersistedState; recoveryCodes: string[] } {
const verified = verifySecondFactor({
password: options.password,
state: options.state,
totp: options.totp,
atMs: options.atMs,
});
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...verified.state,
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
},
};
const verified = verifySecondFactor({
password: options.password,
state: options.state,
totp: options.totp,
atMs: options.atMs,
});
if (!verified.ok) {
throw new Error('验证码不正确');
}
const recoveryCodes = generateRecoveryCodes();
return {
recoveryCodes,
state: {
...verified.state,
recoveryCodeHashes: recoveryCodes.map(hashRecoveryCode),
},
};
}
export function rewrapTotpSecret(
oldPassword: string,
newPassword: string,
state: TotpPersistedState,
oldPassword: string,
newPassword: string,
state: TotpPersistedState,
): TotpPersistedState {
const secret = unwrapTotpSecret(oldPassword, state);
if (secret === null) {
throw new Error('无法使用当前密码解开 2FA 密钥');
}
return {
...state,
...wrapTotpSecret(newPassword, secret),
};
const secret = unwrapTotpSecret(oldPassword, state);
if (secret === null) {
throw new Error('无法使用当前密码解开 2FA 密钥');
}
return {
...state,
...wrapTotpSecret(newPassword, secret),
};
}
const HEX = /^[0-9a-f]+$/i;
function isWrappedShape(value: Record<string, unknown>): value is WrappedTotpSecret & Record<string, unknown> {
return typeof value.wrapSalt === 'string'
&& HEX.test(value.wrapSalt)
&& value.wrapSalt.length === WRAP_SALT_BYTES * 2
&& typeof value.iv === 'string'
&& HEX.test(value.iv)
&& value.iv.length === WRAP_IV_BYTES * 2
&& typeof value.ciphertext === 'string'
&& HEX.test(value.ciphertext)
&& value.ciphertext.length > 0
&& value.ciphertext.length % 2 === 0
&& typeof value.authTag === 'string'
&& HEX.test(value.authTag)
&& value.authTag.length === 32;
function isWrappedShape(
value: Record<string, unknown>,
): value is WrappedTotpSecret & Record<string, unknown> {
return (
typeof value.wrapSalt === 'string' &&
HEX.test(value.wrapSalt) &&
value.wrapSalt.length === WRAP_SALT_BYTES * 2 &&
typeof value.iv === 'string' &&
HEX.test(value.iv) &&
value.iv.length === WRAP_IV_BYTES * 2 &&
typeof value.ciphertext === 'string' &&
HEX.test(value.ciphertext) &&
value.ciphertext.length > 0 &&
value.ciphertext.length % 2 === 0 &&
typeof value.authTag === 'string' &&
HEX.test(value.authTag) &&
value.authTag.length === 32
);
}
export function prepareTotpStateForRestore(value: unknown): TotpPersistedState {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('totp state must be an object');
}
const v = value as Record<string, unknown>;
if (!isWrappedShape(v)) {
throw new Error('totp wrapped secret fields are invalid');
}
if (!Array.isArray(v.recoveryCodeHashes)
|| v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT
|| v.recoveryCodeHashes.some((hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash))) {
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
}
if (typeof v.lastUsedStep !== 'number' || !Number.isInteger(v.lastUsedStep) || v.lastUsedStep < 0) {
throw new Error('totp lastUsedStep must be a non-negative integer');
}
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
throw new Error('totp label must be a non-empty string');
}
const allowed = new Set(['wrapSalt', 'iv', 'ciphertext', 'authTag', 'recoveryCodeHashes', 'lastUsedStep', 'label']);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) throw new Error(`unknown totp field $.${unknown}`);
return {
wrapSalt: v.wrapSalt.toLowerCase(),
iv: v.iv.toLowerCase(),
ciphertext: v.ciphertext.toLowerCase(),
authTag: v.authTag.toLowerCase(),
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
lastUsedStep: v.lastUsedStep,
label: v.label,
};
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error('totp state must be an object');
}
const v = value as Record<string, unknown>;
if (!isWrappedShape(v)) {
throw new Error('totp wrapped secret fields are invalid');
}
if (
!Array.isArray(v.recoveryCodeHashes) ||
v.recoveryCodeHashes.length > RECOVERY_CODE_COUNT ||
v.recoveryCodeHashes.some(
(hash) => typeof hash !== 'string' || !/^[0-9a-f]{64}$/i.test(hash),
)
) {
throw new Error('totp recoveryCodeHashes must be SHA-256 hex strings');
}
if (
typeof v.lastUsedStep !== 'number' ||
!Number.isInteger(v.lastUsedStep) ||
v.lastUsedStep < 0
) {
throw new Error('totp lastUsedStep must be a non-negative integer');
}
if (typeof v.label !== 'string' || v.label.length === 0 || v.label.length > 128) {
throw new Error('totp label must be a non-empty string');
}
const allowed = new Set([
'wrapSalt',
'iv',
'ciphertext',
'authTag',
'recoveryCodeHashes',
'lastUsedStep',
'label',
]);
const unknown = Object.keys(v).find((key) => !allowed.has(key));
if (unknown) {
throw new Error(`unknown totp field $.${unknown}`);
}
return {
wrapSalt: v.wrapSalt.toLowerCase(),
iv: v.iv.toLowerCase(),
ciphertext: v.ciphertext.toLowerCase(),
authTag: v.authTag.toLowerCase(),
recoveryCodeHashes: v.recoveryCodeHashes.map((hash) => (hash as string).toLowerCase()),
lastUsedStep: v.lastUsedStep,
label: v.label,
};
}
export function parseTotpStateLenient(value: unknown): TotpPersistedState | undefined {
if (value === undefined || value === null) return undefined;
try {
return prepareTotpStateForRestore(value);
} catch {
return undefined;
}
if (value === undefined || value === null) {
return undefined;
}
try {
return prepareTotpStateForRestore(value);
} catch {
return undefined;
}
}
File diff suppressed because it is too large. Load diff
+130 -99
View File
@@ -21,38 +21,38 @@ const FETCH_TIMEOUT_MS = 8_000;
const NOTES_MAX = 4_000; // cap the release-body we hand back to the client
export interface UpdateCheckResult {
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
/** The running build's version (no `v` prefix). */
current: string;
/** Latest stable release version, or null when the check did not complete. */
latest: string | null;
/** True only when `latest` is strictly newer than `current`. */
hasUpdate: boolean;
/** GitHub release page URL for the latest release. */
htmlUrl: string | null;
/** Release notes (markdown), truncated to {@link NOTES_MAX}. */
notes: string | null;
/** ISO timestamp the latest release was published. */
publishedAt: string | null;
/** When this result was produced (epoch ms). */
checkedAt: number;
/** Set when the check was skipped or failed; the UI degrades silently. */
error?: string;
}
interface GithubRelease {
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
tag_name?: string;
html_url?: string;
body?: string;
published_at?: string;
}
export function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
}
/**
@@ -63,78 +63,107 @@ function isEnabled(): boolean {
* pulling in a `semver` runtime dependency (the dist bundle ships none).
*/
export function compareVersions(a: string, b: string): number {
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) nums.push(0);
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i];
}
if (pa.pre === pb.pre) return 0;
if (!pa.pre) return 1; // release > prerelease
if (!pb.pre) return -1;
return pa.pre < pb.pre ? -1 : 1;
const parse = (v: string) => {
const [core = '', pre = ''] = v.replace(/^v/, '').split('-', 2);
const nums = core.split('.').map((n) => parseInt(n, 10) || 0);
while (nums.length < 3) {
nums.push(0);
}
return { nums, pre };
};
const pa = parse(a);
const pb = parse(b);
for (let i = 0; i < 3; i++) {
if (pa.nums[i] !== pb.nums[i]) {
return pa.nums[i] - pb.nums[i];
}
}
if (pa.pre === pb.pre) {
return 0;
}
if (!pa.pre) {
return 1;
} // release > prerelease
if (!pb.pre) {
return -1;
}
return pa.pre < pb.pre ? -1 : 1;
}
// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's
// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results
// are intentionally not cached (shouldCache) so the next check retries.
const updateCache = createSingleFlightCache<string, UpdateCheckResult>({
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
ttlMs: CACHE_TTL_MS,
shouldCache: (r) => !r.error,
load: async (current) => {
const result = await fetchLatest(current);
if (result.error) {
log.debug('update check failed: %s', result.error);
} else if (result.hasUpdate) {
log.info('a newer release is available: v%s (running v%s)', result.latest, current);
}
return result;
},
});
async function fetchLatest(current: string): Promise<UpdateCheckResult> {
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) return { ...base, error: `github ${res.status}` };
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) return { ...base, error: 'no tag' };
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
const base: UpdateCheckResult = {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
try {
// `/releases/latest` already excludes drafts and prereleases, so this is
// stable-channel by construction.
const res = await fetch(LATEST_RELEASE_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': `SnowLuma/${current}`,
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) {
return { ...base, error: `github ${res.status}` };
}
const rel = (await res.json()) as GithubRelease;
const tag = (rel.tag_name ?? '').trim();
if (!tag) {
return { ...base, error: 'no tag' };
}
const latest = tag.replace(/^v/, '');
return {
current,
latest,
hasUpdate: compareVersions(latest, current) > 0,
htmlUrl: rel.html_url ?? null,
notes: rel.body ? rel.body.slice(0, NOTES_MAX) : null,
publishedAt: rel.published_at ?? null,
checkedAt: Date.now(),
};
} catch (e) {
return { ...base, error: e instanceof Error ? e.message : 'network error' };
}
}
/**
@@ -144,21 +173,23 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
return updateCache.get(current, { force });
const current = currentVersion();
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
}
return updateCache.get(current, { force });
}
function emptyResult(current: string): UpdateCheckResult {
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
return {
current,
latest: null,
hasUpdate: false,
htmlUrl: null,
notes: null,
publishedAt: null,
checkedAt: Date.now(),
};
}
+53 -37
View File
@@ -1,51 +1,67 @@
import { decideSecondFactorLogin, type TotpPersistedState } from './totp';
export interface WebuiLoginAuth {
verify(password: string): boolean;
totpEnabled(): boolean;
totpState(): TotpPersistedState | undefined;
mustChangePassword(): boolean;
verify(password: string): boolean;
totpEnabled(): boolean;
totpState(): TotpPersistedState | undefined;
mustChangePassword(): boolean;
}
export type WebuiLoginResult =
| { kind: 'bad-request' }
| { kind: 'bad-password' }
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
| { kind: 'bad-request' }
| { kind: 'bad-password' }
| { kind: 'needs-totp' }
| { kind: 'bad-second-factor' }
| { kind: 'ok'; mustChangePassword: boolean; totpState?: TotpPersistedState };
function readString(value: unknown): string {
return typeof value === 'string' ? value : '';
return typeof value === 'string' ? value : '';
}
export function completeWebuiLogin(auth: WebuiLoginAuth, body: unknown, atMs: number): WebuiLoginResult {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return { kind: 'bad-request' };
}
const record = body as Record<string, unknown>;
const password = readString(record.password);
if (!auth.verify(password)) {
return { kind: 'bad-password' };
}
const decision = decideSecondFactorLogin({
totpEnabled: auth.totpEnabled(),
state: auth.totpState(),
password,
totp: readString(record.totp) || undefined,
recoveryCode: readString(record.recoveryCode) || undefined,
atMs,
});
if (decision.kind === 'needs-totp') return { kind: 'needs-totp' };
if (decision.kind === 'bad-second-factor') return { kind: 'bad-second-factor' };
return {
kind: 'ok',
mustChangePassword: auth.mustChangePassword(),
...(decision.state ? { totpState: decision.state } : {}),
};
export function completeWebuiLogin(
auth: WebuiLoginAuth,
body: unknown,
atMs: number,
): WebuiLoginResult {
if (!body || typeof body !== 'object' || Array.isArray(body)) {
return { kind: 'bad-request' };
}
const record = body as Record<string, unknown>;
const password = readString(record.password);
if (!auth.verify(password)) {
return { kind: 'bad-password' };
}
const decision = decideSecondFactorLogin({
totpEnabled: auth.totpEnabled(),
state: auth.totpState(),
password,
totp: readString(record.totp) || undefined,
recoveryCode: readString(record.recoveryCode) || undefined,
atMs,
});
if (decision.kind === 'needs-totp') {
return { kind: 'needs-totp' };
}
if (decision.kind === 'bad-second-factor') {
return { kind: 'bad-second-factor' };
}
return {
kind: 'ok',
mustChangePassword: auth.mustChangePassword(),
...(decision.state ? { totpState: decision.state } : {}),
};
}
export function invalidateOtherSessions<T>(sessions: Map<string, T>, keepToken: string): void {
for (const token of sessions.keys()) {
if (token !== keepToken) sessions.delete(token);
}
for (const token of sessions.keys()) {
if (token !== keepToken) {
sessions.delete(token);
}
}
}