From e6a8d2f7bcc5e68f1ffafc679a7de5db407e6c7b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 27 Nov 2026 03:52:05 +0300 Subject: [PATCH] Require an unambiguous channel ID before post-create actions --- CHANGELOG.md | 2 ++ core/src/admin.rs | 35 +++++++++++++++++++++++++---------- docs/bridge.md | 2 +- docs/mobile-port-progress.md | 2 ++ 4 files changed, 30 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3112f1..fdd3150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Channel creation returns an ID only for a matching notification from the same client under the requested parent. An accepted creation without a unique ID asks the caller to reload the tree before applying further changes. + - When creating a channel, changing its parent clears the previous insertion point. The picker lists only children of the new parent; leaving the position unset lets the server choose it. Creating or editing now also checks the selected predecessor at submission and refuses the change if it moved to another parent or disappeared. diff --git a/core/src/admin.rs b/core/src/admin.rs index e12c867..372c03e 100644 --- a/core/src/admin.rs +++ b/core/src/admin.rs @@ -677,8 +677,8 @@ pub enum Reply { /// Rows of `notify` collected until the command result; `key` filters rows by the first /// entry's id (list notifications carry it there only). Rows { notify: &'static str, key: Option<(&'static str, String)>, rows: Vec, overflow: bool, accept: bool }, - /// `channelcreate`: the id comes from our own `notifychannelcreated` with that name. - Created { name: String, invoker: u16, channel_id: Option }, + /// Only an unambiguous creation by our client under the requested parent identifies the new channel. + Created { name: String, parent: u64, invoker: u16, channel_id: Option, ambiguous: bool }, /// `tokenadd`: the key comes from `notifytokenadd`. Token { token: Option }, GroupCreated { notify: &'static str, key: &'static str, name: String, group_id: Option, ambiguous: bool }, @@ -725,11 +725,14 @@ impl Reply { rows.push(row.clone()); } } - Reply::Created { name, invoker, channel_id } if raw.name == "notifychannelcreated" && channel_id.is_none() => { + Reply::Created { name, parent, invoker, channel_id, ambiguous } if raw.name == "notifychannelcreated" => { for row in &raw.items { let mine = row.get("invokerid").and_then(|v| v.parse::().ok()) == Some(*invoker); - if mine && row.get("channel_name").map(String::as_str) == Some(name.as_str()) { - *channel_id = row.get("cid").and_then(|v| v.parse().ok()); + if mine && row.get("channel_name") == Some(name) && row.get("cpid").and_then(|v| v.parse::().ok()) == Some(*parent) { + if let Some(id) = row.get("cid").and_then(|v| v.parse::().ok()).filter(|id| *id != 0) { + if channel_id.is_some_and(|old| old != id) { *ambiguous = true; } + *channel_id = Some(id); + } } } } @@ -775,7 +778,8 @@ pub fn finish(reply: Reply) -> Result { Reply::GroupCreated { group_id: Some(id), ambiguous: false, .. } => Ok(json!({ "group_id": id })), Reply::GroupCreated { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "group was accepted but its ID was not uniquely returned; reload groups before continuing").with_detail(json!({"created": true}))), Reply::ChannelInfo { .. } => Err(ErrorObj::new(ErrorCode::Internal, "channel info is answered by the session")), - Reply::Created { channel_id, .. } => Ok(json!({ "channel_id": channel_id })), + Reply::Created { channel_id: Some(id), ambiguous: false, .. } => Ok(json!({ "channel_id": id })), + Reply::Created { .. } => Err(ErrorObj::new(ErrorCode::ServerError, "channel was accepted but its ID was not uniquely returned; reload channels before continuing").with_detail(json!({"created": true}))), Reply::Token { token: Some(token) } => Ok(json!({ "token": token })), Reply::Token { token: None } => Err(ErrorObj::new( ErrorCode::ServerError, @@ -822,7 +826,7 @@ pub fn build(cmd: &AdminCommand, live: &Live) -> Result<(OutCommand, Reply), Err let mut a = vec![("cpid", s(*parent_id))]; a.extend(properties.iter().map(|(k, v)| (*k, v.clone()))); let name = properties.iter().find(|(k, _)| *k == "channel_name").map(|(_, v)| v.clone()).unwrap_or_default(); - (menu::command("channelcreate", &a), Reply::Created { name, invoker: live.own_client, channel_id: None }) + (menu::command("channelcreate", &a), Reply::Created { name, parent: *parent_id, invoker: live.own_client, channel_id: None, ambiguous: false }) } C::ChannelEdit { channel_id, properties, .. } => { channel_exists(live, *channel_id, "channel")?; @@ -1070,7 +1074,7 @@ mod tests { assert!(text.starts_with("channelcreate cpid=0 "), "{text}"); assert!(text.contains(&format!("channel_password={}", encode_password(b"secret").replace('/', "\\/"))), "{text}"); assert!(text.contains("channel_flag_password=1") && text.contains("channel_flag_permanent=1") && text.contains("channel_codec_quality=10")); - assert!(matches!(reply, Reply::Created { ref name, invoker: 7, channel_id: None } if name == "Lobby")); + assert!(matches!(reply, Reply::Created { ref name, parent: 0, invoker: 7, channel_id: None, .. } if name == "Lobby")); } #[test] @@ -1164,10 +1168,21 @@ mod tests { let rows = finish(r).unwrap(); assert_eq!(rows["rows"].as_array().unwrap().len(), 3); - let mut c = Reply::Created { name: "A b".into(), invoker: 7, channel_id: None }; + let created = || Reply::Created { name: "A b".into(), parent: 0, invoker: 7, channel_id: None, ambiguous: false }; + let mut c = created(); c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=11 cpid=0 channel_name=A\sb invokerid=8").unwrap()); - c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap()); + c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=10 cpid=3 channel_name=A\sb invokerid=7").unwrap()); + c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=0 cpid=0 channel_name=A\sb invokerid=7").unwrap()); + assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError); + let own = crate::rawcmd::parse(br"notifychannelcreated cid=12 cpid=0 channel_name=A\sb invokerid=7").unwrap(); + let mut c = created(); + c.collect(&own); + c.collect(&own); assert_eq!(finish(c).unwrap(), json!({"channel_id": 12})); + let mut c = created(); + c.collect(&own); + c.collect(&crate::rawcmd::parse(br"notifychannelcreated cid=13 cpid=0 channel_name=A\sb invokerid=7").unwrap()); + assert_eq!(finish(c).unwrap_err().code, ErrorCode::ServerError); assert!(finish(Reply::Token { token: None }).is_err(), "no fake success without the key"); let mut t = Reply::Token { token: None }; diff --git a/docs/bridge.md b/docs/bridge.md index 63a6c9a..62ff035 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -665,7 +665,7 @@ For an isolated Windows beta14 fixture at `127.0.0.1:19987`, set `TEAMSPEACH_QA_ | Command | Arguments / result | |---|---| -| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from own channel-created event. A nonzero `channel_order` must still be a child of `parent_id` at dispatch. | +| `channel_create` | `{generation,parent_id,properties}` → `{channel_id}` from the client's own channel-created notification matching name and parent. A nonzero `channel_order` must still be a child of `parent_id` at dispatch. If the server accepted creation but no unique positive ID was received, the error detail contains `created: true`; refresh the tree instead of retrying creation. | | `channel_edit` | `{generation,channel_id,properties}`; a nonzero `channel_order` must still be a sibling distinct from the edited channel. A stale predecessor returns `target_changed` without sending the edit. | | `channel_move` | `{generation,channel_id,parent_id,order?}`; parent 0 means server root, order 0 means first. A nonzero predecessor must still belong to the destination parent. A missing or cyclic destination ancestry, a destination below the moving channel, or a stale predecessor is refused before sending. An exact match of parent and explicit predecessor returns `{"changed":false}` locally, without a server request. An omitted order does not qualify. | | `channel_delete` | `{generation,channel_id,force,confirm}`; confirm exact current channel name | diff --git a/docs/mobile-port-progress.md b/docs/mobile-port-progress.md index be46cc6..ec6dff4 100644 --- a/docs/mobile-port-progress.md +++ b/docs/mobile-port-progress.md @@ -4,6 +4,8 @@ ## Возврат к разработке на ПК, 2026-11-26 +Windows, база `95ebf37`: подтверждение создания канала сопоставляется с автором, именем и родителем. Отсутствие однозначного положительного ID после принятия команды возвращает ошибку с `created: true`. Повтор одного ID допустим. Прошли три адресных теста ядра и нативный тест `post_create_icon_uses_only_acknowledged_child_id`; живой сервер в этой проверке не участвовал. + Windows, база `b3f73c3`: ядро сверяет ненулевой `channel_order` при создании и редактировании канала с текущим деревом перед отправкой. Удалённый или перемещённый в другую ветку сосед и ссылка редактируемого канала на себя отклоняются. Четыре адресных теста ядра прошли; сетевой запрос и ответ сервера в этом прогоне не проверялись. Windows, база `3c828e3`: при создании канала смена родителя очищает позицию и ограничивает список предшественников его детьми. Тест Slint проверил три команды для родителя 8: без `channel_order`, с явным 0 и с ID 13 второго одноимённого соседа. Прошли шесть адресных тестов. Применение этих команд сервером в этом прогоне не проверялось.