diff --git a/crates/caligo-bridge/src/daemon_client.rs b/crates/caligo-bridge/src/daemon_client.rs index 99f9924e..48c401f0 100644 --- a/crates/caligo-bridge/src/daemon_client.rs +++ b/crates/caligo-bridge/src/daemon_client.rs @@ -917,6 +917,9 @@ fn capability_messages( group_voice: resident.supports_group_voice(), private_image: resident.supports_image(1), group_image: resident.supports_image(2), + private_reply: resident.supports_reply(1), + group_reply: resident.supports_reply(2), + group_mention: resident.supports_mention(2), }, ] } @@ -1214,6 +1217,38 @@ fn session_loop( outcome:OutcomePayload::Failure {reason:"image dispatch rejected before submission".into()}, }).is_err() {return SessionEnd::Broken;} } + Ok(CoreToBridgeMsg::DispatchRich { scope,request_id,wire_seq,timeout_ms,chat_type,peer_uin,segments }) => { + c.dispatches += 1; + let has_reply = segments.iter().any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Reply { .. })); + let has_mention = segments.iter().any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Mention { .. })); + let valid = scope == query_scope && wire_seq > 0 && (1..=30_000).contains(&timeout_ms) + && matches!(chat_type, 1 | 2) && caligo_model::capability::positive_decimal(&peer_uin) + && (chat_type == 2 || peer_uin != cfg.account) + && !segments.is_empty() + && segments.len() <= caligo_model::onebot_traits::MAX_SEND_SEGMENTS + && (!has_reply || resident.supports_reply(chat_type)) + && (!has_mention || resident.supports_mention(chat_type)) + && segments.iter().all(|segment| match segment { + caligo_model::onebot_traits::SendSegment::Text { .. } => true, + caligo_model::onebot_traits::SendSegment::Mention { qq, uid, name } => + chat_type == 2 + && !name.is_empty() + && (qq == "all" && uid == "all" + || caligo_model::capability::positive_decimal(qq) + && uid.len() > 2 + && uid.starts_with("u_")), + caligo_model::onebot_traits::SendSegment::Reply { target } => + target.peer_chat_type == chat_type && target.peer_uin == peer_uin + && (chat_type != 1 || target.reply_msg_client_seq.is_some()), + }); + if valid && resident.submit(crate::resident::OwnedRequest::SendRich { + request_id:request_id.clone(),wire_seq,scope,peer_uin,chat_type,segments, + deadline:Instant::now()+Duration::from_millis(timeout_ms), + }) == crate::resident::SubmitVerdict::Accepted { wake(); } + else if send_json(conn,&BridgeMsg::SendResult {request_id, notice_id: 0, + outcome:OutcomePayload::Failure {reason:"rich dispatch rejected before submission".into()}, + }).is_err() {return SessionEnd::Broken;} + } Ok(message @ (CoreToBridgeMsg::DispatchPrivateVoice { .. } | CoreToBridgeMsg::DispatchGroupVoice { .. })) => { c.dispatches += 1; let (chat_type, scope, request_id, wire_seq, timeout_ms, peer_uin, silk, supported) = match message { @@ -1551,7 +1586,7 @@ mod tests { ); let [ BridgeMsg::QueryCapabilities { revision, scope: query_scope, capabilities }, - BridgeMsg::SendCapabilities { scope: send_scope, private_text, group_text, private_voice: false, group_voice: false, private_image: false, group_image: false }, + BridgeMsg::SendCapabilities { scope: send_scope, private_text, group_text, private_voice: false, group_voice: false, private_image: false, group_image: false, .. }, ] = capability_messages(&resident, &expected_scope) else { panic!("query and send capability announcements missing"); }; diff --git a/crates/caligo-bridge/src/host_adapter.rs b/crates/caligo-bridge/src/host_adapter.rs index d07fe80d..078186b8 100644 --- a/crates/caligo-bridge/src/host_adapter.rs +++ b/crates/caligo-bridge/src/host_adapter.rs @@ -49,6 +49,14 @@ pub enum HostOp { chat_type: u32, png: Vec, }, + SendRich { + request_id: String, + wire_seq: u32, + timeout_ms: u64, + peer_uin: String, + chat_type: u32, + segments: Vec, + }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -130,6 +138,12 @@ pub trait HostAdapter { fn supports_image(&self, _chat_type: u32) -> bool { false } + fn supports_reply(&self, _chat_type: u32) -> bool { + false + } + fn supports_mention(&self, _chat_type: u32) -> bool { + false + } /// Cancel a pending wrapper query on the owner thread. fn cancel_query(&mut self, _request_id: &str, _scope: &QueryScope) {} /// Execute one fixed read-only query on the owner thread. diff --git a/crates/caligo-bridge/src/native_resident.rs b/crates/caligo-bridge/src/native_resident.rs index b30b7eea..fca12ebf 100644 --- a/crates/caligo-bridge/src/native_resident.rs +++ b/crates/caligo-bridge/src/native_resident.rs @@ -512,7 +512,7 @@ impl HostAdapter for NativeHostAdapter { HostOp::ListenerAdd => Ok(HostOpResult::ListenerDeferred), // 延迟模式下 resident 不持有监听器 token,不会到达;到达即如实确认。 HostOp::ListenerRemove { .. } => Ok(HostOpResult::ListenerRemoved), - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => Err(HostError::NoProvenRoute), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => Err(HostError::NoProvenRoute), HostOp::SendText { request_id, wire_seq, diff --git a/crates/caligo-bridge/src/qq_entry.rs b/crates/caligo-bridge/src/qq_entry.rs index 4327fca1..6ca14cf2 100644 --- a/crates/caligo-bridge/src/qq_entry.rs +++ b/crates/caligo-bridge/src/qq_entry.rs @@ -1265,7 +1265,13 @@ impl crate::host_adapter::HostAdapter for QqOwnerAdapter { && value.get("mid").and_then(|v| v.as_str()) == Some(&request_id) { Ok(HostOpResult::SendFired { mid: request_id }) - } else if value.get("err").and_then(|v| v.as_str()).is_some() { + } else if let Some(error) = value.get("err").and_then(|v| v.as_str()) { + let label = error + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(64) + .collect::(); + append_stage_simple("image_send_error", true, &format!("error={label}")); Err(HostError::Native { code: 3 }) } else { Err(HostError::EnvInvalid) @@ -1308,6 +1314,47 @@ impl crate::host_adapter::HostAdapter for QqOwnerAdapter { Err(_) => Err(HostError::EnvInvalid), } } + HostOp::SendRich { + request_id, + wire_seq, + timeout_ms, + peer_uin, + chat_type, + segments, + } => { + if !self.voice_profile { + return Err(HostError::NoProvenRoute); + } + let script = crate::qq_v8::build_rich_send_js( + chat_type, + &self.account, + &peer_uin, + &request_id, + wire_seq, + timeout_ms, + &segments, + ) + .ok_or(HostError::Native { code: 3 })?; + match crate::qq_v8::run_fixed_query_script(&script) { + Ok(out) => { + if let Ok(v) = serde_json::from_str::(&out) { + if v.get("fired").and_then(|x| x.as_bool()) == Some(true) + && v.get("mid").and_then(|x| x.as_str()) == Some(&request_id) + { + return Ok(HostOpResult::SendFired { mid: request_id }); + } + if v.get("err").and_then(|x| x.as_str()).is_some() { + return Err(HostError::Native { code: 3 }); + } + } + Err(HostError::EnvInvalid) + } + Err(crate::qq_v8::V8Error::NoCurrentContext) => { + Err(HostError::NoCurrentContext) + } + Err(_) => Err(HostError::EnvInvalid), + } + } } } @@ -1329,6 +1376,10 @@ impl crate::host_adapter::HostAdapter for QqOwnerAdapter { fn supports_image(&self, chat_type: u32) -> bool { self.voice_profile && matches!(chat_type,1|2) } + fn supports_reply(&self, chat_type: u32) -> bool { self.voice_profile && matches!(chat_type,1|2) } + + fn supports_mention(&self, chat_type: u32) -> bool { self.voice_profile && chat_type == 2 } + fn supports_group_voice(&self) -> bool { self.voice_profile } diff --git a/crates/caligo-bridge/src/qq_image_send.js b/crates/caligo-bridge/src/qq_image_send.js index d047eae5..c7716476 100644 --- a/crates/caligo-bridge/src/qq_image_send.js +++ b/crates/caligo-bridge/src/qq_image_send.js @@ -18,6 +18,11 @@ function (args) { const deadline = Date.now() + args.timeoutMs; let cookie, peerUid, element, image; try { + if (typeof process.getBuiltinModule !== 'function') + return failure('builtin_module_unavailable'); + if (!R.ms || typeof R.ms.getRichMediaFilePathForGuild !== 'function' || + typeof R.ms.sendMsg !== 'function') + return failure('native_image_api_unavailable'); const fs = process.getBuiltinModule('node:fs'); const path = process.getBuiltinModule('node:path'); const crypto = process.getBuiltinModule('node:crypto'); @@ -61,18 +66,44 @@ function (args) { const sha256 = crypto.createHash('sha256').update(bytes).digest('hex'); image = {size:bytes.length, md5, width:args.width, height:args.height, picType:1000}; const name = md5 + '.png'; - const dest = R.ms.getRichMediaFilePathForGuild({ + const rawDest = R.ms.getRichMediaFilePathForGuild({ md5HexStr:md5, fileName:name, elementType:2, elementSubType:0, thumbSize:0, needCreate:true, downloadType:1, file_uuid:'' }); const windows = process.platform === 'win32'; const samePath = (left, right) => windows ? left.toLowerCase() === right.toLowerCase() : left === right; - if (typeof dest !== 'string' || !path.isAbsolute(dest) || dest !== path.normalize(dest) || - (windows && !/^[a-zA-Z]:[\\/]/.test(dest)) || !samePath(path.basename(dest), name)) - return failure('invalid_image_storage_path'); + let rawPath = rawDest; + if (rawDest && typeof rawDest === 'object') { + const keys = ['filePath', 'path', 'file_path', 'filepath']; + for (let i = 0; i < keys.length; i++) { + if (typeof rawDest[keys[i]] === 'string') { rawPath = rawDest[keys[i]]; break; } + } + } + if (typeof rawPath !== 'string') { + const type = rawDest === null ? 'null' : typeof rawDest; + let shape = 'none'; + if (rawDest && typeof rawDest === 'object') { + const names = Object.keys(rawDest).slice(0, 16); + shape = ['filePath', 'path', 'file_path', 'filepath'].find(k => names.indexOf(k) >= 0) || 'other'; + } + return failure('invalid_image_storage_type_' + type + '_' + shape); + } + let dest = path.normalize(rawPath); + if (!path.isAbsolute(dest) || (windows && !/^[a-zA-Z]:[\\/]/.test(dest))) + return failure('invalid_image_storage_path_absolute'); + if (!samePath(path.basename(dest), name)) { + const base = path.basename(dest).toLowerCase(); + const ext = path.extname(base); + return failure('invalid_image_storage_basename_' + + (base.startsWith(md5) ? 'md5' : 'other') + '_' + (ext === '.png' ? 'png' : 'other')); + } const parent = path.dirname(dest); fs.mkdirSync(parent, {recursive:true}); - if (!samePath(fs.realpathSync(parent), parent)) return failure('invalid_image_storage_path'); + const realParent = fs.realpathSync(parent); + if (typeof realParent !== 'string' || !path.isAbsolute(realParent) || + (windows && !/^[a-zA-Z]:[\\/]/.test(realParent))) + return failure('invalid_image_storage_parent'); + dest = path.join(realParent, name); // Create exclusively. A preexisting cache entry can only be reused when // its bytes match, and files handed to QQ stay owned by its cache. try { diff --git a/crates/caligo-bridge/src/qq_query.rs b/crates/caligo-bridge/src/qq_query.rs index 3e28652a..ecf24680 100644 --- a/crates/caligo-bridge/src/qq_query.rs +++ b/crates/caligo-bridge/src/qq_query.rs @@ -25,13 +25,14 @@ pub const SUPPORTED_CAPABILITIES: &[QueryCapability] = &[ QueryCapability::ImageInfo, QueryCapability::ImageDownload, QueryCapability::GroupMembers, + QueryCapability::GroupMemberUid, QueryCapability::LoginInfo, QueryCapability::SelfProfile, ]; pub fn supported_capabilities() -> &'static [QueryCapability] { // Newly admitted operations form a suffix bound to the exact pilot profile. - &SUPPORTED_CAPABILITIES[..SUPPORTED_CAPABILITIES.len() - 8] + &SUPPORTED_CAPABILITIES[..SUPPORTED_CAPABILITIES.len() - 9] } pub fn is_supported(query: &HostQuery) -> bool { @@ -91,6 +92,7 @@ fn kind(query: &HostQuery) -> &'static str { HostQuery::GroupList => "group_list", HostQuery::GroupInfo { .. } => "group_info", HostQuery::GroupMembers { .. } => "group_members", + HostQuery::GroupMemberUid { .. } => "group_member_uid", HostQuery::UinToUid { .. } => "uin_to_uid", HostQuery::UidToUin { .. } => "uid_to_uin", HostQuery::MessagesById { .. } => "messages_by_id", @@ -117,6 +119,11 @@ fn query_args(query: &HostQuery) -> String { ), HostQuery::GroupInfo { group_id } => format!("{{groupCode:{}}}", json_string(group_id)), HostQuery::GroupMembers { group_id, force_refresh } => format!("{{groupCode:{},forceRefresh:{force_refresh}}}",json_string(group_id)), + HostQuery::GroupMemberUid { group_id, user_id } => format!( + "{{groupCode:{},uin:{}}}", + json_string(group_id), + json_string(user_id) + ), HostQuery::VoiceInfo { peer_uid, message_id, @@ -283,11 +290,26 @@ const COMMON_JS: &str = r#" } var directory = fs.mkdtempSync(path.join(root, 'caligo-media-')); var file = path.join(directory, image ? 'image.png' : 'voice.silk'); + function pttCallbackPath(value) { + if (!pilot9936 || image || !voiceCache) return false; + if (typeof value !== 'string' || !path.isAbsolute(value) || value !== path.normalize(value) || + (windows && !/^[a-zA-Z]:[\\/]/.test(value))) return false; + var base = path.basename(value); + if (base.indexOf(info.md5) !== 0) return false; + if (voiceCache.extension && !base.endsWith(voiceCache.extension)) return false; + var parent = path.dirname(value); + var parts = parent.split(path.sep); + var month = parts[parts.length - 2]; + var expected = [p.scope.account, 'nt_qq', 'nt_data', 'Ptt', month, 'Ori'].join(path.sep); + return /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(month) && + samePath(parts.slice(-6).join(path.sep), expected); + } function callbackFile(result) { if (!result || typeof result.filePath !== 'string') return null; if (!image) { if (result.filePath === file) return file; - return cacheFile !== null && samePath(result.filePath, cacheFile) ? cacheFile : null; + if (cacheFile !== null && samePath(result.filePath, cacheFile)) return cacheFile; + return pttCallbackPath(result.filePath) ? path.normalize(result.filePath) : null; } if (!path.isAbsolute(result.filePath)) return null; var normalized = path.normalize(result.filePath); @@ -303,7 +325,7 @@ const COMMON_JS: &str = r#" } function cachedVoice(result, sourceFile) { return !image && result && result.chatType === null && result.fileErrCode === '0' && - cacheFile !== null && sourceFile === cacheFile; + sourceFile !== null && ((cacheFile !== null && sourceFile === cacheFile) || pttCallbackPath(sourceFile)); } function noteDownload(stage, result) { if (!image && !pilot9936) return; @@ -323,6 +345,23 @@ const COMMON_JS: &str = r#" row.path_matches = !!result && result.filePath === file; row.registered_path_matches = callbackFile(result) !== null; row.error_is_string = !!result && typeof result.fileErrCode === 'string'; + try { + var callbackPath = result && result.filePath; + row.path_absolute = typeof callbackPath === 'string' && path.isAbsolute(callbackPath); + row.path_normalized = typeof callbackPath === 'string' && callbackPath === path.normalize(callbackPath); + if (typeof callbackPath === 'string') { + var callbackBase = path.basename(callbackPath); + row.path_md5_prefix = callbackBase.indexOf(info.md5) === 0; + row.path_extension = callbackBase.endsWith('.amr') ? 'amr' : + callbackBase.endsWith('.silk') ? 'silk' : 'other'; + var callbackParts = path.dirname(callbackPath).split(path.sep); + var callbackMonth = callbackParts[callbackParts.length - 2]; + var callbackExpected = [p.scope.account, 'nt_qq', 'nt_data', 'Ptt', callbackMonth, 'Ori'].join(path.sep); + row.path_under_ptt = callbackParts.length >= 6 && + /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(callbackMonth) && + samePath(callbackParts.slice(-6).join(path.sep), callbackExpected); + } + } catch (_) {} row.error_is_zero = !!result && result.fileErrCode === '0'; row.slot_matches = R.voiceDownload === complete; row.pending = !R.stopped && R.queryPending.get(p.requestId) === p && @@ -354,8 +393,21 @@ const COMMON_JS: &str = r#" return; } var stats = fs.lstatSync(sourceFile); + try { + var head = Buffer.alloc(16); + var hf = fs.openSync(sourceFile, 'r'); + var hn = fs.readSync(hf, head, 0, 16, 0); + fs.closeSync(hf); + var silkHeader = hn >= 9 && (head.subarray(0, 9).toString('ascii') === '#!SILK_V3' || + (head[0] === 2 && head.subarray(1, 10).toString('ascii') === '#!SILK_V3')); + var amrHeader = hn >= 5 && head.subarray(0, 5).toString('ascii') === '#!AMR'; + var ext = path.extname(sourceFile).toLowerCase(); + if (pilot9936) noteMedia(R, {media:'voice', stage:'output_shape', size_matches:stats.size === info.size, + silk_header:silkHeader, amr_header:amrHeader, + extension:ext === '.amr' ? 'amr' : ext === '.silk' ? 'silk' : 'other'}); + } catch (_) {} var resolvedFile = fs.realpathSync(sourceFile); - var resolvedMatches = image || sourceFile === cacheFile ? samePath(resolvedFile, sourceFile) : resolvedFile === sourceFile; + var resolvedMatches = image ? samePath(resolvedFile, sourceFile) : true; if (!stats.isFile() || !resolvedMatches || stats.size !== info.size) throw new Error('voice output shape'); descriptor = fs.openSync(sourceFile, 'r'); var opened = fs.fstatSync(descriptor); @@ -506,7 +558,13 @@ pub fn build_profile_query_start_js( if (download && pilot9936) noteMedia(R, {media:'voice',stage:'readback'}); settle(voiceService.getMsgsByMsgId({chatType:chatType,peerUid:args.peerUid,guildId:''}, [args.msgId]), p, function(value) { if (R.stopped || R.queryPending.get(requestId) !== p || p.status !== 'pending' || Date.now() >= p.deadline) return; - if (!value || value.result !== 0 || !Array.isArray(value.msgList) || value.msgList.length !== 1) throw new Error('voice message readback shape'); + if (!value || value.result !== 0 || !Array.isArray(value.msgList) || value.msgList.length !== 1) { + if (value && value.result === 0 && Array.isArray(value.msgList) && value.msgList.length === 0) { + terminal(p, 'rejected', 404, 'voice message unavailable'); + return; + } + throw new Error('voice message readback shape'); + } var message = value.msgList[0]; if (!message || message.msgId !== args.msgId || message.chatType !== chatType || message.peerUid !== args.peerUid || typeof message.senderUin !== 'string' || !/^[1-9][0-9]{0,19}$/.test(message.senderUin) || @@ -552,28 +610,46 @@ pub fn build_profile_query_start_js( if (imageDownload && R.voiceDownload) return terminal(p, 'rejected', 409, 'media download already in flight'); settle(imageService.getMsgsByMsgId({chatType:args.chatType,peerUid:args.peerUid,guildId:''}, [args.msgId]), p, function(value) { if (R.stopped || R.queryPending.get(requestId) !== p || p.status !== 'pending' || Date.now() >= p.deadline) return; - if (!value || value.result !== 0 || !Array.isArray(value.msgList) || value.msgList.length !== 1) throw new Error('image readback shape'); + if (value && (value.result !== 0 || (Array.isArray(value.msgList) && value.msgList.length === 0))) { + terminal(p, 'rejected', 404, 'image message unavailable'); + return; + } + if (!value || !Array.isArray(value.msgList) || value.msgList.length !== 1) throw new Error('image readback shape'); var m = value.msgList[0]; if (!m || m.msgId !== args.msgId || m.chatType !== args.chatType || m.peerUid !== args.peerUid || m.senderUin !== args.senderUin || (m.senderUin === scope.account && m.sendStatus !== 2) || (args.chatType === 1 && m.senderUin !== scope.account && m.senderUid !== args.peerUid) || (args.chatType === 2 && m.peerUin !== args.peerUid) || - !Array.isArray(m.elements) || m.elements.length !== 1) throw new Error('image message identity'); + !Array.isArray(m.elements) || m.elements.length !== 1) { + terminal(p, 'rejected', 404, 'image message unavailable'); + return; + } var element = m.elements[0]; if (!element || element.elementId !== args.elementId || element.elementType !== 2 || - !element.picElement) throw new Error('image element identity'); + !element.picElement) { + terminal(p, 'rejected', 404, 'image message unavailable'); + return; + } var pic = element.picElement; - if ((pic.picType !== 1001 && !(m.senderUin === scope.account && pic.picType === 1000)) || pic.picSubType !== 0) throw new Error('unsupported image format or subtype'); + if ((pic.picType !== 1001 && !(m.senderUin === scope.account && pic.picType === 1000)) || pic.picSubType !== 0) { + terminal(p, 'rejected', 404, 'image message unavailable'); + return; + } var size = pic.fileSize; if (typeof size === 'string' && /^[1-9][0-9]{0,7}$/.test(size)) size = Number(size); if (!Number.isInteger(size) || size < 33 || size > args.maxBytes || !Number.isInteger(pic.picWidth) || pic.picWidth < 1 || pic.picWidth > 32768 || !Number.isInteger(pic.picHeight) || pic.picHeight < 1 || pic.picHeight > 32768 || pic.picWidth * pic.picHeight > 100000000 || typeof pic.md5HexStr !== 'string' || - !/^[0-9a-fA-F]{32}$/.test(pic.md5HexStr)) throw new Error('image metadata shape'); + !/^[0-9a-fA-F]{32}$/.test(pic.md5HexStr)) { + terminal(p, 'rejected', 404, 'image message unavailable'); + return; + } var info = {chat_type:args.chatType,peer_uid:args.peerUid,sender_uin:args.senderUin, message_id:args.msgId,element_id:args.elementId,size:size,md5:pic.md5HexStr.toLowerCase(), width:pic.picWidth,height:pic.picHeight,pic_type:pic.picType}; + if (typeof pic.fileUuid === 'string' && pic.fileUuid.length > 0 && pic.fileUuid.length <= 256) + info.file_uuid = pic.fileUuid; if (!imageDownload) { finish(p, {kind:'image_info',data:info}); return; } if (R.voiceDownload) { p.status = 'rejected'; p.code = 409; return; } startMediaDownload(R, p, imageService, info, args.chatType); @@ -643,6 +719,30 @@ pub fn build_profile_query_start_js( settle(group.getGroupList.call(group, true), p, function(result) { observe(p, 'group_list_result', result, ['result']); if (result && result.result !== undefined && result.result !== 0) fail(p, 'group list result'); }); return reply('pending'); } + if (queryKind === 'group_member_uid') { + var uidService = R.session.getGroupService && R.session.getGroupService(); + if (!uidService || typeof uidService.getAllMemberList !== 'function') return terminal(p, 'unsupported'); + settle(uidService.getAllMemberList.call(uidService, args.groupCode, true), p, function(value) { + observe(p, 'member_result', value, ['errCode','result']); + if (!value || !Number.isInteger(value.errCode)) throw new Error('member response shape'); + if (value.errCode !== 0) { p.status='rejected';p.code=value.errCode;p.reason='native member query rejected';return; } + var result=value.result; + if (!result || result.finish !== true || !(result.infos instanceof Map) || !Array.isArray(result.ids) || + result.infos.size > 2048 || result.ids.length !== result.infos.size) throw new Error('incomplete member snapshot'); + var found=null; + result.ids.forEach(function(id) { + if (!id || typeof id.uid !== 'string' || !/^u_[A-Za-z0-9_-]{1,128}$/.test(id.uid)) throw new Error('invalid member key'); + var m=result.infos.get(id.uid); + if (!m || m.uid !== id.uid || typeof m.uin !== 'string' || !/^[1-9][0-9]{0,19}$/.test(m.uin)) throw new Error('invalid member identity'); + if (m.uin === args.uin) found = m; + }); + if (!found) { p.status='rejected';p.code=404;p.reason='group member not found';return; } + var name = typeof found.nick === 'string' && Buffer.byteLength(found.nick,'utf8') <= 4096 ? found.nick : ''; + if (!name && typeof found.cardName === 'string' && Buffer.byteLength(found.cardName,'utf8') <= 4096) name = found.cardName; + finish(p,{kind:'group_member_uid',data:{group_id:args.groupCode,user_id:args.uin,uid:found.uid,name:name}}); + }); + return reply('pending'); + } if (queryKind === 'group_members') { var memberService = R.session.getGroupService && R.session.getGroupService(); if (!memberService || typeof memberService.getAllMemberList !== 'function') return terminal(p, 'unsupported'); @@ -929,4 +1029,39 @@ mod tests { std::fs::remove_file(&wrapper).unwrap(); std::fs::remove_dir(&dir).unwrap(); } + + #[test] + fn group_member_uid_query_is_pilot_only_and_contract_checked() { + let scope = QueryScope { + account: "10001".into(), + host_nonce: 1, + session_generation: 2, + connection_epoch: 3, + }; + let query = HostQuery::GroupMemberUid { + group_id: "30003".into(), + user_id: "20002".into(), + }; + assert!(!is_supported(&query)); + assert!(SUPPORTED_CAPABILITIES.contains(&QueryCapability::GroupMemberUid)); + let good = decode_query_poll( + &query, + &scope, + r#"{"status":"success","data":{"kind":"group_member_uid","data":{"group_id":"30003","user_id":"20002","uid":"u_member","name":"member"}}}"#, + ) + .unwrap(); + assert!(matches!(good, Some(QueryOutcome::Success(QueryData::GroupMemberUid(_))))); + let wrong_group = decode_query_poll( + &query, + &scope, + r#"{"status":"success","data":{"kind":"group_member_uid","data":{"group_id":"40004","user_id":"20002","uid":"u_member","name":"member"}}}"#, + ); + assert!(wrong_group.is_err()); + let bad_uid = decode_query_poll( + &query, + &scope, + r#"{"status":"success","data":{"kind":"group_member_uid","data":{"group_id":"30003","user_id":"20002","uid":"not-a-uid","name":"member"}}}"#, + ); + assert!(bad_uid.is_err()); + } } diff --git a/crates/caligo-bridge/src/qq_rich_send.js b/crates/caligo-bridge/src/qq_rich_send.js new file mode 100644 index 00000000..235d7091 --- /dev/null +++ b/crates/caligo-bridge/src/qq_rich_send.js @@ -0,0 +1,171 @@ +function (args) { + const reply = value => JSON.stringify(value); + const failure = error => reply({err:error}); + const R = globalThis.__caligo_res; + if (!R || R.stopped || !/^[1-9][0-9]{0,19}$/.test(args.account) || R.voiceAccount !== args.account) + return failure('rich_profile_unavailable'); + const chatType = args.chatType; + if ((chatType !== 1 && chatType !== 2) || + !/^[1-9][0-9]{0,19}$/.test(args.peerUin) || (chatType === 1 && args.peerUin === args.account) || + !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(args.requestId) || + !Number.isInteger(args.wireSeq) || args.wireSeq <= 0 || + !Number.isInteger(args.timeoutMs) || args.timeoutMs <= 0 || + !Array.isArray(args.segments) || args.segments.length < 1 || args.segments.length > 64) + return failure('invalid_rich_request'); + if (Object.hasOwn(R.sends, args.requestId) || Object.hasOwn(R.sendResults, args.requestId) || + Object.keys(R.sends).length >= 128 || Object.keys(R.sendResults).length >= 128) + return failure('send_capacity_or_duplicate'); + + const deadline = Date.now() + args.timeoutMs; + let cookie, peerUid, elements = [], textBytes = 0; + const positive = value => typeof value === 'string' && /^[1-9][0-9]{0,127}$/.test(value); + const nativeUid = value => typeof value === 'string' && /^u_[A-Za-z0-9_-]{1,128}$/.test(value); + try { + peerUid = args.peerUin; + if (chatType === 1) { + const profile = R.session.getProfileService(); + const mapped = profile.getUidByUin('FriendsServiceImpl', [args.peerUin]); + peerUid = mapped instanceof Map && Map.prototype.get.call(mapped, args.peerUin); + if (!nativeUid(peerUid)) return failure('private_uid_mapping_unavailable'); + } + for (let i = 0; i < args.segments.length; i++) { + const segment = args.segments[i]; + if (!segment || typeof segment !== 'object') return failure('invalid_rich_segment'); + if (segment.type === 'text') { + if (typeof segment.text !== 'string') return failure('invalid_rich_segment'); + textBytes += Buffer.byteLength(segment.text, 'utf8'); + elements.push({elementType:1, elementId:'', textElement:{ + content:segment.text, atType:0, atUid:'', atTinyId:'', atNtUid:'' + }}); + } else if (segment.type === 'mention') { + if (chatType !== 2 || typeof segment.name !== 'string' || segment.name.length === 0 || + typeof segment.qq !== 'string' || typeof segment.uid !== 'string') + return failure('invalid_mention'); + if (segment.qq === 'all') { + if (segment.uid !== 'all') return failure('invalid_mention'); + elements.push({elementType:1, elementId:'', textElement:{ + content:'@全体成员', atType:1, atUid:'all', atTinyId:'', atNtUid:'all' + }}); + } else { + if (!positive(segment.qq) || !nativeUid(segment.uid)) return failure('invalid_mention'); + textBytes += Buffer.byteLength('@' + segment.name, 'utf8'); + elements.push({elementType:1, elementId:'', textElement:{ + content:'@' + segment.name, atType:2, atUid:segment.qq, + atTinyId:'', atNtUid:segment.uid + }}); + } + } else if (segment.type === 'reply') { + const target = segment.target; + if (!target || target.peer_chat_type !== chatType || + !positive(target.replay_msg_id) || !positive(target.replay_msg_seq) || + !positive(target.sender_uin) || typeof target.peer_uid !== 'string' || + (chatType === 1 ? !nativeUid(target.peer_uid) : !positive(target.peer_uid))) + return failure('invalid_reply'); + const replyElement = { + replayMsgSeq:target.replay_msg_seq, replayMsgId:target.replay_msg_id, + senderUin:target.sender_uin, senderUinStr:target.sender_uin, + _replyMsgPeer:{chatType:chatType, peerUid:target.peer_uid} + }; + if (target.reply_msg_client_seq !== undefined && target.reply_msg_client_seq !== null) { + if (typeof target.reply_msg_client_seq !== 'string' || + !/^[0-9]{1,20}$/.test(target.reply_msg_client_seq)) return failure('invalid_reply'); + replyElement.replyMsgClientSeq = target.reply_msg_client_seq; + } + elements.push({elementType:7, elementId:'', replyElement:replyElement}); + } else { + return failure('unsupported_rich_segment'); + } + } + if (textBytes > 49152) return failure('rich_text_too_large'); + } catch (_) { + return failure('rich_preparation_failed'); + } + if (R.stopped || Date.now() >= deadline) return failure('rich_preparation_expired'); + + try { + const serverTime = R.session.getMSFService().getServerTime(); + if (typeof serverTime !== 'string' || !serverTime || serverTime === '0') + return failure('server_time_unavailable'); + cookie = R.ms.generateMsgUniqueId(chatType, serverTime); + if (typeof cookie !== 'string' || !cookie || cookie === '0' || + Object.values(R.sends).some(send => send.cookie === cookie)) + return failure('invalid_cookie'); + const guardKey = '__caligo_rich_cookie_guard_v1'; + if (!Object.prototype.hasOwnProperty.call(globalThis, guardKey)) { + const seenCookies = new Set(); + const claimCookie = value => { + if (typeof value !== 'string' || !value || value === '0' || value.length > 256) return 'invalid_cookie'; + if (seenCookies.has(value)) return 'invalid_cookie'; + if (seenCookies.size >= 65536) return 'cookie_history_exhausted'; + seenCookies.add(value); return 'ok'; + }; + Object.defineProperty(globalThis, guardKey, + {value:claimCookie, writable:false, configurable:false, enumerable:false}); + } + const guard = Object.getOwnPropertyDescriptor(globalThis, guardKey); + if (!guard || typeof guard.value !== 'function' || guard.writable !== false || guard.configurable !== false) + return failure('cookie_history_unavailable'); + const claim = guard.value(cookie); + if (claim !== 'ok') return failure(claim); + } catch (_) { + return failure('rich_preparation_failed'); + } + + const key = args.requestId; + // Keep an owned copy for callback correlation: the native send binding may + // consume or mutate the array handed to sendMsg before the add/update event. + const expected = elements.map(function (element) { + if (element.elementType === 1) { + return {elementType:1, textElement:{ + content:element.textElement.content, atType:element.textElement.atType, + atUid:element.textElement.atUid, atNtUid:element.textElement.atNtUid, + atTinyId:element.textElement.atTinyId + }}; + } + if (element.elementType === 7) { + return {elementType:7, replyElement:{ + replayMsgId:element.replyElement.replayMsgId, + replayMsgSeq:element.replyElement.replayMsgSeq + }}; + } + return {elementType:element.elementType}; + }); + const pending = {cookie, chat:chatType, peer:peerUid, peerUin:args.peerUin, rich:expected, + selfUin:args.account, wireSeq:args.wireSeq, + traceSeq:typeof R.allocateTextTrace === 'function' ? R.allocateTextTrace() : 0, + deadline, addId:null, updateId:null, done:false}; + R.sends[key] = pending; + R.sendResults[key] = {status:'pending'}; + if (R.noteTextSend) R.noteTextSend('registered', pending.traceSeq); + function result(status, detail) { + if (R.stopped || R.sends[key] !== pending) return; + pending.promiseDone = true; + pending.promiseStatus = status; + if (status === 'unknown') pending.unknownReason = detail.reason; + if (pending.readback) { + R.settleSendResult(R, key, pending); + } else if (!pending.ambiguous && !pending.timedOut) { + R.sendResults[key] = detail; + } + if (status !== 'accepted') pending.failed = true; + } + function unknown(reason) { + result('unknown', {status:'unknown', + reason:typeof reason === 'string' ? reason : 'rich_submit_unknown'}); + } + try { + const promise = R.ms.sendMsg('0', {chatType, peerUid, guildId:cookie}, elements, new Map()); + Promise.resolve(promise).then(value => { + if (value && value.result === 0) { + result('accepted', {status:'accepted'}); + } else if (value && Number.isSafeInteger(value.result)) { + unknown('send_result_ambiguous=' + String(value.result)); + } else { + unknown(); + } + }, () => unknown()); + } catch (_) { + unknown(); + } + return reply({fired:true, mid:key}); +} diff --git a/crates/caligo-bridge/src/qq_v8.rs b/crates/caligo-bridge/src/qq_v8.rs index 713eecf6..5b28b890 100644 --- a/crates/caligo-bridge/src/qq_v8.rs +++ b/crates/caligo-bridge/src/qq_v8.rs @@ -392,8 +392,40 @@ pub const D8_START_JS: &str = r" } if (!live) return 'ERR:no live session'; var ms = live.getMsgService(); - var R = { sid: sidName, session: live, ms: ms, recv: [], recvBytes: 0, - rejected: 0, overflow: 0, imageShapes: [], listenerId: null, sendResults: {}, sends: {} }; + var rich = null; + try { if (typeof live.getRichMediaService === 'function') rich = live.getRichMediaService(); } catch (_) {} + var mediaCap = function (owner, name) { return !!(owner && typeof owner[name] === 'function'); }; + var mediaMethods = function (owner) { + try { + var names = []; + if (owner) { + names = names.concat(Object.keys(owner)); + var proto = Object.getPrototypeOf(owner); + if (proto) names = names.concat(Object.getOwnPropertyNames(proto)); + } + var seen = {}, out = []; + names.forEach(function (name) { + if (typeof name !== 'string' || name.length > 64 || !/^[A-Za-z0-9_]+$/.test(name) || + !/^(upload|send|file|media|video|download|get)/i.test(name) || seen[name]) return; + if (owner[name] !== undefined && typeof owner[name] !== 'function') return; + seen[name] = true; if (out.length < 64) out.push(name); + }); + return out; + } catch (_) { return []; } + }; + var mediaCapabilities = { + rich_methods: mediaMethods(rich), + msg_methods: mediaMethods(ms), + session_rich_service: typeof live.getRichMediaService === 'function', + msg_send_file: mediaCap(ms, 'sendFile'), + msg_upload_file: mediaCap(ms, 'uploadFile'), + rich_upload_file: mediaCap(rich, 'uploadFile'), + rich_send_file: mediaCap(rich, 'sendFile'), + rich_get_path: mediaCap(rich, 'getRichMediaFilePathForGuild') + }; + var R = { sid: sidName, session: live, ms: ms, mediaCapabilities: mediaCapabilities, recv: [], recvBytes: 0, + rejected: 0, overflow: 0, imageShapes: [], segmentShapes: [], + listenerId: null, sendResults: {}, sends: {} }; var traceText = typeof caligoSendTrace !== 'undefined' && caligoSendTrace === true; R.textSendTrace = []; var traceGeneration = 0; @@ -571,8 +603,81 @@ pub const D8_START_JS: &str = r" md5_valid:typeof p.md5HexStr === 'string' && /^[0-9a-fA-F]{32}$/.test(p.md5HexStr), text_present:!!e.textElement}); } catch (_) {} }; + // Bounded @/reply/unsupported-element shapes. Values, identities, message + // ids and paths never leave this invocation; only fixed labels and counts do. + var noteSegmentShape = function (src, m) { + try { + if (!voiceAccount || R.segmentShapes.length >= 8 || !m || !Array.isArray(m.elements) || + !m.elements.length || m.elements.length > 128) return; + var types = [], atTypes = [], textCount = 0, atCount = 0, replyIndex = -1, numericTypes = true; + for (var i = 0; i < m.elements.length; i++) { + var e = m.elements[i]; + if (!e || typeof e !== 'object') { numericTypes = false; continue; } + var elementType = e.elementType; + if (typeof elementType !== 'number' || !Number.isInteger(elementType) || + elementType < 0 || elementType > 64) numericTypes = false; + else if (types.indexOf(elementType) < 0 && types.length < 8) types.push(elementType); + var t = e.textElement; + if (t && typeof t === 'object') { + if (typeof t.content === 'string') textCount++; + if (typeof t.atType === 'number' && Number.isInteger(t.atType) && t.atType > 0) { + atCount++; + if (atTypes.indexOf(t.atType) < 0 && atTypes.length < 8) atTypes.push(t.atType); + } + } + if (replyIndex < 0 && e.replyElement && typeof e.replyElement === 'object') replyIndex = i; + } + var interesting = atCount > 0 || replyIndex >= 0 || !numericTypes; + for (var j = 0; j < types.length; j++) { + if (types[j] !== 1 && types[j] !== 2 && types[j] !== 4) interesting = true; + } + if (!interesting) return; + var shape = {source:src, chat:m.chatType === 1 ? 'private' : (m.chatType === 2 ? 'group' : 'other'), + arity:m.elements.length === 1 ? 'single' : 'multiple', + element_types:types, numeric_element_types:numericTypes, + text_count:textCount, at_count:atCount, at_types:atTypes, + reply_present:replyIndex >= 0}; + if (replyIndex >= 0) { + var reply = m.elements[replyIndex].replyElement, fields = {}; + var names = ['replayMsgId','replayMsgSeq','sourceMsgText','msgTextWith0x14Face','tinyId']; + for (var k = 0; k < names.length; k++) { + var value = reply[names[k]]; + fields[names[k]] = value === undefined ? 'missing' : value === null ? 'null' : + typeof value === 'string' ? (value === '' ? 'empty' : + (/^[0-9]{1,128}$/.test(value) ? 'decimal' : 'string')) : + typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'other'; + } + var replyType = m.elements[replyIndex].elementType; + shape.reply_element_type = typeof replyType === 'number' && Number.isInteger(replyType) && + replyType >= 0 && replyType <= 64 ? replyType : 'other'; + shape.reply_fields = fields; + shape.reply_key_count = Math.min(Object.keys(reply).length, 64); + } + if (atCount > 0) { + var first = null; + for (var n = 0; n < m.elements.length; n++) { + var candidate = m.elements[n] && m.elements[n].textElement; + if (candidate && typeof candidate.atType === 'number' && candidate.atType > 0) { + first = candidate; break; + } + } + var shapeOf = function (value) { + return value === undefined ? 'missing' : value === null ? 'null' : value === '' ? 'empty' : + typeof value === 'string' ? (/^[0-9]{1,128}$/.test(value) ? 'decimal' : + (/^u_[A-Za-z0-9_-]{1,128}$/.test(value) ? 'uid' : 'string')) : + typeof value === 'number' ? 'number' : 'other'; + }; + shape.at_uid_shape = shapeOf(first && first.atUid); + shape.at_nt_uid_shape = shapeOf(first && first.atNtUid); + shape.at_tiny_id_shape = shapeOf(first && first.atTinyId); + shape.at_content_has_at = !!(first && typeof first.content === 'string' && first.content.indexOf('@') >= 0); + } + R.segmentShapes.push(shape); + } catch (_) {} + }; var push = function (src, m, verifiedVoice) { if (!verifiedVoice) noteImageShape(src, m); + if (!verifiedVoice) noteSegmentShape(src, m); try { if (!m || typeof m !== 'object' || !Array.isArray(m.elements) || !m.elements.length || m.elements.length > 128) { R.rejected++; return; } @@ -609,9 +714,12 @@ pub const D8_START_JS: &str = r" !Number.isInteger(pic.picHeight) || pic.picHeight < 1 || pic.picHeight > 32768 || pic.picWidth * pic.picHeight > 100000000 || typeof pic.md5HexStr !== 'string' || !/^[0-9a-fA-F]{32}$/.test(pic.md5HexStr)) { R.rejected++; return; } - elements.push({elementType:2,image:{chat_type:m.chatType,peer_uid:m.peerUid, + var imageInfo = {chat_type:m.chatType,peer_uid:m.peerUid, sender_uin:m.senderUin,message_id:m.msgId,element_id:e.elementId,size:size, - md5:pic.md5HexStr.toLowerCase(),width:pic.picWidth,height:pic.picHeight,pic_type:pic.picType}}); + md5:pic.md5HexStr.toLowerCase(),width:pic.picWidth,height:pic.picHeight,pic_type:pic.picType}; + if (typeof pic.fileUuid === 'string' && pic.fileUuid.length > 0 && pic.fileUuid.length <= 256) + imageInfo.file_uuid = pic.fileUuid; + elements.push({elementType:2,image:imageInfo}); continue; } if (e && e.elementType === 4 && voiceAccount && m.elements.length === 1 && @@ -627,20 +735,59 @@ pub const D8_START_JS: &str = r" size:Number(ptt.fileSize),md5:ptt.md5HexStr.toLowerCase()}}); continue; } - if (!e || e.elementType !== 1 || !t || typeof t.content !== 'string' || t.atType !== 0 || - !emptyNumericMention(t.atUid) || !emptyNtMention(t.atNtUid) || - !emptyNumericMention(t.atTinyId)) { R.rejected++; return; } + if (e && e.elementType === 7) { + var reply = e.replyElement; + var replyAtType = t && t.atType !== undefined ? t.atType : 0; + if (e.voice || e.image || !reply || typeof reply.replayMsgId !== 'string' || + !/^[1-9][0-9]{0,127}$/.test(reply.replayMsgId) || + typeof reply.replayMsgSeq !== 'string' || + !/^[1-9][0-9]{0,127}$/.test(reply.replayMsgSeq) || + (reply.sourceMsgText !== undefined && typeof reply.sourceMsgText !== 'string') || + (typeof reply.sourceMsgText === 'string' && utf8Bytes(reply.sourceMsgText) > 4096) || + (t && (typeof t.content !== 'string' || replyAtType !== 0 || + !emptyNumericMention(t.atUid) || !emptyNtMention(t.atNtUid) || + !emptyNumericMention(t.atTinyId)))) { + R.rejected++; return; + } + var replyElement = {elementType:7, reply:{replayMsgId:reply.replayMsgId, + replayMsgSeq:reply.replayMsgSeq, sourceMsgText:reply.sourceMsgText || ''}}; + if (t && typeof t.content === 'string' && t.content.length > 0) { + replyElement.textElement = {content:t.content, atType:0, + atUid:'', atNtUid:'', atTinyId:''}; + } + elements.push(replyElement); + continue; + } + if (!e || e.elementType !== 1 || !t || typeof t.content !== 'string') { R.rejected++; return; } + var atType = t.atType === undefined ? 0 : t.atType; + if (!Number.isInteger(atType) || atType < 0 || atType > 2) { R.rejected++; return; } + var atUid = typeof t.atUid === 'string' ? t.atUid : ''; + var atNtUid = typeof t.atNtUid === 'string' ? t.atNtUid : ''; + var atTinyId = typeof t.atTinyId === 'string' ? t.atTinyId : ''; + if (atType === 0) { + if (!emptyNumericMention(t.atUid) || !emptyNtMention(t.atNtUid) || + !emptyNumericMention(t.atTinyId)) { R.rejected++; return; } + atUid = ''; atNtUid = ''; atTinyId = ''; + } else if (atType === 1) { + // @all is target-scoped; the wrapper normalizes the original + // mention fields to decimal/string forms that are not the target. + atUid = 'all'; atNtUid = 'all'; atTinyId = ''; + } else if (!/^[1-9][0-9]{0,19}$/.test(atUid) || + !/^u_[A-Za-z0-9_-]{1,128}$/.test(atNtUid) || + !(atTinyId === '' || atTinyId === '0' || /^[1-9][0-9]{0,19}$/.test(atTinyId))) { + R.rejected++; return; + } textBytes += utf8Bytes(t.content); if (textBytes > 49152) { R.overflow++; return; } - elements.push({elementType:1, textElement:{content:t.content, atType:0, - atUid:'', atNtUid:'', atTinyId:''}}); + elements.push({elementType:1, textElement:{content:t.content, atType:atType, + atUid:atUid, atNtUid:atNtUid, atTinyId:atTinyId}}); } var record = {msgId:m.msgId, msgSeq:m.msgSeq, msgRandom:m.msgRandom, msgTime:m.msgTime, clientSeq:m.clientSeq, guildId:m.guildId, chatType:m.chatType, msgType:m.msgType, subMsgType:m.subMsgType, peerUid:m.peerUid, peerUin:m.peerUin, senderUid:m.senderUid, senderUin:m.senderUin, sendStatus:m.sendStatus, elements:elements}; - if (!verifiedVoice && (src === 'add_send' || src === 'update')) correlateSend(R, m, src); + if (!verifiedVoice && (src === 'add_send' || src === 'update' || src === 'recv')) correlateSend(R, m, src); var item = {source:src, observed_at_unix_ms:Date.now(), record:record}; var bytes = utf8Bytes(JSON.stringify(item)); if (bytes > 65536 || R.recv.length >= 128 || R.recvBytes + bytes > 393216) { @@ -650,9 +797,65 @@ pub const D8_START_JS: &str = r" return true; } catch (err) { R.rejected++; } }; + var emptyRichMention = function (value) { + return value === undefined || value === null || value === '' || value === '0'; + }; + var matchesRichText = function (want, got) { + if (!got || got.atType !== want.atType) return false; + if (want.atType === 0) { + return got.content === want.content && emptyRichMention(got.atUid) && + emptyRichMention(got.atNtUid); + } + if (want.atType === 1) return true; // @all is target-typed, not field-typed. + // The native wrapper rewrites a mention's display text to the current + // group card; target identity is atUid/atNtUid, not the sent content. + return got.atUid === want.atUid && got.atNtUid === want.atNtUid; + }; + var matchesRichElements = function (record, send) { + if (!send.rich || !Array.isArray(record.elements) || + record.elements.length !== send.rich.length) return false; + for (var i = 0; i < send.rich.length; i++) { + var want = send.rich[i], got = record.elements[i]; + if (!want || !got || got.elementType !== want.elementType) return false; + if (want.elementType === 1) { + if (!matchesRichText(want.textElement, got.textElement)) return false; + } else if (want.elementType === 7) { + if (!got.replyElement || + got.replyElement.replayMsgId !== want.replyElement.replayMsgId || + got.replyElement.replayMsgSeq !== want.replyElement.replayMsgSeq) return false; + } else return false; + } + return true; + }; + var richMismatchReason = function (record, send) { + if (!Array.isArray(record.elements)) return 'rich_no_elements'; + if (record.elements.length !== send.rich.length) return 'rich_len'; + for (var i = 0; i < send.rich.length; i++) { + var want = send.rich[i], got = record.elements[i]; + if (!want || !got || got.elementType !== want.elementType) return 'rich_type'; + if (want.elementType === 1) { + if (!got.textElement) return 'rich_text_missing'; + if (got.textElement.atType !== want.textElement.atType) return 'rich_at_type'; + if (want.textElement.atType === 0) { + if (got.textElement.content !== want.textElement.content) return 'rich_text_content'; + if (!emptyRichMention(got.textElement.atUid)) return 'rich_at_uid'; + if (!emptyRichMention(got.textElement.atNtUid)) return 'rich_at_nt_uid'; + } else if (want.textElement.atType !== 1) { + if (got.textElement.atUid !== want.textElement.atUid) return 'rich_at_uid'; + if (got.textElement.atNtUid !== want.textElement.atNtUid) return 'rich_at_nt_uid'; + } + } else if (want.elementType === 7) { + if (!got.replyElement) return 'rich_reply_missing'; + if (got.replyElement.replayMsgId !== want.replyElement.replayMsgId) return 'rich_reply_id'; + if (got.replyElement.replayMsgSeq !== want.replyElement.replayMsgSeq) return 'rich_reply_seq'; + } + } + return 'rich_match'; + }; var matchesSendElement = function (record, send) { - if (!record || !Array.isArray(record.elements) || record.elements.length !== 1 || - !record.elements[0]) return false; + if (!record || !Array.isArray(record.elements)) return false; + if (send.rich) return matchesRichElements(record, send); + if (record.elements.length !== 1 || !record.elements[0]) return false; var element = record.elements[0]; if (send.image) { var pic=element.picElement; @@ -675,12 +878,20 @@ pub const D8_START_JS: &str = r" var keys = Object.keys(R.sends); for (var k = 0; k < keys.length; k++) { var key = keys[k], send = R.sends[key]; + // Value-free first gate label for rich sends; surfaced only on timeout. + if (send && send.rich && !send.done && !send.failed && m.senderUin === send.selfUin && !send.corrReason) { + if (m.guildId !== send.cookie) send.corrReason = 'corr_cookie'; + else if (m.chatType !== send.chat) send.corrReason = 'corr_chat'; + else if (m.peerUid !== send.peer) send.corrReason = 'corr_peer'; + else if (typeof m.msgId !== 'string' || !m.msgId || m.msgId === '0') send.corrReason = 'corr_msg'; + else send.corrReason = matchesRichElements(m, send) ? 'corr_ok' : richMismatchReason(m, send); + } if (!send || send.done || send.failed || m.guildId !== send.cookie || m.chatType !== send.chat || m.peerUid !== send.peer || typeof m.msgId !== 'string' || !m.msgId || m.msgId === '0' || m.senderUin !== send.selfUin || !matchesSendElement(m, send) || ((send.voice || send.image) && (m.peerUin !== send.peerUin || !/^[0-9]{1,128}$/.test(m.msgId) || !/[1-9]/.test(m.msgId)))) continue; - if (src === 'add_send') { + if (src === 'add_send' || src === 'recv') { if (!send.voice && !send.image) { if (traceText) observeCallback('matched_add', 'matched', key, send); R.noteTextSend('matched_add', send.traceSeq); @@ -727,6 +938,23 @@ pub const D8_START_JS: &str = r" (!(pending.voice || pending.image) || (record.peerUin === pending.peerUin && record.elements[0].elementId === pending.addElementId)); var owned; + if (matched && pending.image && Array.isArray(R.mediaDiagnostics) && + R.mediaDiagnostics.length < 8 && record.elements && record.elements[0]) { + var receiptPic = record.elements[0].picElement; + if (receiptPic) { + var receiptKind = function (name) { + if (!Object.prototype.hasOwnProperty.call(receiptPic, name)) return 'missing'; + var value = receiptPic[name]; + if (typeof value === 'string') return value ? 'nonempty' : 'empty'; + return typeof value; + }; + R.mediaDiagnostics.push({media:'image', stage:'image_receipt', + file_uuid:receiptKind('fileUuid'), file_sub_id:receiptKind('fileSubId'), + file_name:receiptKind('fileName'), source_path:receiptKind('sourcePath'), + thumb_size:receiptKind('thumbFileSize'), original:receiptKind('original'), + summary:receiptKind('summary')}); + } + } if (matched && (pending.voice || pending.image)) { owned = {}; var fields = ['msgId','msgSeq','msgRandom','msgTime','clientSeq','guildId', @@ -738,7 +966,11 @@ pub const D8_START_JS: &str = r" owned.elements = pending.image ? [{elementType:2,elementId:pending.addElementId,picElement:{fileSize:String(pending.image.size), md5HexStr:pending.image.md5,picWidth:pending.image.width,picHeight:pending.image.height, - picType:record.elements[0].picElement.picType,picSubType:0}}] + picType:record.elements[0].picElement.picType,picSubType:0, + fileUuid:typeof record.elements[0].picElement.fileUuid === 'string' && + record.elements[0].picElement.fileUuid.length > 0 && + record.elements[0].picElement.fileUuid.length <= 256 + ? record.elements[0].picElement.fileUuid : undefined}}] : [{elementType:4, elementId:pending.addElementId, pttElement:{fileSize:String(pending.voice.size),md5HexStr:pending.voice.md5}}]; } @@ -895,7 +1127,7 @@ pub const D8_POLL_JS: &str = r" var key = keys[k], send = R.sends[key]; if (send && !send.done && !send.timedOut && Date.now() >= send.deadline) { send.timedOut = true; - R.sendResults[key] = {status:'unknown', reason:'timeout'}; + R.sendResults[key] = {status:'unknown', reason:send.corrReason || 'timeout'}; } if (send && Date.now() >= send.deadline + 30000) delete R.sends[key]; } @@ -924,7 +1156,9 @@ pub const D8_POLL_JS: &str = r" } } var out = {schema:1, sid:R.sid, items:R.recv, rejected:R.rejected, overflow:R.overflow, - sendResults:offeredResults, imageShapes:R.imageShapes || [], mediaDiagnostics:R.mediaDiagnostics || [], + sendResults:offeredResults, imageShapes:R.imageShapes || [], segmentShapes:R.segmentShapes || [], + mediaDiagnostics:R.mediaDiagnostics || [], + mediaCapabilities:R.mediaCapabilities || {}, textSendTrace:R.textSendTrace || [], textSendTraceGeneration:R.textTraceGeneration || 0, textSendTraceOverflow:R.textTraceOverflow === true}; var resultKeysForLease = Object.keys(offeredResults); @@ -953,7 +1187,7 @@ pub const D8_POLL_JS: &str = r" out.sendResults = {}; var keys = Object.keys(offeredResults); var isolated = {schema:1, sid:R.sid, items:[], rejected:0, overflow:0, - sendResults:{}, imageShapes:[], mediaDiagnostics:[], textSendTrace:[], + sendResults:{}, imageShapes:[], segmentShapes:[], mediaDiagnostics:[], textSendTrace:[], textSendTraceGeneration:R.textTraceGeneration || 0, textSendTraceOverflow:false}; if (receipt) isolated.resultReceipt = receipt; for (var i = 0; i < keys.length; i++) { @@ -996,7 +1230,7 @@ pub const D8_POLL_JS: &str = r" } R.resultLease = {generation:receipt.generation, sequence:receipt.sequence, refs:refs}; } - R.recv = []; R.recvBytes = 0; R.rejected = 0; R.overflow = 0; R.imageShapes = []; R.mediaDiagnostics = []; R.textSendTrace = []; R.textTraceOverflow = false; + R.recv = []; R.recvBytes = 0; R.rejected = 0; R.overflow = 0; R.imageShapes = []; R.segmentShapes = []; R.mediaDiagnostics = []; R.textSendTrace = []; R.textTraceOverflow = false; if (!leaseMode) { // Compatibility path; serialization is not downstream acknowledgement. var resultKeys = Object.keys(out.sendResults || {}); @@ -1027,7 +1261,7 @@ pub const D8_STOP_JS: &str = r" if (typeof caligoStopProbe !== 'undefined' && caligoStopProbe === true) { try { var before = [R.recv, R.recv.length, R.recvBytes, R.rejected, R.overflow, - R.imageShapes, R.imageShapes.length]; + R.imageShapes, R.imageShapes.length, R.segmentShapes, R.segmentShapes.length]; R.syntheticStopProbe = true; try { R.listener.onRecvMsg(null); @@ -1036,7 +1270,8 @@ pub const D8_STOP_JS: &str = r" } finally { R.syntheticStopProbe = false; } var unchanged = R.recv === before[0] && R.recv.length === before[1] && R.recvBytes === before[2] && R.rejected === before[3] && R.overflow === before[4] && - R.imageShapes === before[5] && R.imageShapes.length === before[6]; + R.imageShapes === before[5] && R.imageShapes.length === before[6] && + R.segmentShapes === before[7] && R.segmentShapes.length === before[8]; probe = unchanged ? ' stop_probe=pass' : ' stop_probe=fail'; } catch (_) { probe = ' stop_probe=error'; } } @@ -1320,6 +1555,20 @@ fn poll_listener_script(source: &str) -> Result { crate::qq_entry::append_stage_simple("receive_image_shape", true, &detail); } } + if let Some(detail) = crate::receive_diagnostics::sanitize_segment_shapes(&output) { + static SEGMENT_REPORTS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SEGMENT_REPORTS.fetch_update(std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, |n| (n < 32).then_some(n + 1)).is_ok() { + crate::qq_entry::append_stage_simple("receive_segment_shape", true, &detail); + } + } + if let Some(detail) = crate::receive_diagnostics::sanitize_media_capabilities(&output) { + static CAP_REPORTS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if CAP_REPORTS.fetch_update(std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, |n| (n < 4).then_some(n + 1)).is_ok() { + crate::qq_entry::append_stage_simple("media_capabilities", true, &detail); + } + } if let Some(detail) = crate::receive_diagnostics::sanitize_media_download(&output) { static MEDIA_REPORTS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if MEDIA_REPORTS.fetch_update(std::sync::atomic::Ordering::Relaxed, @@ -2973,15 +3222,111 @@ mod uid_map_script_tests { println!("{}", String::from_utf8_lossy(&result.stdout)); } + #[test] + fn d8_accepts_reply_element_with_text_and_rejects_bad_reply_text() { + use std::io::Write; + let scripts = serde_json::json!({ + "pilot": listener_script_with_account("10001"), + "poll": super::D8_POLL_JS, + }); + let fixture = r#" +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const scripts = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +let listener; +const service = {sendMsg() {}, addKernelMsgListener(value) { listener = value; return '1'; }}; +const session = {getSessionId: () => '1', getMsgService: () => service}; +const sandbox = vm.createContext({Buffer, process: {_linkedBinding: () => ({ + NodeIQQNTWrapperSession: {getNTWrapperSession: () => session} +})}}); +assert.match(vm.runInContext(scripts.pilot, sandbox), /^ARMED/); +const common = {msgId:'5001',msgSeq:'2',msgRandom:'3',msgTime:'1794567890',guildId:'', + peerUid:'u_peer',peerUin:'20002',senderUid:'u_peer',senderUin:'20002',msgType:2,subMsgType:1}; +const row = (replyText) => ({...common,chatType:1,elements:[{ + elementType:7, + ...(replyText === undefined ? {} : {textElement:{content:replyText,atType:0, + atUid:'',atNtUid:'',atTinyId:''}}), + replyElement:{replayMsgId:'123456',replayMsgSeq:'7',sourceMsgText:''}}]}); +listener.onRecvMsg([row('quoted')]); +let batch = JSON.parse(vm.runInContext(scripts.poll, sandbox)); +assert.equal(batch.items.length, 1);assert.equal(batch.rejected, 0); +assert.equal(batch.items[0].record.elements[0].textElement.content, 'quoted'); +assert.equal(batch.items[0].record.elements[0].reply.replayMsgId, '123456'); +listener.onRecvMsg([row(undefined)]); +batch = JSON.parse(vm.runInContext(scripts.poll, sandbox)); +assert.equal(batch.items.length, 1);assert.equal(batch.rejected, 0); +assert.equal(batch.items[0].record.elements[0].textElement, undefined); +listener.onRecvMsg([{...row('x'),elements:[{elementType:7,textElement:{ + content:'x',atType:2,atUid:'20002',atNtUid:'u_other',atTinyId:'0'}, + replyElement:{replayMsgId:'123456',replayMsgSeq:'7',sourceMsgText:''}}]}]); +batch = JSON.parse(vm.runInContext(scripts.poll, sandbox)); +assert.equal(batch.items.length, 0);assert.equal(batch.rejected, 1); +"#; + let mut child = std::process::Command::new("node") + .args(["-e", fixture]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn().unwrap(); + child.stdin.take().unwrap().write_all(scripts.to_string().as_bytes()).unwrap(); + let result = child.wait_with_output().unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); + } + + #[test] + fn d8_accepts_at_all_and_normalizes_the_target() { + use std::io::Write; + let scripts = serde_json::json!({ + "pilot": listener_script_with_account("10001"), + "poll": super::D8_POLL_JS, + }); + let fixture = r#" +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const scripts = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +let listener; +const service = {sendMsg() {}, addKernelMsgListener(value) { listener = value; return '1'; }}; +const session = {getSessionId: () => '1', getMsgService: () => service}; +const sandbox = vm.createContext({Buffer, process: {_linkedBinding: () => ({ + NodeIQQNTWrapperSession: {getNTWrapperSession: () => session} +})}}); +assert.match(vm.runInContext(scripts.pilot, sandbox), /^ARMED/); +const common = {msgId:'5002',msgSeq:'3',msgRandom:'4',msgTime:'1794567890',guildId:'', + peerUid:'30003',peerUin:'30003',senderUid:'u_peer',senderUin:'20002',msgType:2,subMsgType:1}; +const row = {elementType:1,textElement:{content:'@全体成员',atType:1, + atUid:'0',atNtUid:'all',atTinyId:'0'}}; +listener.onRecvMsg([{...common,chatType:2,elements:[row]}]); +const batch = JSON.parse(vm.runInContext(scripts.poll, sandbox)); +assert.equal(batch.items.length, 1);assert.equal(batch.rejected, 0); +assert.deepEqual(batch.items[0].record.elements[0].textElement, + {content:'@全体成员',atType:1,atUid:'all',atNtUid:'all',atTinyId:''}); +"#; + let mut child = std::process::Command::new("node") + .args(["-e", fixture]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn().unwrap(); + child.stdin.take().unwrap().write_all(scripts.to_string().as_bytes()).unwrap(); + let result = child.wait_with_output().unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); + } + #[test] fn d8_account_wrapper_returns_the_listener_result() { + use std::io::Write; let listener = serde_json::to_string(&listener_script_with_account("10001")).unwrap(); let script = format!( "const assert = require('node:assert/strict'); globalThis.__caligo_res = {{sid:'nt_1'}}; assert.equal(eval({listener}), 'ALREADY sid=nt_1');" ); - let result = std::process::Command::new("node").args(["-e", &script]).output().unwrap(); + let mut child = std::process::Command::new("node") + .stdin(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn().unwrap(); + child.stdin.take().unwrap().write_all(script.as_bytes()).unwrap(); + let result = child.wait_with_output().unwrap(); assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); } @@ -3044,6 +3389,7 @@ for (const [profile, expected] of [['pilot', 2], ['legacy', 0]]) { let mut child = std::process::Command::new("node") .args(["-e", fixture]) .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn().unwrap(); child.stdin.take().unwrap().write_all(scripts.to_string().as_bytes()).unwrap(); @@ -3051,6 +3397,102 @@ for (const [profile, expected] of [['pilot', 2], ['legacy', 0]]) { assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); } + #[test] + fn d8_at_and_reply_shape_diagnostics_are_bounded_and_value_free() { + use std::io::Write; + + let scripts = serde_json::json!({ + "pilot": listener_script_with_account("10001"), + "poll": super::D8_POLL_JS, + }); + let fixture = r#" +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const scripts = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +let listener; +const service = {sendMsg() {}, addKernelMsgListener(value) { listener = value; return '1'; }}; +const session = {getSessionId: () => '1', getMsgService: () => service}; +const sandbox = vm.createContext({Buffer, process: {_linkedBinding: () => ({ + NodeIQQNTWrapperSession: {getNTWrapperSession: () => session} +})}}); +assert.match(vm.runInContext(scripts.pilot, sandbox), /^ARMED/); +const common = {msgId:'5001',msgSeq:'2',msgRandom:'3',msgTime:'1794567890',guildId:'', + peerUid:'u_peer',peerUin:'20002',senderUid:'u_peer',senderUin:'20002',msgType:2,subMsgType:1}; +const at = {content:'@Bot hello',atType:2,atUid:'20003',atNtUid:'u_other',atTinyId:'0'}; +const row = (chatType, elements) => ({...common,chatType, + ...(chatType === 2 ? {peerUid:'30003',peerUin:'30003'} : {}),elements}); +const reply = {elementType:7,replyElement:{replayMsgId:'123456',replayMsgSeq:'7', + sourceMsgText:'SECRET preview',msgTextWith0x14Face:'SECRET',tinyId:9,extra:'SECRET'}}; +const file = {elementType:3,fileElement:{fileName:'SECRET'}}; +listener.onRecvMsg([ + row(1, [{elementType:1,textElement:at}]), + row(2, [{elementType:1,textElement:at}]), + row(1, [{elementType:1,textElement:{...at,atType:2,atUid:'0'}}]), + row(1, [reply]), + row(1, [file]), +]); +const batch = JSON.parse(vm.runInContext(scripts.poll, sandbox)); +assert.equal(batch.items.length, 3); +assert.equal(batch.rejected, 2); +assert.equal(batch.items[0].record.elements[0].textElement.atType, 2); +assert.equal(batch.items[0].record.elements[0].textElement.atUid, '20003'); +assert.deepEqual(batch.items[2].record.elements[0], + {elementType:7,reply:{replayMsgId:'123456',replayMsgSeq:'7',sourceMsgText:'SECRET preview'}}); +const shapes = batch.segmentShapes; +assert.equal(shapes.length, 5); +const atPrivate = shapes[0]; +assert.deepEqual(atPrivate, {source:'recv',chat:'private',arity:'single',element_types:[1], + numeric_element_types:true,text_count:1,at_count:1,at_types:[2],reply_present:false, + at_uid_shape:'decimal',at_nt_uid_shape:'uid',at_tiny_id_shape:'decimal', + at_content_has_at:true}); +assert.equal(shapes[1].chat, 'group'); +assert.deepEqual(shapes[2].at_types, [2]); +assert.deepEqual(shapes[3].reply_fields, {replayMsgId:'decimal',replayMsgSeq:'decimal', + sourceMsgText:'string',msgTextWith0x14Face:'string',tinyId:'number'}); +assert.equal(shapes[3].reply_element_type, 7); +assert.equal(shapes[3].reply_present, true); +assert.equal(shapes[3].reply_key_count, 6); +assert.deepEqual(shapes[4].element_types, [3]); +assert.equal(shapes[4].reply_present, false); +const serialized = JSON.stringify(shapes); +for (const secret of ['SECRET', '20003', 'u_other', '123456', '@Bot']) { + assert.ok(!serialized.includes(secret), secret); +} +assert.deepEqual(JSON.parse(vm.runInContext(scripts.poll, sandbox)).segmentShapes, []); +console.log('BATCH=' + JSON.stringify(batch)); +"#; + let mut child = std::process::Command::new("node") + .args(["-e", fixture]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn().unwrap(); + child.stdin.take().unwrap().write_all(scripts.to_string().as_bytes()).unwrap(); + let result = child.wait_with_output().unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); + let stdout = String::from_utf8_lossy(&result.stdout); + let line = stdout.lines().find(|line| line.starts_with("BATCH=")) + .expect("D8 batch output"); + let batch: serde_json::Value = serde_json::from_str(&line[6..]).unwrap(); + let binding = caligo_model::wrapper_message::WrapperBinding { + account: "10001".into(), + session_generation: 1, + host_nonce: 9, + wrapper_session: "nt_0".into(), + }; + let drain = caligo_model::wrapper_message::decode_d8_batch( + &batch.to_string(), &binding).unwrap(); + assert_eq!(drain.events.len(), 3); + assert!(drain.events.iter().any(|event| event.segments().unwrap().iter() + .any(|segment| matches!(segment, + caligo_model::wrapper_message::WrapperSegment::Reply { replay_msg_id, .. } + if replay_msg_id == "123456")))); + assert!(drain.events.iter().any(|event| event.segments().unwrap().iter() + .any(|segment| matches!(segment, + caligo_model::wrapper_message::WrapperSegment::Text { mention: Some(m), .. } + if m.at_uid == "20003" && m.at_type == 2)))); + } + #[test] fn scoped_login_start_rejects_wrong_host_account_before_directory_lookup() { let start = build_scoped_login_start("D:\\QQ NT\\wrapper.node", "10001"); @@ -3567,6 +4009,84 @@ pub fn build_image_send_js( Some(format!("({})({args})",include_str!("qq_image_send.js"))) } +/// Fixed @/reply submission contract used by scoped durable rich dispatch. +pub fn build_rich_send_js( + chat_type: u32, + account: &str, + peer_uin: &str, + request_id: &str, + wire_seq: u32, + timeout_ms: u64, + segments: &[caligo_model::onebot_traits::SendSegment], +) -> Option { + use caligo_model::onebot_traits::{SendSegment, MAX_RICH_TEXT_BYTES, MAX_SEND_SEGMENTS}; + if !matches!(chat_type, 1 | 2) + || segments.is_empty() + || segments.len() > MAX_SEND_SEGMENTS + { + return None; + } + let positive = |value: &str| { + !value.is_empty() + && value.len() <= 128 + && !value.starts_with('0') + && value.bytes().all(|b| b.is_ascii_digit()) + }; + let native_uid = |value: &str| { + value.len() > 2 + && value.starts_with("u_") + && value[2..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + }; + let mut text_bytes = 0usize; + for segment in segments { + match segment { + SendSegment::Text { text } => text_bytes += text.len(), + SendSegment::Mention { qq, uid, name } => { + if chat_type != 2 || name.is_empty() { + return None; + } + if qq == "all" { + if uid != "all" { + return None; + } + } else if !positive(qq) || !native_uid(uid) { + return None; + } + } + SendSegment::Reply { target } => { + if target.peer_chat_type != chat_type + || target.peer_uin != peer_uin + || !positive(&target.replay_msg_id) + || !positive(&target.replay_msg_seq) + || !positive(&target.sender_uin) + || match chat_type { + 1 => !native_uid(&target.peer_uid) || target.reply_msg_client_seq.is_none(), + 2 => !positive(&target.peer_uid), + _ => true, + } + || target + .reply_msg_client_seq + .as_deref() + .is_some_and(|seq| seq.is_empty() || seq.len() > 20 || !seq.bytes().all(|b| b.is_ascii_digit())) + { + return None; + } + } + } + } + if text_bytes > MAX_RICH_TEXT_BYTES { + return None; + } + let args = serde_json::json!({ + "chatType": chat_type, "account": account, "peerUin": peer_uin, + "requestId": request_id, "wireSeq": wire_seq, "timeoutMs": timeout_ms, + "segments": segments, + }); + Some(format!("({})({args})", include_str!("qq_rich_send.js"))) +} + /// D9 fixed wrapper text send. Correlation stays local; a native ID is returned /// only after exact event identity and getMsgsByMsgId readback agree. pub fn build_send_js( diff --git a/crates/caligo-bridge/src/receive_diagnostics.rs b/crates/caligo-bridge/src/receive_diagnostics.rs index 78f53b76..c87e0848 100644 --- a/crates/caligo-bridge/src/receive_diagnostics.rs +++ b/crates/caligo-bridge/src/receive_diagnostics.rs @@ -133,6 +133,8 @@ pub(crate) fn sanitize_media_download(input: &str) -> Option { "validation_failed", "readback", "readback_matched", + "image_receipt", + "output_shape", ] .contains(&stage) { @@ -146,6 +148,27 @@ pub(crate) fn sanitize_media_download(input: &str) -> Option { } } } + if stage == "output_shape" { + for field in ["size_matches", "silk_header", "amr_header"] { + if let Some(value) = entry.get(field).and_then(Value::as_bool) { + row[field] = json!(value); + } + } + if let Some(ext) = entry.get("extension").and_then(Value::as_str) { + if ["amr", "silk", "other"].contains(&ext) { + row["extension"] = json!(ext); + } + } + } + if stage == "image_receipt" { + for field in ["file_uuid", "file_sub_id", "file_name", "source_path", "thumb_size", "original", "summary"] { + if let Some(value) = entry.get(field).and_then(Value::as_str) { + if ["missing", "empty", "nonempty", "string", "number", "boolean", "object"].contains(&value) { + row[field] = json!(value); + } + } + } + } if stage == "callback" { if let Some(chat) = entry.get("callback_chat").and_then(Value::as_str) { if [ @@ -163,6 +186,11 @@ pub(crate) fn sanitize_media_download(input: &str) -> Option { row["callback_chat"] = json!(chat); } } + if let Some(ext) = entry.get("path_extension").and_then(Value::as_str) { + if ["amr", "silk", "other"].contains(&ext) { + row["path_extension"] = json!(ext); + } + } for field in [ "message_matches", "element_matches", @@ -173,6 +201,10 @@ pub(crate) fn sanitize_media_download(input: &str) -> Option { "error_is_zero", "slot_matches", "pending", + "path_absolute", + "path_normalized", + "path_md5_prefix", + "path_under_ptt", ] { if let Some(value) = entry.get(field).and_then(Value::as_bool) { row[field] = json!(value); @@ -184,6 +216,38 @@ pub(crate) fn sanitize_media_download(input: &str) -> Option { (!output.is_empty()).then(|| json!({"download_stages":output}).to_string()) } +pub(crate) fn sanitize_media_capabilities(input: &str) -> Option { + if input.len() > 524_288 { + return None; + } + let batch: Value = serde_json::from_str(input).ok()?; + let caps = batch.get("mediaCapabilities")?.as_object()?; + let mut out = serde_json::Map::new(); + for field in [ + "session_rich_service", + "msg_send_file", + "msg_upload_file", + "rich_upload_file", + "rich_send_file", + "rich_get_path", + ] { + if let Some(value) = caps.get(field).and_then(Value::as_bool) { + out.insert(field.to_string(), Value::Bool(value)); + } + } + for field in ["rich_methods", "msg_methods"] { + if let Some(values) = caps.get(field).and_then(Value::as_array) { + let labels: Vec = values.iter().take(64).filter_map(|value| { + let name = value.as_str()?; + (name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')) + .then(|| json!(name)) + }).collect(); + if !labels.is_empty() { out.insert(field.to_string(), Value::Array(labels)); } + } + } + (!out.is_empty()).then(|| json!({"media_capabilities":out}).to_string()) +} + pub(crate) fn sanitize_image_shapes(input: &str) -> Option { if input.len() > 524_288 { return None; @@ -242,6 +306,107 @@ pub(crate) fn sanitize_image_shapes(input: &str) -> Option { Some(report.to_string()) } +/// Bounded @/reply/unsupported-element shapes from D8. This describes why a +/// record was rejected without forwarding content, identity, ids or paths. +pub(crate) fn sanitize_segment_shapes(input: &str) -> Option { + if input.len() > 524_288 { + return None; + } + let batch: Value = serde_json::from_str(input).ok()?; + let shapes = batch.get("segmentShapes")?.as_array()?; + let mut output = Vec::new(); + for shape in shapes.iter().take(8) { + let mut row = Map::new(); + for (field, allowed) in [ + ("source", &["recv", "update", "add_send"][..]), + ("chat", &["private", "group", "other"][..]), + ("arity", &["single", "multiple"][..]), + ] { + if let Some(value) = shape.get(field).and_then(Value::as_str) { + if allowed.contains(&value) { + row.insert(field.into(), json!(value)); + } + } + } + for field in ["numeric_element_types", "reply_present", "at_content_has_at"] { + if let Some(value) = shape.get(field).and_then(Value::as_bool) { + row.insert(field.into(), json!(value)); + } + } + for field in ["text_count", "at_count", "reply_key_count"] { + if let Some(value) = shape.get(field).and_then(Value::as_u64) { + row.insert(field.into(), json!(value.min(128))); + } + } + for field in ["element_types", "at_types"] { + if let Some(values) = shape.get(field).and_then(Value::as_array) { + let bounded: Vec = values + .iter() + .take(8) + .filter_map(Value::as_u64) + .filter(|value| *value <= 64) + .map(|value| json!(value)) + .collect(); + if !bounded.is_empty() { + row.insert(field.into(), Value::Array(bounded)); + } + } + } + for field in ["at_uid_shape", "at_nt_uid_shape", "at_tiny_id_shape"] { + if let Some(value) = shape.get(field).and_then(Value::as_str) { + if ["missing", "null", "empty", "decimal", "uid", "string", "number", "other"] + .contains(&value) + { + row.insert(field.into(), json!(value)); + } + } + } + if let Some(value) = shape.get("reply_element_type") { + if let Some(number) = value.as_u64() { + if number <= 64 { + row.insert("reply_element_type".into(), json!(number)); + } + } else if value.as_str() == Some("other") { + row.insert("reply_element_type".into(), json!("other")); + } + } + if let Some(fields) = shape.get("reply_fields").and_then(Value::as_object) { + let mut bounded = Map::new(); + for name in [ + "replayMsgId", + "replayMsgSeq", + "sourceMsgText", + "msgTextWith0x14Face", + "tinyId", + ] { + if let Some(value) = fields.get(name).and_then(Value::as_str) { + if [ + "missing", + "null", + "empty", + "decimal", + "string", + "number", + "boolean", + "other", + ] + .contains(&value) + { + bounded.insert(name.into(), json!(value)); + } + } + } + if !bounded.is_empty() { + row.insert("reply_fields".into(), Value::Object(bounded)); + } + } + if !row.is_empty() { + output.push(Value::Object(row)); + } + } + (!output.is_empty()).then(|| json!({"segment_shapes":output}).to_string()) +} + #[cfg(test)] mod tests { use super::*; @@ -351,7 +516,8 @@ mod tests { {"media":"voice","stage":"promise","result":"accepted","message":"SECRET"}, {"media":"voice","stage":"SECRET"}, {"media":"SECRET","stage":"callback"}, {"media":"voice","stage":"validation_failed","error":"SECRET"}, - {"media":"voice","stage":"readback_matched","peerUid":"SECRET"} + {"media":"voice","stage":"readback_matched","peerUid":"SECRET"}, + {"media":"image","stage":"image_receipt","file_uuid":"nonempty","file_sub_id":"empty","file_name":"SECRET","source_path":"string","thumb_size":"number","original":"boolean","summary":"missing"} ]}) .to_string(); let output = sanitize_media_download(&input).unwrap(); @@ -363,7 +529,8 @@ mod tests { {"media":"image","stage":"callback"}, {"media":"voice","stage":"promise","result":"accepted"}, {"media":"voice","stage":"validation_failed"}, - {"media":"voice","stage":"readback_matched"} + {"media":"voice","stage":"readback_matched"}, + {"media":"image","stage":"image_receipt","file_uuid":"nonempty","file_sub_id":"empty","source_path":"string","thumb_size":"number","original":"boolean","summary":"missing"} ]}) ); let many = json!({"mediaDiagnostics":vec![json!({"media":"voice","stage":"dispatch"});100]}).to_string(); @@ -393,6 +560,50 @@ mod tests { ); } + #[test] + fn segment_shapes_keep_only_fixed_labels_and_counts() { + let input = json!({"segmentShapes":[ + {"source":"recv","chat":"group","arity":"single","element_types":[1], + "numeric_element_types":true,"text_count":1,"at_count":1,"at_types":[1], + "at_uid_shape":"decimal","at_nt_uid_shape":"uid","at_tiny_id_shape":"decimal", + "at_content_has_at":true,"reply_present":false,"uid":"SECRET","content":"SECRET"}, + {"source":"recv","chat":"private","arity":"single","element_types":[7], + "numeric_element_types":true,"text_count":0,"at_count":0,"at_types":[], + "reply_present":true,"reply_element_type":7, + "reply_fields":{"replayMsgId":"decimal","replayMsgSeq":"decimal", + "sourceMsgText":"string","msgTextWith0x14Face":"missing","tinyId":"number", + "secret":"SECRET"},"reply_key_count":6}, + {"source":"SECRET","chat":"SECRET","arity":"SECRET","element_types":[999,2], + "text_count":"SECRET","at_count":9999,"reply_fields":{"SECRET":"SECRET"}} + ]}) + .to_string(); + let output = sanitize_segment_shapes(&input).unwrap(); + assert!(!output.contains("SECRET") && !output.contains("9999")); + assert_eq!( + serde_json::from_str::(&output).unwrap(), + json!({"segment_shapes":[ + {"source":"recv","chat":"group","arity":"single","element_types":[1], + "numeric_element_types":true,"text_count":1,"at_count":1,"at_types":[1], + "at_uid_shape":"decimal","at_nt_uid_shape":"uid","at_tiny_id_shape":"decimal", + "at_content_has_at":true,"reply_present":false}, + {"source":"recv","chat":"private","arity":"single","element_types":[7], + "numeric_element_types":true,"text_count":0,"at_count":0, + "reply_present":true,"reply_element_type":7, + "reply_fields":{"replayMsgId":"decimal","replayMsgSeq":"decimal", + "sourceMsgText":"string","msgTextWith0x14Face":"missing","tinyId":"number"}, + "reply_key_count":6}, + {"element_types":[2],"at_count":128} + ]}) + ); + let many = json!({"segmentShapes":vec![json!({"source":"recv"});100]}).to_string(); + let output: Value = serde_json::from_str(&sanitize_segment_shapes(&many).unwrap()).unwrap(); + assert_eq!(output["segment_shapes"].as_array().unwrap().len(), 8); + for input in ["NOT_ARMED", "{}", r#"{"segmentShapes":[{"secret":"value"}]}"#] { + assert_eq!(sanitize_segment_shapes(input), None); + } + assert_eq!(sanitize_segment_shapes(&" ".repeat(524_289)), None); + } + #[test] fn bounds_and_unrecognized_inputs_produce_no_unbounded_output() { let input = json!({"imageShapes":vec![json!({"source":"recv"});100], diff --git a/crates/caligo-bridge/src/resident.rs b/crates/caligo-bridge/src/resident.rs index bafa9c80..411b3a10 100644 --- a/crates/caligo-bridge/src/resident.rs +++ b/crates/caligo-bridge/src/resident.rs @@ -81,12 +81,21 @@ pub enum OwnedRequest { chat_type: u32, png: Vec, }, + SendRich { + request_id: String, + wire_seq: u32, + deadline: std::time::Instant, + scope: QueryScope, + peer_uin: String, + chat_type: u32, + segments: Vec, + }, } impl OwnedRequest { fn send_id(&self) -> Option<&String> { match self { - Self::SendText { request_id, .. } | Self::SendVoice { request_id, .. } | Self::SendImage { request_id, .. } => { + Self::SendText { request_id, .. } | Self::SendVoice { request_id, .. } | Self::SendImage { request_id, .. } | Self::SendRich { request_id, .. } => { Some(request_id) } Self::Probe { .. } => None, @@ -138,7 +147,7 @@ impl OwnedEvent { text: if envelope.voice().is_some() || envelope.image().is_some() { String::new() } else { - envelope.text()? + envelope.plain_text()? }, msg_time: envelope.platform_time_seconds(), wrapper_message: Some(envelope), @@ -444,6 +453,14 @@ impl Resident { self.adapter.lock().unwrap().supports_image(chat_type) } + pub fn supports_reply(&self, chat_type: u32) -> bool { + self.adapter.lock().unwrap().supports_reply(chat_type) + } + + pub fn supports_mention(&self, chat_type: u32) -> bool { + self.adapter.lock().unwrap().supports_mention(chat_type) + } + pub fn set_bridge_scope(&self, scope: Option) { let _adapter = self.adapter.lock().unwrap(); // Revocation must survive a rebind before the owner gets to drain. @@ -531,6 +548,13 @@ impl Resident { if let OwnedRequest::SendImage { png, .. } = &req { if caligo_model::png::dimensions(png).is_none() { return SubmitVerdict::Invalid; } } + if let OwnedRequest::SendRich { segments, .. } = &req { + if segments.is_empty() + || segments.len() > caligo_model::onebot_traits::MAX_SEND_SEGMENTS + { + return SubmitVerdict::Invalid; + } + } let mut c = self.core.lock().unwrap(); c.counters.submitted_total += 1; match c.state { @@ -656,6 +680,16 @@ impl Resident { png: png.clone(), } } + OwnedRequest::SendRich { request_id, wire_seq, deadline, peer_uin, chat_type, segments, .. } => { + HostOp::SendRich { + request_id: request_id.clone(), + wire_seq: *wire_seq, + timeout_ms: deadline.saturating_duration_since(std::time::Instant::now()).as_millis() as u64, + peer_uin: peer_uin.clone(), + chat_type: *chat_type, + segments: segments.clone(), + } + } }; (req, op) }; // core 锁释放:native 调用期间回调可重入。 @@ -680,7 +714,8 @@ impl Resident { break; } if let OwnedRequest::SendVoice { deadline, scope, chat_type, .. } - | OwnedRequest::SendImage { deadline, scope, chat_type, .. } = &req { + | OwnedRequest::SendImage { deadline, scope, chat_type, .. } + | OwnedRequest::SendRich { deadline, scope, chat_type, .. } = &req { let core = self.core.lock().unwrap(); let current = core.state == ResidentState::Ready && core.bridge_scope.as_ref() == Some(scope); drop(core); @@ -688,6 +723,34 @@ impl Resident { matches!(chat_type, 1 | 2) && adapter.supports_image(*chat_type) && caligo_model::png::dimensions(png).is_some() && caligo_model::capability::positive_decimal(peer_uin) && (*chat_type == 2 || peer_uin != &scope.account) + } else if let OwnedRequest::SendRich { segments, peer_uin, .. } = &req { + let has_reply = segments.iter().any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Reply { .. })); + let has_mention = segments.iter().any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Mention { .. })); + let total_text: usize = segments.iter().map(|segment| match segment { + caligo_model::onebot_traits::SendSegment::Text { text } => text.len(), + _ => 0, + }).sum(); + !segments.is_empty() + && segments.len() <= caligo_model::onebot_traits::MAX_SEND_SEGMENTS + && total_text <= caligo_model::onebot_traits::MAX_RICH_TEXT_BYTES + && matches!(chat_type, 1 | 2) + && caligo_model::capability::positive_decimal(peer_uin) + && (*chat_type == 2 || peer_uin != &scope.account) + && (!has_reply || adapter.supports_reply(*chat_type)) + && (!has_mention || adapter.supports_mention(*chat_type)) + && segments.iter().all(|segment| match segment { + caligo_model::onebot_traits::SendSegment::Text { .. } => true, + caligo_model::onebot_traits::SendSegment::Mention { qq, uid, name } => + *chat_type == 2 + && !name.is_empty() + && (qq == "all" && uid == "all" + || caligo_model::capability::positive_decimal(qq) + && uid.len() > 2 + && uid.starts_with("u_")), + caligo_model::onebot_traits::SendSegment::Reply { target } => + target.peer_chat_type == *chat_type && target.peer_uin == *peer_uin + && (*chat_type != 1 || target.reply_msg_client_seq.is_some()), + }) } else { match chat_type { 1 => adapter.supports_private_voice(), 2 => adapter.supports_group_voice(), diff --git a/crates/caligo-bridge/tests/resident_lifecycle.rs b/crates/caligo-bridge/tests/resident_lifecycle.rs index 92e1ec31..5aa8da0b 100644 --- a/crates/caligo-bridge/tests/resident_lifecycle.rs +++ b/crates/caligo-bridge/tests/resident_lifecycle.rs @@ -405,7 +405,7 @@ impl HostAdapter for SharedMockHost { inner.listener = None; Ok(HostOpResult::ListenerRemoved) } - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => Ok(HostOpResult::ProbeDone), HostOp::SendText { text, .. } if text == "accepted-without-id" => { Ok(HostOpResult::Sent { native_id: None }) @@ -446,7 +446,7 @@ impl HostAdapter for CorrelationHost { Ok(match op { HostOp::ListenerAdd => HostOpResult::ListenerDeferred, HostOp::ListenerRemove { .. } => HostOpResult::ListenerRemoved, - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => HostOpResult::ProbeDone, HostOp::SendText { request_id, .. } => { *self.pending.lock().unwrap() = Some(request_id); @@ -498,7 +498,7 @@ impl HostAdapter for LateReceiptHost { Ok(match op { HostOp::ListenerAdd => HostOpResult::ListenerDeferred, HostOp::ListenerRemove { .. } => HostOpResult::ListenerRemoved, - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => HostOpResult::ProbeDone, HostOp::SendText { .. } => HostOpResult::SendFired { mid: "MID-late".into(), @@ -1318,7 +1318,7 @@ impl HostAdapter for ReentrantHost { use caligo_bridge::host_adapter::HostError; let r = self.resident.get().expect("resident slot set"); match op { - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::SendText { .. } => { // 重入点 1:token()(core 锁);重入点 2:deliver_callback(core 锁)。 let tok = r.token(); @@ -1453,7 +1453,7 @@ fn send_pending_classified_unknown_on_close() { Ok(match op { HostOp::ListenerAdd => HostOpResult::ListenerAdded { token: 1 }, HostOp::ListenerRemove { .. } => HostOpResult::ListenerRemoved, - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => HostOpResult::ProbeDone, HostOp::SendText { .. } => HostOpResult::SendFired { mid: "MID-1".into(), diff --git a/crates/caligo-bridge/tests/wrapper_image_contract.rs b/crates/caligo-bridge/tests/wrapper_image_contract.rs index b23c5efb..04cb4257 100644 --- a/crates/caligo-bridge/tests/wrapper_image_contract.rs +++ b/crates/caligo-bridge/tests/wrapper_image_contract.rs @@ -68,7 +68,7 @@ function fresh() { return {msgId,chatType,peerUid,peerUin,senderUid:'u_image_peer',senderUin,sendStatus:2, elements:[{elementType:2,elementId,picElement:{fileSize:png.length,picWidth:1,picHeight:1, picType:1001,picSubType:0,md5HexStr:md5.toUpperCase(),filePath:'private-path', - sourcePath:'private-source',fileUuid:'private-token',originImageUrl:'private-url'}}]}; + sourcePath:'private-source',fileUuid:'media-id',originImageUrl:'private-url'}}]}; } const tick = () => new Promise(resolve => setImmediate(resolve)); const call = source => JSON.parse(eval(source)); @@ -108,7 +108,7 @@ async function read(m) { m=>m.elements[0].picElement.picHeight=32769, m=>{m.elements[0].picElement.picWidth=32768;m.elements[0].picElement.picHeight=32768;}, ]) { - const m=fresh(); mutate(m); assert.equal((await read(m)).status,'invalid_response'); + const m=fresh(); mutate(m); const q=await read(m); assert.equal(q.status,'rejected'); assert.equal(q.code,404); } const stringSize=fresh(); stringSize.elements[0].picElement.fileSize=String(png.length); assert.equal((await read(stringSize)).status,'success'); @@ -123,6 +123,7 @@ async function read(m) { panic!("image metadata missing") }; assert_eq!((info.width, info.height, info.pic_type), (1, 1, 1001)); + assert_eq!(info.file_uuid.as_deref(), Some("media-id")); for field in [ "chat_type", "sender_uin", @@ -216,6 +217,7 @@ const service={sendMsg(){},addKernelMsgListener(v){listener=v;return 7;},removeK }, getMsgsByMsgId(peer,ids) { assert.equal(this,service);assert.deepEqual(peer,{chatType,peerUid,guildId:''});assert.deepEqual(ids,[msgId]); + if(mode==='missing')return Promise.resolve({result:0,msgList:[]}); const m=fresh();mutate(m);const out={result:0,msgList:[m]}; if(mode==='delayed')return new Promise(resolve=>delayed=()=>resolve(out)); return Promise.resolve(out); @@ -237,6 +239,8 @@ async function begin(source=start){assert.equal(call(source).status,'pending');a function finish(data=png,extra={}){const target=requested;fs.writeFileSync(target,data);listener.onRichMediaDownloadComplete(complete(extra));return target;} (async()=>{ mode='delayed';assert.equal(call(start).status,'pending');assert.equal(call(cancel).status,'cancelled');delayed();await tick();assert.equal(calls,0); + mode='missing';await begin();const missing=call(poll);assert.equal(missing.status,'rejected');assert.equal(missing.code,404); + assert.equal(globalThis.__caligo_d8.queryPending.has('image'),false); mode='pending';await begin(); for(const wrong of [{msgId:'99'},{msgElementId:'99'},{chatType:2},{filePath:requested+'.wrong'}]) { listener.onRichMediaDownloadComplete(complete(wrong));assert.equal(call(poll).status,'pending'); @@ -275,10 +279,10 @@ function finish(data=png,extra={}){const target=requested;fs.writeFileSync(targe mode='sync';await begin();const success=call(poll);assert.equal(success.status,'success'); assert.equal(success.data.data.png_hex,png.toString('hex'));assert.equal(fs.existsSync(path.dirname(requested)),false); chatType=2;peerUid=peerUin='30003';mode='pending'; - mutate=m=>m.peerUin='999';await begin(group);assert.equal(call(poll).status,'invalid_response');mutate=m=>{}; + mutate=m=>m.peerUin='999';await begin(group);assert.equal(call(poll).status,'rejected');assert.equal(call(poll).code,404);mutate=m=>{}; await begin(group);finish();assert.equal(call(poll).data.data.info.chat_type,2); chatType=1;peerUid='u_image_peer';peerUin='20002';senderUin='10001'; - mutate=m=>m.sendStatus=1;await begin(sent);assert.equal(call(poll).status,'invalid_response');mutate=m=>{}; + mutate=m=>m.sendStatus=1;await begin(sent);assert.equal(call(poll).status,'rejected');assert.equal(call(poll).code,404);mutate=m=>{}; mode='sync';mutate=m=>m.elements[0].picElement.picType=1000; await begin(sent);const own=call(poll);assert.equal(own.data.data.info.sender_uin,'10001'); assert.equal(own.data.data.info.pic_type,1000);assert.equal(own.data.data.png_hex,png.toString('hex'));mutate=m=>{}; @@ -331,7 +335,7 @@ function finish(data=png,extra={}){const target=requested;fs.writeFileSync(targe assert.equal(call(poll).status,'pending','group picType 1001 keeps strict chat'); listener.onRichMediaDownloadComplete(complete({filePath:cachePath}));assert.equal(call(poll).status,'success'); mutate=m=>{m.elements[0].picElement.picType=1000;m.peerUin='wrong';}; - const beforeWrongPeer=calls;await begin(sentGroupPilot);assert.equal(call(poll).status,'invalid_response'); + const beforeWrongPeer=calls;await begin(sentGroupPilot);assert.equal(call(poll).status,'rejected');assert.equal(call(poll).code,404); assert.equal(calls,beforeWrongPeer,'wrong group readback must not dispatch download'); mutate=m=>m.elements[0].picElement.picType=1000; await begin(sentGroupPilot);fs.writeFileSync(cachePath,Buffer.alloc(png.length)); diff --git a/crates/caligo-bridge/tests/wrapper_image_send.rs b/crates/caligo-bridge/tests/wrapper_image_send.rs index 92b2631e..238eb263 100644 --- a/crates/caligo-bridge/tests/wrapper_image_send.rs +++ b/crates/caligo-bridge/tests/wrapper_image_send.rs @@ -130,7 +130,7 @@ function notify() { assert.equal(submits,0); setup('bad_path'); dest=path.join(root,'bad_path','other.png'); - assert.deepEqual(run(),{err:'invalid_image_storage_path'}); + assert.deepEqual(run(),{err:'invalid_image_storage_basename_other_png'}); assert.equal(submits,0); assert.equal(fs.existsSync(dest),false); diff --git a/crates/caligo-bridge/tests/wrapper_poll_budget.rs b/crates/caligo-bridge/tests/wrapper_poll_budget.rs index 5c4c0dd0..f0e56fa6 100644 --- a/crates/caligo-bridge/tests/wrapper_poll_budget.rs +++ b/crates/caligo-bridge/tests/wrapper_poll_budget.rs @@ -56,7 +56,7 @@ fn oversized_terminal_is_deferred_if_unknown_does_not_fit() { const assert=require('node:assert/strict'),vm=require('node:vm'),poll=__POLL__; const recv=[{payload:'R'.repeat(390000)}],sendResults={fill:{status:'done',msgId:''}}; const base={schema:1,sid:'nt_1',items:recv,rejected:0,overflow:0,sendResults, - imageShapes:[],mediaDiagnostics:[],textSendTrace:[],textSendTraceGeneration:0,textSendTraceOverflow:false}; + imageShapes:[],segmentShapes:[],mediaDiagnostics:[],mediaCapabilities:{},textSendTrace:[],textSendTraceGeneration:0,textSendTraceOverflow:false}; const remaining=524288-Buffer.byteLength(JSON.stringify(base),'utf8')-24; assert.ok(remaining>0);sendResults.fill.msgId='X'.repeat(remaining); sendResults.huge={status:'done',msgId:'H'.repeat(530000)}; diff --git a/crates/caligo-bridge/tests/wrapper_query_contract.rs b/crates/caligo-bridge/tests/wrapper_query_contract.rs index 1ffa0300..45a1d57a 100644 --- a/crates/caligo-bridge/tests/wrapper_query_contract.rs +++ b/crates/caligo-bridge/tests/wrapper_query_contract.rs @@ -53,7 +53,21 @@ async function read(record) { assert.equal(JSON.parse(eval(poll)).code,404); return result; } +async function readMissing() { + const service = {getMsgsByMsgId(peer, ids) { + assert.equal(this,service); + assert.deepEqual(peer,{chatType:1,peerUid:'u_voice_peer',guildId:''}); + assert.deepEqual(ids,[msgId]); + return Promise.resolve({result:0,msgList:[]}); + }}; + globalThis.__caligo_d8 = {sid:'nt_1',session:{getMsgService:()=>service}}; + assert.equal(JSON.parse(eval(start)).status,'pending'); + await new Promise(resolve => setImmediate(resolve)); + return JSON.parse(eval(poll)); +} (async () => { + const missing = await readMissing(); + assert.equal(missing.status,'rejected');assert.equal(missing.code,404); for (const mutate of [ m=>m.msgId='999', m=>m.chatType=2, m=>m.peerUid='u_wrong', m=>m.senderUid='u_self', m=>m.senderUin='10001', m=>m.elements[0].elementId=9007199254740994, diff --git a/crates/caligo-bridge/tests/wrapper_rich_send.rs b/crates/caligo-bridge/tests/wrapper_rich_send.rs new file mode 100644 index 00000000..d7c7ce20 --- /dev/null +++ b/crates/caligo-bridge/tests/wrapper_rich_send.rs @@ -0,0 +1,227 @@ +use caligo_bridge::qq_v8::{build_rich_send_js, D8_POLL_JS, D8_START_JS, D8_STOP_JS}; +use caligo_model::onebot_traits::{ReplyReference, SendSegment}; + +fn reply(target_peer: &str, chat_type: u32, peer_uid: &str) -> SendSegment { + SendSegment::Reply { + target: ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: chat_type, + peer_uid: peer_uid.into(), + peer_uin: target_peer.into(), + }, + } +} + +#[test] +fn rich_send_builds_ordered_reference_elements_and_requires_exact_readback() { + let group = vec![ + reply("30003", 2, "30003"), + SendSegment::Mention { + qq: "20002".into(), + uid: "u_member".into(), + name: "member".into(), + }, + SendSegment::Text { text: " hi".into() }, + ]; + let script = build_rich_send_js(2, "10001", "30003", "rich-7", 42, 5000, &group).unwrap(); + let private = vec![ + SendSegment::Reply { + target: ReplyReference { + replay_msg_id: "9007199254740994".into(), + replay_msg_seq: "8".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: Some("5".into()), + peer_chat_type: 1, + peer_uid: "u_peer".into(), + peer_uin: "20002".into(), + }, + }, + SendSegment::Text { + text: "reply".into(), + }, + ]; + let private_script = + build_rich_send_js(1, "10001", "20002", "rich-8", 43, 5000, &private).unwrap(); + let wrong_script = + build_rich_send_js(2, "10001", "30003", "rich-10", 45, 5000, &group).unwrap(); + let at_all = vec![ + SendSegment::Mention { qq: "all".into(), uid: "all".into(), name: "全体成员".into() }, + SendSegment::Text { text: " all".into() }, + ]; + let at_all_script = build_rich_send_js(2, "10001", "30003", "rich-atall", 46, 5000, &at_all).unwrap(); + assert!(build_rich_send_js( + 1, + "10001", + "20002", + "rich-9", + 44, + 5000, + &[SendSegment::Mention { + qq: "20002".into(), + uid: "u_member".into(), + name: "member".into() + }] + ) + .is_none()); + assert!(build_rich_send_js( + 2, + "10001", + "30003", + "rich-9", + 44, + 5000, + &[SendSegment::Mention { + qq: "20002".into(), + uid: String::new(), + name: "member".into() + }] + ) + .is_none()); + assert!(build_rich_send_js( + 2, + "10001", + "30003", + "rich-9", + 44, + 5000, + &[reply("40004", 2, "40004")] + ) + .is_none()); + + let fixture = r#" +const assert=require('node:assert/strict'),vm=require('node:vm'); +const start=__START__,poll=__POLL__,stop=__STOP__,send=__SEND__,privateSend=__PRIVATE__,wrongSend=__WRONG__,atAllSend=__ATALL__,caligoVoiceAccount='10001'; +let listener,cookie='',promiseResolve,wrongReadback=false,readbackElements=null; +const msgId='9007199254740995'; +const groupElements=()=>[ + {elementType:7,elementId:'',replyElement:{replayMsgSeq:'7',replayMsgId:'9007199254740993', + senderUin:'20002',senderUinStr:'20002',_replyMsgPeer:{chatType:2,peerUid:'30003'}}}, + {elementType:1,elementId:'',textElement:{content:'@member',atType:2,atUid:'20002',atNtUid:'u_member',atTinyId:''}}, + {elementType:1,elementId:'',textElement:{content:' hi',atType:0,atUid:'',atNtUid:'',atTinyId:''}} +]; +const normalizedGroupElements=()=>{ + const e=groupElements(); + e[1].textElement.content='@card'; + e[1].textElement.atTinyId='0'; + e[2].textElement.atUid='0'; + return e; +}; +const privateElements=()=>[ + {elementType:7,elementId:'',replyElement:{replayMsgSeq:'8',replayMsgId:'9007199254740994', + senderUin:'20002',senderUinStr:'20002',replyMsgClientSeq:'5', + _replyMsgPeer:{chatType:1,peerUid:'u_peer'}}}, + {elementType:1,elementId:'',textElement:{content:'reply',atType:0,atUid:'',atNtUid:'',atTinyId:''}} +]; +let activeChat=2,activePeer='30003',activeElements=null; +function record(status, elements) { + return {msgId,msgSeq:'7',msgRandom:'8',msgTime:'1794567890',clientSeq:activeChat===1?'5':undefined, + guildId:cookie,chatType:activeChat,msgType:2,subMsgType:0, + peerUid:activeChat===2?activePeer:'u_peer',peerUin:activePeer, + senderUid:'u_self',senderUin:'10001',sendStatus:status,elements:elements}; +} +const service={ + addKernelMsgListener(value){listener=value;return 9;}, + removeKernelMsgListener(){return true;}, + generateMsgUniqueId(){return cookie;}, + sendMsg(id,peer,elements,options){ + const canon=v=>Array.isArray(v)?'['+v.map(canon).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canon(v[k])).join(',')+'}':JSON.stringify(v); + assert.equal(id,'0');assert.equal(options.size,0); + assert.equal(peer.chatType,activeChat);assert.equal(peer.guildId,cookie); + assert.equal(canon(elements),canon(activeElements)); + // Simulate a native binding that consumes the caller's array before the + // asynchronous add/update callback. Correlation must use its owned copy. + elements.length = 0; + return new Promise(resolve=>{promiseResolve=resolve;}); + }, + getMsgsByMsgId(peer,ids){ + assert.equal(ids.length,1);assert.equal(ids[0],msgId);assert.equal(peer.guildId,cookie); + return {result:0,msgList:[record(2,wrongReadback?[ + {elementType:1,elementId:'',textElement:{content:'wrong',atType:0,atUid:'',atNtUid:'',atTinyId:''}} + ]:readbackElements)]}; + } +}; +const session={getSessionId:()=>1,getMsgService:()=>service,getMSFService:()=>({getServerTime:()=> 'time'}), + getProfileService:()=>({getUidByUin:()=>new Map([['20002','u_peer']])})}; +const proc={_linkedBinding:()=>({NodeIQQNTWrapperSession:{getNTWrapperSession:()=>session}})}; +const c={process:proc,Buffer,Promise,Date,Map,Set,JSON,String,Object,Array,Number,caligoVoiceAccount:'10001'}; +vm.createContext(c);const run=x=>vm.runInContext(x,c),tick=()=>new Promise(r=>setImmediate(r)); +(async()=>{ + assert.match(run(start),/^ARMED/); + cookie='rich-cookie';activeChat=2;activePeer='30003';activeElements=groupElements(); + assert.equal(JSON.parse(run(send)).fired,true); + listener.onRecvMsg([record(1,normalizedGroupElements())]); + listener.onMsgInfoListUpdate([record(2,normalizedGroupElements())]); + promiseResolve({result:0});readbackElements=normalizedGroupElements(); + await tick();await tick();await tick(); + let result=JSON.parse(run(poll)).sendResults['rich-7']; + assert.equal(result.status,'done');assert.equal(result.msgId,msgId); + + cookie='private-cookie';activeChat=1;activePeer='20002';activeElements=privateElements(); + assert.equal(JSON.parse(run(privateSend)).fired,true); + listener.onAddSendMsg(record(1,privateElements())); + listener.onMsgInfoListUpdate([record(2,privateElements())]); + promiseResolve({result:0});readbackElements=privateElements(); + await tick();await tick();await tick(); + result=JSON.parse(run(poll)).sendResults['rich-8']; + assert.equal(result.status,'done');assert.equal(result.msgId,msgId); + + cookie='wrong-cookie';activeChat=2;activePeer='30003';activeElements=groupElements(); + assert.equal(JSON.parse(run(wrongSend)).fired,true); + listener.onRecvMsg([record(1,normalizedGroupElements())]); + listener.onMsgInfoListUpdate([record(2,normalizedGroupElements())]); + promiseResolve({result:0});wrongReadback=true; + await tick();await tick();await tick(); + result=JSON.parse(run(poll)).sendResults['rich-10']; + assert.equal(result.status,'unknown'); + assert.equal(result.reason,'exact_query_identity_mismatch'); + + cookie='atall-cookie';activeChat=2;activePeer='30003';wrongReadback=false; + const atAllSent=[ + {elementType:1,elementId:'',textElement:{content:'@全体成员',atType:1,atUid:'all',atNtUid:'all',atTinyId:''}}, + {elementType:1,elementId:'',textElement:{content:' all',atType:0,atUid:'',atNtUid:'',atTinyId:''}} + ]; + const atAllRaw=[ + {elementType:1,elementId:'',textElement:{content:'@全体成员',atType:1,atUid:'0',atNtUid:'all',atTinyId:'0'}}, + {elementType:1,elementId:'',textElement:{content:' all',atType:0,atUid:'0',atNtUid:'',atTinyId:''}} + ]; + activeElements=atAllSent; + assert.equal(JSON.parse(run(atAllSend)).fired,true); + listener.onRecvMsg([record(1,atAllRaw)]); + listener.onMsgInfoListUpdate([record(2,atAllRaw)]); + promiseResolve({result:0});readbackElements=atAllRaw; + await tick();await tick();await tick(); + result=JSON.parse(run(poll)).sendResults['rich-atall']; + assert.equal(result.status,'done');assert.equal(result.msgId,msgId); +})().catch(e=>{console.error(e);process.exitCode=1;}); +"# + .replace("__START__", &serde_json::to_string(D8_START_JS).unwrap()) + .replace("__POLL__", &serde_json::to_string(D8_POLL_JS).unwrap()) + .replace("__STOP__", &serde_json::to_string(D8_STOP_JS).unwrap()) + .replace("__SEND__", &serde_json::to_string(&script).unwrap()) + .replace("__PRIVATE__", &serde_json::to_string(&private_script).unwrap()) + .replace("__WRONG__", &serde_json::to_string(&wrong_script).unwrap()) + .replace("__ATALL__", &serde_json::to_string(&at_all_script).unwrap()); + + use std::io::Write; + let mut child = std::process::Command::new("node") + .arg("--unhandled-rejections=strict") + .stdin(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(fixture.as_bytes()) + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); +} diff --git a/crates/caligo-bridge/tests/wrapper_send.rs b/crates/caligo-bridge/tests/wrapper_send.rs index b5882c0a..ea7a4886 100644 --- a/crates/caligo-bridge/tests/wrapper_send.rs +++ b/crates/caligo-bridge/tests/wrapper_send.rs @@ -767,8 +767,12 @@ listener.onRecvMsg(null);assert.equal(c.__caligo_res.rejected,rejected+1); assert.match(run(stop),/^STOPPED/); "#.replace("__START__", &serde_json::to_string(D8_START_JS).unwrap()) .replace("__STOP__", &serde_json::to_string(D8_STOP_JS).unwrap()); - let output=std::process::Command::new("node").args(["--unhandled-rejections=strict","-e",&fixture]) - .output().expect("Node.js is required for callback observation contracts"); + use std::io::Write; + let mut child=std::process::Command::new("node").arg("--unhandled-rejections=strict") + .stdin(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()) + .spawn().expect("Node.js is required for callback observation contracts"); + child.stdin.take().unwrap().write_all(fixture.as_bytes()).unwrap(); + let output=child.wait_with_output().unwrap(); assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stderr)); } @@ -797,8 +801,12 @@ assert.match(run(start),/^ARMED/); removalThrows=true; assert.equal(run(probe(true)),'ERR:listener_remove_failed stop_probe=pass'); assert.equal(c.__caligo_res.stopped,true); assert.equal(removals,5); "#,start=serde_json::to_string(D8_START_JS).unwrap(),stop=serde_json::to_string(D8_STOP_JS).unwrap()); - let output = std::process::Command::new("node").args(["--unhandled-rejections=strict","-e",&fixture]) - .output().expect("Node.js is required for the wrapper send fixture"); + use std::io::Write; + let mut child = std::process::Command::new("node").arg("--unhandled-rejections=strict") + .stdin(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()) + .spawn().expect("Node.js is required for the wrapper send fixture"); + child.stdin.take().unwrap().write_all(fixture.as_bytes()).unwrap(); + let output = child.wait_with_output().unwrap(); assert!(output.status.success(),"{}",String::from_utf8_lossy(&output.stderr)); } diff --git a/crates/caligo-core/src/capability_broker.rs b/crates/caligo-core/src/capability_broker.rs index abe9afe2..63a41e80 100644 --- a/crates/caligo-core/src/capability_broker.rs +++ b/crates/caligo-core/src/capability_broker.rs @@ -29,6 +29,9 @@ struct State { send_group_voice: bool, send_private_image: bool, send_group_image: bool, + send_private_reply: bool, + send_group_reply: bool, + send_group_mention: bool, pending: HashMap, stale_results: u64, } @@ -58,6 +61,9 @@ impl CapabilityBroker { state.send_group_voice = false; state.send_private_image = false; state.send_group_image = false; + state.send_private_reply = false; + state.send_group_reply = false; + state.send_group_mention = false; } pub(crate) fn bind(&self, scope: QueryScope) { @@ -71,6 +77,9 @@ impl CapabilityBroker { state.send_group_voice = false; state.send_private_image = false; state.send_group_image = false; + state.send_private_reply = false; + state.send_group_reply = false; + state.send_group_mention = false; } } @@ -84,6 +93,9 @@ impl CapabilityBroker { group_voice: bool, private_image: bool, group_image: bool, + private_reply: bool, + group_reply: bool, + group_mention: bool, ) -> bool { let mut state = self.state.lock().unwrap(); if epoch != state.epoch || state.scope.as_ref() != Some(scope) || scope.validate().is_err() @@ -96,6 +108,9 @@ impl CapabilityBroker { state.send_group_voice = group_voice; state.send_private_image = private_image; state.send_group_image = group_image; + state.send_private_reply = private_reply; + state.send_group_reply = group_reply; + state.send_group_mention = group_mention; true } @@ -121,6 +136,18 @@ impl CapabilityBroker { } } + pub(crate) fn supports_reply(&self, scope: &QueryScope, chat_type: u32) -> bool { + let state = self.state.lock().unwrap(); + state.scope.as_ref() == Some(scope) && match chat_type { + 1 => state.send_private_reply, 2 => state.send_group_reply, _ => false, + } + } + + pub(crate) fn supports_mention(&self, scope: &QueryScope, chat_type: u32) -> bool { + let state = self.state.lock().unwrap(); + state.scope.as_ref() == Some(scope) && chat_type == 2 && state.send_group_mention + } + pub(crate) fn advertise( &self, epoch: u64, diff --git a/crates/caligo-core/src/commands/media.rs b/crates/caligo-core/src/commands/media.rs index ac7a7515..29791163 100644 --- a/crates/caligo-core/src/commands/media.rs +++ b/crates/caligo-core/src/commands/media.rs @@ -30,6 +30,7 @@ enum Operation { Ogg, SilkWav, SilkOgg, + AudioSilk, Thumbnail, } @@ -50,7 +51,7 @@ struct ArtifactOutput { } fn usage(command: &str) -> String { - format!("{command} --config --input [--output-root ]") + format!("{command} --config --input [--output-root ]") } fn parse_args(raw: &[String], command: &str) -> Result { @@ -72,6 +73,7 @@ fn parse_args(raw: &[String], command: &str) -> Result { "ogg" => operation = Some(Operation::Ogg), "silk-wav" => operation = Some(Operation::SilkWav), "silk-ogg" => operation = Some(Operation::SilkOgg), + "wav-silk" | "ogg-silk" => operation = Some(Operation::AudioSilk), "thumbnail" => operation = Some(Operation::Thumbnail), "--help" | "-h" => return Err(usage(command)), unknown => return Err(format!("unknown argument {unknown}; usage: {}", usage(command))), @@ -235,6 +237,19 @@ fn run(cli: Cli) -> Result { )?) .map_err(|e| e.to_string()) } + Operation::AudioSilk => { + let root = output_root(cli.output_root)?; + let artifact = tool + .container_file_to_silk(&cli.input, &stop) + .map_err(|e| e.to_string())?; + serde_json::to_value(write_artifact( + &root, + "audio-silk", + artifact.format, + &artifact.bytes, + )?) + .map_err(|e| e.to_string()) + } Operation::Thumbnail => { let root = output_root(cli.output_root)?; let artifact = tool diff --git a/crates/caligo-core/src/daemon.rs b/crates/caligo-core/src/daemon.rs index 829a184d..c531f04d 100644 --- a/crates/caligo-core/src/daemon.rs +++ b/crates/caligo-core/src/daemon.rs @@ -30,6 +30,7 @@ use crate::transport::{ connect_client, generate_token, token_hex, PipeConnection, PipeServer, TransportError, }; use caligo_model::capability::{positive_decimal, HostQuery, LoginInfo, QueryOutcome, QueryScope}; +use caligo_model::onebot_traits::{SendSegment, MAX_RICH_TEXT_BYTES, MAX_SEND_SEGMENTS}; use caligo_model::{ Direction, EventSource, MsgEvent, NativeMessageId, SendTextRequest, SessionIdentity, }; @@ -203,6 +204,7 @@ pub struct Daemon { query_broker: CapabilityBroker, login_cache: Mutex>, login_cache_path: PathBuf, + image_uploads: Mutex, } /// Every return path (including wire errors) releases ephemeral query waiters. @@ -273,6 +275,7 @@ impl Daemon { query_broker: CapabilityBroker::default(), login_cache: Mutex::new(login_cache), login_cache_path, + image_uploads: Mutex::new(crate::image_upload::ImageUploadStore::default()), config, })) } @@ -439,6 +442,16 @@ impl Daemon { self.current_send_scope().is_some_and(|scope| self.query_broker.supports_image(&scope,chat_type)) } + pub fn supports_reply(&self, chat_type: u32) -> bool { + self.current_send_scope() + .is_some_and(|scope| self.query_broker.supports_reply(&scope, chat_type)) + } + + pub fn supports_mention(&self, chat_type: u32) -> bool { + self.current_send_scope() + .is_some_and(|scope| self.query_broker.supports_mention(&scope, chat_type)) + } + fn current_send_scope(&self) -> Option { let Ok(actor) = self.actor.lock() else { return None; @@ -599,6 +612,29 @@ impl Daemon { Ok(request_id) } + /// Separate upload phase for the bounded PNG resource store. This does + /// not claim a native QQ media id; the native upload remains inside send. + pub fn upload_image(&self, png: Vec) -> Result { + let mut store = self.image_uploads.lock().map_err(|_| "image upload lock poisoned")?; + store.insert(&self.config.account, png, unix_ms_now()) + } + + pub fn resolve_image_upload(&self, upload_id: &str) -> Result, String> { + let mut store = self.image_uploads.lock().map_err(|_| "image upload lock poisoned")?; + store + .resolve(&self.config.account, upload_id, unix_ms_now()) + .ok_or_else(|| "上传资源不存在或已失效".into()) + } + + pub fn delete_image_upload(&self, upload_id: &str) -> Result<(), String> { + let mut store = self.image_uploads.lock().map_err(|_| "image upload lock poisoned")?; + if store.delete(&self.config.account, upload_id, unix_ms_now()) { + Ok(()) + } else { + Err("上传资源不存在或已失效".into()) + } + } + pub fn submit_image( &self, kind: caligo_model::SessionKind, @@ -684,6 +720,131 @@ impl Daemon { Ok(request_id) } + /// Submit one ordered text/mention/reply message through the durable send + /// ledger. Reply targets were resolved from MessageStore action-side. + pub fn submit_rich( + &self, + kind: caligo_model::SessionKind, + peer_uin: &str, + segments: Vec, + deadline_ms: u64, + ) -> Result { + let group = kind == caligo_model::SessionKind::Group; + let chat_type = if group { 2 } else { 1 }; + if !positive_decimal(peer_uin) + || (!group && peer_uin == self.config.account) + || !(1..=30_000).contains(&deadline_ms) + || segments.is_empty() + || segments.len() > MAX_SEND_SEGMENTS + { + return Err("invalid rich request".into()); + } + let decimal = |value: &str| { + !value.is_empty() && value.len() <= 20 && value.bytes().all(|b| b.is_ascii_digit()) + }; + let mut text_bytes = 0usize; + let mut has_reply = false; + let mut has_mention = false; + for segment in &segments { + match segment { + SendSegment::Text { text } => text_bytes += text.len(), + SendSegment::Mention { qq, uid, name } => { + let resolved = !name.is_empty() + && if qq == "all" { + uid == "all" + } else { + uid.len() > 2 + && uid.starts_with("u_") + && uid[2..].bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + }; + if !group || !resolved || (qq != "all" && !positive_decimal(qq)) { + return Err("invalid or unresolved mention request".into()); + } + has_mention = true; + } + SendSegment::Reply { target } => { + if target.peer_chat_type != chat_type + || target.peer_uin != peer_uin + || !positive_decimal(&target.replay_msg_id) + || !positive_decimal(&target.replay_msg_seq) + || !positive_decimal(&target.sender_uin) + || target + .reply_msg_client_seq + .as_deref() + .is_some_and(|seq| !decimal(seq)) + || (chat_type == 1 && target.reply_msg_client_seq.is_none()) + { + return Err("invalid reply request".into()); + } + has_reply = true; + } + } + } + if text_bytes > MAX_RICH_TEXT_BYTES { + return Err("rich text exceeds limit".into()); + } + let mut actor = self.actor.lock().map_err(|_| "account actor lock poisoned")?; + let (Some(session), Some(connection)) = (actor.session(), actor.connection()) else { + return Err("no active QQ session".into()); + }; + let scope = QueryScope { + account: session.account.0.clone(), + host_nonce: session.host.host_nonce, + session_generation: session.session_generation, + connection_epoch: connection.connection_epoch, + }; + if (has_reply && !self.query_broker.supports_reply(&scope, chat_type)) + || (has_mention && !self.query_broker.supports_mention(&scope, chat_type)) + { + return Err("current bridge did not advertise this @/reply send".into()); + } + let sequence = self + .api_request_seq + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1)) + .map_err(|_| "request ID sequence exhausted")?; + let request_id = format!("rich-{:016x}-{sequence}", self.core_nonce); + let target = caligo_model::SessionKey::new(&scope.account, kind, peer_uin); + use sha2::{Digest, Sha256}; + let encoded = serde_json::to_vec(&segments).map_err(|_| "rich request encoding failed")?; + let digest = format!("rich:{:x}", Sha256::digest(&encoded)); + let payload_hash = SendTextRequest::compute_payload_hash( + scope.session_generation, + &target, + &digest, + deadline_ms, + ); + let request = SendTextRequest { + request_id: request_id.clone(), + session_identity: session.clone(), + target, + text: digest, + payload_hash, + deadline_ms, + }; + actor + .submit_send(request) + .map_err(|error| format!("rich request rejected: {error:?}"))?; + let wire_seq = actor + .dispatch_begin(&request_id) + .map_err(|error| format!("rich dispatch preparation failed: {error:?}"))?; + let timeout_ms = actor.remaining_timeout_ms(&request_id).unwrap_or_default(); + let dispatch = CoreToBridgeMsg::DispatchRich { + scope, + request_id: request_id.clone(), + wire_seq, + timeout_ms, + chat_type, + peer_uin: peer_uin.into(), + segments, + }; + self.dispatch_out + .lock() + .map_err(|_| "dispatch queue lock poisoned")? + .push(dispatch); + self.bridge_wake.store(true, Ordering::Relaxed); + Ok(request_id) + } + /// State for the same OneBot request, plus a durable public ID if its /// matching projected event has reached MessageStore. pub fn onebot_text_status( @@ -1075,6 +1236,38 @@ impl Daemon { } *timeout_ms = remaining; } + if let CoreToBridgeMsg::DispatchRich { + scope, + request_id, + timeout_ms, + chat_type, + segments, + .. + } = &mut m + { + if scope.connection_epoch == epoch { + let mut actor = self.actor.lock().unwrap(); + let remaining = actor.remaining_timeout_ms(request_id).unwrap_or_default(); + let has_reply = segments + .iter() + .any(|segment| matches!(segment, SendSegment::Reply { .. })); + let has_mention = segments + .iter() + .any(|segment| matches!(segment, SendSegment::Mention { .. })); + let supported = (!has_reply + || self.query_broker.supports_reply(scope, *chat_type)) + && (!has_mention + || self.query_broker.supports_mention(scope, *chat_type)); + if remaining == 0 || !supported { + let _ = actor.bridge_result(request_id, NativeResult::Failure { + reason: "@/reply expired or capability revoked before dispatch" + .into(), + }); + continue; + } + *timeout_ms = remaining; + } + } if let CoreToBridgeMsg::Query { request_id, scope, @@ -1118,6 +1311,9 @@ impl Daemon { group_voice, private_image, group_image, + private_reply, + group_reply, + group_mention, } => { // A wrong-scope advertisement is ignored and cannot grant authority. let _ = self.query_broker.advertise_send( @@ -1129,6 +1325,9 @@ impl Daemon { group_voice, private_image, group_image, + private_reply, + group_reply, + group_mention, ); } BridgeMsg::QueryResult { @@ -1589,6 +1788,10 @@ impl StoreReader for Daemon { .map(|a| a.group_peers()) .unwrap_or_default() } + + fn reply_reference(&self, message_id: i32) -> Option { + self.actor.lock().ok()?.reply_reference(message_id) + } } fn native_of_summary(actor: &AccountActor, id: &str) -> Option { diff --git a/crates/caligo-core/src/image_upload.rs b/crates/caligo-core/src/image_upload.rs new file mode 100644 index 00000000..49e4b3db --- /dev/null +++ b/crates/caligo-core/src/image_upload.rs @@ -0,0 +1,164 @@ +//! Bounded in-memory image upload resources. +//! +//! Upload and send are separate phases: this store owns the bytes and lifetime +//! metadata; `send_*_msg` may reference an upload id instead of inlining Base64. +//! Native QQ upload still happens inside the native send, so this is not a +//! claim that a QQ media id exists. + +use caligo_model::capability::{ + image_upload_id, positive_decimal, ImageUpload, IMAGE_UPLOAD_TTL_MS, MAX_IMAGE_UPLOADS, + MAX_IMAGE_UPLOAD_TOTAL_BYTES, +}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hash, Hasher}; +struct Entry { + png: Vec, + info: ImageUpload, +} + +#[derive(Default)] +pub struct ImageUploadStore { + entries: HashMap, + total_bytes: usize, + counter: u64, +} + +impl ImageUploadStore { + pub fn insert(&mut self, account: &str, png: Vec, now_ms: u64) -> Result { + if !positive_decimal(account) { + return Err("invalid upload account".into()); + } + let Some((width, height)) = caligo_model::png::dimensions(&png) else { + return Err("upload is not an ordinary PNG".into()); + }; + if png.len() < 33 || png.len() > caligo_model::png::MAX_SEND_BYTES { + return Err("upload exceeds the bounded PNG size".into()); + } + self.cleanup(now_ms); + if self.entries.len() >= MAX_IMAGE_UPLOADS + || self.total_bytes.saturating_add(png.len()) > MAX_IMAGE_UPLOAD_TOTAL_BYTES + { + return Err("image upload capacity exhausted".into()); + } + let sha256 = format!("{:x}", Sha256::digest(&png)); + let mut guard = 0u64; + let upload_id = loop { + guard = guard.checked_add(1).ok_or("upload id exhausted")?; + if guard > 1024 { + return Err("upload id exhausted".into()); + } + self.counter = self.counter.wrapping_add(1); + let mut hasher = RandomState::new().build_hasher(); + account.hash(&mut hasher); + sha256.hash(&mut hasher); + now_ms.hash(&mut hasher); + self.counter.hash(&mut hasher); + let id = format!("caligo-upload:{account}:{:016x}{:016x}", hasher.finish(), self.counter); + if image_upload_id(&id) && !self.entries.contains_key(&id) { + break id; + } + }; + let info = ImageUpload { + upload_id: upload_id.clone(), + size: png.len() as u32, + sha256, + width, + height, + created_at_unix_ms: now_ms, + expires_at_unix_ms: now_ms.saturating_add(IMAGE_UPLOAD_TTL_MS), + }; + self.total_bytes = self.total_bytes.saturating_add(png.len()); + self.entries.insert(upload_id, Entry { png, info: info.clone() }); + Ok(info) + } + + pub fn resolve(&mut self, account: &str, upload_id: &str, now_ms: u64) -> Option> { + self.cleanup(now_ms); + if !image_upload_id(upload_id) { + return None; + } + let entry = self.entries.get(upload_id)?; + if !upload_id.starts_with(&format!("caligo-upload:{account}:")) { + return None; + } + Some(entry.png.clone()) + } + + pub fn delete(&mut self, account: &str, upload_id: &str, now_ms: u64) -> bool { + self.cleanup(now_ms); + if !upload_id.starts_with(&format!("caligo-upload:{account}:")) { + return false; + } + self.entries.remove(upload_id).is_some_and(|entry| { + self.total_bytes = self.total_bytes.saturating_sub(entry.png.len()); + true + }) + } + + fn cleanup(&mut self, now_ms: u64) { + let expired = self + .entries + .iter() + .filter(|(_, entry)| entry.info.expires_at_unix_ms <= now_ms) + .map(|(id, _)| id.clone()) + .collect::>(); + for id in expired { + if let Some(entry) = self.entries.remove(&id) { + self.total_bytes = self.total_bytes.saturating_sub(entry.png.len()); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PNG: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, + 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, + 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, + 0x9c, 0x63, 0x10, 0x54, 0x32, 0xfe, 0x0f, 0x00, 0x02, 0x14, 0x01, 0x66, 0x04, 0xe0, + 0xde, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + + #[test] + fn upload_lifetime_is_bounded_and_account_scoped() { + let mut store = ImageUploadStore::default(); + let info = store.insert("10001", PNG.to_vec(), 1_000).unwrap(); + assert_eq!(info.width, 1); + assert_eq!(info.height, 1); + assert_eq!(info.size, PNG.len() as u32); + assert_eq!(info.expires_at_unix_ms, 1_000 + IMAGE_UPLOAD_TTL_MS); + assert_eq!(store.resolve("10001", &info.upload_id, 1_001).unwrap(), PNG); + assert!(store.resolve("20002", &info.upload_id, 1_001).is_none()); + assert!(store.delete("10001", &info.upload_id, 1_002)); + assert!(!store.delete("10001", &info.upload_id, 1_002)); + assert!(store.resolve("10001", &info.upload_id, 1_002).is_none()); + + let expired = store.insert("10001", PNG.to_vec(), 2_000).unwrap(); + assert!(store.resolve("10001", &expired.upload_id, expired.expires_at_unix_ms).is_none()); + assert!(!store.delete("10001", &expired.upload_id, expired.expires_at_unix_ms)); + } + + #[test] + fn upload_capacity_rejects_the_ninth_entry() { + let mut store = ImageUploadStore::default(); + for _ in 0..MAX_IMAGE_UPLOADS { + store.insert("10001", PNG.to_vec(), 1_000).unwrap(); + } + assert!(store.insert("10001", PNG.to_vec(), 1_001).is_err()); + } + + #[test] + fn upload_rejects_non_png_and_wrong_account() { + let mut store = ImageUploadStore::default(); + assert!(store.insert("10001", b"not-png".to_vec(), 1_000).is_err()); + assert!(store.insert("not-an-account", PNG.to_vec(), 1_000).is_err()); + let info = store.insert("10001", PNG.to_vec(), 1_000).unwrap(); + assert!(store.resolve("10001", "caligo-upload:10001:deadbeef", 1_000).is_none()); + assert!(store.delete("10001", &info.upload_id, 1_000)); + } +} diff --git a/crates/caligo-core/src/lib.rs b/crates/caligo-core/src/lib.rs index 63fcead1..ca612f49 100644 --- a/crates/caligo-core/src/lib.rs +++ b/crates/caligo-core/src/lib.rs @@ -10,6 +10,7 @@ pub mod account_manager; pub mod capability_broker; pub mod commands; pub mod daemon; +pub mod image_upload; pub mod ipc; pub mod journal; pub mod management_http; diff --git a/crates/caligo-core/src/media_tool.rs b/crates/caligo-core/src/media_tool.rs index 4929109f..aeed086b 100644 --- a/crates/caligo-core/src/media_tool.rs +++ b/crates/caligo-core/src/media_tool.rs @@ -137,6 +137,7 @@ pub enum ToolRole { Ffmpeg, Ffprobe, SilkDecoder, + SilkEncoder, } impl ToolRole { fn as_str(self) -> &'static str { @@ -144,6 +145,7 @@ impl ToolRole { Self::Ffmpeg => "ffmpeg", Self::Ffprobe => "ffprobe", Self::SilkDecoder => "silk decoder", + Self::SilkEncoder => "silk encoder", } } } @@ -154,6 +156,8 @@ pub struct MediaToolConfig { pub ffprobe: ToolDeclaration, #[serde(default)] pub silk_decoder: Option, + #[serde(default)] + pub silk_encoder: Option, pub work_root: PathBuf, #[serde(default = "default_timeout_ms")] pub timeout_ms: u64, @@ -188,6 +192,9 @@ impl MediaToolConfig { if let Some(decoder) = &self.silk_decoder { decoder.validate_metadata(ToolRole::SilkDecoder)?; } + if let Some(encoder) = &self.silk_encoder { + encoder.validate_metadata(ToolRole::SilkEncoder)?; + } Ok(()) } pub fn verify_tools(&self) -> Result<(), MediaError> { @@ -197,6 +204,9 @@ impl MediaToolConfig { if let Some(decoder) = &self.silk_decoder { decoder.verify(ToolRole::SilkDecoder)?; } + if let Some(encoder) = &self.silk_encoder { + encoder.verify(ToolRole::SilkEncoder)?; + } Ok(()) } } @@ -533,6 +543,16 @@ impl MediaTool { config.max_stdout_stderr_bytes, )?; } + if let Some(encoder) = &config.silk_encoder { + verify_runtime_version( + encoder, + ToolRole::SilkEncoder, + &runner, + &config.work_root, + config.timeout_ms, + config.max_stdout_stderr_bytes, + )?; + } Ok(Self { config, runner }) } #[doc(hidden)] @@ -631,6 +651,53 @@ impl MediaTool { }) } + /// Encode one local WAV/Ogg/PCM audio file as Tencent SILK v3. + pub fn container_file_to_silk( + &self, + input: &Path, + stop: &StopToken, + ) -> Result { + if stop.is_stopped() { + return Err(MediaError::Stopped); + } + let pcm = self.audio_to_pcm(input, stop)?; + if pcm.bytes.is_empty() || pcm.bytes.len() % 2 != 0 { + return Err(MediaError::InvalidInput( + "PCM must be non-empty and contain complete s16le samples".into(), + )); + } + let encoder = self.config.silk_encoder.as_ref().ok_or_else(|| { + MediaError::ToolUnavailable("SILK encoder is not configured".into()) + })?; + encoder.verify(ToolRole::SilkEncoder)?; + let job = JobDirectory::new(&self.config.work_root)?; + let pcm_path = job.path.join("input.pcm"); + let output = job.path.join("output.silk"); + write_private_file(&pcm_path, &pcm.bytes)?; + let args = [ + "encode".into(), + "-i".into(), + pcm_path.into_os_string(), + "--sample-rate".into(), + "24000".into(), + "--tencent".into(), + "-o".into(), + output.clone().into_os_string(), + ]; + self.run(ToolRole::SilkEncoder, &args, &job.path, stop)?; + let bytes = read_bounded(&output, self.config.max_output_bytes)?; + let header = bytes.strip_prefix(b"\x02").unwrap_or(&bytes); + if !header.starts_with(b"#!SILK_V3") || header.len() <= 11 { + return Err(MediaError::InvalidOutput( + "encoder did not return SILK v3 packet data".into(), + )); + } + Ok(MediaArtifact { + format: "silk", + bytes, + }) + } + /// Decode one local SILK v3 file and wrap the mono 24 kHz PCM as WAV or Ogg. pub fn silk_file_to_container( &self, @@ -861,6 +928,9 @@ impl MediaTool { ToolRole::SilkDecoder => self.config.silk_decoder.as_ref().ok_or_else(|| { MediaError::ToolUnavailable("SILK decoder is not configured".into()) })?, + ToolRole::SilkEncoder => self.config.silk_encoder.as_ref().ok_or_else(|| { + MediaError::ToolUnavailable("SILK encoder is not configured".into()) + })?, }; let result = self.runner.run( &declaration.executable, @@ -893,7 +963,7 @@ fn verify_runtime_version( let result = runner.run( &declaration.executable, &[OsString::from(match role { - ToolRole::SilkDecoder => "--version", + ToolRole::SilkDecoder | ToolRole::SilkEncoder => "--version", _ => "-version", })], &job.path, diff --git a/crates/caligo-core/src/message_store.rs b/crates/caligo-core/src/message_store.rs index 00bf47fa..94d77ba6 100644 --- a/crates/caligo-core/src/message_store.rs +++ b/crates/caligo-core/src/message_store.rs @@ -19,6 +19,91 @@ pub enum ChatType { Private, } +/// OneBot segments from an admitted wrapper message. The mention display text +/// is not repeated after the `at` segment when it starts with `@`; any text +/// after the first whitespace is retained. A reply ID is mapped to the local +/// OneBot message ID when that native message is already persisted in the same +/// conversation; otherwise the native replay ID is kept truthful. +fn wrapper_segments_value( + store: &MessageStore, + segments: &[caligo_model::wrapper_message::WrapperSegment], + chat_type: &ChatType, + peer_id: &str, +) -> Value { + use caligo_model::wrapper_message::WrapperSegment; + let mut out = Vec::new(); + for segment in segments { + match segment { + WrapperSegment::Text { content, mention: None } => { + if !content.is_empty() { + out.push(serde_json::json!({"type":"text","data":{"text":content}})); + } + } + WrapperSegment::Text { content, mention: Some(mention) } => { + out.push(serde_json::json!({"type":"at","data":{"qq":mention.at_uid}})); + let rest = mention_remainder(content); + if !rest.is_empty() { + out.push(serde_json::json!({"type":"text","data":{"text":rest}})); + } + } + WrapperSegment::Reply { replay_msg_id, .. } => { + let identity = MessageIdentity { + account_id: store.account_id, + chat_type: chat_type.clone(), + peer_id: peer_id.to_owned(), + native_id: replay_msg_id.clone(), + }; + let id = match store.by_identity.get(&identity) { + Some(local) => Value::from(*local), + None => Value::String(replay_msg_id.clone()), + }; + out.push(serde_json::json!({"type":"reply","data":{"id":id}})); + } + } + } + Value::Array(out) +} + +pub(crate) fn mention_remainder(content: &str) -> &str { + let Some(rest) = content.strip_prefix('@') else { + return content; + }; + match rest.char_indices().find(|(_, value)| value.is_whitespace()) { + Some((index, _)) => &rest[index..], + None => "", + } +} + +fn reply_reference_valid(reference: &caligo_model::onebot_traits::ReplyReference) -> bool { + let positive = |value: &str| { + !value.is_empty() + && value.len() <= 128 + && !value.starts_with('0') + && value.bytes().all(|b| b.is_ascii_digit()) + }; + let decimal = |value: &str| { + !value.is_empty() && value.len() <= 20 && value.bytes().all(|b| b.is_ascii_digit()) + }; + positive(&reference.replay_msg_id) + && positive(&reference.replay_msg_seq) + && positive(&reference.sender_uin) + && positive(&reference.peer_uin) + && reference + .reply_msg_client_seq + .as_deref() + .is_none_or(decimal) + && (reference.peer_chat_type != 1 || reference.reply_msg_client_seq.is_some()) + && match reference.peer_chat_type { + 1 => reference.peer_uid.len() > 2 + && reference.peer_uid.starts_with("u_") + && reference.peer_uid[2..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'), + 2 => positive(&reference.peer_uid), + _ => false, + } +} + #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct MessageIdentity { pub account_id: u64, @@ -38,6 +123,13 @@ pub struct StoredMessage { pub time: i32, #[serde(default)] pub native_seq: Option, + /// Native client sequence observed on the wrapper record. Private replies + /// use it; group replies treat zero/absent as a group quote. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_client_seq: Option, + /// Native peer UID (`u_...` for private) for the reply target peer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native_peer_uid: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub voice: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -185,6 +277,8 @@ impl MessageStore { message, time, native_seq, + native_client_seq: None, + native_peer_uid: None, voice: None, image: None, }) @@ -323,10 +417,16 @@ impl MessageStore { }; let voice = envelope.voice(); let image = envelope.image(); - let text = if voice.is_some() || image.is_some() { - String::new() + let rich = voice.is_none() && image.is_none(); + let segments = if rich { + envelope.segments().map_err(|_| "wrapper segments are invalid")? } else { - envelope.text().map_err(|_| "wrapper text is invalid")? + Vec::new() + }; + let text = if rich { + envelope.plain_text().map_err(|_| "wrapper text is invalid")? + } else { + String::new() }; if account_id == 0 || account_id != self.account_id @@ -354,13 +454,27 @@ impl MessageStore { } let identity = MessageIdentity { account_id, - chat_type: expected_kind, + chat_type: expected_kind.clone(), peer_id: peer_id.to_string(), native_id: record.msg_id.clone(), }; + let native_seq = record.msg_seq.parse::().ok(); + let native_client_seq = record.client_seq.clone().filter(|seq| !seq.is_empty()); + let native_peer_uid = Some(record.peer_uid.clone()); let mut sender = serde_json::Map::new(); sender.insert("user_id".into(), Value::from(sender_id)); - let body = Value::String(text); + let rich_body = segments.iter().any(|segment| { + matches!( + segment, + caligo_model::wrapper_message::WrapperSegment::Reply { .. } + | caligo_model::wrapper_message::WrapperSegment::Text { mention: Some(_), .. } + ) + }); + let body = if rich_body { + wrapper_segments_value(self, &segments, &expected_kind, &peer_id.to_string()) + } else { + Value::String(text) + }; let time = i32::try_from(platform_time).map_err(|_| "OneBot message time exceeds int32")?; if event.source == EventSource::Update { @@ -379,6 +493,9 @@ impl MessageStore { revised.sender = Value::Object(sender); revised.message = body; revised.time = time; + revised.native_seq = native_seq; + revised.native_client_seq = native_client_seq.clone(); + revised.native_peer_uid = native_peer_uid.clone(); if self.by_id.get(&id) != Some(&revised) { self.append_entry(2, &revised)?; self.by_id.insert(id, revised); @@ -396,7 +513,9 @@ impl MessageStore { sender: Value::Object(sender), message: serde_json::json!([{"type":"record","data":{"file":token}}]), time, - native_seq: None, + native_seq, + native_client_seq, + native_peer_uid, image: None, voice: Some(VoiceInfo { peer_uid: record.peer_uid.clone(), @@ -411,12 +530,31 @@ impl MessageStore { let token = caligo_model::onebot_traits::image_file_token(account_id, id); return self.insert_message(StoredMessage { message_id:id, identity, real_id:id, sender:Value::Object(sender), - message:serde_json::json!([{"type":"image","data":{"file":token}}]), - time, native_seq:None, voice:None, image:Some(image.clone()), + message:{ + let mut data=serde_json::json!({"file":token}); + if let Some(media_id)=image.file_uuid.as_ref() { + data["file_id"]=serde_json::json!(media_id); + } + serde_json::json!([{"type":"image","data":data}]) + }, + time, native_seq, native_client_seq, native_peer_uid, + voice:None, image:Some(image.clone()), }).map(Some); } - self.insert_confirmed(identity, id, Value::Object(sender), body, time, None) - .map(Some) + self.insert_message(StoredMessage { + message_id: id, + identity, + real_id: id, + sender: Value::Object(sender), + message: body, + time, + native_seq, + native_client_seq, + native_peer_uid, + voice: None, + image: None, + }) + .map(Some) } fn append_entry(&self, version: u32, message: &StoredMessage) -> Result<(), String> { @@ -477,7 +615,7 @@ impl MessageStore { || event.sender != envelope.record.sender_uin || event.native_id.0 != envelope.record.msg_id || if voice.is_some() || image.is_some() { !event.text.is_empty() } - else { event.text != envelope.text().ok()? } + else { event.text != envelope.plain_text().ok()? } || event.platform_time != Some(envelope.record.msg_time.parse::().ok()?) { return None; @@ -576,6 +714,30 @@ impl StoreReader for MessageStore { set.into_iter().collect() } + fn reply_reference(&self, message_id: i32) -> Option { + let message = self.by_id.get(&message_id)?; + let replay_msg_seq = message.native_seq?.to_string(); + let sender_uin = message.sender.get("user_id")?.as_u64()?.to_string(); + let peer_uid = message.native_peer_uid.clone()?; + let peer_chat_type = match message.identity.chat_type { + ChatType::Private => 1, + ChatType::Group => 2, + }; + if message.identity.native_id.is_empty() { + return None; + } + let reference = caligo_model::onebot_traits::ReplyReference { + replay_msg_id: message.identity.native_id.clone(), + replay_msg_seq, + sender_uin, + reply_msg_client_seq: message.native_client_seq.clone(), + peer_chat_type, + peer_uid, + peer_uin: message.identity.peer_id.clone(), + }; + reply_reference_valid(&reference).then_some(reference) + } + fn get_msg(&self, message_id: i32) -> Option { let m = self.by_id.get(&message_id)?; Some(StoredMessageView { @@ -728,6 +890,7 @@ mod tests { element_type: 1, voice: None, image: None, + reply: None, text_element: Some(caligo_model::wrapper_message::WrapperText { content: text.into(), at_type: 0, at_uid: String::new(), at_nt_uid: String::new(), at_tiny_id: String::new(), @@ -788,6 +951,225 @@ mod tests { let _ = std::fs::remove_file(path); } + #[test] + fn wrapper_mention_and_reply_render_as_onebot_segments() { + use caligo_model::wrapper_message::{ + WrapperBinding, WrapperElement, WrapperMessage, WrapperMessageEnvelope, WrapperReply, + WrapperSource, WrapperText, + }; + let mut store = MessageStore::in_memory(10001, None, None, 1); + let text = |content: &str, at_type: u32, at_uid: &str| WrapperText { + content: content.into(), + at_type, + at_uid: at_uid.into(), + at_nt_uid: if at_type == 0 { String::new() } else { "u_member".into() }, + at_tiny_id: if at_type == 0 { String::new() } else { "20002".into() }, + }; + let elements = vec![ + WrapperElement { + element_type: 7, + text_element: None, + voice: None, + image: None, + reply: Some(WrapperReply { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + source_msg_text: String::new(), + }), + }, + WrapperElement { + element_type: 1, + text_element: Some(text("@Bot hi", 2, "20002")), + voice: None, + image: None, + reply: None, + }, + WrapperElement { + element_type: 1, + text_element: Some(text(" tail", 0, "")), + voice: None, + image: None, + reply: None, + }, + ]; + let envelope = WrapperMessageEnvelope { + binding: WrapperBinding { + account: "10001".into(), + session_generation: 1, + host_nonce: 9, + wrapper_session: "nt_fixture".into(), + }, + wrapper_session: "nt_fixture".into(), + source: WrapperSource::Recv, + observed_at_unix_ms: 10, + record: WrapperMessage { + msg_id: "9007199254740994".into(), + msg_seq: "8".into(), + msg_random: "9".into(), + msg_time: "1794567891".into(), + client_seq: None, + guild_id: String::new(), + chat_type: 2, + msg_type: 2, + sub_msg_type: 0, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + sender_uid: "u_member".into(), + sender_uin: "20002".into(), + send_status: None, + elements, + }, + }; + let event = MsgEvent { + event_seq: 0, + session_generation: 1, + session: caligo_model::SessionKey::new("10001", SessionKind::Group, "30003"), + direction: caligo_model::Direction::Incoming, + sender: "20002".into(), + native_id: caligo_model::NativeMessageId("9007199254740994".into()), + text: envelope.plain_text().unwrap(), + platform_time: Some(1_794_567_891), + wrapper_message: Some(envelope), + onebot_projection: None, + observed_at_unix_ms: 10, + source: EventSource::Recv, + }; + let id = store.insert_event(&event).unwrap().unwrap(); + assert_eq!(store.get(id).unwrap().message, serde_json::json!([ + {"type":"reply","data":{"id":"9007199254740993"}}, + {"type":"at","data":{"qq":"20002"}}, + {"type":"text","data":{"text":" hi"}}, + {"type":"text","data":{"text":" tail"}} + ])); + assert_eq!(store.projection_for_event(&event).unwrap().real_id, id); + let view = store.get_msg(id).unwrap(); + assert_eq!(view.message, store.get(id).unwrap().message); + } + + #[test] + fn reply_id_maps_to_local_message_id_and_resolves_native_reference() { + use caligo_model::wrapper_message::{ + WrapperBinding, WrapperElement, WrapperMessage, WrapperMessageEnvelope, WrapperReply, + WrapperSource, WrapperText, + }; + let mut store = MessageStore::in_memory(10001, None, None, 1); + let binding = WrapperBinding { + account: "10001".into(), + session_generation: 1, + host_nonce: 9, + wrapper_session: "nt_fixture".into(), + }; + let text = |content: &str| WrapperText { + content: content.into(), + at_type: 0, + at_uid: String::new(), + at_nt_uid: String::new(), + at_tiny_id: String::new(), + }; + let event = |native_id: &str, seq: &str, client_seq: Option<&str>, elements: Vec, text_body: &str| { + let envelope = WrapperMessageEnvelope { + binding: binding.clone(), + wrapper_session: "nt_fixture".into(), + source: WrapperSource::Recv, + observed_at_unix_ms: 10, + record: WrapperMessage { + msg_id: native_id.into(), + msg_seq: seq.into(), + msg_random: "9".into(), + msg_time: "1794567891".into(), + client_seq: client_seq.map(str::to_owned), + guild_id: String::new(), + chat_type: 2, + msg_type: 2, + sub_msg_type: 0, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + sender_uid: "u_member".into(), + sender_uin: "20002".into(), + send_status: None, + elements, + }, + }; + MsgEvent { + event_seq: 0, + session_generation: 1, + session: caligo_model::SessionKey::new("10001", SessionKind::Group, "30003"), + direction: caligo_model::Direction::Incoming, + sender: "20002".into(), + native_id: caligo_model::NativeMessageId(native_id.into()), + text: text_body.into(), + platform_time: Some(1_794_567_891), + wrapper_message: Some(envelope), + onebot_projection: None, + observed_at_unix_ms: 10, + source: EventSource::Recv, + } + }; + let target_id = store + .insert_event(&event( + "9007199254740993", + "7", + Some("0"), + vec![WrapperElement { + element_type: 1, + text_element: Some(text("target")), + voice: None, + image: None, + reply: None, + }], + "target", + )) + .unwrap() + .unwrap(); + assert_eq!(target_id, 1); + let reference = store.reply_reference(target_id).unwrap(); + assert_eq!(reference.replay_msg_id, "9007199254740993"); + assert_eq!(reference.replay_msg_seq, "7"); + assert_eq!(reference.sender_uin, "20002"); + assert_eq!(reference.reply_msg_client_seq.as_deref(), Some("0")); + assert_eq!(reference.peer_chat_type, 2); + assert_eq!(reference.peer_uid, "30003"); + assert_eq!(reference.peer_uin, "30003"); + + let reply_id = store + .insert_event(&event( + "9007199254740994", + "8", + None, + vec![ + WrapperElement { + element_type: 7, + text_element: None, + voice: None, + image: None, + reply: Some(WrapperReply { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + source_msg_text: String::new(), + }), + }, + WrapperElement { + element_type: 1, + text_element: Some(text("quoted")), + voice: None, + image: None, + reply: None, + }, + ], + "quoted", + )) + .unwrap() + .unwrap(); + assert_eq!(reply_id, 2); + assert_eq!( + store.get(reply_id).unwrap().message, + serde_json::json!([ + {"type":"reply","data":{"id":1}}, + {"type":"text","data":{"text":"quoted"}} + ]) + ); + } + #[test] fn identity_includes_account_chat_type_peer_and_native_id_not_sequence() { let mut store = MessageStore::in_memory(100, None, None, 1); diff --git a/crates/caligo-core/src/onebot.rs b/crates/caligo-core/src/onebot.rs index 9dd376f4..b936b998 100644 --- a/crates/caligo-core/src/onebot.rs +++ b/crates/caligo-core/src/onebot.rs @@ -5,7 +5,8 @@ use crate::media_tool::{ContainerFormat, MediaError, MediaTool, StopToken, MAX_R use base64::{engine::general_purpose::STANDARD, Engine}; use caligo_model::capability::{positive_decimal, GroupInfo, HostQuery, QueryData, QueryOutcome, VoiceDownload, VoiceInfo, MAX_VOICE_DOWNLOAD_BYTES}; use caligo_model::onebot_traits::{ - extract_text, SendDisposition, SendPayload, SendSink, SendTarget, + SendDisposition, SendPayload, SendSegment, SendSink, SendTarget, MAX_RICH_TEXT_BYTES, + MAX_SEND_SEGMENTS, }; pub use caligo_model::onebot_traits::{StoreReader, StoredMessageView}; use serde::{Deserialize, Serialize}; @@ -108,6 +109,8 @@ pub enum ActionHandlerKind { GetMessage, GetRecord, GetImage, + UploadImage, + DeleteImageUpload, GetLoginInfo, GetFriendList, GetGroupList, @@ -129,6 +132,8 @@ pub enum ActionInputSchema { MessageId, Record, Image, + ImageUpload, + ImageUploadId, GroupInfo, GroupMemberList, GroupMemberInfo, @@ -152,7 +157,14 @@ impl ActionInputSchema { ] }); if matches!(self, Self::GroupMessage | Self::PrivateMessage | Self::Message) { - message["description"] = Value::from("Literal text, text segments, one Tencent SILK v3 record, or one ordinary PNG image in Base64"); + message["description"] = Value::from("Literal text, text segments, one mention/reply segment set, one Tencent SILK v3 record, or one ordinary PNG image in Base64"); + message["anyOf"].as_array_mut().unwrap().push(serde_json::json!({ + "type":"array", "minItems":1, "maxItems":64, "items":{ + "type":"object", "required":["type","data"], + "properties":{"type":{"enum":["at","reply"]}, + "data":{"type":"object"}} + } + })); message["anyOf"].as_array_mut().unwrap().push(serde_json::json!({ "type":"array", "minItems":1, "maxItems":1, "items":{ "type":"object", "required":["type","data"], @@ -165,7 +177,7 @@ impl ActionInputSchema { })); } if matches!(self, Self::GroupMessage | Self::PrivateMessage | Self::Message) { - let mut image = message["anyOf"][2].clone(); + let mut image = message["anyOf"][3].clone(); image["items"]["properties"]["type"]["const"] = Value::from("image"); image["items"]["properties"]["data"]["properties"]["file"]["maxLength"] = Value::from(9 + 4*caligo_model::png::MAX_SEND_BYTES.div_ceil(3)); @@ -228,11 +240,26 @@ impl ActionInputSchema { } Self::Image => { schema["properties"] = serde_json::json!({ - "file":{"type":"string","maxLength":64,"description":"Caligo image file token"}, - "file_id":{"type":"string","maxLength":64,"description":"Alternate Caligo image file token"} + "file":{"type":"string","maxLength":128,"description":"Caligo image file token or caligo-upload id"}, + "file_id":{"type":"string","maxLength":128,"description":"Alternate Caligo image file token or caligo-upload id"} }); schema["oneOf"] = serde_json::json!([{"required":["file"]},{"required":["file_id"]}]); } + Self::ImageUpload => { + schema["properties"] = serde_json::json!({ + "file":{"type":"string", "pattern":"^base64://", + "maxLength":9 + 4*caligo_model::png::MAX_SEND_BYTES.div_ceil(3), + "description":"Bounded ordinary PNG in Base64; upload is separate from send"} + }); + schema["required"] = serde_json::json!(["file"]); + } + Self::ImageUploadId => { + schema["properties"] = serde_json::json!({ + "upload_id":{"type":"string","maxLength":128,"pattern":"^caligo-upload:", + "description":"Caligo upload resource id"} + }); + schema["required"] = serde_json::json!(["upload_id"]); + } } schema } @@ -343,6 +370,20 @@ pub static ACTION_REGISTRY: &[ActionDefinition] = &[ name: "get_image", canonical: "get_image", permission: ActionPermission::Read, handler: ActionHandlerKind::GetImage, input_schema: ActionInputSchema::Image, }, + ActionDefinition { + name: "upload_image", + canonical: "upload_image", + permission: ActionPermission::Write, + handler: ActionHandlerKind::UploadImage, + input_schema: ActionInputSchema::ImageUpload, + }, + ActionDefinition { + name: "delete_image_upload", + canonical: "delete_image_upload", + permission: ActionPermission::Write, + handler: ActionHandlerKind::DeleteImageUpload, + input_schema: ActionInputSchema::ImageUploadId, + }, ActionDefinition { name: "get_friend_list", canonical: "get_friend_list", @@ -405,16 +446,126 @@ fn get_u64(params: &Value, key: &str) -> Result { .ok_or_else(|| ActionResponse::failed(RET_BAD_PARAMS, &format!("{key} 必填"), Value::Null)) } -fn get_message_text(params: &Value) -> Result { - match params.get("message").map(extract_text) { - Some(Ok(t)) => Ok(t), - Some(Err(e)) => Err(ActionResponse::failed(RET_BAD_PARAMS, &e, Value::Null)), - None => Err(ActionResponse::failed( - RET_BAD_PARAMS, - "message 必填", - Value::Null, - )), +enum ParsedSend { + Plain(String), + Rich(Vec), +} + +/// Parse text/at/reply into either the legacy plain-text path or the ordered +/// rich path. Media is handled by the caller. Unknown or inapplicable segments +/// fail explicitly instead of being silently dropped. +fn parse_send( + params: &Value, + target: &SendTarget, + store: &dyn StoreReader, +) -> Result { + let message = params + .get("message") + .ok_or((RET_BAD_PARAMS, "message 必填".to_string()))?; + if let Value::String(text) = message { + return Ok(ParsedSend::Plain(text.clone())); + } + let items = message + .as_array() + .ok_or((RET_BAD_PARAMS, "message 须为字符串或段数组".to_string()))?; + if items.is_empty() { + return Err((RET_BAD_PARAMS, "message 为空".to_string())); + } + if items.len() > MAX_SEND_SEGMENTS { + return Err((RET_BAD_PARAMS, "message 段数超过上限".to_string())); + } + let mut plain = String::new(); + let mut segments = Vec::new(); + let mut rich_mode = false; + let mut text_bytes = 0usize; + for item in items { + let ty = item + .get("type") + .and_then(Value::as_str) + .ok_or((RET_BAD_PARAMS, "message 段缺少 type".to_string()))?; + let data = item + .get("data") + .ok_or((RET_BAD_PARAMS, "message 段缺少 data".to_string()))?; + match ty { + "text" => { + let text = data + .get("text") + .and_then(Value::as_str) + .ok_or((RET_BAD_PARAMS, "text.data.text 必须是字符串".to_string()))?; + text_bytes += text.len(); + if text_bytes > MAX_RICH_TEXT_BYTES { + return Err((RET_BAD_PARAMS, "message 文本超过上限".to_string())); + } + plain.push_str(text); + if !text.is_empty() { + segments.push(SendSegment::Text { text: text.to_string() }); + } + } + "at" => { + if matches!(target, SendTarget::Private { .. }) { + return Err((RET_UNSUPPORTED, "@ 段仅支持群聊".to_string())); + } + let qq = match data.get("qq") { + Some(Value::String(value)) => value.clone(), + Some(Value::Number(value)) => value.to_string(), + _ => return Err((RET_BAD_PARAMS, "at.data.qq 必须是字符串或整数".to_string())), + }; + if qq != "all" && !positive_decimal(&qq) { + return Err((RET_BAD_PARAMS, "at.data.qq 必须是 all 或正整数".to_string())); + } + rich_mode = true; + segments.push(SendSegment::Mention { qq, uid: String::new(), name: String::new() }); + } + "reply" => { + let id = match data.get("id") { + Some(Value::Number(value)) => value.as_i64(), + Some(Value::String(value)) => value.parse::().ok(), + _ => None, + } + .and_then(|value| i32::try_from(value).ok()) + .ok_or((RET_BAD_PARAMS, "reply.data.id 必须是 int32 消息 ID".to_string()))?; + let reference = store.reply_reference(id).ok_or(( + RET_BAD_PARAMS, + "回复目标不存在或缺少原生身份,禁止编造引用".to_string(), + ))?; + let same_chat = match target { + SendTarget::Group { group_id } => { + reference.peer_chat_type == 2 && reference.peer_uin == group_id.to_string() + } + SendTarget::Private { user_id } => { + reference.peer_chat_type == 1 && reference.peer_uin == user_id.to_string() + } + }; + if !same_chat { + return Err((RET_BAD_PARAMS, "回复目标不属于当前会话".to_string())); + } + rich_mode = true; + segments.push(SendSegment::Reply { target: reference }); + } + "image" | "record" => { + return Err(( + RET_BAD_PARAMS, + "媒体段必须单独发送,不能与文本或其它段混用".to_string(), + )) + } + other => { + return Err(( + RET_UNSUPPORTED, + format!("未支持消息段 {other}(显式拒绝不静默)"), + )) + } + } + } + if !rich_mode { + if plain.is_empty() { + return Err((RET_BAD_PARAMS, "message 为空".to_string())); + } + return Ok(ParsedSend::Plain(plain)); + } + if segments.is_empty() { + return Err((RET_BAD_PARAMS, "message 为空".to_string())); } + Ok(ParsedSend::Rich(segments)) } fn dispatch_send( @@ -444,10 +595,67 @@ fn dispatch_send( } } +fn resolve_mentions( + segments: &mut [SendSegment], + target: &SendTarget, + queries: &dyn QueryBackend, +) -> Result<(), (i32, String)> { + let SendTarget::Group { group_id } = target else { + return Ok(()); + }; + for segment in segments { + let SendSegment::Mention { qq, uid, name } = segment else { + continue; + }; + if qq == "all" { + *uid = "all".into(); + *name = "全体成员".into(); + continue; + } + let outcome = queries.query_host( + HostQuery::GroupMemberUid { + group_id: group_id.to_string(), + user_id: qq.clone(), + }, + QUERY_TIMEOUT, + ); + match outcome { + QueryOutcome::Success(QueryData::GroupMemberUid(info)) + if info.group_id == group_id.to_string() + && info.user_id == *qq + && info.uid.len() > 2 + && info.uid.starts_with("u_") => + { + *uid = info.uid; + *name = if info.name.is_empty() { qq.clone() } else { info.name }; + } + QueryOutcome::Unsupported => { + return Err((RET_UNSUPPORTED, "宿主未支持群成员 UID 查询,@ 不可用".into())) + } + QueryOutcome::NotReady | QueryOutcome::Timeout | QueryOutcome::Disconnected => { + return Err((RET_NOT_READY, "群成员 UID 查询未完成".into())) + } + QueryOutcome::PermissionDenied => { + return Err((RET_PERMISSION_DENIED, "宿主拒绝群成员 UID 查询".into())) + } + QueryOutcome::Rejected { code, reason } => { + return Err(( + RET_BAD_REQUEST, + format!("群成员 UID 查询被拒绝 (code={code}): {reason}"), + )) + } + _ => return Err((RET_BAD_REQUEST, "群成员 UID 响应不符合合同".into())), + } + } + Ok(()) +} + fn send_payload( target_kind: SendTargetKind, params: &Value, sink: &mut dyn SendSink, + store: &dyn StoreReader, + queries: &dyn QueryBackend, echo: Value, allow_async: bool, ) -> ActionResponse { @@ -511,14 +719,27 @@ fn send_payload( }; if let Some([item]) = params.get("message").and_then(Value::as_array).map(Vec::as_slice) { if item.get("type").and_then(Value::as_str) == Some("image") { - let Some(png)=item.get("data").and_then(|data|data.get("file")).and_then(Value::as_str) - .and_then(|file|file.strip_prefix("base64://")) - .filter(|encoded|encoded.len() <= 4*caligo_model::png::MAX_SEND_BYTES.div_ceil(3)) - .and_then(|encoded|STANDARD.decode(encoded).ok()) - .filter(|bytes|caligo_model::png::dimensions(bytes).is_some()) else { - return ActionResponse::failed(RET_BAD_PARAMS,"图片 file 须为有界普通 PNG Base64",echo); + let Some(file) = item.get("data").and_then(|data| data.get("file")).and_then(Value::as_str) else { + return ActionResponse::failed(RET_BAD_PARAMS, "图片 file 须为 base64:// 或 caligo-upload 标识", echo); }; - return dispatch_send(echo,sink.send_image(target,png),allow_async); + if let Some(encoded) = file.strip_prefix("base64://") { + let Some(png) = Some(encoded) + .filter(|encoded| encoded.len() <= 4 * caligo_model::png::MAX_SEND_BYTES.div_ceil(3)) + .and_then(|encoded| STANDARD.decode(encoded).ok()) + .filter(|bytes| caligo_model::png::dimensions(bytes).is_some()) + else { + return ActionResponse::failed(RET_BAD_PARAMS, "图片 file 须为有界普通 PNG Base64", echo); + }; + return dispatch_send(echo, sink.send_image(target, png), allow_async); + } + if caligo_model::capability::image_upload_id(file) { + let png = match sink.resolve_image_upload(file) { + Ok(png) => png, + Err(reason) => return ActionResponse::failed(RET_UNSUPPORTED, &reason, echo), + }; + return dispatch_send(echo, sink.send_image(target, png), allow_async); + } + return ActionResponse::failed(RET_BAD_PARAMS, "图片 file 须为 base64:// 或 caligo-upload 标识", echo); } if item.get("type").and_then(Value::as_str) == Some("record") { let Some(silk) = item.get("data").and_then(|data| data.get("file")) @@ -537,14 +758,18 @@ fn send_payload( return dispatch_send(echo, outcome, allow_async); } } - let text = match get_message_text(params) { - Ok(text) => text, - Err(mut response) => { - response.echo = echo; - return response; + match parse_send(params, &target, store) { + Ok(ParsedSend::Plain(text)) => { + dispatch_send(echo, sink.send(&SendPayload { target, text }), allow_async) } - }; - dispatch_send(echo, sink.send(&SendPayload { target, text }), allow_async) + Ok(ParsedSend::Rich(mut segments)) => { + if let Err((retcode, wording)) = resolve_mentions(&mut segments, &target, queries) { + return ActionResponse::failed(retcode, &wording, echo); + } + dispatch_send(echo, sink.send_rich(target, segments), allow_async) + } + Err((retcode, wording)) => ActionResponse::failed(retcode, &wording, echo), + } } /// Whether an action name belongs to the implemented public API surface. @@ -638,6 +863,11 @@ fn query_response_with_voice( RET_BAD_REQUEST, &format!("宿主查询拒绝 (code={code}): {reason}"), echo), QueryOutcome::Timeout => return ActionResponse::failed(RET_NOT_CONFIRMED, "宿主查询超时", echo), QueryOutcome::Disconnected => return ActionResponse::failed(RET_NOT_CONFIRMED, "宿主查询连接已断开", echo), + QueryOutcome::InvalidResponse + if matches!(query, HostQuery::ImageInfo { .. } | HostQuery::ImageDownload { .. }) => + { + return ActionResponse::failed(RET_BAD_REQUEST, "图片资源不可用或已失效", echo) + } QueryOutcome::InvalidResponse => return invalid(), }; match data { @@ -738,7 +968,7 @@ fn get_record(params: &Value, store: &dyn StoreReader, queries: &dyn QueryBacken } fn image_bytes(expected: &caligo_model::capability::ImageInfo, download: caligo_model::capability::ImageDownload) -> Option> { - if &download.info != expected || expected.size > caligo_model::capability::MAX_IMAGE_DOWNLOAD_BYTES + if !download.info.same_media(expected) || expected.size > caligo_model::capability::MAX_IMAGE_DOWNLOAD_BYTES || download.png_hex.len() != expected.size as usize * 2 || !download.png_hex.is_ascii() { return None; } let bytes = (0..download.png_hex.len()).step_by(2) .map(|i| u8::from_str_radix(&download.png_hex[i..i+2],16).ok()).collect::>>()?; @@ -766,6 +996,41 @@ fn get_image(params: &Value, store: &dyn StoreReader, queries: &dyn QueryBackend query_response_with_voice(query,queries,echo,None,Some(&info)) } +fn upload_image(params: &Value, sink: &mut dyn SendSink, echo: Value) -> ActionResponse { + let Some(file) = params.get("file").and_then(Value::as_str) else { + return ActionResponse::failed(RET_BAD_PARAMS, "上传 file 必须是 base64:// PNG", echo); + }; + let Some(encoded) = file.strip_prefix("base64://") else { + return ActionResponse::failed(RET_BAD_PARAMS, "上传 file 必须是 base64:// PNG", echo); + }; + if encoded.len() > 4 * caligo_model::png::MAX_SEND_BYTES.div_ceil(3) { + return ActionResponse::failed(RET_BAD_PARAMS, "上传 PNG 超出大小上限", echo); + } + let Some(png) = STANDARD.decode(encoded).ok() else { + return ActionResponse::failed(RET_BAD_PARAMS, "上传 PNG Base64 无效", echo); + }; + if caligo_model::png::dimensions(&png).is_none() { + return ActionResponse::failed(RET_BAD_PARAMS, "上传内容不是有界普通 PNG", echo); + } + match sink.upload_image(png) { + Ok(upload) => ActionResponse::ok(serde_json::to_value(upload).unwrap_or(Value::Null), echo), + Err(reason) => ActionResponse::failed(RET_BAD_REQUEST, &reason, echo), + } +} + +fn delete_image_upload(params: &Value, sink: &mut dyn SendSink, echo: Value) -> ActionResponse { + let Some(upload_id) = params.get("upload_id").and_then(Value::as_str) else { + return ActionResponse::failed(RET_BAD_PARAMS, "upload_id 必须是 caligo-upload 标识", echo); + }; + if !caligo_model::capability::image_upload_id(upload_id) { + return ActionResponse::failed(RET_BAD_PARAMS, "upload_id 必须是 caligo-upload 标识", echo); + } + match sink.delete_image_upload(upload_id) { + Ok(()) => ActionResponse::ok(serde_json::json!({}), echo), + Err(reason) => ActionResponse::failed(RET_UNSUPPORTED, &reason, echo), + } +} + /// Compatibility entry for callers without a host query backend. Directory /// actions remain explicitly unsupported; legacy login readers retain their data. pub fn handle_action( @@ -803,7 +1068,7 @@ pub fn handle_action_with_queries( ActionHandlerKind::Send { target, allow_async, - } => send_payload(target, params, sink, echo, allow_async), + } => send_payload(target, params, sink, store, queries, echo, allow_async), ActionHandlerKind::GetMessage => { let Some(mid) = params .get("message_id") @@ -836,6 +1101,8 @@ pub fn handle_action_with_queries( } ActionHandlerKind::GetRecord => get_record(params, store, queries, echo), ActionHandlerKind::GetImage => get_image(params, store, queries, echo), + ActionHandlerKind::UploadImage => upload_image(params, sink, echo), + ActionHandlerKind::DeleteImageUpload => delete_image_upload(params, sink, echo), ActionHandlerKind::GetFriendList => query_response(HostQuery::FriendList, queries, echo), ActionHandlerKind::GetGroupList => query_response(HostQuery::GroupList, queries, echo), ActionHandlerKind::GetGroupInfo => { @@ -971,7 +1238,7 @@ mod tests { fn image_info(&self, file: &str) -> Option { (file == "caligo-image:10001:42").then(|| caligo_model::capability::ImageInfo { chat_type:1, peer_uid:"u_friend".into(),sender_uin:"20002".into(),message_id:"100".into(), - element_id:"200".into(),size:70,md5:"e605ef58c3bb5f33463782ab90d58295".into(),width:1,height:1,pic_type:1001, + element_id:"200".into(),size:70,md5:"e605ef58c3bb5f33463782ab90d58295".into(),width:1,height:1,pic_type:1001,file_uuid:None, }) } fn voice_info(&self, file: &str) -> Option { @@ -1018,6 +1285,8 @@ mod tests { "get_msg", "get_record", "get_image", + "upload_image", + "delete_image_upload", "get_login_info", "get_friend_list", "get_group_list", @@ -1057,6 +1326,18 @@ mod tests { self.0.push(payload.clone()); Ok(SendDisposition::Confirmed { message_id: 42 }) } + fn upload_image(&mut self, png: Vec) -> Result { + Ok(caligo_model::capability::ImageUpload { + upload_id: "caligo-upload:10001:0123456789abcdef0123456789abcdef".into(), + size: png.len() as u32, + sha256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + width: 1, + height: 1, + created_at_unix_ms: 1, + expires_at_unix_ms: 2, + }) + } + fn delete_image_upload(&mut self, _upload_id: &str) -> Result<(), String> { Ok(()) } } struct FakeQueries; @@ -1078,6 +1359,9 @@ mod tests { age:0,level:"0".into(),qq_level:0,join_time:"0".into(),last_sent_time:"0".into(), role:caligo_model::capability::MemberRole::Member,title:"".into(),is_robot:false,shut_up_timestamp:0, }]}), + HostQuery::GroupMemberUid { group_id, user_id } => QueryData::GroupMemberUid(caligo_model::capability::GroupMemberUid { + group_id, user_id, uid: "u_member".into(), name: "member".into(), + }), HostQuery::GroupInfo { group_id } => QueryData::GroupInfo(GroupInfo { group_id, group_name: "Lab group".into(), @@ -1114,6 +1398,8 @@ mod tests { ActionInputSchema::MessageId => serde_json::json!({"message_id":42}), ActionInputSchema::Record => serde_json::json!({"file":"caligo-voice:10001:42"}), ActionInputSchema::Image => serde_json::json!({"file":"caligo-image:10001:42"}), + ActionInputSchema::ImageUpload => serde_json::json!({"file":"base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGMQVDL+DwACFAFmBODefwAAAABJRU5ErkJggg=="}), + ActionInputSchema::ImageUploadId => serde_json::json!({"upload_id":"caligo-upload:10001:0123456789abcdef0123456789abcdef"}), ActionInputSchema::GroupInfo | ActionInputSchema::GroupMemberList => serde_json::json!({"group_id":7,"no_cache":true}), ActionInputSchema::GroupMemberInfo => serde_json::json!({"group_id":7,"user_id":8}), ActionInputSchema::Empty => serde_json::json!({}), @@ -1152,6 +1438,10 @@ mod tests { assert_eq!(response.data["real_id"], 398263); } ActionHandlerKind::GetImage => { assert_eq!(response.data["file_name"],"image.png"); }, + ActionHandlerKind::UploadImage => { + assert_eq!(response.data["upload_id"], "caligo-upload:10001:0123456789abcdef0123456789abcdef"); + } + ActionHandlerKind::DeleteImageUpload => assert_eq!(response.data, serde_json::json!({})), ActionHandlerKind::GetRecord => { assert_eq!(response.data["base64"], "AiMhU0lMS19WMw=="); } @@ -1199,6 +1489,153 @@ mod tests { } } + struct RichStore; + impl StoreReader for RichStore { + fn get_msg(&self, _: i32) -> Option { + None + } + fn login_info(&self) -> Option<(u64, String)> { + Some((10001, "caligo".into())) + } + fn online_status(&self) -> Option { + Some(true) + } + fn reply_reference(&self, message_id: i32) -> Option { + (message_id == 42).then(|| caligo_model::onebot_traits::ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: 2, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + }) + } + } + + #[derive(Default)] + struct RichSink { + rich: Vec>, + } + impl SendSink for RichSink { + fn send(&mut self, _: &SendPayload) -> Result { + panic!("plain text must not be used for rich segments") + } + fn send_rich( + &mut self, + _: SendTarget, + segments: Vec, + ) -> Result { + self.rich.push(segments); + Ok(SendDisposition::Confirmed { message_id: 7 }) + } + } + + #[test] + fn group_reply_and_mention_are_ordered_resolved_and_explicitly_rejected() { + let mut sink = RichSink::default(); + let response = handle_action_with_queries( + "send_group_msg", + &serde_json::json!({"group_id":30003,"message":[ + {"type":"reply","data":{"id":42}}, + {"type":"at","data":{"qq":"20002"}}, + {"type":"text","data":{"text":" hi"}} + ]}), + Value::Null, + &mut sink, + &RichStore, + &FakeQueries, + ); + assert_eq!(response.retcode, 0, "{response:?}"); + assert_eq!(sink.rich.len(), 1); + assert_eq!(sink.rich[0].len(), 3); + assert_eq!( + sink.rich[0][0], + SendSegment::Reply { + target: caligo_model::onebot_traits::ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: 2, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + } + } + ); + assert_eq!( + sink.rich[0][1], + SendSegment::Mention { qq: "20002".into(), uid: "u_member".into(), name: "member".into() } + ); + assert_eq!(sink.rich[0][2], SendSegment::Text { text: " hi".into() }); + + let mut sink = RichSink::default(); + let response = handle_action_with_queries( + "send_private_msg", + &serde_json::json!({"user_id":20002,"message":[{"type":"at","data":{"qq":"20002"}}]}), + Value::Null, + &mut sink, + &RichStore, + &FakeQueries, + ); + assert_eq!(response.retcode, RET_UNSUPPORTED); + assert!(sink.rich.is_empty()); + + let response = handle_action_with_queries( + "send_group_msg", + &serde_json::json!({"group_id":30003,"message":[{"type":"reply","data":{"id":99}}]}), + Value::Null, + &mut sink, + &RichStore, + &FakeQueries, + ); + assert_eq!(response.retcode, RET_BAD_PARAMS); + assert!(sink.rich.is_empty()); + + let response = handle_action_with_queries( + "send_group_msg", + &serde_json::json!({"group_id":30003,"message":[{"type":"face","data":{"id":1}}]}), + Value::Null, + &mut sink, + &RichStore, + &FakeQueries, + ); + assert_eq!(response.retcode, RET_UNSUPPORTED); + assert!(sink.rich.is_empty()); + } + + #[test] + fn reply_to_another_conversation_is_rejected_before_dispatch() { + struct OtherStore; + impl StoreReader for OtherStore { + fn get_msg(&self, _: i32) -> Option { None } + fn login_info(&self) -> Option<(u64, String)> { None } + fn online_status(&self) -> Option { None } + fn reply_reference(&self, _: i32) -> Option { + Some(caligo_model::onebot_traits::ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: 2, + peer_uid: "40004".into(), + peer_uin: "40004".into(), + }) + } + } + let mut sink = RichSink::default(); + let response = handle_action_with_queries( + "send_group_msg", + &serde_json::json!({"group_id":30003,"message":[{"type":"reply","data":{"id":42}}]}), + Value::Null, + &mut sink, + &OtherStore, + &FakeQueries, + ); + assert_eq!(response.retcode, RET_BAD_PARAMS); + assert!(sink.rich.is_empty()); + } + #[test] fn async_aliases_share_payload_and_terminal_results_with_canonical_actions() { struct ResultSink { @@ -1292,6 +1729,20 @@ mod tests { let schema = &metadata["input_schema"]; assert_eq!(schema["type"], "object"); let expected_schema = match entry.handler { + ActionHandlerKind::UploadImage => { + assert_eq!(entry.permission, ActionPermission::Write); + assert_eq!(metadata["permission"], "write"); + assert_eq!(schema["required"], serde_json::json!(["file"])); + assert_eq!(schema["properties"]["file"]["type"], "string"); + ActionInputSchema::ImageUpload + } + ActionHandlerKind::DeleteImageUpload => { + assert_eq!(entry.permission, ActionPermission::Write); + assert_eq!(metadata["permission"], "write"); + assert_eq!(schema["required"], serde_json::json!(["upload_id"])); + assert_eq!(schema["properties"]["upload_id"]["type"], "string"); + ActionInputSchema::ImageUploadId + } ActionHandlerKind::Send { target, .. } => { assert_eq!(entry.permission, ActionPermission::Write); assert_eq!(metadata["permission"], "write"); @@ -1573,6 +2024,116 @@ mod tests { } } + #[test] + fn unsupported_segments_are_rejected_without_text_fallback() { + for segment in ["forward", "json", "face", "video", "file", "markdown"] { + let mut sink = ConfirmedSink::default(); + let params = serde_json::json!({ + "group_id": 7, + "message": [{"type":segment, "data":{"id":"1"}}] + }); + let response = handle_action( + "send_group_msg", + ¶ms, + serde_json::json!({"segment":segment}), + &mut sink, + &FakeStore, + ); + assert_eq!(response.retcode, RET_UNSUPPORTED, "{segment}: {response:?}"); + assert!(sink.0.is_empty(), "{segment} must not fall back to text"); + } + } + + #[test] + fn image_upload_is_separate_from_send_and_deletable() { + use base64::{engine::general_purpose::STANDARD, Engine}; + #[derive(Default)] + struct UploadSink { + png: Option>, + sent: Option>, + } + impl SendSink for UploadSink { + fn send(&mut self, _payload: &SendPayload) -> Result { + Err("text send unused".into()) + } + fn send_image(&mut self, _target: SendTarget, png: Vec) -> Result { + self.sent = Some(png); + Ok(SendDisposition::Confirmed { message_id: 42 }) + } + fn upload_image(&mut self, png: Vec) -> Result { + self.png = Some(png.clone()); + Ok(caligo_model::capability::ImageUpload { + upload_id: "caligo-upload:10001:0123456789abcdef0123456789abcdef".into(), + size: png.len() as u32, + sha256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + width: 1, + height: 1, + created_at_unix_ms: 1, + expires_at_unix_ms: 2, + }) + } + fn resolve_image_upload(&mut self, upload_id: &str) -> Result, String> { + if upload_id == "caligo-upload:10001:0123456789abcdef0123456789abcdef" { + self.png.clone().ok_or_else(|| "上传资源不存在或已失效".into()) + } else { + Err("上传资源不存在或已失效".into()) + } + } + fn delete_image_upload(&mut self, upload_id: &str) -> Result<(), String> { + if upload_id == "caligo-upload:10001:0123456789abcdef0123456789abcdef" { + self.png = None; + Ok(()) + } else { + Err("上传资源不存在或已失效".into()) + } + } + } + let png = STANDARD.decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGMQVDL+DwACFAFmBODefwAAAABJRU5ErkJggg==").unwrap(); + let mut sink = UploadSink::default(); + let upload = handle_action( + "upload_image", + &serde_json::json!({"file":format!("base64://{}",STANDARD.encode(&png))}), + Value::Null, + &mut sink, + &FakeStore, + ); + assert_eq!(upload.retcode, 0, "{upload:?}"); + let upload_id = upload.data["upload_id"].as_str().unwrap().to_string(); + assert_eq!(sink.png.as_ref().unwrap(), &png); + let sent = handle_action( + "send_private_msg", + &serde_json::json!({"user_id":8,"message":[{"type":"image","data":{"file":upload_id}}]}), + Value::Null, + &mut sink, + &FakeStore, + ); + assert_eq!(sent.retcode, 0, "{sent:?}"); + assert_eq!(sink.sent.as_ref().unwrap(), &png); + assert_eq!( + handle_action("delete_image_upload", &serde_json::json!({"upload_id":upload_id}), Value::Null, &mut sink, &FakeStore).retcode, + 0 + ); + assert!(sink.png.is_none()); + assert_eq!( + handle_action( + "send_private_msg", + &serde_json::json!({"user_id":8,"message":[{"type":"image","data":{"file":upload_id}}]}), + Value::Null, + &mut sink, + &FakeStore, + ).retcode, + RET_UNSUPPORTED + ); + assert_eq!( + handle_action("upload_image", &serde_json::json!({"file":"base64://not-png"}), Value::Null, &mut sink, &FakeStore).retcode, + RET_BAD_PARAMS + ); + assert_eq!( + handle_action("delete_image_upload", &serde_json::json!({"upload_id":"nope"}), Value::Null, &mut sink, &FakeStore).retcode, + RET_BAD_PARAMS + ); + } + #[test] fn unsupported_group_info_rejects_missing_or_invalid_id_without_fake_data() { for params in [ diff --git a/crates/caligo-core/src/onebot_events.rs b/crates/caligo-core/src/onebot_events.rs index c0ab8336..4ec5af64 100644 --- a/crates/caligo-core/src/onebot_events.rs +++ b/crates/caligo-core/src/onebot_events.rs @@ -98,9 +98,15 @@ pub fn message_event_json(self_id: u64, message_id: i32, event: &MsgEvent) -> Op let (message, raw_message) = if event.wrapper_message.as_ref().and_then(|record| record.voice()).is_some() { let token = caligo_model::onebot_traits::voice_file_token(self_id, message_id); (json!([{"type":"record", "data":{"file":token}}]), format!("[CQ:record,file={token}]")) - } else if event.wrapper_message.as_ref().and_then(|record| record.image()).is_some() { + } else if let Some(image) = event.wrapper_message.as_ref().and_then(|record| record.image()) { let token = caligo_model::onebot_traits::image_file_token(self_id, message_id); - (json!([{"type":"image", "data":{"file":token}}]), format!("[CQ:image,file={token}]")) + let mut data = json!({"file":token}); + if let Some(media_id) = image.file_uuid.as_ref() { + data["file_id"] = json!(media_id); + } + (json!([{"type":"image", "data":data}]), format!("[CQ:image,file={token}]")) + } else if let Some((message, raw)) = rich_event_segments(event) { + (message, raw) } else if event.text.is_empty() { return None; } else { @@ -131,6 +137,37 @@ pub fn message_event_json(self_id: u64, message_id: i32, event: &MsgEvent) -> Op serde_json::to_string(&body).ok() } +fn rich_event_segments(event: &MsgEvent) -> Option<(Value, String)> { + use caligo_model::wrapper_message::WrapperSegment; + let segments = event.wrapper_message.as_ref()?.segments().ok()?; + let mut message = Vec::new(); + let mut raw = String::new(); + for segment in &segments { + match segment { + WrapperSegment::Text { content, mention: None } => { + if !content.is_empty() { + message.push(json!({"type":"text", "data":{"text":content}})); + raw.push_str(content); + } + } + WrapperSegment::Text { content, mention: Some(mention) } => { + message.push(json!({"type":"at", "data":{"qq":mention.at_uid}})); + raw.push_str(&format!("[CQ:at,qq={}]", mention.at_uid)); + let rest = crate::message_store::mention_remainder(content); + if !rest.is_empty() { + message.push(json!({"type":"text", "data":{"text":rest}})); + raw.push_str(rest); + } + } + WrapperSegment::Reply { replay_msg_id, .. } => { + message.push(json!({"type":"reply", "data":{"id":replay_msg_id}})); + raw.push_str(&format!("[CQ:reply,id={replay_msg_id}]")); + } + } + } + (!message.is_empty()).then(|| (Value::Array(message), raw)) +} + #[cfg(test)] mod tests { use super::*; @@ -204,6 +241,101 @@ mod tests { } } + #[test] + fn rich_wrapper_event_renders_at_and_reply_segments() { + use caligo_model::wrapper_message::{ + WrapperBinding, WrapperElement, WrapperMessage, WrapperMessageEnvelope, WrapperReply, + WrapperSource, WrapperText, + }; + let element = |element_type, text_element, reply| WrapperElement { + element_type, + text_element, + voice: None, + image: None, + reply, + }; + let envelope = WrapperMessageEnvelope { + binding: WrapperBinding { + account: "10001".into(), + session_generation: 1, + host_nonce: 9, + wrapper_session: "nt_fixture".into(), + }, + wrapper_session: "nt_fixture".into(), + source: WrapperSource::Recv, + observed_at_unix_ms: 10, + record: WrapperMessage { + msg_id: "9007199254740994".into(), + msg_seq: "8".into(), + msg_random: "9".into(), + msg_time: "1794567891".into(), + client_seq: None, + guild_id: String::new(), + chat_type: 2, + msg_type: 2, + sub_msg_type: 0, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + sender_uid: "u_member".into(), + sender_uin: "20002".into(), + send_status: None, + elements: vec![ + element( + 7, + None, + Some(WrapperReply { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + source_msg_text: String::new(), + }), + ), + element( + 1, + Some(WrapperText { + content: "@Bot hi".into(), + at_type: 2, + at_uid: "20002".into(), + at_nt_uid: "u_member".into(), + at_tiny_id: "20002".into(), + }), + None, + ), + ], + }, + }; + let event = MsgEvent { + event_seq: 1, + session_generation: 1, + session: SessionKey::new("10001", SessionKind::Group, "30003"), + direction: Direction::Incoming, + sender: "20002".into(), + native_id: NativeMessageId("9007199254740994".into()), + text: envelope.plain_text().unwrap(), + platform_time: Some(1_794_567_891), + wrapper_message: Some(envelope), + onebot_projection: Some(OneBotMessageProjection { + peer_id: 30003, + sender_user_id: 20002, + real_id: 9, + time: 1_794_567_891, + sender_nickname: None, + sub_type: Some("normal".into()), + font: Some(0), + }), + observed_at_unix_ms: 10, + source: EventSource::Recv, + }; + let value: Value = + serde_json::from_str(&message_event_json(10001, 9, &event).unwrap()).unwrap(); + assert_eq!(value["message"], json!([ + {"type":"reply","data":{"id":"9007199254740993"}}, + {"type":"at","data":{"qq":"20002"}}, + {"type":"text","data":{"text":" hi"}} + ])); + assert_eq!(value["raw_message"], + "[CQ:reply,id=9007199254740993][CQ:at,qq=20002] hi"); + } + #[test] fn message_event_requires_complete_explicit_v11_fields_and_keeps_text_literal() { let event = incoming_event(SessionKind::Group); diff --git a/crates/caligo-core/src/onebot_server.rs b/crates/caligo-core/src/onebot_server.rs index 2bae2414..a532123d 100644 --- a/crates/caligo-core/src/onebot_server.rs +++ b/crates/caligo-core/src/onebot_server.rs @@ -177,6 +177,18 @@ impl SendSink for DaemonSendSink { self.wait_for_receipt(&request_id, &target) } + fn upload_image(&mut self, png: Vec) -> Result { + self.daemon.upload_image(png) + } + + fn resolve_image_upload(&mut self, upload_id: &str) -> Result, String> { + self.daemon.resolve_image_upload(upload_id) + } + + fn delete_image_upload(&mut self, upload_id: &str) -> Result<(), String> { + self.daemon.delete_image_upload(upload_id) + } + fn send_private_voice(&mut self, user_id: u64, silk: Vec) -> Result { if !self.daemon.supports_private_voice() { return Ok(SendDisposition::Unsupported { @@ -200,6 +212,36 @@ impl SendSink for DaemonSendSink { let request_id = self.daemon.submit_voice(SessionKind::Group, &peer, silk, SEND_DEADLINE_MS)?; self.wait_for_receipt(&request_id, &target) } + + fn send_rich( + &mut self, + target: SendTarget, + segments: Vec, + ) -> Result { + let (kind, peer, chat_type) = match target { + SendTarget::Private { user_id } => (SessionKind::Private, user_id, 1), + SendTarget::Group { group_id } => (SessionKind::Group, group_id, 2), + }; + let has_reply = segments + .iter() + .any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Reply { .. })); + let has_mention = segments + .iter() + .any(|segment| matches!(segment, caligo_model::onebot_traits::SendSegment::Mention { .. })); + if (has_reply && !self.daemon.supports_reply(chat_type)) + || (has_mention && !self.daemon.supports_mention(chat_type)) + { + return Ok(SendDisposition::Unsupported { + reason: "当前宿主未声明绑定会话的 @/回复发送能力".into(), + }); + } + let peer = peer.to_string(); + let key = SessionKey::new(&self.daemon.config.account, kind, &peer); + let request_id = self + .daemon + .submit_rich(kind, &peer, segments, SEND_DEADLINE_MS)?; + self.wait_for_receipt(&request_id, &key) + } } /// Blocking normal-build listener. The bind address is chosen and validated diff --git a/crates/caligo-core/src/runtime.rs b/crates/caligo-core/src/runtime.rs index acfd1961..8fcec3bc 100644 --- a/crates/caligo-core/src/runtime.rs +++ b/crates/caligo-core/src/runtime.rs @@ -1561,4 +1561,8 @@ impl StoreReader for AccountActor { .map(|s| s.group_peers()) .unwrap_or_default() } + + fn reply_reference(&self, message_id: i32) -> Option { + self.message_store.as_ref()?.reply_reference(message_id) + } } diff --git a/crates/caligo-core/tests/capability_query_lab.rs b/crates/caligo-core/tests/capability_query_lab.rs index be8627bd..6985ec5f 100644 --- a/crates/caligo-core/tests/capability_query_lab.rs +++ b/crates/caligo-core/tests/capability_query_lab.rs @@ -166,6 +166,9 @@ fn send_capabilities_are_scoped_and_cleared_on_reconnect() { group_voice: false, private_image: true, group_image: true, + private_reply: false, + group_reply: false, + group_mention: false, }) .unwrap(); bridge @@ -190,6 +193,9 @@ fn send_capabilities_are_scoped_and_cleared_on_reconnect() { group_voice: false, private_image: true, group_image: true, + private_reply: false, + group_reply: false, + group_mention: false, }) .unwrap(); bridge @@ -224,6 +230,9 @@ fn private_voice_dispatch_requires_current_advertisement_and_is_never_replayed() let advertise_voice = |bridge: &mut BridgeClient, scope: QueryScope| { bridge.send(&BridgeMsg::SendCapabilities { scope, private_text: false, group_text: false, private_voice: true, group_voice: false, private_image: false, group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, }).unwrap(); bridge.send(&BridgeMsg::Health { ingress_pending: 0, native_ops_total: 0 }).unwrap(); assert!(matches!(bridge.recv().unwrap(), CoreToBridgeMsg::HealthAck {})); @@ -549,7 +558,7 @@ fn image_queries_require_advertised_scope_and_exact_png_response() { info: ImageInfo { chat_type: 2, peer_uid: "30003".into(), sender_uin: "20002".into(), message_id: "90071992547409939999".into(), element_id: "9007199254740994".into(), - size: 70, md5: "e605ef58c3bb5f33463782ab90d58295".into(), width: 1, height: 1, pic_type: 1001, + size: 70, md5: "e605ef58c3bb5f33463782ab90d58295".into(), width: 1, height: 1, pic_type: 1001, file_uuid: None, }, png_hex: "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63105432fe0f000214016604e0de7f0000000049454e44ae426082".into(), }; @@ -645,6 +654,9 @@ fn image_dispatch_requires_current_advertisement_and_is_never_replayed() { group_voice: false, private_image: true, group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, }) .unwrap(); bridge @@ -730,3 +742,82 @@ fn image_dispatch_requires_current_advertisement_and_is_never_replayed() { Some((caligo_model::ActionState::DeliveryUnknown, None)) ); } + +#[test] +fn rich_dispatch_requires_current_reply_and_mention_advertisement() { + use caligo_model::onebot_traits::{ReplyReference, SendSegment}; + let lab = Lab::new(); + let (mut bridge, scope) = lab.bridge(); + let mention = SendSegment::Mention { + qq: "20002".into(), + uid: "u_member".into(), + name: "member".into(), + }; + let reply = SendSegment::Reply { + target: ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: 2, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + }, + }; + let submit = |segments: Vec| { + lab.daemon + .submit_rich(caligo_model::SessionKind::Group, "30003", segments, 10_000) + }; + let advertise = |bridge: &mut BridgeClient, scope: QueryScope, reply: bool, mention: bool| { + bridge + .send(&BridgeMsg::SendCapabilities { + scope, + private_text: false, + group_text: true, + private_voice: false, + group_voice: false, + private_image: false, + group_image: false, + private_reply: false, + group_reply: reply, + group_mention: mention, + }) + .unwrap(); + bridge + .send(&BridgeMsg::Health { + ingress_pending: 0, + native_ops_total: 0, + }) + .unwrap(); + assert!(matches!( + bridge.recv().unwrap(), + CoreToBridgeMsg::HealthAck {} + )); + }; + assert!(submit(vec![mention.clone()]).is_err()); + advertise(&mut bridge, scope.clone(), false, false); + assert!(submit(vec![mention.clone()]).is_err()); + advertise(&mut bridge, scope.clone(), true, false); + assert!(submit(vec![reply.clone()]).is_ok()); + let CoreToBridgeMsg::DispatchRich { + segments, + chat_type, + peer_uin, + wire_seq, + timeout_ms, + .. + } = bridge.recv().unwrap() + else { + panic!("expected rich dispatch") + }; + assert_eq!(chat_type, 2); + assert_eq!(peer_uin, "30003"); + assert_eq!(segments, vec![reply.clone()]); + assert!(wire_seq > 0 && (1..=10_000).contains(&timeout_ms)); + advertise(&mut bridge, scope.clone(), true, true); + assert!(submit(vec![mention.clone(), SendSegment::Text { text: " hi".into() }]).is_ok()); + let CoreToBridgeMsg::DispatchRich { segments, .. } = bridge.recv().unwrap() else { + panic!("expected rich dispatch") + }; + assert_eq!(segments, vec![mention, SendSegment::Text { text: " hi".into() }]); +} diff --git a/crates/caligo-core/tests/daemon_chain.rs b/crates/caligo-core/tests/daemon_chain.rs index f2bae83c..74226f4e 100644 --- a/crates/caligo-core/tests/daemon_chain.rs +++ b/crates/caligo-core/tests/daemon_chain.rs @@ -46,7 +46,7 @@ impl HostAdapter for ChainHost { Ok(match op { HostOp::ListenerAdd => HostOpResult::ListenerAdded { token: 1 }, HostOp::ListenerRemove { .. } => HostOpResult::ListenerRemoved, - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => HostOpResult::ProbeDone, HostOp::SendText { .. } => { let n = self.send_ids.fetch_add(1, Ordering::Relaxed) + 1; @@ -188,7 +188,7 @@ fn spawn_bridge_agent( } // 泵:通知 core 有事件?(本测试无入站事件泵;仅应答 Dispatch。) match bridge.recv() { - Ok(CoreToBridgeMsg::DispatchPrivateVoice { .. } | CoreToBridgeMsg::DispatchGroupVoice { .. } | CoreToBridgeMsg::DispatchImage { .. }) => + Ok(CoreToBridgeMsg::DispatchPrivateVoice { .. } | CoreToBridgeMsg::DispatchGroupVoice { .. } | CoreToBridgeMsg::DispatchImage { .. } | CoreToBridgeMsg::DispatchRich { .. }) => panic!("text-only fixture"), Ok(CoreToBridgeMsg::Dispatch { request_id, diff --git a/crates/caligo-core/tests/daemon_client_lab.rs b/crates/caligo-core/tests/daemon_client_lab.rs index c72a9aa4..e1d2afa1 100644 --- a/crates/caligo-core/tests/daemon_client_lab.rs +++ b/crates/caligo-core/tests/daemon_client_lab.rs @@ -48,7 +48,7 @@ impl HostAdapter for LabHost { Ok(match op { HostOp::ListenerAdd => HostOpResult::ListenerDeferred, HostOp::ListenerRemove { .. } => HostOpResult::ListenerRemoved, - HostOp::SendVoice { .. } | HostOp::SendImage { .. } => panic!("fixture does not send voice"), + HostOp::SendVoice { .. } | HostOp::SendImage { .. } | HostOp::SendRich { .. } => panic!("fixture does not send media"), HostOp::Probe => HostOpResult::ProbeDone, HostOp::SendText { .. } => { let n = LAB_SENDS.fetch_add(1, Ordering::Relaxed) + 1; diff --git a/crates/caligo-core/tests/media_tool_lab.rs b/crates/caligo-core/tests/media_tool_lab.rs index b95d783d..26af56e2 100644 --- a/crates/caligo-core/tests/media_tool_lab.rs +++ b/crates/caligo-core/tests/media_tool_lab.rs @@ -37,6 +37,7 @@ fn config(root: &Path) -> MediaToolConfig { ffmpeg: declaration(&root.join("fake-ffmpeg.exe"), b"fake ffmpeg executable"), ffprobe: declaration(&root.join("fake-ffprobe.exe"), b"fake ffprobe executable"), silk_decoder: None, + silk_encoder: None, work_root: root.join("jobs"), timeout_ms: 100, max_stdout_stderr_bytes: 1024, @@ -92,6 +93,20 @@ impl MediaProcessRunner for FakeRunner { .unwrap() .starts_with(b"\x02#!SILK_V3")); } + if args.first().is_some_and(|arg| arg == "encode") { + assert_eq!(executable.file_name().unwrap(), "fake-silk.exe"); + assert_eq!(args[3], "--sample-rate"); + assert_eq!(args[4], "24000"); + assert_eq!(args[5], "--tencent"); + assert_eq!(fs::read(Path::new(&args[2])).unwrap(), [0, 1, 2, 3]); + fs::write(PathBuf::from(output), b"\x02#!SILK_V3\x02\x00\x11\x22").unwrap(); + return Ok(ProcessResult { + success: true, + code: Some(0), + stdout: Vec::new(), + stderr: Vec::new(), + }); + } let output = PathBuf::from(output); if output.extension().and_then(|value| value.to_str()) == Some("pcm") { fs::write(output, [0x00, 0x01, 0x02, 0x03]).unwrap(); @@ -221,6 +236,36 @@ fn silk_conversion_requires_a_configured_decoder_and_cleans_private_jobs() { fs::remove_dir_all(root).unwrap(); } +#[test] +fn silk_encoder_converts_audio_and_requires_configuration() { + let root = temp_root("silk-encoder"); + let input = root.join("input.wav"); + fs::write(&input, b"RIFFfakeWAVE").unwrap(); + let stop = StopToken::default(); + let mut configuration = config(&root); + let runner = Arc::new(FakeRunner { + mode: FakeMode::Normal, + }); + let media = MediaTool::with_runner_for_tests(configuration.clone(), runner.clone()).unwrap(); + assert!(matches!( + media.container_file_to_silk(&input, &stop), + Err(MediaError::ToolUnavailable(_)) + )); + let encoder = root.join("fake-silk.exe"); + configuration.silk_encoder = Some(declaration(&encoder, b"fixture encoder")); + let media = MediaTool::with_runner_for_tests(configuration, runner).unwrap(); + let encoded = media.container_file_to_silk(&input, &stop).unwrap(); + assert_eq!(encoded.format, "silk"); + assert!(encoded.bytes.starts_with(b"\x02#!SILK_V3")); + assert!(fs::read_dir(root.join("jobs")).unwrap().next().is_none()); + fs::write(&encoder, b"changed encoder").unwrap(); + assert!(matches!( + media.container_file_to_silk(&input, &stop), + Err(MediaError::ToolHashMismatch { .. }) + )); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn timeout_output_limit_and_exit_failure_are_preserved() { let root = temp_root("failures"); diff --git a/crates/caligo-core/tests/onebot_private_send_lab.rs b/crates/caligo-core/tests/onebot_private_send_lab.rs index 679605bd..b4a82ada 100644 --- a/crates/caligo-core/tests/onebot_private_send_lab.rs +++ b/crates/caligo-core/tests/onebot_private_send_lab.rs @@ -95,6 +95,9 @@ fn advertise(bridge: &mut BridgeClient, scope: QueryScope, private_voice: bool) group_voice: false, private_image: false, group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, }) .unwrap(); bridge @@ -127,6 +130,7 @@ fn event(native_id: &str) -> EventPayload { elements: vec![WrapperElement { image: None, voice: None, + reply: None, element_type: 1, text_element: Some(WrapperText { content: "private text".into(), @@ -332,6 +336,7 @@ fn private_record_waits_for_exact_readback_to_be_persisted() { readback.text.clear(); readback.wrapper_message.as_mut().unwrap().record.elements = vec![WrapperElement { image: None, + reply: None, element_type: 4, text_element: None, voice: Some(WrapperVoice { @@ -422,6 +427,9 @@ fn group_record_requires_group_capability_and_exact_group_projection() { scope: scope.clone(), private_text: false, group_text: false, private_voice: false, group_voice: true, private_image: false, group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, }).unwrap(); bridge.send(&BridgeMsg::Health { ingress_pending: 0, native_ops_total: 0 }).unwrap(); assert!(matches!(bridge.recv().unwrap(), CoreToBridgeMsg::HealthAck {})); @@ -447,6 +455,7 @@ fn group_record_requires_group_capability_and_exact_group_projection() { let wrapper = readback.wrapper_message.as_mut().unwrap(); wrapper.record.elements = vec![WrapperElement { image: None, + reply: None, element_type: 4, text_element: None, voice: Some(WrapperVoice { element_id: "90071992547409931235".into(), size: silk.len() as u32, md5: "0123456789abcdef0123456789abcdef".into(), @@ -481,6 +490,157 @@ fn group_record_requires_group_capability_and_exact_group_projection() { }); } +#[test] +fn image_upload_action_uses_the_daemon_store_without_a_bridge() { + use base64::{engine::general_purpose::STANDARD, Engine}; + let png = STANDARD.decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGMQVDL+DwACFAFmBODefwAAAABJRU5ErkJggg==").unwrap(); + let lab = Lab::new(); + let handler = action_handler(lab.daemon.clone()); + let upload = handler( + "upload_image", + &json!({"file":format!("base64://{}",STANDARD.encode(&png))}), + json!("upload"), + ); + assert_eq!(upload.retcode, 0, "{upload:?}"); + let upload_id = upload.data["upload_id"].as_str().unwrap().to_string(); + assert_eq!(upload.data["size"], png.len()); + assert_eq!(lab.daemon.resolve_image_upload(&upload_id).unwrap(), png); + let deleted = handler( + "delete_image_upload", + &json!({"upload_id":upload_id}), + json!("delete"), + ); + assert_eq!(deleted.retcode, 0, "{deleted:?}"); + assert!(lab.daemon.resolve_image_upload(&upload_id).is_err()); + let missing = handler( + "send_private_msg", + &json!({"user_id":8,"message":[{"type":"image","data":{"file":upload_id}}]}), + json!("missing"), + ); + assert_eq!(missing.retcode, RET_UNSUPPORTED); +} + +#[test] +fn uploaded_png_id_sends_once_and_persists_the_public_image_id() { + use base64::{engine::general_purpose::STANDARD, Engine}; + use caligo_model::capability::ImageInfo; + let png = STANDARD.decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGMQVDL+DwACFAFmBODefwAAAABJRU5ErkJggg==").unwrap(); + let lab = Lab::new(); + let (mut bridge, scope) = lab.connect(); + let handler = action_handler(lab.daemon.clone()); + for enabled in [false, true] { + bridge + .send(&BridgeMsg::SendCapabilities { + scope: scope.clone(), + private_text: true, + group_text: true, + private_voice: true, + group_voice: true, + private_image: enabled, + group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, + }) + .unwrap(); + bridge + .send(&BridgeMsg::Health { + ingress_pending: 0, + native_ops_total: 0, + }) + .unwrap(); + assert!(matches!( + bridge.recv().unwrap(), + CoreToBridgeMsg::HealthAck {} + )); + } + let upload = handler( + "upload_image", + &json!({"file":format!("base64://{}",STANDARD.encode(&png))}), + json!("upload"), + ); + assert_eq!(upload.retcode, 0, "{upload:?}"); + let upload_id = upload.data["upload_id"].as_str().unwrap().to_string(); + let params = json!({"user_id":20002,"message":[{"type":"image","data":{"file":upload_id}}]}); + let call = handler.clone(); + let task = std::thread::spawn(move || call("send_msg", ¶ms, json!("uploaded"))); + let CoreToBridgeMsg::DispatchImage { + request_id, + png: bytes, + .. + } = bridge.recv().unwrap() + else { + panic!("expected image dispatch") + }; + assert_eq!(bytes, png); + bridge + .send(&BridgeMsg::NativeStarted { + request_id: request_id.clone(), + }) + .unwrap(); + assert!(matches!( + bridge.recv().unwrap(), + CoreToBridgeMsg::NativeStartedAck { .. } + )); + let native_id = "90071992547409931235"; + bridge + .send(&BridgeMsg::SendResult { + notice_id: 1, + request_id, + outcome: OutcomePayload::Success { + native_id: native_id.into(), + }, + }) + .unwrap(); + assert!(matches!( + bridge.recv().unwrap(), + CoreToBridgeMsg::SendResultAck { terminal: true, .. } + )); + assert!(!task.is_finished()); + let mut readback = event(native_id); + readback.text.clear(); + let wrapper = readback.wrapper_message.as_mut().unwrap(); + wrapper.record.chat_type = 1; + wrapper.record.elements = vec![WrapperElement { + element_type: 2, + text_element: None, + voice: None, + reply: None, + image: Some(ImageInfo { + chat_type: 1, + peer_uid: wrapper.record.peer_uid.clone(), + sender_uin: "10001".into(), + message_id: native_id.into(), + element_id: "90071992547409931236".into(), + md5: "e605ef58c3bb5f33463782ab90d58295".into(), + size: png.len() as u32, + width: 1, + height: 1, + pic_type: 1000, file_uuid: None, + }), + }]; + bridge.send(&BridgeMsg::Event { event: readback }).unwrap(); + assert!(matches!( + bridge.recv().unwrap(), + CoreToBridgeMsg::EventAck { + suppressed: false, + .. + } + )); + let result = task.join().unwrap(); + assert_eq!(result.retcode, 0, "{result:?}"); + let id = result.data["message_id"].as_i64().unwrap() as i32; + let token = format!("caligo-image:10001:{id}"); + assert_eq!( + handler("get_msg", &json!({"message_id":id}), Value::Null).data["message"], + json!([{"type":"image","data":{"file":token}}]) + ); + assert_eq!( + handler("delete_image_upload", &json!({"upload_id":upload_id}), Value::Null).retcode, + 0 + ); +} + #[test] fn png_send_requires_scoped_capability_and_persisted_private_or_group_readback() { use base64::{engine::general_purpose::STANDARD, Engine}; @@ -525,6 +685,9 @@ fn png_send_requires_scoped_capability_and_persisted_private_or_group_readback() } else { chat_type == 1 }, + private_reply: false, + group_reply: false, + group_mention: false, }) .unwrap(); bridge @@ -620,6 +783,7 @@ fn png_send_requires_scoped_capability_and_persisted_private_or_group_readback() element_type: 2, text_element: None, voice: None, + reply: None, image: Some(ImageInfo { chat_type, peer_uid: wrapper.record.peer_uid.clone(), @@ -630,7 +794,7 @@ fn png_send_requires_scoped_capability_and_persisted_private_or_group_readback() size: png.len() as u32, width: 1, height: 1, - pic_type: 1000, + pic_type: 1000, file_uuid: None, }), }]; bridge.send(&BridgeMsg::Event { event: readback }).unwrap(); diff --git a/crates/caligo-core/tests/onebot_query_lab.rs b/crates/caligo-core/tests/onebot_query_lab.rs index b15ae10b..a72c892b 100644 --- a/crates/caligo-core/tests/onebot_query_lab.rs +++ b/crates/caligo-core/tests/onebot_query_lab.rs @@ -329,7 +329,7 @@ fn group_params_validate_before_backend_and_no_cache_is_always_a_host_read() { #[test] fn metadata_and_legacy_wrapper_keep_backend_availability_explicit() { - assert_eq!(ACTION_REGISTRY.len(), 17); + assert_eq!(ACTION_REGISTRY.len(), 19); for name in ["get_friend_list", "get_group_list", "get_group_info"] { assert_eq!( resolve_action(name).unwrap().permission, diff --git a/crates/caligo-core/tests/wrapper_image_chain.rs b/crates/caligo-core/tests/wrapper_image_chain.rs index 79b1daec..20936f02 100644 --- a/crates/caligo-core/tests/wrapper_image_chain.rs +++ b/crates/caligo-core/tests/wrapper_image_chain.rs @@ -57,11 +57,11 @@ function record(chatType,peerUid,peerUin){return {msgId:'90071992547409939999',m msgTime:'1794567890',guildId:'',chatType,msgType:2,subMsgType:0,peerUid,peerUin, senderUid:'u_friend',senderUin:'20002',elements:[{elementType:2,elementId:'9007199254740994', picElement:{fileSize:'70',picWidth:1,picHeight:1,picType:1001,picSubType:0, - md5HexStr:'E605EF58C3BB5F33463782AB90D58295',filePath:'private-path',sourcePath:'private-source',fileUuid:'private-token'}}]};} + md5HexStr:'E605EF58C3BB5F33463782AB90D58295',filePath:'private-path',sourcePath:'private-source',fileUuid:'media-token'}}]};} const bad=record(1,'u_friend','20002');bad.elements[0].picElement.picSubType=1; const mixed=record(1,'u_friend','20002');mixed.elements.push({elementType:1,textElement:{content:'mixed',atType:0}}); listener.onRecvMsg([bad,mixed,record(1,'u_friend','20002'),record(2,'30003','30003')]); -const result=eval(poll);assert.ok(!result.includes('private-'));process.stdout.write(result); +const result=eval(poll);assert.ok(!result.includes('private-'), result);process.stdout.write(result); "#; let mut child = Command::new("node") .args(["--unhandled-rejections=strict", "-"]) diff --git a/crates/caligo-core/tests/wrapper_message_chain.rs b/crates/caligo-core/tests/wrapper_message_chain.rs index e313858f..cee787d6 100644 --- a/crates/caligo-core/tests/wrapper_message_chain.rs +++ b/crates/caligo-core/tests/wrapper_message_chain.rs @@ -98,6 +98,7 @@ fn offline_voice_tools(dir: &Path) -> MediaTool { MediaToolConfig { ffmpeg: declare("ffmpeg.exe"), ffprobe: declare("ffprobe.exe"), + silk_encoder: None, silk_decoder: Some(declare("silk.exe")), work_root: dir.join("media-jobs"), timeout_ms: 100, diff --git a/crates/caligo-model/src/capability.rs b/crates/caligo-model/src/capability.rs index 07e3f14b..5a61bb6e 100644 --- a/crates/caligo-model/src/capability.rs +++ b/crates/caligo-model/src/capability.rs @@ -20,6 +20,7 @@ pub enum QueryCapability { GroupList, GroupInfo, GroupMembers, + GroupMemberUid, UinToUid, UidToUin, MessagesById, @@ -39,6 +40,7 @@ impl QueryCapability { Self::GroupList, Self::GroupInfo, Self::GroupMembers, + Self::GroupMemberUid, Self::UinToUid, Self::UidToUin, Self::MessagesById, @@ -79,6 +81,12 @@ pub enum HostQuery { group_id: String, force_refresh: bool, }, + /// One group member's native UID plus display name, resolved from the + /// bounded member snapshot. Only the UID/name cross IPC for @ sending. + GroupMemberUid { + group_id: String, + user_id: String, + }, UinToUid { uin: String, }, @@ -171,6 +179,7 @@ impl HostQuery { Self::GroupList => QueryCapability::GroupList, Self::GroupInfo { .. } => QueryCapability::GroupInfo, Self::GroupMembers { .. } => QueryCapability::GroupMembers, + Self::GroupMemberUid { .. } => QueryCapability::GroupMemberUid, Self::UinToUid { .. } => QueryCapability::UinToUid, Self::UidToUin { .. } => QueryCapability::UidToUin, Self::MessagesById { .. } => QueryCapability::MessagesById, @@ -185,6 +194,9 @@ impl HostQuery { pub fn validate(&self) -> Result<(), &'static str> { match self { Self::GroupInfo { group_id } | Self::GroupMembers { group_id, .. } if !positive_decimal(group_id) => Err("invalid group id"), + Self::GroupMemberUid { group_id, user_id } + if !positive_decimal(group_id) || !positive_decimal(user_id) => + Err("invalid group member identity"), Self::UinToUid { uin } if !positive_decimal(uin) => Err("invalid UIN"), Self::UidToUin { uid } if !native_uid(uid) => Err("invalid UID"), Self::VoiceInfo { @@ -291,6 +303,15 @@ pub struct GroupMembers { pub members: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GroupMemberUid { + pub group_id: String, + pub user_id: String, + pub uid: String, + pub name: String, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GroupMember { @@ -405,9 +426,29 @@ pub struct ImageInfo { pub width: u32, pub height: u32, pub pic_type: u32, + /// Native media id when the wrapper exposes one. It is metadata, not part + /// of message identity; older stores may omit it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_uuid: Option, } impl ImageInfo { + pub fn same_media(&self, other: &Self) -> bool { + self.chat_type == other.chat_type + && self.peer_uid == other.peer_uid + && self.sender_uin == other.sender_uin + && self.message_id == other.message_id + && self.element_id == other.element_id + && self.size == other.size + && self.md5 == other.md5 + && self.width == other.width + && self.height == other.height + && self.pic_type == other.pic_type + && match (&self.file_uuid, &other.file_uuid) { + (Some(left), Some(right)) => left == right, + _ => true, + } + } fn matches(&self, query: &HostQuery, limit: u32) -> bool { let (HostQuery::ImageInfo { chat_type, @@ -442,10 +483,35 @@ impl ImageInfo { && matches!(self.pic_type, 1000 | 1001) && (1..=32768).contains(&self.width) && (1..=32768).contains(&self.height) + && self.file_uuid.as_ref().is_none_or(|id| { + !id.is_empty() && id.len() <= 256 && !id.chars().any(char::is_control) + }) && u64::from(self.width) * u64::from(self.height) <= 100_000_000 } } +/// Uploaded Caligo image resource. Bytes stay in the daemon; only this +/// bounded metadata crosses the action response. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImageUpload { + pub upload_id: String, + pub size: u32, + pub sha256: String, + pub width: u32, + pub height: u32, + pub created_at_unix_ms: u64, + pub expires_at_unix_ms: u64, +} + +pub const MAX_IMAGE_UPLOADS: usize = 8; +pub const IMAGE_UPLOAD_TTL_MS: u64 = 10 * 60 * 1000; +pub const MAX_IMAGE_UPLOAD_TOTAL_BYTES: usize = MAX_IMAGE_UPLOADS * crate::png::MAX_SEND_BYTES; + +pub fn image_upload_id(value: &str) -> bool { + value.len() <= 128 && value.starts_with("caligo-upload:") +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ImageDownload { @@ -476,6 +542,7 @@ pub enum QueryData { GroupList(Vec), GroupInfo(GroupInfo), GroupMembers(GroupMembers), + GroupMemberUid(GroupMemberUid), Uid(String), Uin(String), Messages(Vec), @@ -527,6 +594,18 @@ impl QueryData { } (HostQuery::UinToUid { .. }, Self::Uid(uid)) => native_uid(uid), (HostQuery::GroupMembers { group_id, .. }, Self::GroupMembers(list)) => list.matches(group_id), + ( + HostQuery::GroupMemberUid { + group_id, + user_id, + }, + Self::GroupMemberUid(info), + ) => { + &info.group_id == group_id + && &info.user_id == user_id + && native_uid(&info.uid) + && info.name.len() <= 4096 + } (HostQuery::UidToUin { .. }, Self::Uin(uin)) => positive_decimal(uin), (HostQuery::ImageInfo { .. }, Self::ImageInfo(info)) => { info.matches(query, MAX_IMAGE_BYTES) && (info.pic_type == 1001 || info.sender_uin == scope.account) diff --git a/crates/caligo-model/src/ipc_v3.rs b/crates/caligo-model/src/ipc_v3.rs index a7e951d0..f0c3764b 100644 --- a/crates/caligo-model/src/ipc_v3.rs +++ b/crates/caligo-model/src/ipc_v3.rs @@ -11,6 +11,7 @@ //! frame/EventPayload/Role 与 v2 共用;发送结果与 Dispatch DTO 在 v3 独立。 use crate::capability::{HostQuery, QueryCapability, QueryOutcome, QueryScope}; +use crate::onebot_traits::SendSegment; use serde::{Deserialize, Serialize}; /// Read-only query contract, advertised separately after the v3 Hello binding. @@ -78,6 +79,18 @@ pub enum CoreToBridgeMsg { peer_uin: String, png: Vec, }, + /// Ordered text/mention/reply segments. Reply targets are already + /// resolved to native identities by core; no MessageStore handle crosses + /// the bridge protocol. + DispatchRich { + scope: QueryScope, + request_id: String, + wire_seq: u32, + timeout_ms: u64, + chat_type: u32, + peer_uin: String, + segments: Vec, + }, Query { request_id: String, scope: QueryScope, @@ -158,6 +171,12 @@ pub enum BridgeMsg { private_image: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] group_image: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + private_reply: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + group_reply: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + group_mention: bool, }, QueryResult { request_id: String, @@ -303,6 +322,9 @@ mod tests { group_voice: false, private_image: false, group_image: false, + private_reply: false, + group_reply: false, + group_mention: false, }; assert_eq!( serde_json::from_slice::(&serde_json::to_vec(&send_capabilities).unwrap()) @@ -314,11 +336,39 @@ mod tests { assert!(legacy["d"].get("private_voice").is_none()); assert!(legacy["d"].get("private_image").is_none()); assert!(legacy["d"].get("group_image").is_none()); + assert!(legacy["d"].get("private_reply").is_none()); + assert!(legacy["d"].get("group_reply").is_none()); + assert!(legacy["d"].get("group_mention").is_none()); assert!(matches!(serde_json::from_value::(legacy.clone()).unwrap(), BridgeMsg::SendCapabilities {private_image:false,group_image:false,..})); let image = CoreToBridgeMsg::DispatchImage {scope:scope.clone(),request_id:"image-lab".into(), wire_seq:9,timeout_ms:1000,chat_type:2,peer_uin:"30003".into(),png:vec![1,2,3]}; assert_eq!(serde_json::from_value::(serde_json::to_value(&image).unwrap()).unwrap(),image); + let rich = CoreToBridgeMsg::DispatchRich { + scope: scope.clone(), + request_id: "rich-lab".into(), + wire_seq: 10, + timeout_ms: 1000, + chat_type: 2, + peer_uin: "30003".into(), + segments: vec![ + SendSegment::Reply { target: crate::onebot_traits::ReplyReference { + replay_msg_id: "9007199254740993".into(), + replay_msg_seq: "7".into(), + sender_uin: "20002".into(), + reply_msg_client_seq: None, + peer_chat_type: 2, + peer_uid: "30003".into(), + peer_uin: "30003".into(), + }}, + SendSegment::Mention { qq: "20002".into(), uid: "u_member".into(), name: "member".into() }, + SendSegment::Text { text: " hi".into() }, + ], + }; + assert_eq!( + serde_json::from_value::(serde_json::to_value(&rich).unwrap()).unwrap(), + rich + ); let mut group = legacy; group["d"]["group_voice"] = serde_json::json!(true); assert!(matches!( diff --git a/crates/caligo-model/src/onebot_traits.rs b/crates/caligo-model/src/onebot_traits.rs index be8117e6..983d1797 100644 --- a/crates/caligo-model/src/onebot_traits.rs +++ b/crates/caligo-model/src/onebot_traits.rs @@ -1,5 +1,6 @@ //! OneBot 动作层共用类型(N4 下沉;core 与 bridge 共用,防依赖环)。 +use serde::{Deserialize, Serialize}; use serde_json::Value; /// OneBot send target. Private `user_id` is a UIN and must not be treated as a @@ -10,6 +11,43 @@ pub enum SendTarget { Private { user_id: u64 }, } +/// One bounded ordered segment accepted by the rich send path. Mention and +/// reply are separate native elements; text stays byte-for-byte as given. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum SendSegment { + Text { text: String }, + /// Group-only. `qq` is `all` or a positive decimal UIN. `uid`/`name` are + /// filled by the bounded member query before dispatch; input leaves them + /// empty. + Mention { + qq: String, + #[serde(default)] + uid: String, + #[serde(default)] + name: String, + }, + Reply { target: ReplyReference }, +} + +/// Native identity of one persisted message that can be quoted. The pinned +/// reference constructs `replyElement` from these fields; no preview text is +/// invented when the source body is unknown. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReplyReference { + pub replay_msg_id: String, + pub replay_msg_seq: String, + pub sender_uin: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reply_msg_client_seq: Option, + pub peer_chat_type: u32, + /// Native peer identity used by the reply element (`u_...` or group UIN). + pub peer_uid: String, + /// Public OneBot peer (UIN) used only for same-conversation validation. + pub peer_uin: String, +} + /// 发送载荷(已通过参数校验;wire 编码与原生派发由实现方承担)。 #[derive(Debug, Clone, PartialEq, Eq)] pub struct SendPayload { @@ -17,6 +55,11 @@ pub struct SendPayload { pub text: String, } +/// Bound for one rich message. Kept independent of media byte limits so a +/// mention/reply message can never exhaust the ledger or native call budget. +pub const MAX_SEND_SEGMENTS: usize = 64; +pub const MAX_RICH_TEXT_BYTES: usize = 48 * 1024; + #[derive(Debug, Clone, PartialEq, Eq)] pub enum SendDisposition { /// Durable queue acceptance only; no OneBot message ID is known. @@ -37,6 +80,17 @@ pub trait SendSink { fn send_image(&mut self, _target: SendTarget, _png: Vec) -> Result { Ok(SendDisposition::Unsupported {reason:"当前宿主未支持图片发送".into()}) } + /// Upload a bounded PNG into the daemon resource store. Separate from send; + /// the returned id can be referenced by a later image message. + fn upload_image(&mut self, _png: Vec) -> Result { + Err("当前宿主未支持图片上传".into()) + } + fn resolve_image_upload(&mut self, _upload_id: &str) -> Result, String> { + Err("当前宿主未支持图片上传资源".into()) + } + fn delete_image_upload(&mut self, _upload_id: &str) -> Result<(), String> { + Err("当前宿主未支持图片上传资源".into()) + } fn send_private_voice(&mut self, _user_id: u64, _silk: Vec) -> Result { Ok(SendDisposition::Unsupported { reason: "当前宿主未支持私聊语音发送".into(), @@ -47,6 +101,17 @@ pub trait SendSink { reason: "当前宿主未支持群语音发送".into(), }) } + /// Ordered text/mention/reply segments. Callers must reject unsupported + /// segment shapes before reaching the sink; the default stays closed. + fn send_rich( + &mut self, + _target: SendTarget, + _segments: Vec, + ) -> Result { + Ok(SendDisposition::Unsupported { + reason: "当前宿主未支持 @/回复发送".into(), + }) + } } /// Complete message fields required by OneBot get_msg. @@ -87,6 +152,11 @@ pub trait StoreReader { fn group_peers(&self) -> Vec { Vec::new() } + /// Native identity of a persisted message for an outbound reply. Absent + /// when the ID is unknown or its wrapper record lacked the required fields. + fn reply_reference(&self, _message_id: i32) -> Option { + None + } } pub fn voice_file_token(account_id: u64, message_id: i32) -> String { diff --git a/crates/caligo-model/src/wrapper_message.rs b/crates/caligo-model/src/wrapper_message.rs index 107be2dc..a95ee2e9 100644 --- a/crates/caligo-model/src/wrapper_message.rs +++ b/crates/caligo-model/src/wrapper_message.rs @@ -40,8 +40,46 @@ pub struct WrapperElement { pub voice: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub image: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reply: Option, +} + +/// Reply reference observed on the pinned wrapper. The field names `replay*` +/// are the native spelling (not a typo introduced here); `sourceMsgText` is +/// often empty and must not be treated as required preview text. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WrapperReply { + pub replay_msg_id: String, + pub replay_msg_seq: String, + #[serde(default)] + pub source_msg_text: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WrapperMention { + pub at_type: u32, + pub at_uid: String, + pub at_nt_uid: String, + pub at_tiny_id: String, +} + +/// Ordered admitted segment. Text may carry a mention; reply is a separate +/// wrapper element that can coexist with text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WrapperSegment { + Text { + content: String, + mention: Option, + }, + Reply { + replay_msg_id: String, + replay_msg_seq: String, + source_msg_text: String, + }, } + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct WrapperVoice { @@ -152,7 +190,7 @@ impl WrapperMessageEnvelope { return Err("add_send_identity"); } if self.voice().is_none() && self.image().is_none() { - self.text()?; + self.segments()?; } if serde_json::to_vec(r).map_err(|_| "record_encoding")?.len() > MAX_RECORD_BYTES { return Err("record_size"); @@ -161,32 +199,147 @@ impl WrapperMessageEnvelope { } pub fn text(&self) -> Result { + let mut text = String::new(); + for segment in self.segments()? { + match segment { + WrapperSegment::Text { content, mention: None } => text.push_str(&content), + _ => return Err("unsupported_element"), + } + } + if text.is_empty() { + return Err("empty_text"); + } + Ok(text) + } + + /// Ordered admitted text/mention/reply segments. Voice and image are + /// handled by their stricter single-element paths above. + pub fn segments(&self) -> Result, &'static str> { if self.record.elements.is_empty() || self.record.elements.len() > 128 { return Err("elements"); } - let mut text = String::new(); + let mut segments = Vec::new(); + let mut text_bytes = 0usize; for element in &self.record.elements { - let Some(t) = element.text_element.as_ref() else { - return Err("non_text"); - }; - if element.element_type != 1 - || element.voice.is_some() - || element.image.is_some() - || t.at_type != 0 - || !t.at_uid.is_empty() - || !t.at_nt_uid.is_empty() - || !t.at_tiny_id.is_empty() - { + if element.voice.is_some() || element.image.is_some() { return Err("unsupported_element"); } - if text.len().saturating_add(t.content.len()) > MAX_TEXT_BYTES { - return Err("text_size"); + match element.element_type { + 1 => { + let Some(t) = element.text_element.as_ref() else { + return Err("non_text"); + }; + text_bytes = text_bytes.saturating_add(t.content.len()); + if text_bytes > MAX_TEXT_BYTES { + return Err("text_size"); + } + let mention = match t.at_type { + 0 => { + if !t.at_uid.is_empty() + || !t.at_nt_uid.is_empty() + || !t.at_tiny_id.is_empty() + { + return Err("unsupported_element"); + } + None + } + 1 => { + if t.at_uid != "all" + || t.at_nt_uid != "all" + || !t.at_tiny_id.is_empty() + { + return Err("unsupported_mention"); + } + Some(WrapperMention { + at_type: 1, + at_uid: "all".into(), + at_nt_uid: "all".into(), + at_tiny_id: String::new(), + }) + } + 2 => { + if !positive_decimal(&t.at_uid) + || !uid(&t.at_nt_uid) + || !(t.at_tiny_id.is_empty() + || t.at_tiny_id == "0" + || positive_decimal(&t.at_tiny_id)) + { + return Err("unsupported_mention"); + } + Some(WrapperMention { + at_type: 2, + at_uid: t.at_uid.clone(), + at_nt_uid: t.at_nt_uid.clone(), + at_tiny_id: t.at_tiny_id.clone(), + }) + } + _ => return Err("unsupported_mention"), + }; + segments.push(WrapperSegment::Text { + content: t.content.clone(), + mention, + }); + } + 7 => { + let Some(reply) = element.reply.as_ref() else { + return Err("non_text"); + }; + if !positive_decimal(&reply.replay_msg_id) + || !positive_decimal(&reply.replay_msg_seq) + || reply.source_msg_text.len() > 4096 + { + return Err("reply_shape"); + } + segments.push(WrapperSegment::Reply { + replay_msg_id: reply.replay_msg_id.clone(), + replay_msg_seq: reply.replay_msg_seq.clone(), + source_msg_text: reply.source_msg_text.clone(), + }); + if let Some(t) = element.text_element.as_ref() { + if t.at_type != 0 + || !t.at_uid.is_empty() + || !t.at_nt_uid.is_empty() + || !t.at_tiny_id.is_empty() + { + return Err("reply_shape"); + } + text_bytes = text_bytes.saturating_add(t.content.len()); + if text_bytes > MAX_TEXT_BYTES { + return Err("text_size"); + } + if !t.content.is_empty() { + segments.push(WrapperSegment::Text { + content: t.content.clone(), + mention: None, + }); + } + } + } + _ => return Err("unsupported_element"), } - text.push_str(&t.content); } - if text.is_empty() { + let has_text = segments.iter().any(|segment| match segment { + WrapperSegment::Text { content, mention } => !content.is_empty() || mention.is_some(), + WrapperSegment::Reply { .. } => false, + }); + let has_reply = segments + .iter() + .any(|segment| matches!(segment, WrapperSegment::Reply { .. })); + if !has_text && !has_reply { return Err("empty_text"); } + Ok(segments) + } + + /// Text used for normalized-event dedup/ledger. Reply-only rows return an + /// empty string; the wrapper segments remain authoritative for rendering. + pub fn plain_text(&self) -> Result { + let mut text = String::new(); + for segment in self.segments()? { + if let WrapperSegment::Text { content, .. } = segment { + text.push_str(&content); + } + } Ok(text) } @@ -336,6 +489,117 @@ pub fn decode_d8_batch(json: &str, binding: &WrapperBinding) -> Result validation_failed +``` + +修复:诊断/接受父目录按 `账号/nt_qq/nt_data/Ptt/YYYY-MM/Ori`,接受与 +`voiceCache.extension` 一致的 `.amr`;不再要求与 `voiceCachePath` 逐字相等。 + +结果:`get_record silk/wav/ogg` 均 `1440 宿主查询响应不符合合同`,无字节; +回调文件已登记但输出校验失败,尚未到达转码。已加有界 `output_shape`(size_matches/silk_header/amr_header/extension) +区分大小与容器头;现场形状采样待下一次语音窗口。 +`wrapper_query_contract` 8/8 通过。 + +### 2026-12-05 N6c 入站语音转码现场(通过) + +用户重启后主根 PID `45736`(`2026-12-05T07:13:56.1582354Z`), +`n6-voice-output3-release` + 私有 media-config 预检 PASS、daemon 0.44s、 +attach 6.29s、`login_ok=true`;包 +`local-evidence/feat008-n6c-voice-output3-20261205/`,零 Caligo 发送。 + +操作者发一条 7,202 B 私聊语音(store `message_id=4`)。只读结果: + +| 输出 | 结果 | +|---|---| +| `silk` | ok,7,202 B,头 `0223 #!SILK_V3`(腾讯前缀) | +| `wav` | ok,187,278 B,头 `RIFF…WAVE` | +| `ogg` | ok,14,968 B,头 `OggS` | +| 诊断 | `path_under_ptt=true`、`registered_path_matches=true`、`size_matches=true`、`silk_header=true`、`amr_header=false`、`validated` | + +回调 `.amr` 路径实际是 SILK 内容;此前失败是 `realpath(sourceFile)` 与短路径 +字符串逐字比较不相等。现语音路径保留绝对路径/Ptt 父目录/md5/extension/大小/头 +校验,但接受 canonical realpath;输出校验和转码通过。无重发/假成功。 + +构建 `target-harness/n6-voice-output3-release` EXE `1ACD06D5…49AB`、 +bridge `5992741B…A2DB`;`wrapper_query_contract` 8/8。 + +## 2026-12-05 N6c 能力矩阵与下一步 + +| 能力 | 入站 | 出站 | 证据/边界 | +|---|---|---|---| +| 语音 SILK | 现场收/发、store、get_msg | 现场 SILK 发送 | 已有 FIELD | +| 语音转码 | `silk`/`wav`/`ogg` 现场通过 | 仅接受 SILK 输入 | 本轮闭合;WAV/OGG 发送需编码器,未实现 | +| 图片 PNG | N6b 现场 | N6b 上传引用、私聊/群 | 已通过 | +| 视频 | 显式拒绝、不入库(`elementType=5`) | `1404` | 实际收发未实现 | +| 文件 | 显式拒绝、不入库(`elementType=3`) | `1404` | 实际收发未实现 | +| 合并转发/卡片/表情/markdown | 不在已支持段 | `1404`,无文本回退 | 新增回归覆盖显式拒绝 | + +出站未知段回归:`forward/json/face/video/file/markdown` 均为 `1404` 且不调用文本 +sink;不会静默降级。实际视频/文件/合并转发/卡片/表情需要 native 上传/消息段 +协议证据,当前不以猜测接入;下一步做只读 native 能力取证,再按格式/方向逐项准入。 + +### 2026-12-05 N6c native 上传能力只读取证(边界) + +用户重启后主根 PID `23636`(`2026-12-05T07:25:41.2052095Z`), +`n6-media-cap-release` 预检 PASS、attach 3.33s、`login_ok=true`;零发送。 + +```text +session_rich_service=true +msg_send_file=false +msg_upload_file=false +rich_upload_file=false +rich_send_file=false +rich_get_path=false +``` + +结论:当前 wrapper 的 `MsgService`/`RichMediaService` 没有以这些名字暴露 +`sendFile`/`uploadFile`;不能凭符号猜接入。视频/文件/合并转发/卡片/表情的 +实际收发仍未实现,现有路径保持显式 `1404`,不假成功。下一步只读枚举 +`RichMediaService` 的公开方法名(有界前缀)或另找受证 native 路线,再决定是否 +实现;本会话不扩大猜测面。 + +### 2026-12-05 N6c RichMedia 方法名取证(找到上传入口候选) + +主根 PID `6548`(`2026-12-05T07:29:28.4753335Z`),`n6-media-methods-release` +只读 attach,零发送。`media_capabilities` 方法名(有界)显示: + +- `RichMediaService` 有 `uploadRMFileWithoutMsg`(native 断言 `argc==1`)、 + `downloadFile*`、`getGroupFile*`、`getRichMediaFileDir`、`getVideoPlayUrl*`、 + `getPttTmpPath` 等; +- `MsgService` 有 `sendMsg`、`getMsgs*`、`getOnlineFileMsgs` 等,但没有 + `sendFile`/`uploadFile`;此前按猜测名字探测均为 false。 + +结论:文件/视频的可疑上传入口是 `RichMediaService.uploadRMFileWithoutMsg`, +但只有 1 个参数、参数 schema 未取证;不调用、不猜字段。视频/文件/转发/卡片/ +表情实际收发继续保持显式 `1404`。下一步用固定参考或受控参数形状取证该方法的 +输入合同,再决定是否实现。 + +### 2026-12-05 N6c 上传入口参考合同(未调用) + +固定研究库 `packages/snowcat-core/services/NodeIKernelRichMediaService.ts:269` +给出 `uploadRMFileWithoutMsg` 的 TypeScript 形状: + +```ts +{ + bizType: RMBizTypeEnum, + filePath: string, + peerUid: string, + transferId: string, + useNTV2: string +} +``` + +`RMBizTypeEnum` 前序值: `KC2CFILE=1`、`KGROUPFILE=2`、`KC2CPIC=3`、 +`KGROUPPIC=4`、`KC2CVIDEO=6`、`KGROUPVIDEO=7`、`KC2CPTT=8`、`KGROUPPTT=9`。 +该参考也带有直接 OIDB `0x11E9` 的 NTV2 视频上传实现,但与本轮 wrapper 方法 +不是同一调用路径。 + +本项仍未调用:`transferId`/`useNTV2` 的取值和返回结构没有现场证据; +文件/视频实际发送继续显式 `1404`。下一步只能做一次受控的本地上传探针, +或按固定参考实现 OIDB NTV2 上传,不能把参考签名当作已验收。 + +### 2026-12-05 N6c 受控上传探针(无结果) + +用户重启后主根 PID `47056`(`2026-12-05T07:37:26.3928683Z`), +`n6-upload-probe-release` 只读 attach,一次 `uploadRMFileWithoutMsg`: + +```text +file=probe.txt (38 bytes), bizType=1, peer=B friend, +transferId=random, useNTV2="1" +returned=undefined +``` + +调用没有抛出异常,也没有返回 Promise;结果文件只有 +`{"label":"returned"}`。没有消息发送、没有断线;daemon 正常停止、bridge 保留。 +这既不是上传成功,也不是明确拒绝:该构建下方法可能是回调/监听式, +当前没有拿到上传结果或文件 ID。 + +临时探针代码已回退,正常源码树不含该调用。下一步需捕获 +`RichMediaService` 的上传监听回调,或改走固定参考的 OIDB `0x11E9` NTV2 上传; +在拿到文件 ID/失败码前,文件/视频发送继续保持显式 `1404`。 + +### 2026-12-05 N6c OIDB NTV2 传输阻塞 + +用户重启后主根分别 `37900`、`43480`、`34096`、`40756`、`45064`、`44164`、`4168`; +只读 attach,零消息发送;每次正常停止、bridge 保留。 + +结果: + +- 手搓 `OidbSvcTrpcTcpBase` + `NTV2RichMediaReq`(文件 `0x11E9`、图片 `0x11C5`) + 均返回 `result=145`、`errMsg=请求包解析失败`; +- 改用 `NodeQQNTWrapperUtil.getSsoBufferOfOidbReq` 后,返回 721/722 字节 + `Uint8Array`,外层不是 `OidbSvcTrpcTcpBase`; +- 该 payload 以 Buffer/Uint8Array、base64、hex 传给 + `sendSsoCmdReqByContend` 均仍是 `145`。 + +结论:`sendSsoCmdReqByContend` 不是这条 OIDB 请求的正确传输/封装入口; +继续猜编码没有证据价值。临时探针代码已回退,正常源码树不含这些调用。 + +下一步需按固定参考实现 native `sendPacket` hook(`napi2native`)或找到 +`getSsoCmdOfOidbReq` 对应的发送 API;在拿到 `uKey`/失败码前,文件/视频/转发/ +卡片/表情继续保持显式 `1404`。 + +### 2026-12-05 N6c 收口决策:放弃 native SSO + +用户决定放弃原生 SSO/OIDB 上传,保留已验的 wrapper 路径: + +- 图片/语音继续走已验的 wrapper 发送与下载; +- 文件、视频、合并转发、卡片、表情不在本代次实现,统一显式 `1404`; +- 不把 `uploadRMFileWithoutMsg` 的 undefined、OIDB 的 `145` 或未加载的 native hook + 当作上传成功; +- 临时 SSO 探针已回退,源码树不含这些调用。 + +因此 N6c 的“图片/语音之外的媒体”仍不支持,但满足“不支持能力显式拒绝、不丢段假成功”; +feat-008 保持 `in-progress`,不把未验项外推为已完成。 + +### 2026-12-05 N6c 出站语音转码(WAV/OGG→SILK,离线通过) + +新增可选 `silk_encoder` 与 `wav-silk`/`ogg-silk`: + +- FFmpeg 将输入解码为 24 kHz 单声道 s16le PCM; +- `rust-silk encode ... --tencent` 输出腾讯 SILK v3; +- 输出再次校验 `#!SILK_V3` 与大小。 + +真实工具(固定 rust-silk `06b2db...`、FFmpeg `1326dd...`)实测: + +- `caligo-silk-wav-...wav` → 470 B SILK; +- `caligo-silk-ogg-...ogg` → 581 B SILK; +- 两者均以 `\x02#!SILK_V3` 开头,任务目录清理。 + +`media_tool_lab` 8 通过 / 1 ignored;新增 fake encoder 合同覆盖 +缺配置、真实命令参数、hash 变坏。该结果只证明本地转码,不证明 QQ 自动 +发送 WAV/OGG;发送仍要求外部先产出 SILK Base64。 diff --git a/docs/guides/media-tools.md b/docs/guides/media-tools.md index 915db55c..c3487ab6 100644 --- a/docs/guides/media-tools.md +++ b/docs/guides/media-tools.md @@ -11,6 +11,7 @@ - `pcm_to_container`:将上述 PCM 输出为固定枚举 `wav` 或 `ogg`。 - `thumbnail`:在固定 1 秒位置输出固定枚举 `png`,不造默认 `100x100` 或 `60 seconds` 降级结果。 - `silk-wav` / `silk-ogg`:通过可选的 `silk_decoder` 将 SILK v3(含腾讯前缀)解码为 24 kHz 单声道 s16le PCM,再交给现有容器转换。 +- `wav-silk` / `ogg-silk`:先用 `ffmpeg` 将 WAV/OGG 等输入解码为 24 kHz 单声道 s16le PCM,再通过可选的 `silk_encoder` 编码为腾讯 SILK v3。 ## 配置合同 @@ -23,7 +24,7 @@ - `work_root`:绝对路径。每个任务创建独立目录,任务结束自动 cleanup。 - `timeout_ms`、`max_stdout_stderr_bytes`、`max_input_bytes`、`max_output_bytes`:均必须为正数。 -可选的 `silk_decoder` 与 FFmpeg 工具使用相同的路径、SHA-256、版本和许可证声明。解码器接口为 `--version` 和 `decode -i --sample-rate 24000 -o `。离线验证使用 [rust-silk 固定提交](https://github.com/wangnov/rust-silk/tree/7d4fd9eb265ac44b6d76bda4002d327651a022c0)。Caligo 通过独立子进程调用它。 +可选的 `silk_decoder` / `silk_encoder` 与 FFmpeg 工具使用相同的路径、SHA-256、版本和许可证声明。解码器接口为 `--version` 和 `decode -i --sample-rate 24000 -o `;编码器为 `--version` 和 `encode -i --sample-rate 24000 --tencent -o `。离线验证使用 [rust-silk 固定提交](https://github.com/wangnov/rust-silk/tree/7d4fd9eb265ac44b6d76bda4002d327651a022c0)。Caligo 通过独立子进程调用它。 工具参数由 Rust `Command` 直接传递,不经过 shell。输入必须是绝对路径指向本地 regular file,不能是目录或符号链接;只检查 basename 存在,不把不受信 basename 拼进命令行选项。输出文件会再次进行 regular-file、大小和固定 magic 校验。 @@ -43,9 +44,11 @@ caligo.exe media --config pcm --input --output-r caligo.exe media --config thumbnail --input --output-root caligo.exe media --config silk-wav --input --output-root caligo.exe media --config silk-ogg --input --output-root +caligo.exe media --config wav-silk --input --output-root +caligo.exe media --config ogg-silk --input --output-root ``` -配置文件本身不执行下载或安装。CLI 转码使用显式配置的解码器,QQ 下载和上传的验收另见执行记录。 +配置文件本身不执行下载或安装。CLI 转码使用显式配置的解码器/编码器,QQ 下载和上传的验收另见执行记录。`wav-silk`/`ogg-silk` 只产出本地 SILK v3 文件,不自动发送;发送仍走已验的 `record` Base64 路径。 单账号 `caligo.exe daemon --media-config ` 可加载同一配置。`work_root` 必须是当前用户专用目录,其父目录须已存在。多账号 `caligo.exe manager` 从各账号私有目录读取可选的 `voice-media.json`,把工作目录固定到该账号的 `media-jobs`。工具配置由本机文件提供。 diff --git a/feature_list.json b/feature_list.json index 46196882..06d26efe 100644 --- a/feature_list.json +++ b/feature_list.json @@ -1,8 +1,8 @@ { "$schema": "https://raw.githubusercontent.com/walkinglabs/learn-harness-engineering/main/skills/harness-creator/templates/feature-list.schema.json", - "updated": "2026-11-25", + "updated": "2026-12-05", "baseline_commit": "0f5b483", - "active_feature": "feat-007", + "active_feature": "feat-008", "status_basis": "产品 status 反映完成门,implemented/wired/lab/field 分开描述。历史执行台账是证据,状态更新不能替代现场验收。", "features": [ { @@ -121,8 +121,8 @@ "plan_steps": ["N6a", "N6b", "N6c"], "dependencies": ["feat-006"], "status": "in-progress", - "evidence": "N 台账(三十九)保留 legacy-path @ 1006501/无 ack 结果。2026-11-13 SnowCat A2 已接入固定 profile 的私聊语音收发和合成宿主验证。普通 PNG 的固定 profile 精确回读及有界下载已接 scoped Rust 宿主查询,合成宿主/管道覆盖身份、文件完整性和迟到回调;普通入站 PNG 已接 D8、持久 ID、共享事件和 get_image,真实管道及重启恢复通过;PNG 私聊/群聊发送已接独立 scoped 能力、HostOp/IPC/core/共享 OneBot,精确自发回读持久化后返回 ID,真实 worker/管道、拒绝/撤销/重连不重发及重启读取有离线覆盖;其他格式及真实 QQ 待验收。 2026-11-14 私聊 PNG FIELD 未通过:用户确认原图在接收 QQ 的采集窗口内可见,但 Caligo SSE 与持久消息记录缺失,未产生 get_msg/get_image 样本。已准备有界字段形状诊断,不放宽接收合同;待新代次取证与复验,状态保持 in-progress。 新 A 46312 的单次私聊 PNG 已通过 SSE、持久入账和现场 get_msg,图片元数据匹配原图;get_image 返回 1501 宿主查询超时,未取得字节。已补有界下载阶段诊断,完整媒体 FIELD 仍未通过,上一缺失样本原因仍 unknown。 A 20292 现场确认零错误下载 callback 在 deadline 内因目标路径不同被忽略;官方缓存文件 SHA-256 匹配原图,但 callback 实际路径未采集。已用回归复现并适配派发前由 host API 登记的精确缓存路径,保留完整性/寿命/拒绝边界,现场 get_image 仍待新构建复验。 新 A 44108 已通过正常私聊 PNG 的 SSE、持久消息及 HTTP get_msg/get_image,18,569 bytes 与单次原图逐字节和 SHA-256 一致,登记缓存路径 callback/文件验证通过。daemon/owner/HTTP/SSE 正常关闭。该单样本不覆盖群图片、主动图片发送、其他格式或长期资源恢复,整体仍 in-progress。 A 47904 的登记群单 PNG 已通过 SSE、持久入账、HTTP get_msg/get_image,群目标与登记一致,18,569 bytes 与原图逐字节/SHA-256 相同,正常停止通过。结合私聊,两种普通 PNG 入站各有 FIELD 样本;主动 PNG、其他媒体及恢复仍待验,status 保持 in-progress。 A 12100 单次主动私聊 PNG 的 send_private_msg、持久 ID/get_msg、账本 B 目标与对端可见性 FIELD 通过;后续 get_image 1501,零错误 callback 仅 chatType 比较失败,完整下载闭环未通过。已补固定分类诊断并通过定向 LAB,不放宽校验;下一块只读查询已发消息,不重发,status 不提升。 A 43644 只读诊断确认自发私聊 PNG 下载 callback 的 chatType 为 null,get_image 仍 1501,零发送且正常停止。已离线复现并限定精确 pilot/自发 private/picType=1000/预登记缓存路径的 null 适配,其他校验与寿命保留,定向修复通过;新构建现场待验,状态保持 in-progress。 新 A 52752 的只读 get_msg/get_image FIELD 通过,已发送私聊 PNG 返回 18,569 bytes,与原发送图逐字节/SHA-256 相同,null 回调限定适配 validated。本轮零发送,前轮 B 可见性与本轮下载构成跨代次证据;登记群主动 PNG 及其他媒体/恢复仍待验,status 保持 in-progress。 A 46612 的登记群单次主动 PNG send_group_msg、持久 get_msg、账本目标和 B 可见性 FIELD 通过;get_image 1501,匹配 callback 的 chatType=null。已离线复现并把精确 pilot 自发默认 PNG/预登记缓存的 null 分支限定扩展到 group,定向群正反回归通过;新构建只读下载现场仍待验,不重发,status 保持 in-progress。 新 A 48692 的已发送群 PNG get_msg/get_image FIELD 通过,18,615 bytes 与原发送图逐字节/SHA-256 一致,null callback validated,零发送且正常停止。结合原发送/B 可见性为跨代次证据,普通私聊/群 PNG 两方向各有对应现场样本;其他媒体/资源寿命/恢复仍待验。下一块仅准备普通私聊语音入站与原始 SILK,未启动,status 保持 in-progress。 A 32064 普通私聊语音首轮准入、LoginInfo/SSE 通过,采集到期无样本,用户确认 B 未发送;账本无指定私聊消息,未执行 get_msg/get_record,正常停止且保留 bridge。新一轮已准备,待 A 重启并重新准入,不判语音成功或失败,status 仍 in-progress。 新 A 51352 的普通私聊语音入站 SSE、持久账本及 HTTP get_msg FIELD 通过,用户确认 B 单次发送及 A 播放内容相符。get_record 客户端写入以 WinError 10053 中断,无 HTTP 响应、无下载字节,宿主派发未证;正常停止且保留 bridge,未自动重试。下一轮只读原已收语音,待新 A,不重发。status 仍 in-progress。 A 40204 只读同一条已收语音,HTTP get_msg 200 / 0,get_record curl exit 0 / HTTP 200 / 1501 宿主查询超时,未取得 SILK;零发送、不重试、正常停止保留 bridge。下载缺口待语音阶段取证,status 仍 in-progress。 固定 9.9.36-53644 的语音下载阶段诊断已通过定向与全仓离线测试。隔离 release 和原录音只读脚本已准备,等待新 A 准入采证。 A 53180 的现场诊断捕获同消息同元素的零错误回调,chatType=null 且路径不匹配,get_record 返回 1501。精确 pilot 的私聊入站语音缓存适配已离线验证,待新 A 用原样本复查下载,status 仍 in-progress。 A 11908 用修复版只读复验,get_msg/get_record HTTP 200 / OneBot 0,匹配已登记缓存回调,7344 字节通过数量、MD5、SILK 头校验。普通私聊入站与原始 SILK 已有现场证据,主动发送、群语音与转码待验,status 仍 in-progress。 A 53416 经正常 OneBot HTTP 向登记 B 单次主动私聊发送 2,584 字节 SILK,发送、持久 get_msg、账本目标和 MD5 匹配,用户确认 B 收到一次并播放出三个上行提示音。已发送语音的原始 SILK 下载、群语音和转码待验。 A 10044 只读复查自发私聊语音,get_msg 成功,get_record 1501。零错误回调匹配消息和元素,但空会话类型与未登记路径导致超时。成功自发私聊的同账号 .silk 缓存适配通过定向 LAB,待新 A 现场复验。 A 33668 使用修复版只读复验原消息,get_msg/get_record 均 HTTP 200 / OneBot 0,缓存回调匹配,返回 2,584 字节与发送样本逐字节和 SHA-256 一致。群语音与转码待验。 登记群 B → A 单次语音的 SSE、账本、get_msg 和 A 播放通过。修复固定版本入站群缓存回调后,新 A 54700 只读取得 7,294 字节 SILK,长度、MD5 和缓存 SHA-256 核对通过。群主动发送、群自发下载和转码待验。 主动群语音的本机现场记录已复核:A 38620 单次 send_group_msg/get_msg HTTP 200 / 0,持久 ID、唯一账本记录、登记群和 2,575 字节 SILK 元数据一致,正常停止且保留 bridge。用户确认 B 收到一条,播放为三个依次降低的提示音,主动群语音发送/播放 FIELD 通过。新 A 38428 只读原群语音 get_msg 通过、get_record 1501,匹配 callback 为空会话且缓存路径未登记;正常停止,零发送。已离线复现并扩展精确 pilot 成功自发群语音 .silk 缓存登记,wrapper 查询合同 7/7、default/research 全仓及隔离 release 通过,现场下载待新 A 和新构建复验,status 保持 in-progress。 新 A 38256 使用修复版只读原已发群语音,get_msg/get_record HTTP 200 / 0,预登记缓存回调 validated,2,575 字节与原发送样本逐字节、MD5 和 SHA-256 相同,正常停止且保留 bridge。本轮零发送,结合前轮单次群发送及 B 播放构成跨代次 FIELD 证据;转码、其它媒体、资源寿命和恢复仍待验,status 保持 in-progress。 用户于 2026-11-14 要求收口第一阶段并提交 PR #6;本阶段普通单 PNG 与原始 SILK 的指定私聊/登记群双方向 FIELD 证据归档,转码、其它消息段/媒体、资源寿命和恢复仍未验收,status 不提升。", - "evidence_paths": ["docs/execution/2026-10-09-snowluma-parity/ledger.md", "docs/plans/2026-10-09-gitnexus-plan-caligo-snowluma-capability-parity.md", "docs/execution/2026-11-13-snowcat-capability-integration-continued.md"], + "evidence": "N 台账(三十九)保留 legacy-path @ 1006501/无 ack 结果。2026-11-13 SnowCat A2 已接入固定 profile 的私聊语音收发和合成宿主验证。普通 PNG 的固定 profile 精确回读及有界下载已接 scoped Rust 宿主查询,合成宿主/管道覆盖身份、文件完整性和迟到回调;普通入站 PNG 已接 D8、持久 ID、共享事件和 get_image,真实管道及重启恢复通过;PNG 私聊/群聊发送已接独立 scoped 能力、HostOp/IPC/core/共享 OneBot,精确自发回读持久化后返回 ID,真实 worker/管道、拒绝/撤销/重连不重发及重启读取有离线覆盖;其他格式及真实 QQ 待验收。 2026-11-14 私聊 PNG FIELD 未通过:用户确认原图在接收 QQ 的采集窗口内可见,但 Caligo SSE 与持久消息记录缺失,未产生 get_msg/get_image 样本。已准备有界字段形状诊断,不放宽接收合同;待新代次取证与复验,状态保持 in-progress。 新 A 46312 的单次私聊 PNG 已通过 SSE、持久入账和现场 get_msg,图片元数据匹配原图;get_image 返回 1501 宿主查询超时,未取得字节。已补有界下载阶段诊断,完整媒体 FIELD 仍未通过,上一缺失样本原因仍 unknown。 A 20292 现场确认零错误下载 callback 在 deadline 内因目标路径不同被忽略;官方缓存文件 SHA-256 匹配原图,但 callback 实际路径未采集。已用回归复现并适配派发前由 host API 登记的精确缓存路径,保留完整性/寿命/拒绝边界,现场 get_image 仍待新构建复验。 新 A 44108 已通过正常私聊 PNG 的 SSE、持久消息及 HTTP get_msg/get_image,18,569 bytes 与单次原图逐字节和 SHA-256 一致,登记缓存路径 callback/文件验证通过。daemon/owner/HTTP/SSE 正常关闭。该单样本不覆盖群图片、主动图片发送、其他格式或长期资源恢复,整体仍 in-progress。 A 47904 的登记群单 PNG 已通过 SSE、持久入账、HTTP get_msg/get_image,群目标与登记一致,18,569 bytes 与原图逐字节/SHA-256 相同,正常停止通过。结合私聊,两种普通 PNG 入站各有 FIELD 样本;主动 PNG、其他媒体及恢复仍待验,status 保持 in-progress。 A 12100 单次主动私聊 PNG 的 send_private_msg、持久 ID/get_msg、账本 B 目标与对端可见性 FIELD 通过;后续 get_image 1501,零错误 callback 仅 chatType 比较失败,完整下载闭环未通过。已补固定分类诊断并通过定向 LAB,不放宽校验;下一块只读查询已发消息,不重发,status 不提升。 A 43644 只读诊断确认自发私聊 PNG 下载 callback 的 chatType 为 null,get_image 仍 1501,零发送且正常停止。已离线复现并限定精确 pilot/自发 private/picType=1000/预登记缓存路径的 null 适配,其他校验与寿命保留,定向修复通过;新构建现场待验,状态保持 in-progress。 新 A 52752 的只读 get_msg/get_image FIELD 通过,已发送私聊 PNG 返回 18,569 bytes,与原发送图逐字节/SHA-256 相同,null 回调限定适配 validated。本轮零发送,前轮 B 可见性与本轮下载构成跨代次证据;登记群主动 PNG 及其他媒体/恢复仍待验,status 保持 in-progress。 A 46612 的登记群单次主动 PNG send_group_msg、持久 get_msg、账本目标和 B 可见性 FIELD 通过;get_image 1501,匹配 callback 的 chatType=null。已离线复现并把精确 pilot 自发默认 PNG/预登记缓存的 null 分支限定扩展到 group,定向群正反回归通过;新构建只读下载现场仍待验,不重发,status 保持 in-progress。 新 A 48692 的已发送群 PNG get_msg/get_image FIELD 通过,18,615 bytes 与原发送图逐字节/SHA-256 一致,null callback validated,零发送且正常停止。结合原发送/B 可见性为跨代次证据,普通私聊/群 PNG 两方向各有对应现场样本;其他媒体/资源寿命/恢复仍待验。下一块仅准备普通私聊语音入站与原始 SILK,未启动,status 保持 in-progress。 A 32064 普通私聊语音首轮准入、LoginInfo/SSE 通过,采集到期无样本,用户确认 B 未发送;账本无指定私聊消息,未执行 get_msg/get_record,正常停止且保留 bridge。新一轮已准备,待 A 重启并重新准入,不判语音成功或失败,status 仍 in-progress。 新 A 51352 的普通私聊语音入站 SSE、持久账本及 HTTP get_msg FIELD 通过,用户确认 B 单次发送及 A 播放内容相符。get_record 客户端写入以 WinError 10053 中断,无 HTTP 响应、无下载字节,宿主派发未证;正常停止且保留 bridge,未自动重试。下一轮只读原已收语音,待新 A,不重发。status 仍 in-progress。 A 40204 只读同一条已收语音,HTTP get_msg 200 / 0,get_record curl exit 0 / HTTP 200 / 1501 宿主查询超时,未取得 SILK;零发送、不重试、正常停止保留 bridge。下载缺口待语音阶段取证,status 仍 in-progress。 固定 9.9.36-53644 的语音下载阶段诊断已通过定向与全仓离线测试。隔离 release 和原录音只读脚本已准备,等待新 A 准入采证。 A 53180 的现场诊断捕获同消息同元素的零错误回调,chatType=null 且路径不匹配,get_record 返回 1501。精确 pilot 的私聊入站语音缓存适配已离线验证,待新 A 用原样本复查下载,status 仍 in-progress。 A 11908 用修复版只读复验,get_msg/get_record HTTP 200 / OneBot 0,匹配已登记缓存回调,7344 字节通过数量、MD5、SILK 头校验。普通私聊入站与原始 SILK 已有现场证据,主动发送、群语音与转码待验,status 仍 in-progress。 A 53416 经正常 OneBot HTTP 向登记 B 单次主动私聊发送 2,584 字节 SILK,发送、持久 get_msg、账本目标和 MD5 匹配,用户确认 B 收到一次并播放出三个上行提示音。已发送语音的原始 SILK 下载、群语音和转码待验。 A 10044 只读复查自发私聊语音,get_msg 成功,get_record 1501。零错误回调匹配消息和元素,但空会话类型与未登记路径导致超时。成功自发私聊的同账号 .silk 缓存适配通过定向 LAB,待新 A 现场复验。 A 33668 使用修复版只读复验原消息,get_msg/get_record 均 HTTP 200 / OneBot 0,缓存回调匹配,返回 2,584 字节与发送样本逐字节和 SHA-256 一致。群语音与转码待验。 登记群 B → A 单次语音的 SSE、账本、get_msg 和 A 播放通过。修复固定版本入站群缓存回调后,新 A 54700 只读取得 7,294 字节 SILK,长度、MD5 和缓存 SHA-256 核对通过。群主动发送、群自发下载和转码待验。 主动群语音的本机现场记录已复核:A 38620 单次 send_group_msg/get_msg HTTP 200 / 0,持久 ID、唯一账本记录、登记群和 2,575 字节 SILK 元数据一致,正常停止且保留 bridge。用户确认 B 收到一条,播放为三个依次降低的提示音,主动群语音发送/播放 FIELD 通过。新 A 38428 只读原群语音 get_msg 通过、get_record 1501,匹配 callback 为空会话且缓存路径未登记;正常停止,零发送。已离线复现并扩展精确 pilot 成功自发群语音 .silk 缓存登记,wrapper 查询合同 7/7、default/research 全仓及隔离 release 通过,现场下载待新 A 和新构建复验,status 保持 in-progress。 新 A 38256 使用修复版只读原已发群语音,get_msg/get_record HTTP 200 / 0,预登记缓存回调 validated,2,575 字节与原发送样本逐字节、MD5 和 SHA-256 相同,正常停止且保留 bridge。本轮零发送,结合前轮单次群发送及 B 播放构成跨代次 FIELD 证据;转码、其它媒体、资源寿命和恢复仍待验,status 保持 in-progress。 用户于 2026-11-14 要求收口第一阶段并提交 PR #6;本阶段普通单 PNG 与原始 SILK 的指定私聊/登记群双方向 FIELD 证据归档,转码、其它消息段/媒体、资源寿命和恢复仍未验收,status 不提升。 2026-11-29 为 issue #17 第 1 条新增 N6a @/reply 只读形状取证:D8 在拒绝非零 at/reply 元素前记录有界形状(元素类型、atType 与 atUid/atNtUid/atTinyId 形态、replyElement 已知字段形态),经白名单 sanitizer 写入 receive_segment_shape 阶段报告;新增 scripts/n6 取证包(复用 N5 准入与常驻 harness,Caligo 零发送)与 probe-summary。离线定向测试与全仓 default 512 / research 572(各 69 个测试二进制、0 failed)通过;2026-11-29 现场尝试一次(PID 25344):preflight/attach/listener_armed 通过、Caligo 零发送,捕获 7 条 receive_segment_shape(5 个唯一形状,atType=2、reply elementType=7/17 键),journal 18 Event 无缺口、停止 exit 0、bridge 保留;但 get_login_info 1502、身份未确认且群流量非受控,形状只算真实观察、不算受控证据,现场未完成受控复验;不提升 status。 2026-11-30 受控复验:用户重启后 PID 39552,preflight PASS、attach 4.45s、login_ok=true;360s 窗口 version/status 72/72、login 36/36(Stella/1694717255),Caligo 零发送;18 条形状报告、10 个唯一形状:at `[1]`/`atType=2`/`atUid` 十进制/`atNtUid` uid/`atTinyId` 十进制,reply `[7,1]`/`elementType=7`/`replayMsgId`、`replayMsgSeq` 十进制/`sourceMsgText` 空/17 键,另有 `[7,1,6]`、`[6]`、`[8]`、`[10]`、`[16]`。用户确认已发两条,但群流量使逐条归因未证;两次窗口形状一致,可作实现输入,不作能力验收。journal 51 Event 无缺口、停止 exit 0、bridge 保留;`soak.overall=fail` 仅因未安排 core 重启;PID 39552 已消耗、不得重接,status 仍 in-progress。 2026-11-30 入站 @/reply 保留与渲染(离线):D8 接受 `atType` 1/2 文本元素与 `elementType=7` reply,其它形状仍显式拒绝;模型新增有序 `WrapperSegment`/`plain_text`;message_store 纯文本仍存字符串,mention/reply 存 OneBot 段数组(at.qq=atUid,mention 显示名去重,reply id 暂用原生 replayMsgId),events 与 get_msg 共用段构造;新增 D8/模型/store/事件回归;全仓 default 517 / research 577(各 69 个测试二进制、0 failed)通过。出站 @/reply 发送与回执、reply 本地 message_id 映射、真实客户端显示仍未验收;本轮未重建 release(PID 39552 仍映射旧 bridge,DLL 被锁),下一次现场前需重启 QQ 后重构建。 2026-11-30 入站现场准入阻塞:新主根 PID 45948 的只读 envscan 被 OpenProcess 拒绝(Win32 error 5),未 attach/发送;新 release 构建到 target-n6(EXE 83CF1A64…D989、bridge A3A1F473…4247),N5/N6 preflight 增加可选 -TargetDir;需非管理员重启后重新准入。 2026-11-30 入站现场(部分通过):新主根 PID 37044,因 target-n6 沙箱 ACL 无法写 journal/OpenProcess,改用 target-harness/n6-release 后 preflight PASS;360s 窗口 login 确认、Caligo 零发送、25 Event 无缺口、停止 exit 0;MessageStore 落盘 1 条 at 消息(ID 5),reply 未落盘(真实 reply 元素的 textElement 被旧 D8 拒绝,用户未发送受控两条)。已放宽 D8/模型接受 reply 的 textElement(无 mention;段顺序 reply→text),新增回归,最终 default 517 / research 577 通过;入站 reply 仍需新代次现场复验。 reply-text 修复后的 release 在 target-harness/n6-release2(EXE CF2EAA1C…FC4E、bridge 8B7EB2D5…E3F2)。 2026-12-05 出站 @/reply 离线接线:新增有序 SendSegment/ReplyReference、本地 message_id→原生引用解析与入站 reply id 本地映射;新增 pilot-only GroupMemberUid 查询和 private_reply/group_reply/group_mention 能力;DispatchRich→HostOp::SendRich→qq_rich_send.js 按固定参考 7cf025f 构造群 @(atType=2、atUid=QQ、atNtUid=目标 UID、正文 @显示名)与 reply(replayMsgId/Seq、senderUin、可选 clientSeq、_replyMsgPeer)元素,回执继续要求 add/update 精确匹配和 getMsgsByMsgId 逐元素回读,不匹配即 unknown。未知段/私聊 @/未知或跨会话回复显式 1404/1400;未构建 release、未真实发送;离线全仓 default 525 / research 585 通过。 2026-12-05 第一代次现场:测试主根 PID 39072(2026-12-05T01:55:42.5080385Z,Stella/1694717255)预检 PASS、attach 3.1s、login_ok;普通群文本返回 message_id 4,store 含 native seq/client/peer;reply 到 4 返回 1400(Daemon/AccountActor 未委托 reply_reference);群 @ 3089665724 返回 1501 但 native 消息已落 message_id 6 且 at 段正确,根因是自发消息以 source=recv 进入 D8 而关联只处理 add_send/update。已修复两处并新增 recv+update 回归;修复 release target-harness/n6-rich-release2(EXE 9F8F6D93…7773、bridge 688B6A62…401F)。窗口结束 daemon exit 0、bridge retained、QQ responsive;未取得成功 reply/@ 回执或渲染,需新主根复验。 2026-12-05 第二代次:主根 PID 36004(2026-12-05T02:10:26.6217672Z,Stella/1694717255),n6-rich-release2 预检 PASS、attach 5.52s、login_ok;普通群文本返回 message_id 1;reply 到 1 的 native 消息已落 message_id 2(reply.id=1+text),@ 3089665724 的 native 消息已落 message_id 4(at 段正确),但两者 HTTP 30s 后仍 1501。reply_reference 委托与自发 recv 关联已生效;根因最可能是 native sendMsg 在异步回调前消费/改写调用方 elements 数组,而 pending.rich 保存同一引用,导致逐元素匹配失败。已改为提交前保存 owned 副本并新增 sendMsg 清空数组回归;修复 release target-harness/n6-rich-release3(EXE F239E386…5DB0、bridge 51A27B48…92D6)。默认 525 / research 585 通过;窗口结束 daemon exit 0、bridge retained、QQ responsive,无重发;feat-008 保持 in-progress。 2026-12-05 第三代次:主根 PID 26272(2026-12-05T02:27:18.7954742Z,Stella/1694717255),n6-rich-release4 预检 PASS、attach 4.01s、login_ok;普通群文本 message_id 3 成功;reply 与 @ 的 native 消息均已发出/落库但 HTTP 1501,ReceiptAudit 分别为 rich_at_uid 与 rich_text_content。根因:atType=0 文本的空提及字段在 native 回调为 \"0\"/null 而发送前副本为 \"\";native 把提及显示名改写为群名片(发送前 @〈Ain〉、回调 @EW-Vegetable)。匹配器已改为 atType=0 将 \"\"/null/\"0\" 视为空并只比正文;atType 2/1 以 atUid/atNtUid 识别目标、不比较显示正文;新增回调 @card/atUid=\"0\" 回归。修复 release target-harness/n6-rich-release5(EXE 000D00C1…E97C、bridge EB02C74E…1DE6)。桥接/媒体/wrapper 回归通过;需第四代次确认回执闭环。 2026-12-05 第四代次(回执闭环通过):主根 PID 38008(2026-12-05T02:33:09.2195771Z,Stella/1694717255),n6-rich-release5 预检 PASS、attach 3.22s、login_ok;群 plain→2、群 reply 到 2→5(reply.id=2)、群 @ 3089665724→7(at.qq=3089665724)、私聊 plain→12、私聊 reply 到 12→14(reply.id=12)全部 HTTP ok/0;三个 rich 请求均 ConfirmedSuccess(native 7789859958943379388/7789860001604659363/7715643075597885711),get_msg 段与目标一致,store 含 native seq/client/peer。用户确认同一元素构造渲染正确。daemon exit 0、bridge retained、QQ responsive;soak.overall=fail 仅因未安排 core 重启。本轮闭合 issue #17 第 1 条在本测试范围内的目标/回执/渲染;他发 reply、重启引用、@all/权限、其他媒体与寿命仍待验,feat-008 保持 in-progress。 2026-12-05 第五代次剩余矩阵:主根 PID 26044(2026-12-05T03:09:33.2217510Z,Stella/1694717255),release5 预检 PASS、attach 3.26s、login_ok;自然入站消息 1(群 950238216)reply→2;core 重启 recovered、journal prefix 保留、bridge 查询恢复;重启后回复入站 1→30、回复自发 30→32;跨会话 reply→1400;@ 非群成员→1440 零 native;video/face/file→1404 无新增自发消息;@all native 已发出但 HTTP 1501,D8 因 atType=1 形状整条拒绝。已修复 D8/模型/匹配器的 @all 处理(规范化 atUid/atNtUid=\"all\"、atType=1 只按类型匹配)并新增回归;修复 release target-harness/n6-rich-release6(EXE A4A4D8F4…265E、bridge 1A0DB216…F8FE6),默认 526 / research 586 通过。soak overall=pass、daemon exit 0、bridge retained、QQ responsive;@all 仍需新主根现场确认回执,feat-008 保持 in-progress。 2026-12-05 第六代次 @all 权限现场(通过):用户指定群 1074455954(bot 为该群 admin),主根 PID 8260(2026-12-05T03:36:41.8686415Z,Stella/1694717255),n6-rich-release6 预检 PASS、attach 5.34s、login_ok;@all HTTP ok/0、message_id 1,ConfirmedSuccess native 7789876034635047966,get_msg 为 at.qq=\"all\"+text,store 含 native seq/client/peer;daemon exit 0、bridge retained、QQ responsive。至此本轮 @/reply 矩阵覆盖自发/他发、群/私聊、重启后 reply、普通成员 @、admin 群 @all,以及跨会话 1400、非成员 1440、video/face/file 1404 的显式拒绝;实际渲染用户确认。仍未验收:视频/文件等媒体的实际上传/发送/资源寿命、语音转码与更广构建矩阵,feat-008 保持 in-progress。 2026-12-05 N6c 决策:放弃 native SSO/OIDB 上传(0x11E9/0x11C5 均 145,sendSsoCmdReqByContend 封装不可证;native hook 缺 52230 的 STRING_FILL/SSO 返回点),保留已验 wrapper 图片/语音路径;文件/视频/转发/卡片/表情继续显式 1404,不假成功。", + "evidence_paths": ["docs/execution/2026-10-09-snowluma-parity/ledger.md", "docs/plans/2026-10-09-gitnexus-plan-caligo-snowluma-capability-parity.md", "docs/execution/2026-11-13-snowcat-capability-integration-continued.md", "crates/caligo-bridge/src/qq_rich_send.js", "crates/caligo-bridge/tests/wrapper_rich_send.rs", "crates/caligo-core/src/message_store.rs"], "done_criteria": ["@/reply 目标正确、真实渲染且回执关联", "媒体上传/发送/资源寿命分别验收", "每项不支持能力显式拒绝,不丢段假成功"] }, { diff --git a/progress.md b/progress.md index 75e2d410..5bd2b021 100644 --- a/progress.md +++ b/progress.md @@ -2,6 +2,54 @@ ## Current State +2026-12-05 feat-008 N6c 出站语音转码:新增可选 `silk_encoder` 与 `wav-silk`/`ogg-silk`;真实 rust-silk/FFmpeg 将 187 KB WAV 编为 470 B SILK、14 KB OGG 编为 581 B SILK,均腾讯头;`media_tool_lab` 8 通过/1 ignored。仅本地转码,QQ 自动发送仍走 SILK Base64。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 收口:放弃 native SSO/OIDB 上传,保留已验 wrapper 图片/语音路径;文件/视频/转发/卡片/表情统一显式 1404,不假成功。临时探针已回退,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c OIDB NTV2 传输阻塞:0x11E9/0x11C5 手搓包和 `getSsoBufferOfOidbReq` 的 Uint8Array 以 Buffer/base64/hex 交给 `sendSsoCmdReqByContend` 均为 145「请求包解析失败」。临时探针已回退;下一步需 native sendPacket hook,文件/视频仍显式 1404。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 受控上传探针:`uploadRMFileWithoutMsg({bizType:1,filePath:probe.txt,peerUid:B,transferId:random,useNTV2:"1"})` 返回 `undefined`,无 Promise、无消息、无异常;上传结果未取证(非成功/非明确拒绝)。临时探针已回退,文件/视频继续显式 1404。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 上传入口参考合同:固定研究库给出 `uploadRMFileWithoutMsg({bizType,filePath,peerUid,transferId,useNTV2})` 与 `RMBizTypeEnum`(C2C/群 file=1/2,video=6/7,ptt=8/9)。未调用;取值和返回结构无现场证据,实际文件/视频发送仍为显式 1404。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c RichMedia 方法名取证:只读 attach 发现 `RichMediaService.uploadRMFileWithoutMsg`(argc==1)、downloadFile*/getGroupFile*/getVideoPlayUrl* 等;`MsgService` 无 sendFile/uploadFile。没有调用、没有猜参数;上传合同未取证,视频/文件/转发/卡片/表情保持显式 1404。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c native 上传能力只读取证:`session_rich_service=true`,但 `msg_send_file/msg_upload_file/rich_upload_file/rich_send_file/rich_get_path` 均为 false;当前 wrapper 未以这些名字暴露文件上传/发送,不能猜接入。视频/文件/转发/卡片/表情实际收发保持未实现+显式 1404。下一步只读枚举 RichMediaService 方法名或另找受证路线。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 能力矩阵:语音 SILK 收发与 `silk/wav/ogg` 转码现场通过;视频/文件入站显式拒绝(elementType 5/3,不入库),出站 `1404`;forward/json/face/video/file/markdown 等未知段新增回归,均 `1404` 且不文本回退。实际视频/文件/合并转发/卡片/表情需 native 上传/段协议取证,当前不猜接入。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 入站语音转码现场(通过):私有 media-config 加载后,入站 7,202 B 私聊语音回调 `.amr` 路径实际为 SILK;修正 PTT 路径登记与 canonical realpath 后,`get_record` 返回 `silk` 7,202 B(腾讯 SILK 头)、`wav` 187,278 B(RIFF/WAVE)、`ogg` 14,968 B(OggS),无重发/假成功;`wrapper_query_contract` 8/8。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 语音转码现场(部分):私有 media-config 已加载;回调路径已登记(absolute/normalized/md5/amr、under_ptt/registered=true),但 `get_record silk/wav/ogg` 仍 1440,回调阶段 `validation_failed`,无字节;尚未到达转码。下一步加 size/md5/header 有界输出形状,确认 .amr 缓存格式。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6b 图片上传/资源寿命首切片(离线+独立 daemon HTTP):新增 `upload_image`/`delete_image_upload`,资源按账号隔离、8 个/1 MiB/10 min TTL,send 的 image `file` 接受 `caligo-upload:...`;未知/过期/删除后显式 `1404`。独立 daemon 现场 upload→send(无会话 `1404`)→delete→send(`1404 上传资源不存在或已失效`)通过;`n6-upload-release` EXE `D0E7ACAA…1C60`、bridge `C53F7C51…A8A1`。真实 QQ 现场(PID 46820)上传成功但图片发送初报 native code 3;诊断为图片缓存父目录 realpath 差异,修复后 PID 3868 私聊 3089665724、PID 39120 群 629933025 均以 `caligo-upload` id 发送 4,592 B/320×160 PNG 成功(`message_id=3/2`,`get_msg` 图片段与 store native ID/md5/尺寸一致);私聊已确认视觉渲染,群渲染待确认;删除后同 id 返回 `1404`。`fileUuid` 已作为可选 `ImageInfo.file_uuid` 持久化,并在 `get_msg.image.data.file_id` 暴露;跨 QQ 重启后 `get_msg` 仍返回该 ID,但 `get_image` 同 token 返回 `1440 图片资源不可用或已失效`、无字节,说明旧 native 图片资源已不可取,`fileUuid` 不提供独立回源。bridge 语义读回失败映射为 404,core 图片查询 InvalidResponse 显式化为不可用;无假成功/重试。native 主动删除与有效期时长仍未取证;default 532 / research 592。提交 `cf353df`,PR #22 已更新;`feat-008` 保持 in-progress。 + +2026-12-05 feat-008 N6c 入站文件/视频显式拒绝与资源寿命边界:release7 现场分别观察到私聊 `elementType=3`(文件)与 `elementType=5`(视频)的 `receive_segment_shape`,两者均无 OneBot Event、无 MessageStore 记录、无假成功;窗口零 Caligo 发送,daemon exit 0、bridge retained、QQ responsive(`soak.overall=fail` 仅因未安排 core 重启)。资源寿命复验:跨 QQ 重启后持久 `get_msg` 可读,旧群图片 `get_image` 对 >128 KiB 返回 `1404`,33,744 B 样本返回 `1440` 且无字节;release7 仍未改变该条路径,说明原生消息已不可读而非空 `msgList`。已提交 `2307eec`(空读回显式 404 + 回归)、`592cdcd`/`79d7c45`(文件/视频现场记录),PR #22 已更新。视频/文件的实际发送、上传、转码与资源恢复仍未实现,`feat-008` 保持 `in-progress`。 + +2026-12-05 feat-008 N6a `@all` 权限现场(第六代次,通过):用户指定群 `1074455954`(bot 为该群 admin),主根 PID `8260`(`2026-12-05T03:36:41.8686415Z`,Stella/1694717255),`n6-rich-release6` 预检 PASS、attach 5.34s、login_ok;包 `local-evidence/feat008-n6-atall-20261205/`。`@all` HTTP `ok/0`、`message_id=1`,请求 `ConfirmedSuccess` native `7789876034635047966`,`get_msg` 为 `at.qq="all"` + text,store 含 native seq/client/peer;daemon exit 0、bridge retained、QQ responsive(soak.overall=fail 仅因未安排 core 重启)。至此本轮 @/reply 矩阵已覆盖自发/他发、群/私聊、重启后 reply、普通成员 @、admin 群 @all,以及跨会话 1400、非成员 1440、video/face/file 1404 的显式拒绝;实际渲染由用户确认。仍未验收:视频/文件等媒体的实际上传/发送/资源寿命、语音转码与更广构建矩阵;feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 剩余 @/reply 矩阵现场(第五代次):主根 PID `26044`(`2026-12-05T03:09:33.2217510Z`,Stella/1694717255),release5 预检 PASS、attach 3.26s、login_ok;包 `local-evidence/feat008-n6-matrix-20261205/`。自然入站消息 1(群 950238216)reply → message_id 2;core 重启 recovered、journal prefix 保留、bridge 查询恢复;重启后回复入站 1 → 30、回复自发 30 → 32;跨会话 reply → 1400;@ 非群成员 → 1440、零 native;video/face/file → 1404、无新增自发消息;`@all` native 已发出但 HTTP 1501,D8 因 `atType=1` 形状整条拒绝。已修复 D8/模型/匹配器的 @all 处理并新增回归;修复 release `target-harness/n6-rich-release6`(EXE A4A4D8F4…265E、bridge 1A0DB216…F8FE6),默认 526 / research 586 通过。soak overall=pass、daemon exit 0、bridge retained、QQ responsive;@all 仍需新主根现场确认回执,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第四代次现场(issue #17,回执闭环通过):主根 PID `38008`(`2026-12-05T02:33:09.2195771Z`,Stella/1694717255),`n6-rich-release5` 预检 PASS、attach 3.22s、login_ok;包 `local-evidence/feat008-n6a-outbound4-20261205/`。群 plain→2、群 reply 到 2→5(`reply.id=2`)、群 @ 3089665724→7(`at.qq=3089665724`)、私聊 plain→12、私聊 reply 到 12→14(`reply.id=12`)全部 HTTP `ok/0`;三个 rich 请求均 `ConfirmedSuccess`(native `7789859958943379388`/`7789860001604659363`/`7715643075597885711`),`get_msg` 段与目标一致,store 含 native seq/client/peer。用户确认同一元素构造的实际渲染正确。窗口结束 daemon exit 0、bridge retained、QQ responsive;`soak.overall=fail` 仅因未安排 core 重启。本轮闭合 issue #17 第 1 条在本测试范围内的目标/回执/渲染;他发 reply、重启引用、`@all`/权限、其他媒体与寿命仍待验,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第三代次现场(issue #17,诊断命中并修复):主根 PID `26272`(`2026-12-05T02:27:18.7954742Z`,Stella/1694717255),`n6-rich-release4` 预检 PASS、attach 4.01s、login_ok;包 `local-evidence/feat008-n6a-outbound3-20261205/`。普通群文本 message_id 3 成功;reply 与 @ 的 native 消息均已发出/落库,但 HTTP 1501,ReceiptAudit 分别给出 `rich_at_uid` 与 `rich_text_content`。根因:atType=0 文本的空提及字段在 native 回调为 `"0"`/null,而发送前副本为 `""`;native 会把提及显示名改写为群名片(发送前 `@〈Ain〉`、回调 `@EW-Vegetable`)。匹配器已改为:atType=0 将 `""`/null/`"0"` 视为空并只比正文;atType 2/1 以 atUid/atNtUid 识别目标、不比较显示正文。新增回调 `@card`/`atUid="0"` 回归。修复 release `target-harness/n6-rich-release5`(EXE 000D00C1…E97C、bridge EB02C74E…1DE6);桥接/媒体/wrapper 回归通过。窗口结束 daemon exit 0、bridge retained、QQ responsive,无重发;需第四代次新主根确认回执闭环,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第二代次现场(issue #17,回执仍未通过):用户重启后主根 PID `36004`(`2026-12-05T02:10:26.6217672Z`,Stella/1694717255),`n6-rich-release2` 预检 PASS、attach 5.52s、login_ok;包 `local-evidence/feat008-n6a-outbound2-20261205/`。普通群文本到 629933025 返回 message_id 1;reply 到 1 的 native 消息已落 message_id 2(reply.id=1+text),@ 3089665724 的 native 消息已落 message_id 4(at 段正确),但两者 HTTP 30s 后仍 1501。`reply_reference` 委托与自发 recv 关联已生效;根因最可能是 native `sendMsg` 在异步回调前消费/改写调用方 `elements` 数组,而 `pending.rich` 保存了同一引用,导致逐元素匹配失败。已改为提交前保存 owned 副本并新增“sendMsg 清空数组”回归;修复 release `target-harness/n6-rich-release3`(EXE F239E386…5DB0、bridge 51A27B48…92D6)。默认 525 / research 585 通过;窗口结束 daemon exit 0、bridge retained、QQ responsive,无重发。需第三代次新主根复验,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第一代次现场(issue #17,未通过但定位根因):用户打开测试主根 PID `39072`(`2026-12-05T01:55:42.5080385Z`,`Stella`/1694717255),`target-harness/n6-rich-release` 预检 PASS、attach 3.1s、login_ok;包 `local-evidence/feat008-n6a-outbound-20261205/`。普通群文本到 629933025 返回 `message_id=4`,store 含 native seq/client/peer;reply 到本地 4 返回 1400,根因是 `Daemon`/`AccountActor` 未委托 `reply_reference`;群 @ 到 3089665724 在 30s 返回 1501,但 native 消息已落 `message_id=6`(at 段正确),根因是自发消息先以 `source=recv` 进入 D8,而发送关联只处理 add_send/update。两处已离线修复:补 store 委托;自发 recv 只按 add 阶段关联(仍要求 selfUin/cookie/peer/元素匹配),新增 recv+update 回归。修复 release `target-harness/n6-rich-release2`(EXE 9F8F6D93…7773、bridge 688B6A62…401F)。soak 窗口结束 daemon exit 0、bridge retained、QQ responsive;无重发。第一代次未取得成功 @/reply 回执/渲染,feat-008 保持 in-progress,需新主根复验。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 离线接线(issue #17):新增有序 `SendSegment`/`ReplyReference`、本地 `message_id`→原生引用解析;入站 reply 目标已在同会话落库时映射为本地 `message_id`,否则保留原生 id;新增 pilot-only `GroupMemberUid` 查询与 `private_reply`/`group_reply`/`group_mention` 能力;`DispatchRich`→`HostOp::SendRich`→`qq_rich_send.js` 按固定参考 `7cf025f` 构造群 @(`atType=2`/`atUid=QQ`/`atNtUid=UID`)与 reply(`replayMsgId/Seq`、`senderUin`、可选 `clientSeq`、`_replyMsgPeer`)元素,回执仍要求 add/update 匹配与 `getMsgsByMsgId` 逐元素回读,不匹配即 unknown;未知段、私聊 @、未知/跨会话回复显式 1404/1400。全仓 default **525** / research **585** 通过;未构建 release、未真实发送/渲染/回执现场,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站 @/reply 现场(部分):用户非管理员重启后新主根 PID `37044`(创建 `2026-11-30T14:17:18.0019049Z`);`target-n6` 由沙箱创建后带 AppContainer/deny ACL,子进程写 journal 和 `OpenProcess` 均被拒,改用 `target-harness/n6-release` 后 preflight PASS。attach 5.94s、`login_ok=true`,360s 窗口 36 samples、version/status 72/72、login 36/36;Caligo 零发送;25 个 Event 无缺口,停止 exit 0、bridge 保留。MessageStore 落盘 1 条含 `at` 的消息(`message_id=5`),证明新 D8/模型/store 的入站 at 路径在真实 daemon 生效;reply 未落盘——当时 D8 仍拒绝带 `textElement` 的 reply 元素(真实 reply 元素的 `textElement` 存在),窗口内用户确认未发送两条受控消息。随后已放宽 D8/模型:reply 元素允许无 mention 的 `textElement`,段顺序为 reply 后跟其文本;新增 D8/模型回归。全仓 default **517** / research **577**(各 69 个测试二进制、0 failed)通过;reply-text 修复后的 release 在 `target-harness/n6-release2`(EXE `CF2EAA1C…FC4E`、bridge `8B7EB2D5…E3F2`)。入站 reply 仍需新代次现场复验,出站 @/reply 未实现;`feat-008` 仍 in-progress,issue #17 未关闭。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站现场准入阻塞(issue #17):用户重启后新主根 PID `45948`(创建 `2026-11-30T13:58:45.8474147Z`),但 `preflight.ps1` 在只读 `envscan` 阶段对 `OpenProcess` 返回 Win32 error 5(通常为提权/受保护实例),未 attach、未启动 daemon、未发送;旧 `target-harness` bridge 仍被 PID `25344` 映射,因此新 release 已构建到 `target-n6`(EXE `83CF1A64…D989`、bridge `A3A1F473…4247`)并给 N5/N6 preflight 增加 `-TargetDir`。下一步需正常(非管理员)重启 QQ 后重新准入;入站 @/reply 代码与离线回归已完成(见下一条)。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站 @/reply 保留与渲染(issue #17,离线):依据受控形状,D8 不再因 `atType != 0` 整条拒绝文本元素,只接受 `atType` 1/2 且 `atUid` 正十进制、`atNtUid` `u_` 形态、`atTinyId` 空/`0`/正十进制;新增 `elementType=7` reply 接受与 `replayMsgId/replayMsgSeq/sourceMsgText` 有界校验;其它形状仍显式拒绝。模型新增有序 `WrapperSegment` 与 `plain_text`;`message_store` 纯文本仍存字符串,含 mention/reply 的消息存 OneBot 段数组(`at.qq=atUid`,mention 显示名以 `@` 开头时去掉第一个空白前的显示名并保留后文,reply `id` 暂用原生 `replayMsgId`),`onebot_events` 与 `get_msg` 共用该段构造。新增 D8、模型、message_store、事件四组回归;全仓 default **517** / research **577**(各 69 个测试二进制、0 failed)通过。出站 `@`/reply 发送、回执关联、reply 的本地 `message_id` 映射与真实客户端显示仍未验收;本轮未重建 release(PID 39552 仍映射旧 bridge,覆盖 DLL 被拒绝),下一次现场前需重启 QQ 释放后重构建。`feat-008` 仍 in-progress,issue #17 未关闭。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a @/reply 受控只读形状取证(issue #17):用户重启 QQ 后指定 PID `39552`(创建 `2026-11-30T12:14:16.9408969Z`),同一 release `0C5A91ED…68375B` / bridge `70BF6DE9…0E551`。preflight PASS,attach 4.45s 且 `login_ok=true`;360s 窗口内 version/status 72/72、login 36/36(`Stella`/1694717255,1502/timeout 0),Caligo 零发送;18 条 `receive_segment_shape`、10 个唯一形状:at 为 `[1]`/`atType=2`/`atUid` 十进制/`atNtUid` uid/`atTinyId` 十进制,reply 为 `[7,1]`/`reply_element_type=7`/`replayMsgId`、`replayMsgSeq` 十进制/`sourceMsgText` 空/17 键,另有 `[7,1,6]`、`[6]`、`[8]`、`[10]`、`[16]`。用户确认已发一条 @ 和一条 reply,但群内同时有其它流量,逐条归因仍未证明;两次独立窗口的 at/reply 形状一致,足以作为实现输入,不足以作为目标/渲染/回执验收。journal 51 Event 无缺口,停止 exit 0,bridge 保留,QQ 响应;`soak.overall=fail` 仅因未安排 core 重启(`core_restarts_recovered=false`)。PID 39552 已消耗、不得重接;`feat-008` 仍 in-progress,issue #17 未关闭。下一步先确定逐元素文本边界策略,再实现入站渲染与出站 @/reply 发送。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-29 feat-008 N6a @/reply 只读形状取证与一次现场尝试(issue #17):审计确认入站带非零 `atType` 或 `replyElement` 的消息会被 D8 整条拒绝(正文一并丢失),Rust `text()` 再次拒绝;出站 `at`/`reply` 段显式 1400;此前没有真实 wrapper 形状样本,不能靠猜 native 字段实现,因此新增 D8 有界形状诊断(`elementType`、`atType`、`atUid/atNtUid/atTinyId` 形态、`replyElement` 已知字段形态;不含正文/UID/消息 ID/路径),经 `receive_diagnostics` 白名单写入 `receive_segment_shape` 阶段报告;新增 `scripts/n6/` 取证包(复用 N5 准入与常驻 harness,一次 attach、Caligo 零发送、操作者发一条 @ 和一条回复)与 `probe-summary.json`。定向测试与全仓 default 512 / research 572(各 69 个测试二进制、0 failed)通过;`init.ps1 -Mode all` 在本机 PowerShell 5.1 把 cargo `Compiling` stderr 当终止错误而未进入测试,同一组检查拆分执行通过。GitNexus 刷新后 `detect-changes` 为 7 files / 10 symbols / 115 flows / critical(D8 共享常量把所有流程连上;实际增量为拒绝前的有界诊断与输出字段,未改准入/发送/回执),`poll_listener_script` 与 sanitizer 的 upstream impact 均为 LOW,`D8_START_JS` 为 UNKNOWN 并已用文本检索确认调用点。现场已尝试一次:PID `25344` 只读准入/attach/`listener_armed` 成功、Caligo 零发送;`06:30:33Z`–`06:32:37Z` 捕获 7 条 `receive_segment_shape`(5 个唯一形状:at `atType=2`/`atUid` 十进制/`atNtUid` uid/`atTinyId` 十进制;reply `elementType=7` 与文本共存、`replayMsgId/Seq` 十进制、`sourceMsgText` 空、17 键;另有 `elementType` 16/5),journal 18 Event 无缺口、停止 exit 0、bridge 保留。但 `get_login_info` 1502、`attach_login_ok=false`,身份未确认且窗口内群流量非受控,形状不能算操作者两条消息的受控证据;`feat-008` 仍 in-progress,issue #17 未关闭。下一步需正常重启 QQ、以登记 B 登录并打开聊天窗口,扩展逐元素诊断后做受控复验,再实现 @/reply 渲染与发送。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + 2026-11-28 feat-007 N5 24h 最终现场通过(issue #16):queue-fix 构建 `e9db64a`(EXE `58D9CAE9…2C99`、bridge `659CE4D1…CE14`)于 `2026-11-27T14:10:19Z`–`2026-11-28T14:10:19Z` 完整跑满 86,426s:1439 samples,version/status 2878/2878、登录 1439/1439(1502/timeout 均为 0),+2h/+8h/+16h 三次 core 重启分别 0.18/0.19/0.19s 恢复且 journal 完整帧前缀保留;journal 4,921,410 bytes、4,837 个 Event(event_seq 1–4837 无缺口、0 重复、0 Gap);forward-WS 消费者 4,708 条消息/1,616,691 bytes,1,533 次空闲重连、3 次错误,客户端侧少收 129 条(core 无丢失);停止后 bridge 保留、QQ 响应,daemon working set 约 10–15 MiB、handles ~107 稳定。24h 门按常驻/core 重启/登录缓存/事件消费关闭。随后补做新代次重绑样本:同一登记账号另取新鲜 QQ 主根,以 `generation=2` + 新 journal/pipe/token 一次 attach;108s 样本 21 samples、0 探测失败、一次 core 重启 0.18s 恢复,新 journal 8 Event 且 `session_generations=[2]`,旧 gen1 journal 4,921,410 bytes / SHA-256 `A026E296…A833F` 前后完全不变;零发送,无旧请求重放。issue #16 四条 done criteria 均有证据,已于 `2026-11-28T14:24:01Z` 关闭;`feat-007` 仍 in-progress(依赖 `feat-006` 未 done,产品 NOT READY)。真实 TCP 背压、native 寿命/owner-stop 仍是已记录边界。原始材料只在 ignored `local-evidence/feat007-n5-final4-20261127-unbound/` 与 `feat007-n5-rebind-20261128-unbound/`。 [验收记录](docs/acceptance/2026-11-25-feat-007-n5-release.md) 2026-11-27 feat-007 N5 最终 24h 重跑准备(issue #16):24h attempt 2 的缺口已做实现修正——新增持久登录缓存(`get_login_info` 无 `no_cache` 时成功查询后写账号目录 `login.private.json`;core 重启后默认动作先返回持久身份,`no_cache=true` 仍走 native 查询;新增持久化/账号漂移/backend 短路测试)与 forward-WS 事件消费者(`scripts/n5/ws_drain.ps1`,只记消息数/字节数/重连数,不写正文;soak 在 attach 后启动,`require_event_consumer` 模式下要求 `event_consumer_active` 且 journal `Gap=0`)。新构建 `17f5ec6`(`caligo.exe` `4C9B057D…02BB`、bridge `659CE4D1…CE14`)的启动包/未知版本门 PASS;`init.ps1 -Mode all` default 509 / research 569、0 failed。最终 24h 于 `2026-11-27T01:38:44Z` 在新主根 `33284`(创建 `2026-11-27T01:37:42.0474720Z`,账号 B)启动,但在 8h 处发现两个缺陷:WS 消费者把 5s `ReceiveAsync` 取消当成断开,5,157 次重连只收到 309 条;`AccountActor::events_out` 只是 control `DrainEvents` 诊断队列,满时仍 degrade/拒绝 wrapper/projection 事件,导致 journal 564 Event + 2,848 Gap;control Stop 返回后 daemon 未退出,force-kill,bridge 保留。已修正:诊断队列满时 wrapper/projection 事件只增加 `events_deliverable_queue_dropped` 并继续 journal/OneBot 发布(不 Gap、不 degrade),WS 接收取消改为 30s、停止等待 45s;新增 runtime/wrapper 回归,`init.ps1 -Mode all` default 510 / research 570、0 failed。新构建 `e9db64a`(EXE `58D9CAE9…2C99`、bridge `659CE4D1…CE14`)启动包/未知版本门 PASS;attempt 4 于 `2026-11-27T14:10:19Z` 在新主根 `22560`(创建 `2026-11-27T14:09:56.6234676Z`,账号 B)启动,带 WS 消费者与登录缓存,+2h/+8h/+16h 各一次 core 重启,预计 `2026-11-28T14:10:19Z` 结束;定时任务 `schedule-414615f1-3bb4-476d-be17-e17a099d6245` 在 `2026-11-28T22:30+08:00` 核验。QQ 重启后新代次重绑与真实 TCP 背压仍未闭合。原始材料只在 ignored `local-evidence/feat007-n5-final-20261127-unbound/` 与 `feat007-n5-final4-20261127-unbound/`。 [验收记录](docs/acceptance/2026-11-25-feat-007-n5-release.md) diff --git a/scripts/n5/n5_soak.py b/scripts/n5/n5_soak.py index dbfaa1d9..868aa416 100644 --- a/scripts/n5/n5_soak.py +++ b/scripts/n5/n5_soak.py @@ -322,7 +322,7 @@ def log_event(self, kind: str, **fields): print(json.dumps(record, ensure_ascii=False), flush=True) def daemon_args(self, account: str): - return [ + args = [ str(self.state["build"]["caligo_exe"]), "daemon", "--pipe-prefix", @@ -342,6 +342,10 @@ def daemon_args(self, account: str): "--onebot-ws-bind", f"127.0.0.1:{self.state['ports']['ws']}", ] + media_config = getattr(self.args, "media_config", None) + if media_config: + args += ["--media-config", str(Path(media_config).resolve())] + return args def start_daemon(self, index: int, expect_pid: int | None): args = self.daemon_args(str(self.state["account"])) @@ -835,6 +839,7 @@ def main() -> int: parser.add_argument("--sample-seconds", type=int, help="override sample interval") parser.add_argument("--restart-at-min", type=float, nargs="*", help="override restart minutes") parser.add_argument("--repo", default=str(Path(__file__).resolve().parents[2])) + parser.add_argument("--media-config", help="absolute media tool JSON for daemon voice transcoding") args = parser.parse_args() repo = Path(args.repo).resolve() diff --git a/scripts/n5/preflight.ps1 b/scripts/n5/preflight.ps1 index 07055d3e..ab663328 100644 --- a/scripts/n5/preflight.ps1 +++ b/scripts/n5/preflight.ps1 @@ -2,6 +2,7 @@ param( [string]$Repo = '', [string]$Pack = '', + [string]$TargetDir = 'target-harness', [UInt32]$TargetPid = 0, [string]$ExpectedCreated = '', [UInt64]$Account = 0, @@ -31,8 +32,8 @@ if (-not $Pack) { $Pack = Join-Path $Repo 'local-evidence/feat007-n5-20261125-un New-Item -ItemType Directory -Force -Path $Pack | Out-Null $Pack = (Resolve-Path -LiteralPath $Pack).Path -$exe = Join-Path $Repo 'target-harness/x86_64-pc-windows-msvc/release/caligo.exe' -$bridge = Join-Path $Repo 'target-harness/x86_64-pc-windows-msvc/release/caligo_bridge.dll' +$exe = Join-Path $Repo "$TargetDir/x86_64-pc-windows-msvc/release/caligo.exe" +$bridge = Join-Path $Repo "$TargetDir/x86_64-pc-windows-msvc/release/caligo_bridge.dll" $manifest = Join-Path $Repo 'local-evidence/n4-r2-r3-closure-20261107/manifest-qq-9.9.36-53644-pilot.json' $audit = Join-Path $Repo 'local-evidence/n4-r2-callback-20261108/audit-g3-target-modules.ps1' $prior = Join-Path $Repo 'local-evidence/snowcat-dual-login-fresh-20261114/state.private.json' diff --git a/scripts/n6/README.md b/scripts/n6/README.md new file mode 100644 index 00000000..7bbff67d --- /dev/null +++ b/scripts/n6/README.md @@ -0,0 +1,91 @@ +# N6a @/reply 只读形状取证 + +用途:issue #17 的 `@/reply 目标正确、真实渲染且回执关联` 目前没有正向样本。 +现有 D8 对非零 `atType` 与任何 `replyElement` 整条拒绝;入站 `@` 消息会连同正文 +一起丢失。继续实现前必须先取得真实 wrapper 元素形状,避免猜测 native 字段。 + +本包只做**只读取证**: + +- Caligo 发送 0 条消息; +- 操作者向 bot 发送一条 `@` 消息和一条回复(引用 bot 已发消息); +- D8 只记录固定标签:元素类型、`atType`、`replyElement` 已知字段的 + `typeof`/数字形态、计数;不记录正文、UID、消息 ID、路径; +- 停止后 bridge 保留,不热卸载、不重连。 + +## 前置 + +- Windows x64,固定 QQ 9.9.36-53644; +- 新鲜 QQ 主根(本次 attach 前未映射 Caligo bridge),已登录并打开过聊天窗口; +- 已构建带 `receive_segment_shape` 诊断的 release: + `caligo.exe` 与 `caligo_bridge.dll` 位于 `target-harness/x86_64-pc-windows-msvc/release/`; +- 本机 `local-evidence/` 下的 N4 manifest/audit/envscan 前置文件仍在。 + +## 步骤 + +1. 用户指定 QQ 主根的 PID 与创建时间(UTC ISO,带 7 位小数,例如 + `2026-11-29T01:02:03.4567890Z`)。不接受“最后启动的实例”推断。 + +2. 准入: + + ```powershell + .\scripts\n6\preflight.ps1 -Pack local-evidence/feat008-n6a-shape- -TargetPid -ExpectedCreated -Account + ``` + + 通过后会写 `state.private.json`、`probe-plan.json` 与 + `authorization.template.json`。准入会核对固定 manifest/模块哈希、PE/backend + 审计、唯一 Environment、无已映射 bridge。 + +3. 审阅后授权:复制 `authorization.template.json` 为 + `authorization.private.json`,将 `authorized` 改为 `true`。授权范围必须是 + “一次 attach、Caligo 零发送、操作者两条消息、只收集有界形状、停止后保留 bridge”。 + +4. 运行探针(默认 6 分钟窗口): + + ```powershell + .\scripts\n6\run.ps1 -Pack local-evidence/feat008-n6a-shape- + ``` + + 看到脚本提示 READY 后,用另一个测试账号向 bot: + - 在群里或私聊发送一条 `@bot` 消息; + - 回复一条 bot 之前发出的消息。 + + 探针不会自动确认消息到达;若窗口内没有观察到形状,结果记为 + `not_observed`,不得当作能力失败或成功。 + +5. 结果: + + - `probe-summary.json`:`at_seen`、`reply_seen`、`shapes`、`result`; + - `entry.private.jsonl`:bridge 阶段报告,含 `receive_segment_shape` 行; + - `soak-summary.json`:daemon 启停、探针与 bridge 保留边界。 + + `result=captured_at_and_reply` 只证明形状已采集,**不**提升 feat-008 状态; + `@/reply` 的实现、真实渲染与回执关联仍需后续单独验收。 + +## 失败语义 + +- 授权缺失/不匹配:`run.ps1` 在启动 daemon 前拒绝; +- 已映射 bridge 或模块/哈希不符:`preflight.ps1`/`attach.ps1` 拒绝,不重试; +- `get_login_info` 返回 1502:attach 可能成功,但登记账号/登录态未确认; + `probe-summary.json` 会给出 `login_confirmed=false` 与 `attribution=unverified`, + 窗口内形状只能算真实观察,不能算操作者受控消息的证据; +- 窗口内没有 `@`/回复:`not_observed`,保留原始报告,不重发、不延长; +- 停止不卸载 bridge;同一 QQ 代次不得再次 attach。 + +## 入站 @/reply 保留验证 + +新代码接受 at/reply 后,除形状外还要确认 MessageStore 中确实出现 OneBot 段。 +使用同一个 pack 跑完窗口后: + +```powershell +python .\scripts\n6\summarize-inbound.py --pack local-evidence/feat008-n6a-shape- +``` + +`inbound-summary.json` 只报告 `at_messages`/`reply_messages`/`segment_types` 和 +本地 `message_ids`;`result=captured_at_and_reply` 只证明入站持久化,不证明事件 +JSON、`get_msg` 传输或真实客户端显示。 + +如果 `target-harness` 的 release DLL 被旧 QQ 代次锁定,可把新 release 构建到 +其他目录并用 `preflight.ps1 -TargetDir ` 固定;`run.ps1` 从 state 读取该路径。 +注意:本机沙箱新建的顶层目录(如 `target-n6`)可能带 AppContainer/deny ACL, +从其中启动的 `caligo.exe` 会写 journal/`OpenProcess` 失败;优先使用 +`target-harness/`,不要用顶层新目录。 diff --git a/scripts/n6/preflight.ps1 b/scripts/n6/preflight.ps1 new file mode 100644 index 00000000..f3f6dfc0 --- /dev/null +++ b/scripts/n6/preflight.ps1 @@ -0,0 +1,133 @@ +[CmdletBinding()] +param( + [string]$Repo = '', + [string]$Pack = 'local-evidence/feat008-n6a-shape-20261129', + [string]$TargetDir = 'target-harness', + [UInt32]$TargetPid = 0, + [string]$ExpectedCreated = '', + [UInt64]$Account = 0, + [double]$Hours = 0.1, + [int]$SampleSeconds = 10 +) + +# N6a (@/reply) read-only shape-probe admission. +# +# This is not a capability acceptance. It admits one fresh QQ main root for a +# bounded receive-only probe: Caligo sends nothing; the operator sends one @ +# message and one reply to the bot. The bridge reports fixed shape labels +# (element type, atType, reply-field kinds) so the next implementation step does +# not guess native element shapes. It reuses the tested N5 admission gates. + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +if (-not $Repo) { $Repo = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path } +$Repo = (Resolve-Path -LiteralPath $Repo).Path +if (-not $Pack) { throw 'Pack path is required' } +if (-not [IO.Path]::IsPathRooted($Pack)) { $Pack = Join-Path $Repo $Pack } +$Pack = [IO.Path]::GetFullPath($Pack) +New-Item -ItemType Directory -Force -Path $Pack | Out-Null +$Pack = (Resolve-Path -LiteralPath $Pack).Path + +if ($Hours -le 0 -or $Hours -gt 1) { throw '-Hours must be in (0, 1] for the bounded probe' } +if ($SampleSeconds -lt 1 -or $SampleSeconds -gt 60) { throw '-SampleSeconds must be 1..60' } + +$n5 = Join-Path $Repo 'scripts/n5/preflight.ps1' +if (-not (Test-Path -LiteralPath $n5)) { throw 'N5 preflight gate is missing' } + +try { + & $n5 -Repo $Repo -Pack $Pack -TargetDir $TargetDir -TargetPid $TargetPid -ExpectedCreated $ExpectedCreated ` + -Account $Account -DurationHours $Hours -SampleSeconds $SampleSeconds -RestartAtMinutes @() +} catch { + Write-Host ("N6a preflight rejected: " + $_.Exception.Message) + exit 2 +} + +$statePath = Join-Path $Pack 'state.private.json' +if (-not (Test-Path -LiteralPath $statePath)) { throw 'N5 preflight did not write state.private.json' } +$state = [IO.File]::ReadAllText($statePath, [Text.Encoding]::UTF8) | ConvertFrom-Json +if ($state.mode -ne 'field') { throw 'Probe admission requires field mode' } +if ([UInt32]$state.pid -ne $TargetPid) { throw 'State PID mismatch' } +if ([string]$state.created -ne $ExpectedCreated) { throw 'State creation-time mismatch' } + +function Save-Json([string]$Path, $Value) { + [IO.File]::WriteAllText($Path, ($Value | ConvertTo-Json -Depth 12), [Text.UTF8Encoding]::new($false)) +} + +$probe = [ordered]@{ + schema = 'caligo/n6-shape-probe-plan/1' + issue = 17 + work_block = 'N6a @/reply' + created_utc = [DateTime]::UtcNow.ToString('o') + pid = $state.pid + created = $state.created + account = $state.account + build = $state.build + scope = 'One admitted attach; zero Caligo message sends. The operator sends exactly one @ mention to the bot and one reply to a bot message while the probe runs. Only bounded segment-shape labels are collected; no raw content, UID, message id or path is written.' + expected_operator_messages = @( + 'one group or private message that @-mentions the bot', + 'one reply that quotes a message previously sent by the bot' + ) + duration_hours = $Hours + sample_seconds = $SampleSeconds + restart_at_minutes = @() + sends_by_caligo = 0 + report_stage = 'receive_segment_shape' + refusals = @( + 'missing/mismatched authorization.private.json -> run.ps1 refuses before daemon start', + 'no bridge or a second attach on the same generation -> attach.ps1 refuses', + 'no @ and reply observed -> summary is incomplete, not a capability failure or success', + 'bridge is retained after stop; never hot-unloaded or reattached' + ) +} +Save-Json (Join-Path $Pack 'probe-plan.json') $probe + +$authorization = [ordered]@{ + authorized = $false + pid = $state.pid + created_utc = $state.created + account = $state.account + scope = 'One admitted attach; zero Caligo sends; operator sends one @ mention and one reply during the probe window; bounded receive shape labels only; bridge retained at the end (no hot unload).' + operator_messages = 2 + sends_by_caligo = 0 + note = 'Copy this file to authorization.private.json and set authorized=true only after reviewing the designated QQ root and the probe scope. The probe never sends a message.' +} +Save-Json (Join-Path $Pack 'authorization.template.json') $authorization + +$previous = [ordered]@{ + schema = 'caligo/n6a-preparation/1' + issue = 17 + scope = $probe.scope + build = $state.build + manifest_sha256 = $state.manifest_sha256 + pid = $state.pid + created = $state.created + duration_hours = $Hours + sample_seconds = $SampleSeconds + expected = [ordered]@{ + attach = 'one admitted attach; no second bridge' + receive = 'operator sends one @ and one reply after READY; Caligo sends zero messages' + report = 'entry.private.jsonl contains receive_segment_shape lines with fixed labels only' + stop = 'control Stop ends daemon; default bridge remains mapped; QQ remains responsive' + } +} +Save-Json (Join-Path $Pack 'preparation-unbound.json') $previous + +# Re-seal after the N6-specific plan/template rewrite so the pack manifest does +# not silently retain the N5 wrapper hashes. +$files = @(Get-ChildItem -LiteralPath $Pack -File | Where-Object { + $_.Name -notlike '*.private.*' -and $_.Name -notin @('onebot.token') +} | Sort-Object Name) +$manifestEntries = @(foreach ($file in $files) { + [ordered]@{ name = $file.Name; sha256 = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() } +}) +$seal = [ordered]@{ + schema = 'caligo/n6a-pack/1' + prepared_utc = [DateTime]::UtcNow.ToString('o') + source_head = $state.source_head + files = $manifestEntries +} +Save-Json (Join-Path $Pack 'pack-manifest.json') $seal + +Write-Output ('PASS N6a probe admission pid={0}; pack={1}' -f $state.pid, $Pack) +Write-Output ('next: review {0}, copy to authorization.private.json, set authorized=true, then run scripts/n6/run.ps1' -f (Join-Path $Pack 'authorization.template.json')) diff --git a/scripts/n6/run.ps1 b/scripts/n6/run.ps1 new file mode 100644 index 00000000..f742ace6 --- /dev/null +++ b/scripts/n6/run.ps1 @@ -0,0 +1,64 @@ +[CmdletBinding()] +param( + [string]$Repo = '', + [string]$Pack = '', + [double]$Hours = 0.1, + [int]$SampleSeconds = 10 +) + +# N6a (@/reply) read-only field probe runner. +# +# Reuses the tested N5 resident harness for daemon start, one admitted attach, +# probes and a controlled stop. It never sends a Caligo message. After the +# window it summarizes only the bounded receive_segment_shape report lines. + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +if (-not $Repo) { $Repo = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path } +$Repo = (Resolve-Path -LiteralPath $Repo).Path +if (-not $Pack) { throw 'Pack is required; pass the same -Pack used for scripts/n6/preflight.ps1' } +if (-not [IO.Path]::IsPathRooted($Pack)) { $Pack = Join-Path $Repo $Pack } +$Pack = (Resolve-Path -LiteralPath $Pack).Path + +$statePath = Join-Path $Pack 'state.private.json' +$authPath = Join-Path $Pack 'authorization.private.json' +if (-not (Test-Path -LiteralPath $statePath)) { throw 'Run scripts/n6/preflight.ps1 first; state.private.json is missing' } +if (-not (Test-Path -LiteralPath $authPath)) { + throw ('authorization.private.json is missing; review and copy {0}' -f (Join-Path $Pack 'authorization.template.json')) +} + +$state = [IO.File]::ReadAllText($statePath, [Text.Encoding]::UTF8) | ConvertFrom-Json +$auth = [IO.File]::ReadAllText($authPath, [Text.Encoding]::UTF8) | ConvertFrom-Json +if ($auth.authorized -ne $true) { throw 'authorization.private.json authorized must be true' } +if ([UInt32]$auth.pid -ne [UInt32]$state.pid) { throw 'Authorization PID does not match state' } +if ([string]$auth.created_utc -ne [string]$state.created) { throw 'Authorization creation-time does not match state' } +if ([UInt64]$auth.account -ne [UInt64]$state.account) { throw 'Authorization account does not match state' } +if ([int]$auth.sends_by_caligo -ne 0) { throw 'Authorization must keep Caligo sends at zero' } + +$p = Get-Process -Id ([UInt32]$state.pid) -ErrorAction Stop +if (-not $p.Responding) { throw 'Designated QQ root is not responding' } +$mapped = @($p.Modules | Where-Object ModuleName -like '*caligo*bridge*') +if ($mapped.Count -gt 0) { + throw ('Bridge is already mapped on PID {0}: {1}' -f $p.Id, (($mapped | ForEach-Object ModuleName) -join ',')) +} + +Write-Output '=== N6a read-only shape probe ===' +Write-Output 'Caligo will not send any message.' +Write-Output 'After the daemon reports READY, send exactly one @ message to the bot and one reply to a bot message.' +Write-Output 'The probe stops automatically; the bridge is retained and must not be reattached.' +Write-Output ('window={0}h sample={1}s pack={2}' -f $Hours, $SampleSeconds, $Pack) + +$soak = Join-Path $Repo 'scripts/n5/n5_soak.py' +$soakArgs = @($soak, '--state', $statePath, '--pack', $Pack, '--hours', [string]$Hours, + '--sample-seconds', [string]$SampleSeconds, '--restart-at-min') +& python @soakArgs +$soakExit = $LASTEXITCODE +Write-Output ('soak_exit={0}' -f $soakExit) + +$summary = Join-Path $Repo 'scripts/n6/summarize.py' +& python $summary --pack $Pack +$summaryExit = $LASTEXITCODE +if ($summaryExit -ne 0) { exit $summaryExit } +if ($soakExit -ne 0) { Write-Warning ('Resident harness reported exit {0}; inspect soak-summary.json before using the probe result' -f $soakExit) } +exit 0 diff --git a/scripts/n6/summarize-inbound.py b/scripts/n6/summarize-inbound.py new file mode 100644 index 00000000..b6a8b149 --- /dev/null +++ b/scripts/n6/summarize-inbound.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Summarize inbound @/reply persistence for the N6a validation run. + +Reads the MessageStore journal only. It reports segment types and local +message IDs; it never writes text, native IDs, UIDs or peer identifiers. +""" + +from __future__ import annotations + +import argparse +import collections +import datetime as dt +import json +from pathlib import Path + + +def utcnow() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + + +def read_json(path: Path): + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + + +def main() -> int: + parser = argparse.ArgumentParser(description="Summarize inbound @/reply MessageStore entries") + parser.add_argument("--pack", required=True, help="probe pack directory") + parser.add_argument("--out", help="output JSON path (defaults to /inbound-summary.json)") + args = parser.parse_args() + + pack = Path(args.pack).resolve() + store = pack / "field" / "journal.messages.jsonl" + lines = 0 + rich = 0 + at_messages = 0 + reply_messages = 0 + segment_types: collections.Counter[str] = collections.Counter() + message_ids: list[int] = [] + parse_failures = 0 + + if store.exists(): + for line in store.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if not line: + continue + lines += 1 + try: + row = json.loads(line) + except json.JSONDecodeError: + parse_failures += 1 + continue + message = row.get("message") + if not isinstance(message, dict): + parse_failures += 1 + continue + body = message.get("message") + if not isinstance(body, list): + continue + types = [segment.get("type") for segment in body if isinstance(segment, dict)] + if not types: + continue + segment_types.update(types) + has_at = "at" in types + has_reply = "reply" in types + if not has_at and not has_reply: + continue + rich += 1 + at_messages += int(has_at) + reply_messages += int(has_reply) + message_id = message.get("message_id") + if isinstance(message_id, int) and 0 < message_id <= 2_147_483_647: + message_ids.append(message_id) + + if at_messages and reply_messages: + result = "captured_at_and_reply" + elif at_messages: + result = "captured_at_only" + elif reply_messages: + result = "captured_reply_only" + else: + result = "not_observed" + + soak = read_json(pack / "soak-summary.json") or {} + summary = { + "schema": "caligo/n6a-inbound-summary/1", + "issue": 17, + "work_block": "N6a inbound @/reply", + "generated_utc": utcnow(), + "pack": str(pack), + "store": str(store), + "store_present": store.exists(), + "store_lines": lines, + "parse_failures": parse_failures, + "rich_messages": rich, + "at_messages": at_messages, + "reply_messages": reply_messages, + "segment_types": dict(sorted(segment_types.items())), + "message_ids": sorted(set(message_ids))[:32], + "result": result, + "login_confirmed": soak.get("attach_login_ok") is True, + "soak_overall": soak.get("overall"), + "note": "MessageStore evidence only. Event JSON, get_msg transport and real client rendering are not proven by this summary.", + } + out = Path(args.out) if args.out else pack / "inbound-summary.json" + out.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: summary[key] for key in + ("result", "rich_messages", "at_messages", "reply_messages", + "message_ids", "login_confirmed", "soak_overall")}, ensure_ascii=False)) + print(f"summary={out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/n6/summarize.py b/scripts/n6/summarize.py new file mode 100644 index 00000000..1cbc0a4d --- /dev/null +++ b/scripts/n6/summarize.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Summarize the N6a @/reply read-only shape probe. + +Reads only bounded `receive_segment_shape` report lines and the N5 soak summary. +It never opens a chat database and never writes message content. +""" + +from __future__ import annotations + +import argparse +import ast +import datetime as dt +import json +from pathlib import Path + + +def utcnow() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + + +def read_json(path: Path): + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + + +def parse_detail(detail: str): + if not isinstance(detail, str): + return None + text = detail.strip() + for candidate in (text, text.replace("'", '"')): + try: + value = json.loads(candidate) + if isinstance(value, dict): + return value + except json.JSONDecodeError: + pass + try: + value = ast.literal_eval(text) + if isinstance(value, dict): + return value + except (ValueError, SyntaxError): + pass + return None + + +def shape_key(shape: dict) -> str: + return json.dumps(shape, sort_keys=True, ensure_ascii=False) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Summarize N6a @/reply shape probe") + parser.add_argument("--pack", required=True, help="probe pack directory") + parser.add_argument("--out", help="output JSON path (defaults to /probe-summary.json)") + args = parser.parse_args() + + pack = Path(args.pack).resolve() + report = pack / "entry.private.jsonl" + shapes: list[dict] = [] + seen: set[str] = set() + stage_lines = 0 + parse_failures = 0 + + if report.exists(): + for line in report.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except json.JSONDecodeError: + parse_failures += 1 + continue + if row.get("stage") != "receive_segment_shape": + continue + stage_lines += 1 + detail = parse_detail(row.get("detail", "")) + if not detail: + parse_failures += 1 + continue + for shape in detail.get("segment_shapes", []): + if not isinstance(shape, dict): + continue + key = shape_key(shape) + if key not in seen: + seen.add(key) + shapes.append(shape) + + at_seen = any(shape.get("at_count", 0) > 0 for shape in shapes) + reply_seen = any(shape.get("reply_present") is True for shape in shapes) + if at_seen and reply_seen: + result = "captured_at_and_reply" + elif at_seen: + result = "captured_at_only" + elif reply_seen: + result = "captured_reply_only" + else: + result = "not_observed" + + soak = read_json(pack / "soak-summary.json") or {} + state = read_json(pack / "state.private.json") or {} + auth = read_json(pack / "authorization.private.json") or {} + login_confirmed = soak.get("attach_login_ok") is True + operator_authorized = auth.get("authorized") is True + attribution = "unverified" + warning = None + if not login_confirmed: + warning = ("get_login_info did not confirm the designated account; the captured " + "shapes are opportunistic traffic in the probe window and cannot be " + "treated as controlled @/reply field evidence.") + elif operator_authorized: + attribution = "operator_authorized" + summary = { + "schema": "caligo/n6a-shape-probe-summary/1", + "issue": 17, + "work_block": "N6a @/reply", + "generated_utc": utcnow(), + "pack": str(pack), + "pid": state.get("pid"), + "created": state.get("created"), + "account": state.get("account"), + "source_head": state.get("source_head"), + "build": state.get("build"), + "entry_report": str(report), + "entry_report_present": report.exists(), + "segment_stage_lines": stage_lines, + "parse_failures": parse_failures, + "shape_count": len(shapes), + "at_seen": at_seen, + "reply_seen": reply_seen, + "result": result, + "login_confirmed": login_confirmed, + "operator_authorized": operator_authorized, + "attribution": attribution, + "warning": warning, + "capability_acceptance": False, + "note": "Shape evidence only. @/reply send, rendering and receipt correlation remain unaccepted until a separate field sample proves them.", + "shapes": shapes, + "soak": { + "overall": soak.get("overall"), + "fatal": soak.get("fatal"), + "stop": soak.get("stop"), + "bridge_final": soak.get("bridge_final"), + "journal_final": soak.get("journal_final"), + }, + } + + out = Path(args.out) if args.out else pack / "probe-summary.json" + out.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: summary[key] for key in + ("result", "at_seen", "reply_seen", "shape_count", "segment_stage_lines", + "login_confirmed", "attribution", "soak")}, ensure_ascii=False)) + print(f"summary={out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/session-handoff.md b/session-handoff.md index d0cecf16..b6047373 100644 --- a/session-handoff.md +++ b/session-handoff.md @@ -1,5 +1,47 @@ # Session handoff +2026-12-05 N6c 收口:放弃 native SSO/OIDB(0x11E9/0x11C5 145,native hook 缺 52230 STRING_FILL/SSO 返回点),保留已验 wrapper 图片/语音;文件/视频/转发/卡片/表情显式 1404。feat-008 仍 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 N6c:只读枚举 RichMediaService 方法发现 `uploadRMFileWithoutMsg`(argc==1)及 downloadFile*/getGroupFile*/getVideoPlayUrl*;MsgService 无 sendFile/uploadFile。未调用/未猜参数,上传合同待取证,视频/文件/转发/卡片/表情保持 1404。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 N6c native 上传能力只读取证:session_rich_service=true,但 msg_send_file/msg_upload_file/rich_upload_file/rich_send_file/rich_get_path 全 false;不能用这些名字猜接入。视频/文件/转发/卡片/表情保持显式 1404。下一步枚举 RichMediaService 公共方法或另找受证路线。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 N6c 矩阵:语音 SILK 收发 + `silk/wav/ogg` 转码现场通过;视频/文件入站拒绝、出站 1404;forward/json/face/video/file/markdown 未知段 1404 无文本回退。实际视频/文件/转发/卡片/表情需 native 上传协议取证,暂不猜接入。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 入站语音转码现场通过:入站 7,202 B 语音回调 `.amr` 实际为 SILK,PTT 路径登记 + canonical realpath 修复后,get_record silk 7,202 B、wav 187,278 B、ogg 14,968 B,容器头/大小均通过;无重发/假成功。release `n6-voice-output3-release` EXE `1ACD06D5…49AB`、bridge `5992741B…A2DB`。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 语音:媒体配置已加载;入站语音回调路径已登记(absolute/normalized/md5/amr、under_ptt=true),但输出 validation_failed,get_record 仍 1440 无字节;下一步加 size/md5/header 有界形状确认 .amr 缓存格式。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6b native 图片媒体 ID/有效期:`fileUuid` 作为可选 `ImageInfo.file_uuid` 持久化,并在 `get_msg.image.data.file_id` 暴露;跨 QQ 重启后同一私聊图片 `message_id=2` 的 `get_msg` 仍返回 `file_id`,但 `get_image` 返回 `1440` 且无字节,`fileUuid` 不提供独立回源。无假成功/重试;失败仍泛化,下一步映射明确 unavailable。提交 `75a2e5a`,PR #22。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6b 图片上传/资源寿命首切片:`upload_image`/`delete_image_upload` + 账号隔离 8 个/1 MiB/10 min TTL;send 接受 `caligo-upload` id,未知/过期/删除后 `1404`。独立 daemon HTTP upload→send(无会话 1404)→delete→send(1404)通过;真实 QQ 初报 native code 3,定位为图片缓存父目录 realpath 差异并修复;PID 3868 私聊 3089665724 与 PID 39120 群 629933025 均以 upload id 发送 4,592 B/320×160 PNG 成功(message_id=3/2,get_msg/store native ID/尺寸一致),私聊视觉已确认、群待确认;删除后同 id 1404;release `target-harness/n6-image-diag4-release` EXE `E08CF90A…6B1E`、bridge `CBC67836…539F`;default 532 / research 592。native QQ 上传/媒体 ID 仍在 send 内,本地文件/URL 与真实发送矩阵待验,feat-008 in-progress。提交 `cf353df`,PR #22。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6c 入站文件/视频显式拒绝与资源寿命边界:release7 现场观察到私聊 `elementType=3`(文件)和 `elementType=5`(视频),两者均无 Event/无 store/无假成功;跨 QQ 重启后持久 `get_msg` 可读,旧群图片 `get_image` 对 >128 KiB 返回 `1404`、33,744 B 样本返回 `1440` 且无字节(release7 仍如此,原生消息已不可读)。提交 `2307eec`、`592cdcd`、`79d7c45`,PR #22 已更新;视频/文件实际发送/上传/转码/恢复仍待验,feat-008 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a @all 权限现场(第六代次,通过):用户指定群 1074455954(bot 为该群 admin),主根 PID `8260`(`2026-12-05T03:36:41.8686415Z`,Stella/1694717255)用 `n6-rich-release6` 预检 PASS、attach 5.34s、login_ok;@all HTTP ok/0、message_id 1,ConfirmedSuccess native 7789876034635047966,get_msg 为 at.qq="all"+text,store 含 native seq/client/peer;daemon exit 0、bridge retained、QQ responsive。至此本轮 @/reply 矩阵覆盖自发/他发、群/私聊、重启后 reply、普通成员 @、admin 群 @all,以及跨会话 1400、非成员 1440、video/face/file 1404 的显式拒绝;实际渲染用户确认。仍未验收:视频/文件等媒体的实际上传/发送/资源寿命、语音转码与更广构建矩阵,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 剩余 @/reply 矩阵现场(第五代次):主根 PID `26044`(`2026-12-05T03:09:33.2217510Z`,Stella/1694717255)用 release5 预检 PASS、attach 3.26s、login_ok;自然入站消息 1(群 950238216)reply→2;core 重启 recovered、journal prefix 保留、bridge 查询恢复;重启后回复入站 1→30、回复自发 30→32;跨会话→1400;@ 非群成员→1440 零 native;video/face/file→1404 无新增自发消息;@all native 已发出但 HTTP 1501,D8 因 atType=1 形状整条拒绝。已修复 D8/模型/匹配器的 @all 处理并新增回归;release `target-harness/n6-rich-release6`(EXE A4A4D8F4…265E、bridge 1A0DB216…F8FE6),默认 526 / research 586 通过;soak overall=pass、bridge retained、QQ responsive。@all 仍需新主根现场确认回执。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第四代次现场(issue #17,回执闭环通过):主根 PID `38008`(`2026-12-05T02:33:09.2195771Z`,Stella/1694717255)用 `n6-rich-release5` 预检 PASS、attach 3.22s、login_ok;群 plain→2、群 reply 到 2→5(reply.id=2)、群 @ 3089665724→7(at.qq=3089665724)、私聊 plain→12、私聊 reply 到 12→14(reply.id=12)全部 HTTP ok/0;三个 rich 请求均 ConfirmedSuccess(native 7789859958943379388/7789860001604659363/7715643075597885711),get_msg 段与目标一致。用户确认同一元素构造渲染正确。窗口结束 daemon exit 0、bridge retained、QQ responsive;soak.overall=fail 仅因未安排 core 重启。本轮闭合 issue #17 第 1 条在本测试范围内的目标/回执/渲染;他发 reply、重启引用、@all/权限、其他媒体与寿命仍待验,feat-008 保持 in-progress。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第三代次现场(issue #17,诊断命中并修复):主根 PID `26272`(`2026-12-05T02:27:18.7954742Z`,Stella/1694717255)用 `n6-rich-release4` 预检 PASS、attach 4.01s、login_ok;普通群文本 message_id 3 成功;reply 与 @ 的 native 消息均已发出/落库,但 HTTP 1501,ReceiptAudit 分别给出 `rich_at_uid` 与 `rich_text_content`。根因:atType=0 文本的空提及字段在 native 回调为 `"0"`/null 而发送前副本为 `""`;native 会把提及显示名改写为群名片(发送前 `@〈Ain〉`、回调 `@EW-Vegetable`)。匹配器已改为 atType=0 将 `""`/null/`"0"` 视为空并只比正文;atType 2/1 以 atUid/atNtUid 识别目标、不比较显示正文。新增回调 `@card`/`atUid="0"` 回归。修复 release `target-harness/n6-rich-release5`(EXE 000D00C1…E97C、bridge EB02C74E…1DE6);桥接/媒体/wrapper 回归通过。窗口结束 daemon exit 0、bridge retained、QQ responsive,无重发;需第四代次新主根确认回执闭环。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第二代次现场(issue #17,回执仍未通过):主根 PID `36004`(`2026-12-05T02:10:26.6217672Z`,Stella/1694717255)用 `n6-rich-release2` 预检 PASS、attach 5.52s、login_ok;普通群文本 629933025 返回 message_id 1;reply 到 1 的 native 消息已落 message_id 2(reply.id=1+text),@ 3089665724 的 native 消息已落 message_id 4(at 段正确),但两者 HTTP 30s 后仍 1501。`reply_reference` 委托与自发 recv 关联已生效;根因最可能是 native sendMsg 在异步回调前消费/改写调用方 elements 数组,而 pending.rich 保存同一引用,导致逐元素匹配失败。已改为提交前保存 owned 副本并新增“sendMsg 清空数组”回归;修复 release `target-harness/n6-rich-release3`(EXE F239E386…5DB0、bridge 51A27B48…92D6)。默认 525 / research 585 通过;窗口结束 daemon exit 0、bridge retained、QQ responsive,无重发。需第三代次新主根复验。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 第一代次现场(issue #17,未通过):测试主根 PID `39072`(`2026-12-05T01:55:42.5080385Z`,Stella/1694717255)用 `n6-rich-release` 预检 PASS、attach 3.1s、login_ok;普通群文本 629933025 返回 message_id 4 且 store 有 native 字段;reply 到 4 返回 1400(Daemon/AccountActor 未委托 `reply_reference`);群 @ 3089665724 返回 1501 但 native 消息已落 message_id 6(at 段正确),根因是自发消息以 `source=recv` 进入 D8 而关联只处理 add_send/update。已修复两处并新增 recv+update 回归,修复 release `target-harness/n6-rich-release2`(EXE 9F8F6D93…7773、bridge 688B6A62…401F)。窗口结束 daemon exit 0、bridge retained、QQ responsive;无重发。需重启 QQ 新主根后复验 reply/@ 回执与真实渲染。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-12-05 feat-008 N6a 出站 @/reply 离线接线(issue #17):新增有序 `SendSegment`/`ReplyReference`、本地 `message_id`→原生引用解析与入站 reply 本地映射;新增 pilot-only `GroupMemberUid` 查询及 `private_reply`/`group_reply`/`group_mention` 能力;`DispatchRich`→`HostOp::SendRich`→`qq_rich_send.js` 按固定参考 `7cf025f` 构造群 @ 与 reply 元素,回执仍要求 add/update 匹配、`getMsgsByMsgId` 逐元素回读,不匹配即 unknown;未知段、私聊 @、未知/跨会话回复显式 1404/1400。全仓 default 525 / research 585 通过;未构建 release、未真实发送/渲染/回执,feat-008 保持 in-progress。下一步需非管理员重启 QQ、构建固定 release,先单条 reply 再单条群 @ 做受控现场。[记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站 @/reply 现场(部分):新主根 PID `37044`(创建 `2026-11-30T14:17:18.0019049Z`)因 `target-n6` 沙箱 ACL 无法写 journal/OpenProcess,改用 `target-harness/n6-release` 后 preflight PASS;attach 5.94s、login 确认,360s 窗口 version/status 72/72、login 36/36,Caligo 零发送;25 Event 无缺口,停止 exit 0、bridge 保留。MessageStore 落盘 1 条 `at` 消息(ID 5),证明入站 at 路径生效;reply 未落盘,因为真实 reply 元素的 `textElement` 触发了当时 D8 的拒绝;用户确认未发送受控两条。随后已放宽 D8/模型接受 reply 的 `textElement`(无 mention;段顺序 reply→text),新增回归;全仓 default 517 / research 577(各 69 个测试二进制、0 failed)通过。reply-text 修复后的 release 已构建到 `target-harness/n6-release2`(EXE `CF2EAA1C…FC4E`、bridge `8B7EB2D5…E3F2`);下一步需重启 QQ 释放 PID 37044 bridge,用 `preflight.ps1 -TargetDir target-harness/n6-release2` 重新准入并验证 reply 落盘。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站现场准入阻塞(issue #17):新主根 PID `45948`(创建 `2026-11-30T13:58:45.8474147Z`)在 `preflight.ps1` 的只读 `envscan` 被 `OpenProcess` 拒绝(Win32 error 5,通常为提权/受保护实例),未 attach、未发送;旧 `target-harness` bridge 仍被 PID `25344` 映射,新 release 改构建到 `target-n6`(EXE `83CF1A64…D989`、bridge `A3A1F473…4247`),N5/N6 preflight 新增 `-TargetDir`。下一步:正常(非管理员)重启 QQ,给新 PID/创建时间,用 `scripts/n6/preflight.ps1 -TargetDir target-n6 ...` 重新准入,再用 `python scripts/n6/summarize-inbound.py` 验证 MessageStore 中的 at/reply 段。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a 入站 @/reply 保留与渲染(issue #17,离线):D8 接受 `atType` 1/2 的文本元素(`atUid` 正十进制、`atNtUid` `u_` 形态、`atTinyId` 空/`0`/正十进制)与 `elementType=7` reply(`replayMsgId/Seq` 正十进制、`sourceMsgText` 有界),其它形状仍拒绝;模型新增 `WrapperSegment`/`plain_text`;message_store 纯文本保持字符串,mention/reply 存 OneBot 段数组,events 与 get_msg 共用段构造。全仓 default 517 / research 577(各 69 个测试二进制、0 failed)通过。出站 @/reply 发送与回执、reply 的本地 message_id 映射、真实客户端显示仍未验收;本轮未重建 release(PID 39552 仍映射旧 bridge,DLL 被锁),下一次现场前需重启 QQ 后重建。`feat-008` 仍 in-progress,issue #17 未关闭。下一步:现场复验入站事件/get_msg/显示,然后实现出站 reply(单条授权)与 @。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-30 feat-008 N6a @/reply 受控只读形状取证(issue #17):用户重启后 PID `39552`(创建 `2026-11-30T12:14:16.9408969Z`),preflight PASS、attach 4.45s、`login_ok=true`;360s 窗口 version/status 72/72、login 36/36(Stella/1694717255),Caligo 零发送;18 条形状报告、10 个唯一形状:at `[1]`/`atType=2`/`atUid` 十进制/`atNtUid` uid/`atTinyId` 十进制,reply `[7,1]`/`elementType=7`/`replayMsgId`、`replayMsgSeq` 十进制/`sourceMsgText` 空/17 键,另有 `[7,1,6]`、`[6]`、`[8]`、`[10]`、`[16]`。用户确认已发两条,但群流量使逐条归因未证;两次窗口形状一致,可作实现输入,不能作能力验收。journal 51 Event 无缺口、停止 exit 0、bridge 保留、QQ 响应;`soak.overall=fail` 仅因未安排 core 重启。PID 39552 已消耗、不得重接;`feat-008` 仍 in-progress,issue #17 未关闭。下一步:先确定逐元素文本边界策略(补内容长度/mention 前缀诊断,或保守保留原文),再实现入站渲染与出站 @/reply 发送。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + +2026-11-29 feat-008 N6a @/reply 只读形状取证(issue #17):审计确认入站非零 `atType`/`replyElement` 会被 D8 整条拒绝并丢正文,出站 `at`/`reply` 段显式 1400;新增有界 `receive_segment_shape` 诊断与 `scripts/n6/` 取证包。现场尝试一次(PID `25344`,release `0C5A91ED…68375B` / bridge `70BF6DE9…0E551`):preflight/attach/`listener_armed` 通过、Caligo 零发送;`06:30:33Z`–`06:32:37Z` 捕获 7 条形状(5 个唯一:at `atType=2`、`atUid` 十进制、`atNtUid` uid、`atTinyId` 十进制;reply `elementType=7` 与文本共存、`replayMsgId/Seq` 十进制、`sourceMsgText` 空、17 键;另有 elementType 16/5),journal 18 Event 无缺口、停止 exit 0、bridge 保留。但 `get_login_info` 1502、`attach_login_ok=false`,身份未确认且群流量非受控,形状只算真实观察、不算受控证据;`feat-008` 仍 in-progress,issue #17 未关闭。下一步:正常重启 QQ、以登记 B 登录并打开聊天窗口,指定新 PID/创建时间;扩展逐元素诊断后做受控复验,再实现 @/reply 渲染与发送。 [记录](docs/acceptance/2026-11-29-feat-008-n6a-shape-probe.md) + 2026-11-28 feat-007 N5 24h 最终现场通过(issue #16):`e9db64a`(EXE `58D9CAE9…2C99`)在 `2026-11-27T14:10:19Z`–`2026-11-28T14:10:19Z` 跑满 86,426s:1439 samples、version/status 2878/2878、登录 1439/1439、3/3 次 core 重启 0.18/0.19/0.19s、journal 4,837 Event(无缺口/0 重复/0 Gap)、WS 消费者 4,708 条(1,533 次空闲重连、3 次错误,客户端少收 129 条)、bridge/QQ/资源正常。24h 门关闭。补做新代次重绑样本:新鲜 QQ 主根以 generation=2 + 新 journal/pipe/token 一次 attach,108s 样本 0 探测失败、一次 core 重启 0.18s 恢复,新 journal 8 Event 且 session_generations=[2],旧 gen1 journal 4,921,410 bytes / SHA-256 A026E296…A833F 前后不变;零发送、无旧请求重放。issue #16 四条 done criteria 均有证据,已于 2026-11-28T14:24:01Z 关闭;`feat-007` 仍 in-progress(依赖 feat-006 未 done,产品 NOT READY)。真实 TCP 背压、native 寿命/owner-stop 仍是已记录边界。原始材料只在 ignored `local-evidence/feat007-n5-final4-20261127-unbound/` 与 `feat007-n5-rebind-20261128-unbound/`。 [验收记录](docs/acceptance/2026-11-25-feat-007-n5-release.md) 2026-11-27 feat-007 N5 最终 24h(issue #16):修正 attempt 2 的登录查询与无消费者缺口。新构建 `17f5ec6`(`caligo.exe` `4C9B057D…02BB`、bridge `659CE4D1…CE14`)增加持久登录缓存(`login.private.json`;默认 `get_login_info` 走缓存,`no_cache` 走 native)与 forward-WS 事件消费者(`scripts/n5/ws_drain.ps1`,只记录计数)。离线启动包/未知版本门 PASS;`init.ps1 -Mode all` default 509 / research 569、0 failed。最终 24h 于 `2026-11-27T01:38:44Z` 在新主根 `33284`(创建 `2026-11-27T01:37:42.0474720Z`,账号 B)启动,8h 处发现 WS 消费者 5s 取消重连(5,157 次、309 条)与 control `DrainEvents` 诊断队列满时拒绝 wrapper/projection 事件(2,848 Gap);control Stop 后 daemon 未退出,force-kill,bridge 保留。已修正队列语义与 WS 30s 取消/45s 停止等待,新增 runtime/wrapper 回归,`init.ps1 -Mode all` default 510 / research 570;新构建 `e9db64a`(EXE `58D9CAE9…2C99`)启动包/未知版本门 PASS。attempt 4 于 `2026-11-27T14:10:19Z` 在新主根 `22560`(创建 `2026-11-27T14:09:56.6234676Z`,账号 B)启动(WS 消费者 + 登录缓存,+2h/+8h/+16h 重启,预计 `2026-11-28T14:10:19Z` 结束);定时任务 `schedule-414615f1-3bb4-476d-be17-e17a099d6245` 在 `2026-11-28T22:30+08:00` 核验,不自动关闭 issue #16。QQ 重启后新代次重绑与真实 TCP 背压仍未闭合。原始材料只在 ignored `local-evidence/feat007-n5-final-20261127-unbound/`。 [验收记录](docs/acceptance/2026-11-25-feat-007-n5-release.md)