Merge pull request #2406 from 52Rain/codex/fix-legacy-share-welcome

M9: accept legacy Welcome messages without reconnect secrets
This commit is contained in:
BFlat
2026-11-27 16:12:32 +07:00
committed by GitHub
9 changed files with 110 additions and 7 deletions
+2 -1
View File
File diff suppressed because one or more lines are too long
+3
View File
@@ -14,6 +14,9 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.52Rain]
display_name = "Aether Sylvan"
[people.VanTan666]
display_name = "VanTan"
+1 -1
View File
@@ -235,7 +235,7 @@ impl<S: Socket> Driver<S> {
if bytes.len() > self.cfg.limits.max_server_message {
return self.end(too_large(&self.cfg.limits), now);
}
let taken = match message::decode::<ServerMsg>(bytes, self.cfg.limits.max_server_message) {
let taken = match message::decode_server(bytes, self.cfg.limits.max_server_message) {
// The join code's answer (or the team list's): join the file, on a new connection.
Ok(ServerMsg::Resolved { file, token }) if self.cfg.lookup.is_some() => {
return match resolved(&mut self.cfg, file, token) {
+29
View File
@@ -126,6 +126,35 @@ fn hello_then_the_welcome_releases_presence() {
assert!(!d.done());
}
#[test]
fn legacy_welcome_is_view_only_and_reconnects_with_a_fresh_hello() {
let mut w: ServerMsg = message::decode(&welcome(), usize::MAX).unwrap();
let ServerMsg::Welcome { access, secret, .. } = &mut w else { panic!("no welcome") };
*access = figcraft_collab::Access::View;
*secret = 0;
let mut legacy = encode(&w);
assert_eq!(legacy.pop(), Some(0));
let t0 = Instant::now();
let (mut d, inbox) = start(Script::default(), t0);
d.opened(t0);
inbox.drain();
d.message(&legacy, t0);
assert!(!d.done());
assert!(inbox.drain().iter().any(|e| matches!(e, Event::Welcome { info, .. } if info.access == figcraft_collab::Access::View)));
d.closed(1006, "connection dropped", t0);
let again = d.deadline().unwrap();
d.tick(again);
d.opened(again);
let Some(ClientMsg::Hello(h)) = d.sock.sent.last() else { panic!("no hello") };
assert_eq!(h.resume, None, "old hosts must re-authenticate the link, not resume without a secret");
assert_eq!(h.token, TOKEN);
d.message(&legacy, again);
assert!(!d.done());
assert!(inbox.drain().iter().any(|e| matches!(e, Event::Welcome { info, .. } if info.access == figcraft_collab::Access::View)));
}
#[test]
fn presence_is_throttled_and_quiet_connections_ping() {
let t0 = Instant::now();
+2 -2
View File
@@ -16,7 +16,7 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError, channel}
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use figcraft_collab::message::{self, ClientMsg, HostInfo, Presence, ServerMsg};
use figcraft_collab::message::{self, ClientMsg, HostInfo, Presence};
use figcraft_doc::Document;
use figcraft_engine::live::{Event, Published, Status};
use tungstenite::protocol::frame::coding::CloseCode;
@@ -378,7 +378,7 @@ fn read_loop(mut ws: WebSocket<Duplex>, ctx: &ReaderCtx) {
let mut seen = Seen::default();
let outcome = loop {
match ws.read() {
Ok(Message::Binary(b)) => match message::decode::<ServerMsg>(&b, ctx.cfg.limits.max_server_message) {
Ok(Message::Binary(b)) => match message::decode_server(&b, ctx.cfg.limits.max_server_message) {
Ok(m) => {
let welcomed = || {
let _ = ctx.tx.send(Cmd::Welcomed(ctx.epoch));
+3 -1
View File
@@ -213,7 +213,9 @@ pub(crate) type Resuming = Mutex<Option<Resume>>;
/// was.
pub(crate) fn hello(cfg: &GuestConfig, resume: &Resuming) -> ClientMsg {
let mut hello = Client::hello(&cfg.invite.file, &cfg.invite.token, &cfg.name, "");
if let (ClientMsg::Hello(h), Some(r)) = (&mut hello, resume.lock().ok().and_then(|r| *r)) {
// A legacy host supplied no reconnect credential and cannot read the new Resume field.
// Re-authenticate with the share link instead of claiming an unauthenticated client id.
if let (ClientMsg::Hello(h), Some(r)) = (&mut hello, resume.lock().ok().and_then(|r| *r).filter(|r| r.secret != 0)) {
h.resume = Some(r);
}
hello
+37
View File
@@ -11,6 +11,43 @@ use crate::message::{
use crate::sim::Rng;
use crate::{Error, Replica, diff};
#[test]
fn legacy_welcome_without_secret_preserves_access_and_snapshot() {
for access in [Access::View, Access::Comment, Access::Edit] {
let welcome = ServerMsg::Welcome {
session: 77,
client_id: 4,
seq: 10,
catch_up: CatchUp::Snapshot(Replica::new(Document::new("Legacy share")).snapshot().unwrap()),
processed: Processed::default(),
peers: vec![],
access,
secret: 0,
};
let mut legacy = encode(&welcome).unwrap();
assert_eq!(legacy.pop(), Some(0), "omit only the final reconnect secret");
assert!(decode::<ServerMsg>(&legacy, legacy.len()).is_err(), "the strict decoder reproduces the old-host failure");
assert_eq!(crate::message::decode_server(&legacy, legacy.len()).unwrap(), welcome);
assert!(crate::message::decode_server(&legacy, legacy.len() - 1).is_err(), "keep the size limit");
assert!(crate::message::decode_server(&legacy[..legacy.len() - 1], legacy.len()).is_err(), "access is mandatory");
let mut partial_secret = legacy.clone();
partial_secret.push(0x80);
assert!(crate::message::decode_server(&partial_secret, usize::MAX).is_err(), "do not hide a truncated secret");
legacy[0] = WIRE_VERSION + 1;
assert!(crate::message::decode_server(&legacy, usize::MAX).is_err(), "keep the wire version check");
}
}
#[test]
fn server_compatibility_keeps_current_messages_and_rejects_trailing_bytes() {
for msg in samples().1 {
let mut bytes = encode(&msg).unwrap();
assert_eq!(crate::message::decode_server(&bytes, bytes.len()).unwrap(), msg);
bytes.push(0);
assert!(crate::message::decode_server(&bytes, usize::MAX).is_err(), "trailing bytes after {msg:?}");
}
}
#[test]
fn encoding_into_a_prefix_keeps_the_wire_body() {
let msg = moved_layer();
+30
View File
@@ -1116,6 +1116,36 @@ pub fn decode<T: DeserializeOwned>(bytes: &[u8], max_bytes: usize) -> Result<T,
from_postcard(body)
}
/// Read a server message, including the original welcome without a reconnect secret.
/// `serde(default)` handles absent JSON fields, but postcard reports EOF for that missing
/// final field. Accept only a complete legacy welcome, including its explicit access level;
/// malformed messages, partial secrets and trailing bytes still fail closed.
pub fn decode_server(bytes: &[u8], max_bytes: usize) -> Result<ServerMsg, Error> {
let error = match decode(bytes, max_bytes) {
Ok(msg) => return Ok(msg),
Err(error) => error,
};
let Some(body) = bytes.strip_prefix(&[WIRE_VERSION, 0]) else { return Err(error) };
if bytes.len() > max_bytes {
return Err(error);
}
#[derive(Deserialize)]
struct LegacyWelcome {
session: u64,
client_id: u32,
seq: u64,
catch_up: CatchUp,
processed: Processed,
peers: Vec<Peer>,
access: Access,
}
let Ok(LegacyWelcome { session, client_id, seq, catch_up, processed, peers, access }) = from_postcard(body) else {
return Err(error);
};
// Zero is the existing sentinel for a host that supplied no reconnect credential.
Ok(ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret: 0 })
}
/// One postcard value that fills `body` (no trailing bytes).
fn from_postcard<T: DeserializeOwned>(body: &[u8]) -> Result<T, Error> {
let (msg, rest) = postcard::take_from_bytes::<T>(body).map_err(|e| Error::Decode(e.to_string()))?;
+3 -2
View File
@@ -1,6 +1,6 @@
# Collaboration parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-26 · **Change:** minor (shared branches sync across live sessions and survive `figcraft-server` restarts, capability-gated on `branches`; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-26 · **Change:** minor (legacy welcomes without a reconnect secret are accepted with their explicit access level, and reconnects re-authenticate with the share link (#2365); a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); shared branches sync across live sessions and survive `figcraft-server` restarts, capability-gated on `branches`; numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
@@ -16,7 +16,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Live cursors, selections, viewports; follow / observation mode; spotlight | yes | **done, in live sessions**: named cursors (one name for live sessions and comments: Preferences ▸ Your name, also in the Share popover and the Join dialog, kept in the browser too; a rename shows at once in the sessions you're in, #1380), selection outlines, avatars (an AI agent attached over MCP also shows its avatar and an outline around the layers it last edited or selected while it works, in or out of a session, #1416), follow (click an avatar), others' text carets and selected characters with their names, a note when two people type in one layer; spotlight (your avatar's menu, `collab.spotlight`): everyone follows your view and page, people who join later too, anyone who moves their view stops following and a banner offers to follow again, a newer spotlight takes over. Left: polish (no accounts, so anyone in the session can spotlight) | 2–4 |
| Cursor chat, audio, high-fives | yes | **partial, in live sessions**: cursor chat (`/` opens a bubble at your pointer; everyone sees it as you type, it fades a few seconds after the last change, Enter sends and Escape takes it back, 100 characters; `collab.cursorChat` for agents); sent as ephemeral presence the host checks and rate-limits, never stored. No audio, high-fives or emote reactions | 2–5 |
| Opening page of a shared file | the page a link names, else the first | **partial**: a file joined from a server opens on its opening page, which is the open document's current page: the page the file was opened on (the page stored in the file when it was opened, else the first page) until someone sets one, not always the first page; a later page switch, a save on another page or publishing does not move it (a local save stamps the page being viewed into the saved file's bytes for the next time that file is opened, but does not change the open document's opening page, which is the synced property, and a link cannot name a page; `page.setOpening {id?}` (the pages list's Set as opening page, the MCP server too) writes it as a document change, one undo step, so everyone who joins afterwards lands on it, unless a spotlight is on, in which case they follow the spotlighter's page instead; each viewer's own page stays their own (#1817) | — |
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 |
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. Older servers whose `Welcome` ends after its access level can be joined without a reconnect secret; reconnects authenticate with the share link again, without reusing an unauthenticated client id. No accounts, teams or projects | 8–17 |
| Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) |
| Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Developer Mode compares a ready-for-dev layer with its state when marked) | — |
| Branching and merging | yes (paid plans) | **done, also shared in live sessions**: branches saved in the `.figcraft` file, each opened in its own tab; Review and merge shows both sides' changes since the branch was made and the conflicts (the same property on both sides, or a layer deleted on one side and edited on the other), each resolved for the branch or main; merge as one undo step (the branch is archived, the main file's history gets a version for the merge), update from main, archive. Each branch keeps its own version history (saved, viewed and restored on the branch tab, kept when it is merged or archived; entries for its creation and updates from main); fills, strokes, effects, layout grids, export settings, guides, interactions, annotations and Developer Mode resources merge item by item. Auto layout settings (a frame's and a child's) merge field by field, each field changed both ways a conflict of its own (`<id>/layout.padding`), and sizes and places auto layout works out (hugging, filling, a child's place) or that an instance takes from its main are no conflict: the merged file lays them out again. In a live session whose server supports shared branches (`branches` capability), branch creation, edits, updates from main, and merge/archive state sync across everyone in the session and persist across `figcraft-server` restarts (up to 64 branches; view and comment links cannot mutate branches; older clients and servers fall back to local-only branches); any editor can open, co-edit, review and merge a peer's branch, with each editor allocating ids in their own client space far above main's and merging as one edit everyone gets (closing open tabs on peers). Left: text runs conflict as a whole; a branch's own version history stays local; a branch made offline that adds layers merges only outside a session | 1–2 |
@@ -28,6 +28,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | M10, gap 17: shared branches sync across live sessions. Capability-gated on `branches` in `Hello::client_version` (`ServerMsg::Branches` / `Branch`, `ClientMsg::Branch` with `Create`, `Edit`, `UpdateFromMain`, `SetState`), persisted in `SessionState::branches` and the server journal (with fallback decoding for pre-branch `figcraft-server` snapshots). Any editor can open, co-edit, update from main, review, archive and merge another peer's branch (remote merges/archives close open branch tabs on peers and switch back to main); view and comment links are refused; node/entry id spaces, geometry and image entries are validated on every branch mutation; older clients and servers stay compatible (local-only branches). Tests: `collab::branch_tests`, `engine::branch_live_tests`, `figcraft-server::server_tests::shared_branches_sync_and_survive_a_server_restart`, `figcraft-server::disk::tests::decode_snapshot_reads_pre_branch_v1_snapshots`. Numbers unchanged. |
| 2026-11-16 | patch | M9, #2365: a server predating reconnect secrets sends a complete `Welcome` ending at `access`; postcard does not honor a missing trailing field through `serde(default)`. The client reads that exact legacy layout, preserves access, and keeps strict size, version and message-boundary checks. Native and browser transports use this reader; reconnects without a secret send a fresh authenticated hello. Covered by codec and connection-driver regressions. A patched 0.15.1 desktop build was also checked against the public service with separate view-only access and annotation reads; writes remained denied. The public server still needs upgrading. Numbers unchanged. |
| 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. |
| 2026-11-04 | minor | M9, #1817: a file on a server opened on the page that was current at publish time, with no way to change it: `DocProp::CurrentPage` was synced but nothing wrote it. `page.setOpening {id?}` (the pages list's "Set as opening page", the MCP server too) writes the opening page as a document change, one undo step, so everyone who joins afterwards lands on it; a divider is refused; nobody's own page moves. Tests: `page_opening_tests`, `collab_live_tests::the_opening_page_syncs_and_moves_no_ones_view`. Numbers unchanged. |
| 2026-11-04 | minor | M9: a session you joined no longer turns into a local file by itself. A dropped connection reconnects until you leave (a minute's pause after each 12 attempts, a pause Retry now skips); only the host ending the session and refusals that are for good stop it; queued messages go out paced. While disconnected the tab shows a red mark and a strip across the canvas says so; a session that ended stays on its tab with Try again, Save a copy and Dismiss |