diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 3319baf40d..fe14920a4c 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -3745,3 +3745,72 @@ mod tests { } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod collab_route_tests { + //! Route-level proof for #2830: the production router registers + //! `/ws/collab/{doc_id}` as a single-segment route (see + //! `create_router`); the web client percent-encodes the docId into + //! that one segment, and axum matches the raw path, so `%2F` stays + //! inside the segment and Path extraction percent-decodes it back + //! to the exact filename — while a real second segment still + //! fails to match. This mini-router uses the identical route + //! pattern on the same axum stack; the handler is an echo so the + //! decoded value itself is asserted. (Behavior verified against + //! the locked axum 0.8.9 with a standalone probe on 2026-11-02; + //! in-crate execution currently waits on #4340.) + use axum::{ + Router, + body::{Body, to_bytes}, + extract::Path, + http::{Request, StatusCode}, + routing::get, + }; + use tower::ServiceExt as _; + + async fn echo_doc_id(Path(doc_id): Path) -> String { + doc_id + } + + async fn get(uri: &str) -> (StatusCode, String) { + let app = Router::new().route("/ws/collab/{doc_id}", get(echo_doc_id)); + let response = app + .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = response.status(); + let bytes = to_bytes(response.into_body(), 1024).await.unwrap(); + (status, String::from_utf8(bytes.to_vec()).unwrap()) + } + + #[tokio::test] + async fn encoded_slash_round_trips_to_the_exact_filename() { + assert_eq!( + get("/ws/collab/a%2Fb.md").await, + (StatusCode::OK, "a/b.md".to_owned()) + ); + } + + #[tokio::test] + async fn encoded_percent_names_round_trip() { + // a%20b.md the file, not "a b.md": the client sends a%2520b.md. + assert_eq!( + get("/ws/collab/a%2520b.md").await, + (StatusCode::OK, "a%20b.md".to_owned()) + ); + assert_eq!( + get("/ws/collab/100%25.md").await, + (StatusCode::OK, "100%.md".to_owned()) + ); + assert_eq!( + get("/ws/collab/notes.md").await, + (StatusCode::OK, "notes.md".to_owned()) + ); + } + + #[tokio::test] + async fn a_real_second_segment_does_not_match() { + assert_eq!(get("/ws/collab/a/b.md").await.0, StatusCode::NOT_FOUND); + } +} diff --git a/pkgs/id/web/src/collab.test.ts b/pkgs/id/web/src/collab.test.ts index 9ca5de86f8..4326898029 100644 --- a/pkgs/id/web/src/collab.test.ts +++ b/pkgs/id/web/src/collab.test.ts @@ -1,6 +1,6 @@ import { Packr, Unpackr } from "msgpackr"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, initCollab, stepBatch } from "./collab"; +import { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, buildCollabWsUrl, initCollab, stepBatch } from "./collab"; // Same MessagePack configuration as collab.ts const packr = new Packr({ useRecords: false, structuredClone: true }); @@ -286,3 +286,46 @@ describe("stepBatch (client side of the server step cap, #1965)", () => { expect(batch).toEqual(["exact"]); }); }); + +describe("buildCollabWsUrl (#2830)", () => { + // [docId, expected single path segment] — the segment must decode + // back to the exact docId, and plain names must be untouched. + const cases: Array<[string, string]> = [ + ["notes.md", "notes.md"], + ["a/b.md", "a%2Fb.md"], + ["a#b.md", "a%23b.md"], + ["a?b.md", "a%3Fb.md"], + ["a%20b.md", "a%2520b.md"], + ["100%.md", "100%25.md"], + ["my notes.md", "my%20notes.md"], + ["caf\u00e9.md", "caf%C3%A9.md"], + ]; + it.each(cases)("docId %s -> one segment %s that decodes back exactly", (docId, segment) => { + const url = new URL(buildCollabWsUrl("ws:", "example.test", docId)); + expect(url.pathname).toBe(`/ws/collab/${segment}`); + const parts = url.pathname.split("/"); + expect(parts).toHaveLength(4); // "", "ws", "collab", segment + expect(decodeURIComponent(parts[3])).toBe(docId); + }); + + it("keeps the filename query parameter intact for a # name", () => { + vi.useFakeTimers(); + FakeWebSocket.instances = []; + vi.stubGlobal("WebSocket", FakeWebSocket); + const conn = track( + initCollab( + buildCollabWsUrl("ws:", "example.test", "a#b.md"), + makeContainer(), + "a#b.md", + "a#b.md", + null, + ), + ); + const socket = FakeWebSocket.instances.at(-1)!; + const url = new URL(socket.url); + expect(decodeURIComponent(url.pathname.split("/")[3])).toBe("a#b.md"); + expect(url.searchParams.get("filename")).toBe("a#b.md"); + conn.disconnect(); + vi.useRealTimers(); + }); +}); diff --git a/pkgs/id/web/src/collab.ts b/pkgs/id/web/src/collab.ts index d7c22e6a5b..481507214d 100644 --- a/pkgs/id/web/src/collab.ts +++ b/pkgs/id/web/src/collab.ts @@ -132,6 +132,18 @@ export type StatusCallback = (status: "connecting" | "connected" | "disconnected * @param onEditorReady - Callback when editor is initialized * @returns The collab connection */ +/** + * Build the collab WebSocket URL for a document (#2830). The docId goes + * into a single path segment, so it must be percent-encoded: a raw `/` + * breaks the single-segment route, a raw `#`/`?` truncates the URL + * (losing the query string), and a raw `%20` in a name is decoded by + * the server into a *different* file. The axum route percent-decodes + * the segment, so encoding here round-trips to the exact filename. + */ +export function buildCollabWsUrl(wsProtocol: string, host: string, docId: string): string { + return `${wsProtocol}//${host}/ws/collab/${encodeURIComponent(docId)}`; +} + export function initCollab( wsUrl: string, container: HTMLElement, diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index 236f680e9b..29d441bf0f 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -8,7 +8,7 @@ import { initHome } from "./home"; import "./world"; import "./world"; import { AutoSaveManager, type SaveResult } from "./auto-save"; -import { type CollabConnection, initCollab } from "./collab"; +import { buildCollabWsUrl, type CollabConnection, initCollab } from "./collab"; import { type EditorInstance, getEditorState } from "./editor"; import { updateHeaderSubtitle } from "./header-subtitle"; import { identityNeedsRefresh } from "./identity-refresh"; @@ -954,7 +954,7 @@ async function init(): Promise { // Connect to collab server - editor will be initialized after receiving server doc updateStatus("connecting"); const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - const wsUrl = `${wsProtocol}//${window.location.host}/ws/collab/${docId}`; + const wsUrl = buildCollabWsUrl(wsProtocol, window.location.host, docId); console.log("[id] Connecting to WebSocket:", wsUrl); this.collab = initCollab(