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
69 changes: 69 additions & 0 deletions pkgs/id/src/web/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>) -> 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);
}
}
45 changes: 44 additions & 1 deletion pkgs/id/web/src/collab.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
Expand Down Expand Up @@ -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();
});
});
12 changes: 12 additions & 0 deletions pkgs/id/web/src/collab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions pkgs/id/web/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -954,7 +954,7 @@ async function init(): Promise<void> {
// 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(
Expand Down
Loading