Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 83 additions & 29 deletions pkgs/id/src/web/collab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -380,6 +380,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;
Expand Down Expand Up @@ -698,6 +701,44 @@ pub async fn ws_collab_handler(
})
}

async fn store_and_broadcast_cursor(
doc: &Document,
client_id: u64,
head: u32,
anchor: u32,
cached_display_name: Option<String>,
incoming_name: Option<String>,
identity_client_id: Option<String>,
) -> Option<String> {
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.
async fn handle_collab_socket(
socket: WebSocket,
Expand Down Expand Up @@ -1097,7 +1138,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={:?}",
Expand All @@ -1107,33 +1161,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");
Expand Down Expand Up @@ -1413,6 +1440,33 @@ mod tests {
}
}

#[allow(clippy::unwrap_used, clippy::panic)]
#[tokio::test]
async fn test_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() {
Expand Down
64 changes: 43 additions & 21 deletions pkgs/id/src/web/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>) -> Option<String> {
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<String>) -> Option<String> {
name.map(|name| {
name.chars()
.filter(|ch| !ch.is_control() && !is_bidi_override_or_isolate(*ch))
.take(MAX_NAME_LENGTH)
.collect::<String>()
.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).
Expand Down Expand Up @@ -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]
Expand Down
18 changes: 18 additions & 0 deletions pkgs/id/web/src/collab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,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 {
Expand Down
Loading