From cbfb52a64103c85b4008a4d575b2edaa1ac00b0e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:55:32 -0600 Subject: [PATCH 1/3] fix(id): sanitize collaborative cursor names --- pkgs/id/src/web/collab.rs | 117 ++++++++++++++++++++++++++---------- pkgs/id/src/web/identity.rs | 64 +++++++++++++------- 2 files changed, 129 insertions(+), 52 deletions(-) diff --git a/pkgs/id/src/web/collab.rs b/pkgs/id/src/web/collab.rs index e1890059ad..c38accf74f 100644 --- a/pkgs/id/src/web/collab.rs +++ b/pkgs/id/src/web/collab.rs @@ -64,7 +64,7 @@ use std::{ use tokio::sync::{RwLock, broadcast}; use super::content_mode::{ContentMode, detect_mode_with_content}; -use super::identity::short_id; +use super::identity::{sanitize_name, short_id}; use super::markdown::{ markdown_to_prosemirror, plain_text_to_prosemirror, raw_text_to_prosemirror, }; @@ -376,6 +376,9 @@ impl CollabState { /// Finds all cursors with the matching `identity_client_id`, updates the /// stored name, and broadcasts the updated cursor to all connected clients. pub async fn update_client_name(&self, identity_client_id: &str, new_name: &str) { + let Some(new_name) = sanitize_name(Some(new_name.to_owned())) else { + return; + }; let docs = self.documents.read().await; for (doc_id, doc) in docs.iter() { let mut cursors = doc.cursors.write().await; @@ -633,7 +636,8 @@ pub async fn ws_collab_handler( Query(params): Query, State(state): State, ) -> impl IntoResponse { - ws.on_upgrade(move |socket| { + ws.max_message_size(crate::world_session::MAX_FRAME_BYTES) + .on_upgrade(move |socket| { handle_collab_socket( socket, doc_id, @@ -642,7 +646,45 @@ pub async fn ws_collab_handler( state.store, state.identity, ) - }) + }) +} + +async fn store_and_broadcast_cursor( + doc: &Document, + client_id: u64, + head: u32, + anchor: u32, + cached_display_name: Option, + incoming_name: Option, + identity_client_id: Option, +) -> Option { + let effective_name = sanitize_name(cached_display_name.or(incoming_name)); + let client_id_str = client_id.to_string(); + + { + let mut cursors = doc.cursors.write().await; + cursors.insert( + client_id_str, + CursorPosition { + head, + anchor, + name: effective_name.clone(), + identity_client_id, + last_update: Instant::now(), + disconnected_at: None, + }, + ); + } + + let cursor_msg = CollabMessage::Cursor { + client_id, + head, + anchor, + name: effective_name.clone(), + idle_secs: None, + }; + let _ = doc.broadcast.send(cursor_msg); + effective_name } /// Handle a WebSocket connection for collaborative editing. @@ -1076,7 +1118,20 @@ async fn handle_collab_socket( }) ); } - let effective_name = cached_display_name.clone().or(name); + // Remember this client's ID for disconnect cleanup before + // storing and broadcasting its cursor. + *client_id_for_cleanup.write().await = Some(client_id_str); + + let effective_name = store_and_broadcast_cursor( + &doc, + client_id, + head, + anchor, + cached_display_name.clone(), + name, + identity_client_id.clone(), + ) + .await; tracing::debug!( "[collab] Received Cursor: client={}, head={}, anchor={}, name={:?}", @@ -1086,33 +1141,6 @@ async fn handle_collab_socket( effective_name ); - // Remember this client's ID for disconnect cleanup - *client_id_for_cleanup.write().await = Some(client_id_str.clone()); - - { - let mut cursors = doc.cursors.write().await; - cursors.insert( - client_id_str, - CursorPosition { - head, - anchor, - name: effective_name.clone(), - identity_client_id: identity_client_id.clone(), - last_update: Instant::now(), - disconnected_at: None, - }, - ); - } - - // Broadcast cursor position to all clients (no idle_secs for live updates) - let cursor_msg = CollabMessage::Cursor { - client_id, - head, - anchor, - name: effective_name, - idle_secs: None, - }; - let _ = doc.broadcast.send(cursor_msg); } _ => { tracing::debug!("[collab] Received unexpected message type, ignoring"); @@ -1353,6 +1381,33 @@ mod tests { } } + #[allow(clippy::unwrap_used, clippy::panic)] + #[tokio::test] + async fn cursor_ingest_sanitizes_before_storage_and_broadcast() { + let doc = Document::new(); + let mut updates = doc.broadcast.subscribe(); + + let name = store_and_broadcast_cursor( + &doc, + 54321, + 100, + 50, + None, + Some("A\n\u{202e}lice".to_owned()), + None, + ) + .await; + assert_eq!(name.as_deref(), Some("Alice")); + + let stored = doc.cursors.read().await.get("54321").unwrap().name.clone(); + assert_eq!(stored.as_deref(), Some("Alice")); + + match updates.recv().await.unwrap() { + CollabMessage::Cursor { name, .. } => assert_eq!(name.as_deref(), Some("Alice")), + _ => panic!("Expected sanitized cursor broadcast"), + } + } + #[allow(clippy::unwrap_used, clippy::panic)] #[test] fn test_collab_message_cursor_without_name() { diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index d77cc84925..e351c91f0d 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -58,8 +58,8 @@ use sha2::Sha256; use tokio::sync::RwLock; use tokio::sync::watch; -/// Maximum allowed display name length (bytes). -const MAX_NAME_LENGTH: usize = 64; +/// Maximum allowed display name length (Unicode scalar values). +const MAX_NAME_LENGTH: usize = 48; /// Maximum token age before it's considered expired (30 days in seconds). const TOKEN_MAX_AGE_SECS: u64 = 30 * 24 * 60 * 60; @@ -408,22 +408,28 @@ fn hex_encode(bytes: &[u8]) -> String { }) } -/// Sanitize a display name: trim whitespace, enforce max length, return `None` if empty. -fn sanitize_name(name: Option) -> Option { - name.map(|n| n.trim().to_owned()) - .filter(|n| !n.is_empty()) - .map(|n| { - if n.len() > MAX_NAME_LENGTH { - // Truncate at char boundary - let mut end = MAX_NAME_LENGTH; - while !n.is_char_boundary(end) && end > 0 { - end -= 1; - } - n[..end].to_owned() - } else { - n - } - }) +/// Sanitize a display name consistently for identities and cursor frames. +pub(super) fn sanitize_name(name: Option) -> Option { + name.map(|name| { + name.chars() + .filter(|ch| !ch.is_control() && !is_bidi_override_or_isolate(*ch)) + .take(MAX_NAME_LENGTH) + .collect::() + .trim() + .to_owned() + }) + .filter(|name| !name.is_empty()) +} + +fn is_bidi_override_or_isolate(ch: char) -> bool { + matches!( + ch, + '\u{061c}' + | '\u{200e}' + | '\u{200f}' + | '\u{202a}'..='\u{202e}' + | '\u{2066}'..='\u{2069}' + ) } /// Create a short display ID from a `client_id` (first 6 chars). @@ -871,10 +877,26 @@ mod tests { Some("Bob".to_owned()) ); - // Long name truncation - let long_name = "a".repeat(100); + assert_eq!( + sanitize_name(Some("A\n\t\u{001b}\u{202e}lice".to_owned())), + Some("Alice".to_owned()) + ); + assert_eq!( + sanitize_name(Some("A\u{061c}\u{200e}\u{200f}\u{202a}\u{202d}\u{202e}\u{2066}\u{2067}\u{2068}\u{2069}B".to_owned())), + Some("AB".to_owned()) + ); + assert_eq!( + sanitize_name(Some("a\u{200d}b\u{200c}c".to_owned())), + Some("a\u{200d}b\u{200c}c".to_owned()) + ); + assert_eq!( + sanitize_name(Some("こんにちは世界".to_owned())), + Some("こんにちは世界".to_owned()) + ); + + let long_name = "界".repeat(50); let sanitized = sanitize_name(Some(long_name)).unwrap(); - assert!(sanitized.len() <= MAX_NAME_LENGTH); + assert_eq!(sanitized.chars().count(), MAX_NAME_LENGTH); } #[test] From 72a3897018f3f95cf1dd35706eb070da5bd90de4 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 04:26:07 -0600 Subject: [PATCH 2/3] fix(id): never send over-cap collab messages (Codex P2 on #4052) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 1 MiB max_message_size added for #1833 closes the socket when exceeded, and the reconnect INIT rebuild discards every unconfirmed local edit — a >1 MiB paste would be lost. Guard send() in web/src/collab.ts: a packed message over MAX_FRAME_BYTES is dropped with an error status instead of sent, keeping the socket and the local document alive; the edit simply cannot sync until it is smaller. True chunked sending of oversized step batches is filed as #4324. --- pkgs/id/web/src/collab.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/pkgs/id/web/src/collab.ts b/pkgs/id/web/src/collab.ts index b313cc6f7e..562ba93ee7 100644 --- a/pkgs/id/web/src/collab.ts +++ b/pkgs/id/web/src/collab.ts @@ -135,9 +135,27 @@ export function initCollab( if (onStatus) onStatus(status); }; + // The server caps WebSocket messages at MAX_FRAME_BYTES (1 MiB; + // pkgs/id/src/frames.rs, applied as max_message_size in + // pkgs/id/src/web/collab.rs) and exceeding it closes the socket. + // On reconnect the INIT handler rebuilds the editor from server + // state, so one oversized STEPS message (e.g. a >1 MiB paste) + // would silently discard every unconfirmed local edit. Never send + // an over-cap message: dropping it keeps the socket — and the + // local document — alive, and the error status says why sync is + // stuck. Splitting oversized step batches is tracked separately. + const MAX_MESSAGE_BYTES = 1024 * 1024; + // Encode and send a message (always uses currentWs) const send = (msgType: number, ...fields: unknown[]): void => { const data = packr.pack([msgType, ...fields]); + if (data.byteLength > MAX_MESSAGE_BYTES) { + console.error( + `[collab] not sending oversized message (type ${msgType}, ${data.byteLength} bytes > ${MAX_MESSAGE_BYTES} cap); local changes are preserved but cannot sync until they are smaller`, + ); + updateStatus("error"); + return; + } if (connected && currentWs && currentWs.readyState === WebSocket.OPEN) { currentWs.send(data); } else { From 134364f20117b0925eb03981b01a4324391599e8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 06:31:52 -0600 Subject: [PATCH 3/3] fix(id): close ws_collab_handler after merge resolution (task 5053) --- pkgs/id/src/web/collab.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pkgs/id/src/web/collab.rs b/pkgs/id/src/web/collab.rs index f54743a692..c7d20f8b2f 100644 --- a/pkgs/id/src/web/collab.rs +++ b/pkgs/id/src/web/collab.rs @@ -699,6 +699,7 @@ pub async fn ws_collab_handler( state.identity, ) }) +} async fn store_and_broadcast_cursor( doc: &Document,