diff --git a/docs/research/channel-network-design.md b/docs/research/channel-network-design.md index 1996c8bb6..6d83f67ef 100644 --- a/docs/research/channel-network-design.md +++ b/docs/research/channel-network-design.md @@ -530,6 +530,7 @@ Browser preference; the App holds only the current process registration. | An administration page closes while Server owns the runtime | The deliberately running service continues; its lifetime is independent of that page. | | Browser-owned room runtime closes or expires | The room pauses; Browser hosting must not silently move to the domain owner's device. | | Room owner stops the hosting runtime | The room becomes unavailable; saved data remains. No automatic replacement is selected. | +| A manager deletes or removes a room | Retire its activities and bindings; data disposition follows the [room removal scope](./channel-storage-and-identity.md#room-creation-and-removal). Other rooms keep their leases. | | Same owner restarts using saved room data | Restore room identity/history and establish new live sessions. Captures require explicit activation; reopening data does not resume a saved call. | | Sharer stops or leaves | End that publication, preserving other sources and the room base tree. | | A relay leaves | Repair affected paths through the same route owners; keep unrelated flows. | diff --git a/docs/research/channel-storage-and-identity.md b/docs/research/channel-storage-and-identity.md index 1e2183d11..9a1cc942c 100644 --- a/docs/research/channel-storage-and-identity.md +++ b/docs/research/channel-storage-and-identity.md @@ -1,6 +1,6 @@ # Piik 3.0 Room Data And Hosting -Reviewed 2026-10-28. The [accepted network model](./channel-network-design.md) +Reviewed 2026-11-07. The [accepted network model](./channel-network-design.md) owns responsibilities, routing and live lifecycles. This document records the accepted data ownership and develops synchronization, delivery and recovery. The [prototype README](../../prototype/channel-server/README.md) describes running @@ -325,8 +325,9 @@ process-only room behavior. The [network model](./channel-network-design.md#activity-and-lifecycle) owns hosting availability, signaling recovery and participant lifetimes. When the hosting runtime ends, the room pauses and retains its data. Restarting with the -same data restores that room's identity and history without resuming captures -or calls. Recreating a same-named room without its data creates a new room. +same data restores that room's identity and history while its directory entry +remains admitted, without resuming captures or calls. Recreating a same-named +room without its data creates a new room. The domain directory can retain the unavailable room's summary and owner binding. It does not automatically become a substitute room host or recover data it never @@ -335,6 +336,31 @@ directory entry; continuing that room requires an explicit transfer of hosting and state. Automatic election and offline concurrent writing are outside this first model. +### Room Creation And Removal + +Explicit creation asks the domain for a fresh room ID and creator binding before +the hosting runtime saves its policy. Host registration only binds an existing +directory entry; automatic recovery cannot recreate a removed room. Explicit +backup import may restore an absent entry only with domain-owner approval. +An archive's identifiers do not grant that authority. + +An online room's creator or domain owner can delete its authoritative policy and +history. The hosting runtime commits that local deletion before the domain +confirms directory removal. Removing only a directory entry is a separate user +intent: it retires room access and activity without deleting the host's data, +even if that host comes online during confirmation. The UI offers this operation +for an offline room. Downloaded files and participant-held copies retain their +existing owners. + +The two owners have separate stores. If local deletion commits but the directory +cannot confirm removal, the old binding retires and the summary remains offline +for explicit removal. Already-authorized deletion completion survives the +requester's disconnect; a lost reply cannot keep a nonexistent host available. +Existing directory membership and live binding/revision checks provide recovery +without a second deletion ledger. + +### Backups + Backup follows ownership: a domain export contains the domain's data; a room export contains that room's state and retained local content. A domain export alone cannot include history held only by another room owner. Never give a room diff --git a/docs/todo.md b/docs/todo.md index 863408b43..42b6b4e3a 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -62,32 +62,17 @@ the feedback period; they do not delay that delivery. ## Next -- [ ] **2.x to 3.0 behavior parity.** Review routing/lifecycle, media/input and - App/room-data flows against their maintained 2.x behavior. Separate intended - model changes from missing capability and unnecessary complexity. Keep the - simple sharing mode on the same 3.0 core, preserving quick create/share/join - without requiring the full domain workspace. - [ ] **Playback and interaction parity.** Restore picture-in-picture/theater - viewing, the saved direct-touch/trackpad choice, detail-versus-motion preference, - picture chat overlays and readable chat export through the existing shared + viewing, detail-versus-motion preference, picture chat overlays and readable + chat export through the existing shared components. Restore the launcher's last Local/public mode through its existing preference owner. Check actual reachability; retained component files alone do not provide these controls in the 3.0 room UI. -- [ ] **3.0 room deletion feedback.** Internal testers cannot delete a room; - the current UI and runtime implement settings and hosting pause, but no delete - operation. Add an explicit room/domain-owner action through the existing - authority and storage owners. Confirm history, retained-file and offline-host - disposition before implementing irreversible removal; closing and reopening - must remain distinct from deletion. Schedule after current blocking fixes. - [ ] **3.0 invitation controls feedback.** Distinguish domain admission from a room invitation in the UI. The user confirmed the existing 2.x-style controls: public/private access, a passphrase and resetting the invitation link. Reuse the current permission and settings owners; private-room settings and link rotation already exist, while domain invitation copying has no such controls. -- [ ] **QR invitations.** Reuse the locally generated QR prototype on - `archive/deferred-prototypes` when integrating the invitation controls. Encode - the exact copied URL, including room/access fragments, and provide a scannable - image for sharing from a computer. No external QR service is needed. - [ ] **3.0 forwarding limits feedback.** Add the requested room default and per-endpoint override, allowing an endpoint's choice above or below the default. Use the room's existing base/publication planning owner and actual resource @@ -99,19 +84,16 @@ the feedback period; they do not delay that delivery. opportunities than 2.x, and its central-fallback and route-preference controls are not equivalent. Choose required behavior with the accepted multi-source model before extending existing admission and switch owners. -- [ ] **3.0 capture settings feedback.** Make the existing Windows process-audio - exclusion discoverable from sharing audio settings; it currently lives in the - display source picker with source sound enabled. Reuse the same source settings - and replacement owner for live changes. - [ ] **3.0 Native platform acceptance.** Complete the remaining Linux/macOS device acceptance, including macOS Quit, Dock/Finder return and permissions, and Linux hardware encoding and physical sound. Retain the accepted [network model](./research/channel-network-design.md) and [room-data model](./research/channel-storage-and-identity.md). -- [ ] **First-beta usability follow-up.** Review the sharing-view study before - applying it alongside the full room UI with the same room and route owners. - Restore the App terminal's useful presentation and review the prepared - website/help wording around being unable to join a friend's room. +- [ ] **Simple sharing view.** Apply the reviewed sharing-view study alongside + the full room UI on the same 3.0 core and session. Preserve quick create/share/join + without requiring the domain workspace or reviving separate 2.x controllers. +- [ ] **Entry presentation.** Restore the App terminal's useful presentation + and review the prepared website/help wording for joining a friend's room. - [ ] **Native H264 scene-change latency.** Reduce encoded bursts while preserving low-rate startup and live bitrate restoration. Keep CBR; the [encoder assessment](./research/webrtc-encoder-pool.md#h264-burst-and-recovery) diff --git a/prototype/channel-browser/src/room-host.ts b/prototype/channel-browser/src/room-host.ts index 38ff76b9e..f6825f6b7 100644 --- a/prototype/channel-browser/src/room-host.ts +++ b/prototype/channel-browser/src/room-host.ts @@ -24,7 +24,7 @@ interface ReadRequest { type: "read"; roomId: string; before: number | null } interface AttachmentRequest { type: "attachment"; roomId: string; messageSeq: number; attachmentId: string } interface ReactionRequest { type: "set_reaction"; roomId: string; messageSeq: number; userId: string; reaction: string; active: boolean } type HistoryRequest = SendRequest | ReadRequest | AttachmentRequest | ReactionRequest; -interface HostWork { policy: object | null; history: HistoryRequest | null } +interface HostWork { policy: object | null; history: HistoryRequest | null; delete: boolean } type ConversationWork = { type: "history"; value: HistoryRequest } | { type: "immediate"; value: ConversationReply["record"] }; type ConversationResult = { type: "history"; value: HistoryResult } | { type: "immediate"; value: ConversationReply["record"] }; @@ -304,7 +304,13 @@ export class BrowserRoomHost { const work: HostWork = JSON.parse(this.room.dispatch(JSON.stringify(input))); try { let result: HistoryResult | undefined; - if (work.history) result = await this.executeHistory(work.history, work.policy, signal); + if (work.delete) { + await this.roomTransaction(["rooms", "messages"], "readwrite", tx => { + tx.objectStore("rooms").delete(this.roomId); + tx.objectStore("messages").delete(IDBKeyRange.bound([this.roomId], [this.roomId, Infinity])); + }, () => {}, signal); + this.bindingId = undefined; + } else if (work.history) result = await this.executeHistory(work.history, work.policy, signal); else await this.roomTransaction(["rooms"], work.policy ? "readwrite" : "readonly", tx => { this.savePolicy(tx, work.policy); }, () => {}, signal); diff --git a/prototype/channel-core/src/channel.rs b/prototype/channel-core/src/channel.rs index a6f5198a2..ec2fe6609 100644 --- a/prototype/channel-core/src/channel.rs +++ b/prototype/channel-core/src/channel.rs @@ -117,6 +117,9 @@ impl Channel { broadcast = true; } Command::HostRegister { .. } + | Command::CreateRoom { .. } + | Command::AdmitRoom { .. } + | Command::DeleteRoom { .. } | Command::HostOutput { .. } | Command::HostStop { .. } => return Err("invalid_request"), Command::SetRoles { @@ -506,28 +509,12 @@ impl Channel { let member = self .identity .member(self.identity.sessions[&session].user_id)?; - if summary.creator_id != member.user_id - || (!self.remote.contains_key(&summary.id) && !member.participates) - { + if summary.creator_id != member.user_id { return Err("forbidden"); } - if !valid_id(&summary.id) - || summary.name.trim().is_empty() - || summary.name.encode_utf16().count() > 64 - { - return Err("invalid_room_name"); - } - if !crate::access::valid_audio_bitrate(summary.voice_bitrate) { - return Err("invalid_audio_bitrate"); - } - if !self.remote.contains_key(&summary.id) && self.remote.len() >= 32 { - return Err("room_limit"); - } + summary.validate()?; let room_id = summary.id.clone(); - let remote = self - .remote - .entry(room_id.clone()) - .or_insert_with(|| RemoteRoom::restored(summary.clone())); + let remote = self.remote.get_mut(&room_id).ok_or("room_not_in_domain")?; if remote.summary.creator_id != member.user_id { return Err("forbidden"); } @@ -583,6 +570,83 @@ impl Channel { Ok((events, replies)) } + pub(crate) fn create_room( + &mut self, + session: Uuid, + mut room: RoomSummary, + ) -> Result { + let member = self + .identity + .member(self.identity.sessions[&session].user_id)?; + if !member.participates { + return Err("forbidden"); + } + room.id = Uuid::new_v4().to_string(); + room.creator_id = member.user_id; + self.insert_room(room.clone())?; + Ok(room) + } + + pub(crate) fn admit_room( + &mut self, + session: Uuid, + room: RoomSummary, + ) -> Result<(), &'static str> { + let member = self + .identity + .member(self.identity.sessions[&session].user_id)?; + if !member.domain_owner { + return Err("forbidden"); + } + self.identity.member(room.creator_id)?; + room.validate()?; + if let Some(current) = self.remote.get(&room.id) { + return if current.summary.creator_id == room.creator_id { + Ok(()) + } else { + Err("forbidden") + }; + } + self.insert_room(room) + } + + fn insert_room(&mut self, room: RoomSummary) -> Result<(), &'static str> { + room.validate()?; + if self.remote.len() >= 32 { + return Err("room_limit"); + } + self.remote + .insert(room.id.clone(), RemoteRoom::restored(room)); + Ok(()) + } + + pub(crate) fn manages_room(&self, session: Uuid, id: &str) -> Result<(), &'static str> { + let member = self + .identity + .member(self.identity.sessions[&session].user_id)?; + let room = self.remote.get(id).ok_or("room_not_in_domain")?; + if member.domain_owner || member.user_id == room.summary.creator_id { + Ok(()) + } else { + Err("forbidden") + } + } + + pub(crate) fn room_online(&self, id: &str) -> bool { + self.remote + .get(id) + .is_some_and(|room| Self::host_online(&self.identity, room)) + } + + pub(crate) fn remove_room(&mut self, id: &str) -> Vec { + let replies = self + .remote + .remove(id) + .map_or_else(Vec::new, |mut room| room.drain_replies()); + self.reconcile(); + replies + } + pub(crate) fn host_input( &mut self, id: &str, @@ -805,6 +869,33 @@ impl Channel { if !reply_valid { return Err("invalid_room_reply"); } + if let Some(reply) = output + .reply + .as_ref() + .filter(|reply| matches!(reply.result, RoomResult::Deleted { .. })) + { + if !matches!(reply.result, RoomResult::Deleted { data_removed: true }) + || !matches!( + binding.replies.get(&output.revision), + Some(ReplyOwner::Request { delete: true, .. }) + ) + { + return Err("invalid_room_reply"); + } + self.remote + .get_mut(id) + .unwrap() + .binding + .as_mut() + .unwrap() + .replies + .remove(&output.revision); + return Ok(HostAcceptance { + projection_applied: false, + invitation_current: false, + replies: vec![reply.clone()], + }); + } let projection_applied = output.revision >= binding.projection_floor; let room = &self.remote[id]; if !projection_applied { @@ -1065,6 +1156,7 @@ impl Channel { context, member, completion: Some(result), + .. } = owner else { return None; diff --git a/prototype/channel-core/src/host.rs b/prototype/channel-core/src/host.rs index 3523773be..e1d979d94 100644 --- a/prototype/channel-core/src/host.rs +++ b/prototype/channel-core/src/host.rs @@ -27,6 +27,18 @@ pub struct RoomSummary { } impl RoomSummary { + pub(crate) fn validate(&self) -> Result<(), &'static str> { + if !crate::wire::valid_id(&self.id) + || self.name.trim().is_empty() + || self.name.encode_utf16().count() > 64 + { + return Err("invalid_room_name"); + } + if !crate::access::valid_audio_bitrate(self.voice_bitrate) { + return Err("invalid_audio_bitrate"); + } + Ok(()) + } pub fn from_policy(policy: &RoomState) -> Self { let view = policy.view(policy.creator_id, false).expect("room owner"); Self { @@ -113,6 +125,9 @@ pub struct HostInput { )] pub enum RoomResult { Done, + Deleted { + data_removed: bool, + }, Topology { topology: crate::topology::RoomTopology, }, @@ -164,6 +179,7 @@ pub struct HostOutput { pub struct HostWork { pub policy: Option, pub history: Option, + pub delete: bool, } pub(crate) struct RoomOperation { @@ -638,6 +654,7 @@ impl RoomHost { let mut work = HostWork { policy: None, history: None, + delete: false, }; let context = match &input.action { HostAction::Command { context, .. } @@ -691,6 +708,18 @@ impl RoomHost { return Ok(RoomResult::Invited); } HostAction::Command { context, command } => { + if matches!( + command, + Command::DeleteRoom { + delete_data: true, + .. + } + ) { + self.room + .authorize(member.unwrap(), crate::RoomPermission::Manage)?; + work.delete = true; + return Ok(RoomResult::Deleted { data_removed: true }); + } let op = self.room.command( member.unwrap(), context.session_id, @@ -732,6 +761,7 @@ impl RoomHost { work = HostWork { policy: None, history: None, + delete: false, }; RoomResult::Error { code: code.into() } } diff --git a/prototype/channel-core/src/lib.rs b/prototype/channel-core/src/lib.rs index e70f56a86..1b37036e7 100644 --- a/prototype/channel-core/src/lib.rs +++ b/prototype/channel-core/src/lib.rs @@ -138,6 +138,9 @@ impl Authority { .remote .get(room_id) .is_some_and(|room| room.summary != output.projection.summary) + || output.reply.as_ref().is_some_and(|reply| { + matches!(reply.result, RoomResult::Deleted { data_removed: true }) + }) || output .reply .as_ref() @@ -146,6 +149,9 @@ impl Authority { Command::Join { .. } | Command::SetName { .. } | Command::UpdateDomain { .. } + | Command::CreateRoom { .. } + | Command::AdmitRoom { .. } + | Command::DeleteRoom { .. } | Command::SetRoles { .. } => true, _ => false, } @@ -201,6 +207,68 @@ impl Authority { now, }; match &request.command { + Command::CreateRoom { room } => { + match self.channel.create_room(session_id, room.clone()) { + Ok(room) => { + self.broadcast(None, &mut effects); + effects.events.push(( + connection, + Event::RoomCreated { + room, + request_id: request.request_id, + }, + )); + } + Err(code) => Self::error(connection, request.request_id, code, &mut effects), + } + return effects; + } + Command::AdmitRoom { room } => { + match self.channel.admit_room(session_id, room.clone()) { + Ok(()) => { + self.broadcast(None, &mut effects); + if let Some(request_id) = request.request_id { + effects.events.push((connection, Event::Ack { request_id })); + } + } + Err(code) => Self::error(connection, request.request_id, code, &mut effects), + } + return effects; + } + Command::DeleteRoom { + room_id, + delete_data, + } => { + if let Err(code) = self.channel.manages_room(session_id, room_id) { + Self::error(connection, request.request_id, code, &mut effects); + } else if *delete_data && self.channel.room_online(room_id) { + match self + .channel + .forward_room(room_id, context, request.command.clone()) + { + Ok((session, event)) => self.deliver(session, event, &mut effects), + Err(code) => { + Self::error(connection, request.request_id, code, &mut effects) + } + } + } else { + for (room, binding, reply) in self.channel.remove_room(room_id) { + self.room_reply(&room, binding, reply, &mut effects); + } + self.broadcast(None, &mut effects); + effects.events.push(( + connection, + Event::RoomReply { + room_id: room_id.clone(), + request_id: request.request_id, + result: RoomResult::Deleted { + data_removed: false, + }, + }, + )); + } + return effects; + } Command::RoomTopology { room_id, publication_id, @@ -349,6 +417,22 @@ impl Authority { effects } + /// Room data is already deleted, but the directory checkpoint failed. + /// Preserve its prior summary as unavailable so removal can be retried. + pub fn failed_room_delete(&mut self, id: &str, request: &RequestContext) -> Effects { + let mut effects = Effects::default(); + if let Some(room) = self.channel.remote.get_mut(id) { + for (room, binding, reply) in room.pause() { + if &reply.context != request { + self.room_reply(&room, binding, reply, &mut effects); + } + } + } + self.channel.reconcile(); + self.broadcast(None, &mut effects); + effects + } + /// Expire endpoint activities together, keeping unrelated publications alive. pub fn expire(&mut self, now: u64) -> Effects { self.channel.now = now; @@ -547,6 +631,16 @@ impl Authority { let accepted = self .channel .accept_host(room_id, session, connection, &output)?; + if output + .reply + .as_ref() + .is_some_and(|reply| matches!(reply.result, RoomResult::Deleted { data_removed: true })) + { + for (room, binding, reply) in self.channel.remove_room(room_id) { + self.room_reply(&room, binding, reply, effects); + } + self.broadcast(None, effects); + } if accepted.projection_applied { self.broadcast(None, effects); } @@ -696,6 +790,9 @@ impl Authority { }, )), RoomResult::Error { code } => completion = RoomResult::Error { code }, + RoomResult::Deleted { data_removed } => { + completion = RoomResult::Deleted { data_removed } + } _ => {} } effects.events.push(( diff --git a/prototype/channel-core/src/remote.rs b/prototype/channel-core/src/remote.rs index 52e501793..b0775121e 100644 --- a/prototype/channel-core/src/remote.rs +++ b/prototype/channel-core/src/remote.rs @@ -26,6 +26,7 @@ pub(crate) enum ReplyOwner { context: RequestContext, member: Member, completion: Option, + delete: bool, }, Invitation { ticket: Uuid, @@ -109,6 +110,16 @@ impl RemoteRoom { context: context.clone(), member: endpoints[&context.session_id].member, completion: None, + delete: matches!( + &action, + HostAction::Command { + command: crate::wire::Command::DeleteRoom { + delete_data: true, + .. + }, + .. + } + ), }), HostAction::RouteWake => Some(ReplyOwner::RouteWake), HostAction::VerifyInvite { ticket, member, .. } => Some(ReplyOwner::Invitation { diff --git a/prototype/channel-core/src/storage.rs b/prototype/channel-core/src/storage.rs index 0637eb9e4..923e02acc 100644 --- a/prototype/channel-core/src/storage.rs +++ b/prototype/channel-core/src/storage.rs @@ -54,6 +54,16 @@ impl Storage { Ok(()) } + /// One room store loses policy and history together. An empty container is + /// skipped by discovery; filesystem unlink is not a second commit boundary. + pub fn delete_room(&mut self, room_id: &str) -> StoreResult<()> { + let transaction = self.connection.transaction()?; + transaction.execute("DELETE FROM checkpoint WHERE id=1", [])?; + transaction.execute("DELETE FROM message WHERE room_id=?1", [room_id])?; + transaction.commit()?; + Ok(()) + } + /// Freeze this database with SQLite's online backup API. The caller owns the /// disposable destination and keeps it until its streaming reader finishes. pub fn snapshot(&self, path: &Path) -> StoreResult { diff --git a/prototype/channel-core/src/stored_room.rs b/prototype/channel-core/src/stored_room.rs index e75188adf..63e3d38c5 100644 --- a/prototype/channel-core/src/stored_room.rs +++ b/prototype/channel-core/src/stored_room.rs @@ -148,6 +148,12 @@ impl StoredRoomHost { pub fn dispatch(&mut self, input: HostInput) -> Result { let work = self.host.dispatch(input)?; let result = (|| { + if work.delete { + self.store + .delete_room(&self.host.policy().id) + .map_err(|_| "storage_failed")?; + return Ok(None); + } if let Some(policy) = work.policy { let value = serde_json::to_value(policy).map_err(|_| "storage_failed")?; self.store.save(&value).map_err(|_| "storage_failed")?; diff --git a/prototype/channel-core/src/wire.rs b/prototype/channel-core/src/wire.rs index 637e8d503..2b0ef8788 100644 --- a/prototype/channel-core/src/wire.rs +++ b/prototype/channel-core/src/wire.rs @@ -52,6 +52,16 @@ pub enum Command { room: crate::host::RoomSummary, resume_binding: Option, }, + CreateRoom { + room: crate::host::RoomSummary, + }, + AdmitRoom { + room: crate::host::RoomSummary, + }, + DeleteRoom { + room_id: String, + delete_data: bool, + }, HostOutput { room_id: String, output: crate::host::HostOutput, @@ -690,6 +700,11 @@ pub enum Event { #[serde(skip_serializing_if = "Option::is_none")] request_id: Option, }, + RoomCreated { + room: crate::host::RoomSummary, + #[serde(skip_serializing_if = "Option::is_none")] + request_id: Option, + }, Signal { pair_id: Uuid, from_session_id: Uuid, diff --git a/prototype/channel-core/tests/authority.rs b/prototype/channel-core/tests/authority.rs index 0d7a4fb60..15668ad2b 100644 --- a/prototype/channel-core/tests/authority.rs +++ b/prototype/channel-core/tests/authority.rs @@ -271,7 +271,7 @@ fn public_dispatch_owns_authorization_state_before_ack_and_explicit_leave() { let forbidden = apply( &mut core, guest, - json!({"type":"host_register", "room":{"id":Uuid::new_v4(), "name":"Denied", "icon":"couch", "creatorId":guest_user, + json!({"type":"create_room", "room":{"id":Uuid::new_v4(), "name":"Denied", "icon":"couch", "creatorId":guest_user, "access":"public", "hidden":false, "hasPassword":false}, "requestId":"create"}), 2, ); diff --git a/prototype/channel-core/tests/host_review.rs b/prototype/channel-core/tests/host_review.rs index ace012d78..8eacb1d5d 100644 --- a/prototype/channel-core/tests/host_review.rs +++ b/prototype/channel-core/tests/host_review.rs @@ -174,6 +174,23 @@ fn review_register( host_connection: Uuid, host: &RoomHost, ) -> piik_channel_core::host::HostInput { + let administrator = if host.summary().creator_id == core.identity().1 { + host_connection + } else { + let connection = Uuid::new_v4(); + review_admit(core, connection, "owner"); + connection + }; + core.handle( + administrator, + piik_channel_core::wire::Request { + request_id: None, + command: Command::AdmitRoom { + room: host.summary(), + }, + }, + 0, + ); core.handle( host_connection, piik_channel_core::wire::Request { @@ -617,6 +634,13 @@ fn successful_publish_projection_survives_a_later_queued_ordinary_command() { .any(|(_, e)| matches!(e, Event::HostInput { .. }))); host.dispatch(input).unwrap(); let mut output = host.finish(None).unwrap(); + let mut forged_delete = output.clone(); + forged_delete.reply.as_mut().unwrap().result = + piik_channel_core::host::RoomResult::Deleted { data_removed: true }; + let rejected = review_host_turn(&mut core, b, "concurrent-review", forged_delete); + assert!(rejected.events.iter().any( + |(_, event)| matches!(event, Event::Error { code, .. } if code == "invalid_room_reply") + )); for view in output.projection.views.values_mut() { view.room.delivery = Some(piik_channel_core::wire::RoomDelivery { host_session_id: Uuid::new_v4(), diff --git a/prototype/channel-core/tests/room_access.rs b/prototype/channel-core/tests/room_access.rs index ee656ef6d..2b2b9ecfd 100644 --- a/prototype/channel-core/tests/room_access.rs +++ b/prototype/channel-core/tests/room_access.rs @@ -10,6 +10,230 @@ use uuid::Uuid; mod support; use support::RoomNetwork; +#[test] +fn deletion_withdraws_directory_authority_across_restart_without_recreating_the_room() { + let mut network = RoomNetwork::new(); + let owner = Uuid::new_v4(); + let creator = Uuid::new_v4(); + let stranger = Uuid::new_v4(); + admit( + &mut network, + owner, + json!({"type":"join","name":"Domain owner","key":"owner"}), + ); + let (_, credential, _) = admit( + &mut network, + creator, + json!({"type":"join","name":"Creator","key":"invite"}), + ); + admit( + &mut network, + stranger, + json!({"type":"join","name":"Stranger","key":"invite"}), + ); + let deleted = room(&mut network, creator, "private", true); + let sibling = room(&mut network, owner, "public", false); + let policy = network.policy(&deleted); + let summary = piik_channel_core::host::RoomSummary::from_policy(&policy); + let forbidden = command( + &mut network, + stranger, + json!({"type":"delete_room","deleteData":true,"roomId":deleted,"requestId":"deny"}), + ); + assert!(forbidden + .events + .iter() + .any(|(_, event)| matches!(event, Event::Error { code, .. } if code == "forbidden"))); + let pending = network.authority.handle( + owner, + piik_channel_core::wire::Request::parse( + &json!({"type":"delete_room","deleteData":true,"roomId":deleted,"requestId":"delete"}) + .to_string(), + ) + .unwrap(), + 100, + ); + let input = pending + .events + .into_iter() + .find_map(|(_, event)| match event { + Event::HostInput { input, .. } => Some(input), + _ => None, + }) + .unwrap(); + let output = network.host_turn(&deleted, input); + network.authority.disconnect(owner, 100); + let removed = command( + &mut network, + creator, + json!({"type":"host_output","roomId":deleted,"output":output}), + ); + assert!( + !removed + .events + .iter() + .any(|(target, event)| *target == owner && matches!(event, Event::RoomReply { .. })), + "a closed requester receives no completion" + ); + assert!(!network + .state(creator) + .channel + .rooms + .iter() + .any(|room| room.id == deleted)); + assert!(network + .state(creator) + .channel + .rooms + .iter() + .any(|room| room.id == sibling)); + + let checkpoint = network.authority.export_state(); + let mut reopened = RoomNetwork::new(); + reopened.authority.import_state(checkpoint).unwrap(); + let returning = Uuid::new_v4(); + admit( + &mut reopened, + returning, + json!({"type":"join","name":"Creator","credential":credential}), + ); + for value in [ + json!({"type":"host_register","room":summary}), + json!({"type":"admit_room","room":summary}), + ] { + let result = command(&mut reopened, returning, value); + assert!(result + .events + .iter() + .any(|(_, event)| matches!(event, Event::Error { .. }))); + } + let created = command( + &mut reopened, + returning, + json!({"type":"create_room","room":summary}), + ); + assert!(created.events.iter().any(|(_, event)| matches!(event, Event::RoomCreated { room, .. } if room.id != deleted && room.creator_id == policy.creator_id))); + let administrator = Uuid::new_v4(); + admit( + &mut reopened, + administrator, + json!({"type":"join","name":"Domain owner","key":"owner"}), + ); + let admitted = command( + &mut reopened, + administrator, + json!({"type":"admit_room","room":summary,"requestId":"restore"}), + ); + assert!(admitted + .events + .iter() + .any(|(_, event)| matches!(event, Event::Ack { request_id } if request_id == "restore"))); + reopened.restore_room(returning, policy); +} + +#[test] +fn offline_removal_and_correlated_online_deletion_keep_room_scopes_separate() { + use piik_channel_core::wire::Request; + let mut network = RoomNetwork::new(); + let owner = Uuid::new_v4(); + admit( + &mut network, + owner, + json!({"type":"join","name":"Owner","key":"owner"}), + ); + let first = room(&mut network, owner, "public", false); + let second = room(&mut network, owner, "public", false); + let directory_only = room(&mut network, owner, "public", false); + let removal = network.authority.handle(owner, Request::parse(&json!({"type":"delete_room","deleteData":false,"roomId":directory_only,"requestId":"no-data-consent"}).to_string()).unwrap(), 100); + assert!( + !removal + .events + .iter() + .any(|(_, event)| matches!(event, Event::HostInput { .. })), + "an online host must never receive a storage deletion without consent" + ); + let removal = network.deliver(removal); + assert!(removal.events.iter().any(|(_, event)| matches!( + event, + Event::RoomReply { + result: RoomResult::Deleted { + data_removed: false + }, + .. + } + ))); + let binding = network + .state(owner) + .channel + .rooms + .iter() + .find(|room| room.id == second) + .unwrap() + .delivery + .as_ref() + .unwrap() + .binding_id; + let effects = network.authority.handle( + owner, + Request::parse( + &json!({"type":"delete_room","deleteData":true,"roomId":first,"requestId":"scoped"}) + .to_string(), + ) + .unwrap(), + 100, + ); + let input = effects + .events + .into_iter() + .find_map(|(_, event)| match event { + Event::HostInput { input, .. } => Some(input), + _ => None, + }) + .unwrap(); + let output = network.host_turn(&first, input); + let wrong = command( + &mut network, + owner, + json!({"type":"host_output","roomId":second,"output":output}), + ); + assert!(wrong + .events + .iter() + .any(|(_, event)| matches!(event, Event::Error { .. }))); + let valid = command( + &mut network, + owner, + json!({"type":"host_output","roomId":first,"output":output}), + ); + assert!(valid.events.iter().any(|(_, event)| matches!( + event, + Event::RoomReply { + result: RoomResult::Deleted { data_removed: true }, + .. + } + ))); + command( + &mut network, + owner, + json!({"type":"host_stop","roomId":second,"bindingId":binding}), + ); + let removed = command( + &mut network, + owner, + json!({"type":"delete_room","deleteData":true,"roomId":second,"requestId":"offline"}), + ); + assert!(removed.events.iter().any(|(_, event)| matches!( + event, + Event::RoomReply { + result: RoomResult::Deleted { + data_removed: false + }, + .. + } + ))); + assert!(network.state(owner).channel.rooms.is_empty()); +} + fn command(core: &mut RoomNetwork, connection: Uuid, value: Value) -> Effects { core.command(connection, value) } diff --git a/prototype/channel-core/tests/stored_room.rs b/prototype/channel-core/tests/stored_room.rs index f254d7a83..5eeab1b66 100644 --- a/prototype/channel-core/tests/stored_room.rs +++ b/prototype/channel-core/tests/stored_room.rs @@ -109,6 +109,90 @@ fn sent( } } +#[test] +fn deleting_room_policy_and_history_is_one_commit_and_keeps_other_stores() { + use piik_channel_core::{history::HistoryRequest, storage::Storage}; + let folder = std::env::temp_dir().join(format!("piik-room-delete-{}", Uuid::new_v4())); + std::fs::create_dir(&folder).unwrap(); + let path = folder.join("deleted.sqlite"); + let sibling_path = folder.join("sibling.sqlite"); + let owner = Uuid::new_v4(); + let stranger = Uuid::new_v4(); + let mut host = + StoredRoomHost::create(&path, policy("deleted", owner, RoomAccess::Public)).unwrap(); + let sibling = + StoredRoomHost::create(&sibling_path, policy("sibling", owner, RoomAccess::Public)) + .unwrap(); + command( + &mut host, + owner, + owner, + json!({"type":"browse","roomId":"deleted","active":true}), + ); + sent(peer( + &mut host, + owner, + owner, + ConversationCommand::Chat { + text: "Retained".into(), + nonce: "before-delete".into(), + attachments: vec![], + }, + )); + let denied = command( + &mut host, + owner, + stranger, + json!({"type":"delete_room","deleteData":true,"roomId":"deleted"}), + ); + assert!( + matches!(denied.reply.unwrap().result, RoomResult::Error { code } if code == "forbidden") + ); + let connection = rusqlite::Connection::open(&path).unwrap(); + connection.execute_batch("CREATE TRIGGER reject_delete BEFORE DELETE ON message BEGIN SELECT RAISE(ABORT,'held'); END;").unwrap(); + let failed = command( + &mut host, + owner, + owner, + json!({"type":"delete_room","deleteData":true,"roomId":"deleted"}), + ); + assert!( + matches!(failed.reply.unwrap().result, RoomResult::Error { code } if code == "storage_failed") + ); + let mut retained = Storage::open(&path).unwrap(); + assert!( + retained.load().unwrap().is_some(), + "history failure rolled back policy deletion" + ); + assert!( + matches!(retained.history(&HistoryRequest::Read { room_id: "deleted".into(), before: None }).unwrap(), HistoryResult::Page { messages, .. } if messages.len() == 1) + ); + connection + .execute_batch("DROP TRIGGER reject_delete") + .unwrap(); + let removed = command( + &mut host, + owner, + owner, + json!({"type":"delete_room","deleteData":true,"roomId":"deleted"}), + ); + assert!(matches!( + removed.reply.unwrap().result, + RoomResult::Deleted { data_removed: true } + )); + assert!(retained.load().unwrap().is_none()); + assert!( + matches!(retained.history(&HistoryRequest::Read { room_id: "deleted".into(), before: None }).unwrap(), HistoryResult::Page { messages, .. } if messages.is_empty()) + ); + assert!(Storage::open(&sibling_path) + .unwrap() + .load() + .unwrap() + .is_some()); + drop((host, sibling, retained, connection)); + std::fs::remove_dir_all(folder).unwrap(); +} + #[test] fn portable_snapshot_restores_complete_rows_and_retry_identity_without_live_state() { use piik_channel_core::{backup::Metadata, storage::Storage, RoomBackup}; diff --git a/prototype/channel-core/tests/support/mod.rs b/prototype/channel-core/tests/support/mod.rs index 36bf6988f..9f06ef325 100644 --- a/prototype/channel-core/tests/support/mod.rs +++ b/prototype/channel-core/tests/support/mod.rs @@ -110,7 +110,7 @@ impl RoomNetwork { .find(|entry| entry.id == session) .unwrap() .user_id; - let policy = RoomState::new( + let mut policy = RoomState::new( Uuid::new_v4().to_string(), "Friends".into(), Default::default(), @@ -120,6 +120,19 @@ impl RoomNetwork { None, ) .unwrap(); + let summary = piik_channel_core::host::RoomSummary::from_policy(&policy); + let created = self.command( + connection, + json!({"type":"create_room", "room":summary, "requestId":"new-room"}), + ); + policy.id = created + .events + .into_iter() + .find_map(|(_, event)| match event { + Event::RoomCreated { room, .. } => Some(room.id), + _ => None, + }) + .expect("domain assigned room identity"); self.restore_room(connection, policy) } diff --git a/prototype/channel-native/README.md b/prototype/channel-native/README.md index 1a9c49c71..f2020817b 100644 --- a/prototype/channel-native/README.md +++ b/prototype/channel-native/README.md @@ -243,7 +243,7 @@ $env:CHANNEL_WS_URL = "ws://127.0.0.1:8791/prototype/channel" $env:CHANNEL_UI_ORIGIN = "http://127.0.0.1:8790" $env:PIIK_CHANNEL_NATIVE_KEY = "" New-Item -ItemType Directory -Force build/channel-native-data | Out-Null -cargo +1.91.0 run --manifest-path prototype/channel-native/Cargo.toml -- --room build/channel-native-data/lounge.sqlite lounge "Lounge" +cargo +1.91.0 run --manifest-path prototype/channel-native/Cargo.toml -- --room build/channel-native-data/lounge.sqlite "Lounge" ``` Use your configured key, never the placeholder. An existing user credential can @@ -252,7 +252,8 @@ instead be supplied through `PIIK_CHANNEL_NATIVE_CREDENTIAL`; the optional printed or saved by this launcher. Reopening saved room data requires the same authenticated user. Reuse the domain owner's stable key for the example above. -Repeat `--room ` to operate several rooms. Each room has a +Repeat `--room ` to operate several rooms. The domain assigns +each new room's ID; an existing database restores its saved identity. Each room has a separate database and an OS file lock held by its runtime. A second process cannot open that room while the first holds it. Existing files restore their saved policy; command-line names do not overwrite it. Live calls, captures and diff --git a/prototype/channel-native/src/hosted_room.rs b/prototype/channel-native/src/hosted_room.rs index ee97f39db..0cd691ca6 100644 --- a/prototype/channel-native/src/hosted_room.rs +++ b/prototype/channel-native/src/hosted_room.rs @@ -122,7 +122,7 @@ impl HostedRoom { } } -fn backup_identity(backup: &RoomBackup, (domain, owner): (Uuid, Uuid)) -> Result<()> { +pub(crate) fn backup_identity(backup: &RoomBackup, (domain, owner): (Uuid, Uuid)) -> Result<()> { if backup.metadata().domain_id != domain || backup.metadata().policy.creator_id != owner { bail!("backup_owner_mismatch"); } diff --git a/prototype/channel-native/src/main.rs b/prototype/channel-native/src/main.rs index a820a14fc..b3bf442d0 100644 --- a/prototype/channel-native/src/main.rs +++ b/prototype/channel-native/src/main.rs @@ -17,12 +17,13 @@ async fn run_native() -> Result<()> { let mut rooms = Vec::new(); while let Some(flag) = args.next() { if flag != "--room" { - bail!("usage: piik-channel-native --room [--room ...]"); + bail!("usage: piik-channel-native --room [--room ...]"); } rooms.push(RoomFile { path: PathBuf::from(args.next().context("missing room database path")?), - id: args.next().context("missing room id")?, + id: uuid::Uuid::new_v4().to_string(), name: args.next().context("missing room name")?, + bootstrap: false, }); } if rooms.is_empty() { diff --git a/prototype/channel-native/src/peer/tests.rs b/prototype/channel-native/src/peer/tests.rs index be2a0e773..b96817d10 100644 --- a/prototype/channel-native/src/peer/tests.rs +++ b/prototype/channel-native/src/peer/tests.rs @@ -169,6 +169,16 @@ fn capture_scope_survives_host_signaling_recovery_but_not_retired_authority() { .unwrap(); policy.grants.insert(native_user); let mut host = RoomHost::new(policy.clone()); + let admitted = send( + &mut core, + host_connection, + json!({"type":"admit_room","room":host.summary()}), + 2, + ); + assert!(!admitted + .events + .iter() + .any(|(_, event)| matches!(event, CoreEvent::Error { .. }))); let registered = send( &mut core, host_connection, diff --git a/prototype/channel-native/src/session.rs b/prototype/channel-native/src/session.rs index eb2bbb9ea..ab297ab8e 100644 --- a/prototype/channel-native/src/session.rs +++ b/prototype/channel-native/src/session.rs @@ -231,6 +231,7 @@ pub struct RoomFile { // Creation defaults for explicitly configured files; discoveries leave this // empty so a missing saved database is never recreated without its history. pub name: String, + pub bootstrap: bool, } struct Live { @@ -259,8 +260,30 @@ pub struct OpenRoom { struct OpeningRoom { request_id: String, - previous_binding: Option, - replies: Vec>>, + work: OpeningWork, +} +enum OpeningWork { + Register { + previous_binding: Option, + replies: Vec>>, + }, + AdmitRestore(RestoreRoom), + Create(RoomFile), +} +impl OpeningRoom { + fn fail(self, code: &str) { + match self.work { + OpeningWork::Register { replies, .. } => { + for reply in replies { + let _ = reply.send(Err(code.into())); + } + } + OpeningWork::AdmitRestore(request) => { + let _ = request.result.send(Err(code.into())); + } + OpeningWork::Create(_) => eprintln!("Native room creation failed: {code}"), + } + } } pub struct SnapshotRoom { @@ -490,9 +513,7 @@ pub async fn run_host( } } for opening in session.opening.into_values() { - for reply in opening.replies { - let _ = reply.send(Err(error.clone())); - } + opening.fail(&error); } result.and(closed) } @@ -506,6 +527,19 @@ impl Session { async fn release(&mut self) -> Result<()> { self.fail_captures("hosting_unavailable"); + let restoring: Vec<_> = self + .opening + .iter() + .filter_map(|(id, opening)| { + (!matches!(opening.work, OpeningWork::Register { .. })).then(|| id.clone()) + }) + .collect(); + for id in restoring { + self.opening + .remove(&id) + .unwrap() + .fail("hosting_unavailable"); + } // A canceled connection turn must leave the Driver's join owned here. let closed = if let Some(live) = self.live.as_mut() { live.room.snapshot.send_replace(None); @@ -574,6 +608,16 @@ impl Session { if let Some(live) = &self.live { live.room.snapshot.send_replace(None); } + let result = if matches!(result, Ok(false)) + && self + .opening + .values() + .any(|opening| matches!(opening.work, OpeningWork::Create(_))) + { + Err(anyhow!("room_creation_interrupted: the domain did not confirm this creation; restart explicitly to try again")) + } else { + result + }; if !matches!(result, Ok(false)) { let released = self.release().await; leave(&mut socket).await; @@ -821,12 +865,34 @@ impl Session { .live .as_ref() .is_some_and(|live| live.session == session_id); + let mut new_rooms = BTreeSet::new(); + let mut creating = Vec::new(); if !resumed { self.release().await?; let mut rooms = BTreeMap::new(); - for file in &self.files { + for mut file in std::mem::take(&mut self.files) { let host = match std::fs::metadata(&file.path) { - Ok(_) => HostedRoom::open(&file.path, &file.id, user), + Ok(_) => { + let store = piik_channel_core::storage::Storage::open(&file.path) + .map_err(anyhow::Error::from_boxed)?; + let Some(policy) = + store.load().map_err(anyhow::Error::from_boxed)? + else { + self.files.push(file); + continue; + }; + let policy: RoomState = serde_json::from_value(policy)?; + file.id = policy.id; + if !state.channel.rooms.iter().any(|room| room.id == file.id) { + if file.bootstrap { + new_rooms.insert(file.id.clone()); + } else { + self.files.push(file); + continue; + } + } + HostedRoom::open(&file.path, &file.id, user) + } Err(error) if error.kind() == std::io::ErrorKind::NotFound && !file.name.is_empty() => @@ -841,13 +907,35 @@ impl Session { None, ) .map_err(anyhow::Error::msg)?; + if !file.bootstrap { + let request_id = Uuid::new_v4().to_string(); + creating.push(( + request_id.clone(), + RoomSummary::from_policy(&policy), + )); + self.opening.insert( + file.id.clone(), + OpeningRoom { + request_id, + work: OpeningWork::Create(file), + }, + ); + continue; + } + new_rooms.insert(file.id.clone()); HostedRoom::create(&file.path, policy) } Err(error) => Err(error.into()), - }?; + }; + let host = match host { + Ok(host) => host, + Err(error) if error.to_string() == "room_not_found" => continue, + Err(error) => return Err(error), + }; if rooms.insert(file.id.clone(), host).is_some() { bail!("duplicate room id"); } + self.files.push(file); } let ice = state .ice_servers @@ -895,6 +983,16 @@ impl Session { .await?; } for (id, hosted) in &mut self.live.as_mut().unwrap().room.rooms { + if new_rooms.contains(id) { + write( + socket, + &Command::AdmitRoom { + room: hosted.summary(), + }, + None, + ) + .await?; + } write( socket, &Command::HostRegister { @@ -909,6 +1007,23 @@ impl Session { ) .await?; } + for (request_id, room) in creating { + write(socket, &Command::CreateRoom { room }, Some(&request_id)).await?; + } + let restoring: Vec<_> = self + .opening + .values() + .filter_map(|opening| match &opening.work { + OpeningWork::AdmitRestore(request) => Some(( + opening.request_id.clone(), + RoomSummary::from_policy(&request.snapshot.room.metadata().policy), + )), + _ => None, + }) + .collect(); + for (request_id, room) in restoring { + write(socket, &Command::AdmitRoom { room }, Some(&request_id)).await?; + } self.hosting_ready(); eprintln!( "Native session admitted ({})", @@ -936,7 +1051,7 @@ impl Session { if self .opening .get(&room_id) - .is_some_and(|opening| opening.previous_binding == Some(binding_id)) + .is_some_and(|opening| matches!(opening.work, OpeningWork::Register { previous_binding: Some(previous), .. } if previous == binding_id)) { return Ok(()); } @@ -950,20 +1065,69 @@ impl Session { } self.hosting_ready(); } + Event::RoomCreated { + room, + request_id: Some(request_id), + } => { + let pending = self.opening.iter().find_map(|(id, opening)| { + (opening.request_id == request_id + && matches!(opening.work, OpeningWork::Create(_))) + .then(|| id.clone()) + }); + if let Some(pending) = pending { + let OpeningWork::Create(mut file) = self.opening.remove(&pending).unwrap().work + else { + unreachable!() + }; + let policy = RoomState::new( + room.id.clone(), + room.name.clone(), + room.icon.clone(), + room.creator_id, + room.access, + room.hidden, + None, + ) + .map_err(anyhow::Error::msg)?; + let host = HostedRoom::create(&file.path, policy)?; + file.id = room.id.clone(); + self.files.push(file); + if let Some(live) = &mut self.live { + live.room.rooms.insert(room.id.clone(), host); + } + write( + socket, + &Command::HostRegister { + room: room.clone(), + resume_binding: None, + }, + Some(&room.id), + ) + .await?; + } + } Event::Ack { request_id: id } => { - if let Some(room_id) = self + let room_id = self .opening .iter() - .find_map(|(room, opening)| (opening.request_id == id).then(|| room.clone())) - { + .find_map(|(room, opening)| (opening.request_id == id).then(|| room.clone())); + if let Some(room_id) = room_id { let opening = self.opening.remove(&room_id).unwrap(); + let replies = match opening.work { + OpeningWork::AdmitRestore(request) => { + self.restore_room(request, socket).await?; + return Ok(()); + } + OpeningWork::Register { replies, .. } => replies, + OpeningWork::Create(_) => return Ok(()), + }; let summary = self .live .as_ref() .and_then(|live| live.room.rooms.get(&room_id)) .filter(|host| host.binding().is_some()) .map(HostedRoom::summary); - for reply in opening.replies { + for reply in replies { let _ = reply.send(summary.clone().ok_or_else(|| "room_unavailable".into())); } @@ -976,6 +1140,12 @@ impl Session { && live.session == input.host_session_id { let output = hosted.dispatch(input).map_err(anyhow::Error::msg)?; + if output.reply.as_ref().is_some_and(|reply| { + matches!(reply.result, RoomResult::Deleted { data_removed: true }) + }) { + live.room.rooms.remove(&room_id); + self.files.retain(|file| file.id != room_id); + } write(socket, &Command::HostOutput { room_id, output }, None).await?; } } @@ -1031,6 +1201,14 @@ impl Session { } } Event::Error { code, request_id } => { + if let Some(room) = self.opening.iter().find_map(|(room, opening)| { + (!matches!(opening.work, OpeningWork::Register { .. }) + && request_id.as_ref() == Some(&opening.request_id)) + .then(|| room.clone()) + }) { + self.opening.remove(&room).unwrap().fail(&code); + return Ok(()); + } if let Some(request) = request_id .as_ref() .and_then(|id| self.pending_captures.remove(id)) @@ -1051,16 +1229,14 @@ impl Session { .as_ref() .is_some_and(|live| live.room.rooms.contains_key(id)) }) { - if self.hosting.is_none() { + if self.hosting.is_none() && code != "room_not_in_domain" { bail!("room registration failed: {code}"); } let id = request_id.as_ref().unwrap(); self.live.as_mut().unwrap().room.rooms.remove(id); self.files.retain(|file| &file.id != id); if let Some(opening) = self.opening.remove(id) { - for reply in opening.replies { - let _ = reply.send(Err(code.clone())); - } + opening.fail(&code); } self.hosting_ready(); return Ok(()); @@ -1432,6 +1608,7 @@ impl Session { path, id: id.clone(), name: host.summary().name, + bootstrap: false, }); live.room.rooms.insert(id.clone(), host); } @@ -1487,6 +1664,44 @@ impl Session { return Ok(()); } let id = request.snapshot.room.metadata().policy.id.clone(); + let admission = (|| -> Result { + let hosting = self + .hosting + .as_ref() + .ok_or_else(|| anyhow!("hosting_unavailable"))?; + crate::hosted_room::backup_identity(&request.snapshot.room, hosting.identity)?; + if self.opening.contains_key(&id) { + bail!("room_busy"); + } + let live = self + .live + .as_ref() + .ok_or_else(|| anyhow!("hosting_unavailable"))?; + let snapshot = live.room.snapshot.borrow(); + let snapshot = snapshot + .as_ref() + .ok_or_else(|| anyhow!("hosting_unavailable"))?; + Ok(!snapshot.channel.rooms.iter().any(|room| room.id == id)) + })(); + match admission { + Ok(true) => { + let request_id = Uuid::new_v4().to_string(); + let room = RoomSummary::from_policy(&request.snapshot.room.metadata().policy); + self.opening.insert( + id, + OpeningRoom { + request_id: request_id.clone(), + work: OpeningWork::AdmitRestore(request), + }, + ); + return write(socket, &Command::AdmitRoom { room }, Some(&request_id)).await; + } + Err(error) => { + let _ = request.result.send(Err(error.to_string())); + return Ok(()); + } + Ok(false) => {} + } let restored = (|| -> Result<(RoomSummary, Option)> { let hosting = self .hosting @@ -1522,6 +1737,7 @@ impl Session { path, id: id.clone(), name: String::new(), + bootstrap: false, }); } live.room.rooms.insert(id.clone(), host); @@ -1556,11 +1772,17 @@ impl Session { .entry(id.clone()) .or_insert_with(|| OpeningRoom { request_id: Uuid::new_v4().to_string(), - previous_binding, - replies: vec![], + work: OpeningWork::Register { + previous_binding, + replies: vec![], + }, }); - opening.replies.push(result); - if opening.replies.len() == 1 { + let OpeningWork::Register { replies, .. } = &mut opening.work else { + let _ = result.send(Err("room_busy".into())); + return Ok(()); + }; + replies.push(result); + if replies.len() == 1 { write( socket, &Command::HostRegister { @@ -1575,6 +1797,13 @@ impl Session { } async fn state(&mut self, state: Snapshot, socket: &mut Socket) -> Result<()> { + if let Some(live) = &mut self.live { + live.room.rooms.retain(|id, room| { + room.binding().is_none() + || state.channel.rooms.iter().any(|summary| &summary.id == id) + }); + } + self.retire_missing_hosts(&state, socket).await?; let retired: Vec<_> = self .pending_captures .iter() @@ -1646,6 +1875,38 @@ impl Session { } Ok(()) } + + async fn retire_missing_hosts(&mut self, state: &Snapshot, socket: &mut Socket) -> Result<()> { + let Some(live) = self.live.as_ref() else { + return Ok(()); + }; + let missing: Vec<_> = state + .channel + .rooms + .iter() + .filter_map(|room| { + room.delivery + .as_ref() + .filter(|delivery| { + delivery.host_session_id == live.session + && !live.room.rooms.contains_key(&room.id) + }) + .map(|delivery| (room.id.clone(), delivery.binding_id)) + }) + .collect(); + for (room_id, binding_id) in missing { + write( + socket, + &Command::HostStop { + room_id, + binding_id, + }, + None, + ) + .await?; + } + Ok(()) + } } /// Physical names are local storage, not room identities. Imported named rooms @@ -1662,16 +1923,15 @@ fn stored_rooms(directory: &std::path::Path) -> Result> { } let store = piik_channel_core::storage::Storage::open(&path).map_err(anyhow::Error::from_boxed)?; - let policy: RoomState = serde_json::from_value( - store - .load() - .map_err(anyhow::Error::from_boxed)? - .ok_or_else(|| anyhow!("room_not_found"))?, - )?; + let Some(policy) = store.load().map_err(anyhow::Error::from_boxed)? else { + continue; + }; + let policy: RoomState = serde_json::from_value(policy)?; files.push(RoomFile { path, id: policy.id, name: String::new(), + bootstrap: false, }); } Ok(files) diff --git a/prototype/channel-native/src/session/tests.rs b/prototype/channel-native/src/session/tests.rs index aef68236f..d0eb14cc1 100644 --- a/prototype/channel-native/src/session/tests.rs +++ b/prototype/channel-native/src/session/tests.rs @@ -1,6 +1,237 @@ use super::*; use serde_json::json; +#[tokio::test] +async fn resumed_endpoint_retires_its_missing_host_after_a_deleted_output_cannot_be_sent() { + use piik_channel_core::{ + host::{HostAction, HostInput, RequestContext}, + Endpoint, Member, + }; + let (mut session, mut socket, mut remote, mut state) = capture_projection_session().await; + let native = session.live.as_ref().unwrap().session; + let user = state + .sessions + .iter() + .find(|entry| entry.id == native) + .unwrap() + .user_id; + let binding = state.channel.rooms[0].delivery.as_ref().unwrap().binding_id; + state.channel.rooms[0].creator_id = user; + state.channel.rooms[0] + .delivery + .as_mut() + .unwrap() + .host_session_id = native; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("room.sqlite"); + let policy = RoomState::new( + "target".into(), + "Target".into(), + Default::default(), + user, + RoomAccess::Public, + false, + None, + ) + .unwrap(); + let mut host = HostedRoom::create(&path, policy).unwrap(); + host.bind(binding).unwrap(); + session + .live + .as_mut() + .unwrap() + .room + .rooms + .insert("target".into(), host); + session.files.push(RoomFile { + path: path.clone(), + id: "target".into(), + name: "Target".into(), + bootstrap: false, + }); + session.state(state.clone(), &mut socket).await.unwrap(); + remote.close(None).await.unwrap(); + let _ = socket.close(None).await; + let input = HostInput { + now: 1, + binding_id: binding, + host_session_id: native, + revision: 1, + endpoints: [( + native, + Endpoint { + signing_key: session.signer.signing_key(), + member: Member { + user_id: user, + participates: true, + domain_owner: false, + }, + connected: true, + }, + )] + .into(), + action: HostAction::Command { + context: RequestContext { + connection: Uuid::new_v4(), + session_id: native, + request_id: Some("delete".into()), + now: 1, + }, + command: Command::DeleteRoom { + room_id: "target".into(), + delete_data: true, + }, + }, + }; + assert!(session + .event( + Event::HostInput { + room_id: "target".into(), + input + }, + &mut socket + ) + .await + .is_err()); + assert!(!session + .live + .as_ref() + .unwrap() + .room + .rooms + .contains_key("target")); + assert!(session.files.is_empty()); + assert!(piik_channel_core::storage::Storage::open(&path) + .unwrap() + .load() + .unwrap() + .is_none()); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let (client, peer) = tokio::join!(tokio_tungstenite::connect_async(url), async { + tokio_tungstenite::accept_async(listener.accept().await.unwrap().0).await + }); + let (mut socket, _) = client.unwrap(); + let mut peer = peer.unwrap(); + session + .event( + Event::Welcome { + credential: "fixture".into(), + session_id: native, + state, + invite_key: None, + invitation_origin: None, + }, + &mut socket, + ) + .await + .unwrap(); + let packet = tokio::time::timeout(std::time::Duration::from_secs(1), peer.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let request = piik_channel_core::wire::Request::parse(packet.to_text().unwrap()).unwrap(); + assert!( + matches!(request.command, Command::HostStop { room_id, binding_id } if room_id == "target" && binding_id == binding) + ); + session.release().await.unwrap(); +} + +#[tokio::test] +async fn missing_room_restore_waits_for_domain_admission_and_drops_denied_or_retired_staging() { + use piik_channel_core::{backup::RoomMetadata, wire::Request, RoomBackup}; + let (mut session, mut socket, mut remote, state) = capture_projection_session().await; + let directory = tempfile::tempdir().unwrap(); + let user = state + .sessions + .iter() + .find(|entry| Some(entry.id) == session.live.as_ref().map(|live| live.session)) + .unwrap() + .user_id; + let (_commands, received) = mpsc::channel(1); + session.hosting = Some(Hosting { + directory: directory.path().into(), + identity: (state.channel.id, user), + commands: received, + ready: watch::channel(None).0, + desktop: None, + }); + for denied in [true, false] { + let staging = tempfile::tempdir().unwrap(); + let path = staging.path().to_owned(); + let policy = RoomState::new( + "restored".into(), + "Restored".into(), + Default::default(), + user, + RoomAccess::Public, + false, + None, + ) + .unwrap(); + let room = RoomBackup::stage( + &path.join("room.sqlite"), + RoomMetadata { + version: 1, + domain_id: state.channel.id, + policy, + own_credential: None, + retained_files: vec![], + }, + std::iter::empty(), + ) + .unwrap(); + let (result, response) = oneshot::channel(); + session + .restore_room( + RestoreRoom { + snapshot: RoomSnapshot { + room, + directory: staging, + }, + result, + }, + &mut socket, + ) + .await + .unwrap(); + let request = + Request::parse(remote.next().await.unwrap().unwrap().to_text().unwrap()).unwrap(); + assert!(matches!(request.command, Command::AdmitRoom { .. })); + assert!( + stored_rooms(directory.path()).unwrap().is_empty(), + "no destination room was written before admission" + ); + if denied { + session + .event( + Event::Error { + code: "forbidden".into(), + request_id: request.request_id, + }, + &mut socket, + ) + .await + .unwrap(); + assert_eq!(response.await.unwrap().err().unwrap(), "forbidden"); + } else { + session.release().await.unwrap(); + assert_eq!( + response.await.unwrap().err().unwrap(), + "hosting_unavailable" + ); + } + assert!( + !path.exists(), + "the staged database is released with its request" + ); + assert!(stored_rooms(directory.path()).unwrap().is_empty()); + assert!(session.opening.is_empty()); + } +} + async fn capture_projection_session() -> (Session, Socket, WebSocketStream, Snapshot) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("ws://{}", listener.local_addr().unwrap()); diff --git a/prototype/channel-server/README.md b/prototype/channel-server/README.md index 1fdc1bced..efc66b7e2 100644 --- a/prototype/channel-server/README.md +++ b/prototype/channel-server/README.md @@ -204,6 +204,11 @@ domain owner saves them at that room's runtime. Both surfaces share preset icons and custom images. The browser crops images to a small square; saving retains them with the domain or room metadata, including after a restart. +Room settings also offers **Delete room** while hosting is online, or **Remove +from domain** while offline. Deletion clears the hosting runtime's room and chat +history; directory-only removal leaves the offline host's data. Saved downloads +are kept. Both operations end access through that room's old invitation. + In the design studies, room creation and editing share one native dialog with conditional private options. Pencils beside the user, domain and room names open their corresponding editors. Colours, controls, icons and animated people come from Piik's diff --git a/prototype/channel-server/browser-native-acceptance.mjs b/prototype/channel-server/browser-native-acceptance.mjs index ee6521236..998b2066d 100644 --- a/prototype/channel-server/browser-native-acceptance.mjs +++ b/prototype/channel-server/browser-native-acceptance.mjs @@ -476,12 +476,13 @@ export async function nativeRoom({ initial, serverRoom, browser, action, view, e capturedScreen, playing, progressing, assertNoError, hook, output }) { const directory = await mkdtemp(join(tmpdir(), "piik-native-room-check-")); const database = join(directory, "room.sqlite"); - const room = "native-room", name = "Native room"; + let room; + const name = "Native room"; const executable = resolve(process.env.CHANNEL_NATIVE_EXECUTABLE ?? `prototype/channel-native/target/debug/piik-channel-native${process.platform === "win32" ? ".exe" : ""}`); let native, log = ""; const start = () => { - native = spawn(executable, ["--room", database, room, name], { + native = spawn(executable, ["--room", database, name], { env: { ...process.env, PIIK_CHANNEL_NATIVE_KEY: process.env.PIIK_CHANNEL_OWNER_KEY, PIIK_CHANNEL_NATIVE_NAME: "Native operator" }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], @@ -508,7 +509,8 @@ export async function nativeRoom({ initial, serverRoom, browser, action, view, e await until("Native room becomes available", async () => { if (native.exitCode !== null) throw new Error(`Native host exited: ${log}`); return view(0); - }, value => value.state.channel.rooms.some(entry => entry.id === room && entry.available)); + }, value => value.state.channel.rooms.some(entry => entry.name === name && entry.available)); + room = (await view(0)).state.channel.rooms.find(entry => entry.name === name && entry.available).id; for (const index of [1, 2]) await browser(index, "click", `.c3-room-link[aria-label="${name}"]`); await until("both Browsers join the Native base", async () => Promise.all([view(1), view(2)]), values => values.every(value => value.state.pairs.some(pair => pair.rooms.includes(room)))); diff --git a/prototype/channel-server/examples/network_lab.rs b/prototype/channel-server/examples/network_lab.rs index b86e74bba..fd3e61477 100644 --- a/prototype/channel-server/examples/network_lab.rs +++ b/prototype/channel-server/examples/network_lab.rs @@ -90,6 +90,7 @@ async fn host(path: PathBuf) -> Result<()> { path: path.join("room.sqlite"), id: ROOM.into(), name: "Kernel room".into(), + bootstrap: true, }], stop(), ) diff --git a/prototype/channel-server/src/domain.rs b/prototype/channel-server/src/domain.rs index 1dbcdafd6..0d8b7afd9 100644 --- a/prototype/channel-server/src/domain.rs +++ b/prototype/channel-server/src/domain.rs @@ -58,7 +58,23 @@ impl Hub { let room_projection = matches!(&request.command, piik_channel_core::wire::Command::HostOutput { output, .. } if !output.reply.as_ref().is_some_and(|reply| matches!(reply.result, - piik_channel_core::host::RoomResult::Invited))); + piik_channel_core::host::RoomResult::Invited | piik_channel_core::host::RoomResult::Deleted { .. }))); + let deleted = match &request.command { + piik_channel_core::wire::Command::HostOutput { room_id, output } + if output.reply.as_ref().is_some_and(|reply| { + matches!( + reply.result, + piik_channel_core::host::RoomResult::Deleted { data_removed: true } + ) + }) => + { + Some(( + room_id.clone(), + output.reply.as_ref().unwrap().context.clone(), + )) + } + _ => None, + }; let (failure_target, request_id) = match &request.command { piik_channel_core::wire::Command::HostOutput { output, .. } => output .reply @@ -89,6 +105,10 @@ impl Hub { return; } self.authority = before.expect("metadata request checkpoint"); + if let Some((room, context)) = deleted { + let effects = self.authority.failed_room_delete(&room, &context); + self.apply(effects); + } self.send( failure_target, Event::Error { @@ -535,3 +555,144 @@ impl Domain { #[cfg(test)] #[path = "runtime_tests.rs"] mod runtime_tests; + +#[cfg(test)] +mod tests { + use super::*; + use piik_channel_core::{ + host::{HostInput, RoomSummary}, + RoomState, StoredRoomHost, + }; + use serde_json::json; + + #[test] + fn failed_deleted_room_checkpoint_keeps_only_an_offline_retry_entry() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("domain.sqlite"); + let authority = Authority::new("owner".into(), "invite".into(), vec![]).unwrap(); + let mut storage = storage::Storage::open(&path).unwrap(); + storage + .save(&serde_json::to_value(authority.export_backup()).unwrap()) + .unwrap(); + let connection = Uuid::new_v4(); + let (events, mut receiver) = mpsc::channel(64); + let mut hub = Hub { + authority, + clients: [( + connection, + Client { + events, + close: watch::channel(false).0, + }, + )] + .into(), + storage: Arc::new(Mutex::new(storage)), + invitation_origin: None, + room_commands: None, + }; + let request = |value: serde_json::Value| Request::parse(&value.to_string()).unwrap(); + let drain = |receiver: &mut mpsc::Receiver| { + let mut events = Vec::new(); + while let Ok(event) = receiver.try_recv() { + events.push(event); + } + events + }; + hub.request( + connection, + request(json!({"type":"join","name":"Owner","key":"owner","signingKey":vec![0;32]})), + ); + drain(&mut receiver); + let owner = hub.authority.identity().1; + let mut policy = RoomState::new( + "unused".into(), + "Delete".into(), + Default::default(), + owner, + piik_channel_core::wire::RoomAccess::Public, + false, + None, + ) + .unwrap(); + hub.request(connection, request(json!({"type":"create_room","room":RoomSummary::from_policy(&policy),"requestId":"create"}))); + policy.id = drain(&mut receiver) + .into_iter() + .find_map(|event| match event { + Event::RoomCreated { room, .. } => Some(room.id), + _ => None, + }) + .unwrap(); + let id = policy.id.clone(); + let mut host = StoredRoomHost::create(Path::new(":memory:"), policy).unwrap(); + hub.request( + connection, + request(json!({"type":"host_register","room":host.summary()})), + ); + let input: HostInput = drain(&mut receiver) + .into_iter() + .find_map(|event| match event { + Event::HostInput { input, .. } => Some(input), + _ => None, + }) + .unwrap(); + let output = host.dispatch(input).unwrap(); + hub.request( + connection, + request(json!({"type":"host_output","roomId":id,"output":output})), + ); + drain(&mut receiver); + hub.request( + connection, + request( + json!({"type":"delete_room","deleteData":true,"roomId":id,"requestId":"delete"}), + ), + ); + let input = drain(&mut receiver) + .into_iter() + .find_map(|event| match event { + Event::HostInput { input, .. } => Some(input), + _ => None, + }) + .unwrap(); + let output = host.dispatch(input).unwrap(); + let failure = rusqlite::Connection::open(&path).unwrap(); + failure.execute_batch("CREATE TRIGGER reject_checkpoint BEFORE UPDATE ON checkpoint BEGIN SELECT RAISE(ABORT,'held'); END;").unwrap(); + hub.request( + connection, + request(json!({"type":"host_output","roomId":id,"output":output})), + ); + let failed = drain(&mut receiver); + assert!(failed.iter().any(|event| matches!(event, Event::Error { code, request_id: Some(request) } if code == "storage_failed" && request == "delete"))); + assert!(failed.iter().any(|event| matches!(event, Event::State { state } if state.channel.rooms.iter().any(|room| room.id == id && !room.available)))); + assert!(!failed.iter().any(|event| matches!( + event, + Event::RoomReply { + result: piik_channel_core::host::RoomResult::Deleted { .. }, + .. + } + ))); + failure + .execute_batch("DROP TRIGGER reject_checkpoint") + .unwrap(); + hub.request( + connection, + request( + json!({"type":"delete_room","deleteData":true,"roomId":id,"requestId":"retry"}), + ), + ); + assert!(drain(&mut receiver).iter().any(|event| matches!( + event, + Event::RoomReply { + result: piik_channel_core::host::RoomResult::Deleted { + data_removed: false + }, + .. + } + ))); + let saved = hub.storage.lock().unwrap().load().unwrap().unwrap(); + assert!(saved["state"]["hostedRooms"] + .as_object() + .unwrap() + .is_empty()); + } +} diff --git a/prototype/channel-server/src/lib.rs b/prototype/channel-server/src/lib.rs index c6fcfcfcf..fa808b63c 100644 --- a/prototype/channel-server/src/lib.rs +++ b/prototype/channel-server/src/lib.rs @@ -57,6 +57,7 @@ impl NativeService { path: directory.join(format!("{id}.sqlite")), id: id.into(), name: name.into(), + bootstrap: true, }) .collect() } else { diff --git a/prototype/channel-server/src/runtime_tests.rs b/prototype/channel-server/src/runtime_tests.rs index 9fffde1d0..529d85977 100644 --- a/prototype/channel-server/src/runtime_tests.rs +++ b/prototype/channel-server/src/runtime_tests.rs @@ -322,6 +322,15 @@ fn directory_save_failure_cannot_restore_a_room_hosts_revoked_flows() { room_store .save(&serde_json::to_value(host.policy()).unwrap()) .unwrap(); + let administrator = Endpoint::join(&mut hub, "owner"); + administrator.request( + &mut hub, + json!({"type":"admit_room", "room":host.summary()}), + ); + let admitted_users = serde_json::to_value(hub.authority.export_state()).unwrap()["users"] + .as_array() + .unwrap() + .len(); operator.request( &mut hub, json!({"type":"host_register", "room":host.summary()}), @@ -443,7 +452,7 @@ fn directory_save_failure_cannot_restore_a_room_hosts_revoked_flows() { .as_array() .unwrap() .len(), - 2, + admitted_users, "an unconfirmed domain identity must not be checkpointed" ); drop(database); @@ -517,6 +526,10 @@ fn room_peer_commit_owns_confirmation_retry_without_domain_checkpoint() { .unwrap(), ) .unwrap(); + sender.request( + &mut hub, + json!({"type":"admit_room", "room":host.summary()}), + ); sender.request( &mut hub, json!({"type":"host_register", "room":host.summary()}), @@ -1313,7 +1326,6 @@ async fn native_hosting_failure_stops_the_http_service() { .unwrap(); let identity = domain.identity(); let rooms = crate::room_directory(&folder, identity); - drop(domain); std::fs::create_dir_all(&rooms).unwrap(); drop( StoredRoomHost::create( @@ -1331,6 +1343,15 @@ async fn native_hosting_failure_stops_the_http_service() { ) .unwrap(), ); + { + let mut hub = domain.hub.lock().unwrap(); + let owner = Endpoint::join(&mut hub, "owner"); + let room = StoredRoomHost::open(&rooms.join("living.sqlite")) + .unwrap() + .summary(); + owner.request(&mut hub, json!({"type":"admit_room", "room":room})); + } + drop(domain); let lock = std::fs::OpenOptions::new() .create(true) .truncate(false) diff --git a/prototype/channel-server/tests/native_session.rs b/prototype/channel-server/tests/native_session.rs index ae6c403f8..52aa98a34 100644 --- a/prototype/channel-server/tests/native_session.rs +++ b/prototype/channel-server/tests/native_session.rs @@ -138,6 +138,163 @@ async fn app_http( (status, serde_json::from_str(body).unwrap_or(Value::Null)) } +#[tokio::test] +async fn interrupted_unconfirmed_native_creation_reports_failure_without_replaying_it() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("pending.sqlite"); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/prototype/channel", listener.local_addr().unwrap()); + let expected_path = path.clone(); + let native = tokio::spawn(run( + Config { + url, + origin: "http://localhost".into(), + name: "Participant".into(), + key: Some("invite".into()), + credential: None, + server_udp: None, + }, + vec![RoomFile { + path, + id: "new-room".into(), + name: "New room".into(), + bootstrap: false, + }], + std::future::pending(), + )); + let mut domain = Domain::accept(&listener).await; + domain + .until(|_, event| matches!(event, Event::Welcome { .. })) + .await; + let request = Request::parse( + domain + .socket + .next() + .await + .unwrap() + .unwrap() + .to_text() + .unwrap(), + ) + .unwrap(); + assert!(matches!(request.command, Command::CreateRoom { .. })); + let effects = domain + .authority + .handle(domain.connection, request, domain.now); + assert!(effects + .events + .iter() + .any(|(_, event)| matches!(event, Event::RoomCreated { .. }))); + // The directory commit succeeds, but its response cannot reach the creator. + domain.socket.close(None).await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(5), native) + .await + .unwrap() + .unwrap(); + assert!(result + .unwrap_err() + .to_string() + .contains("room_creation_interrupted")); + assert!( + !expected_path.exists(), + "unconfirmed creation never wrote a local policy" + ); + assert_eq!( + serde_json::to_value(domain.authority.export_state()).unwrap()["hostedRooms"] + .as_object() + .unwrap() + .len(), + 1 + ); + assert!( + tokio::time::timeout(Duration::from_millis(100), listener.accept()) + .await + .is_err(), + "failure does not start another creation or reconnect" + ); +} + +#[tokio::test] +async fn ordinary_native_creation_uses_the_domain_id_and_reopens_that_saved_identity() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("participant.sqlite"); + let mut authority = None; + let mut credential = None; + let mut saved_id = None; + for first in [true, false] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/prototype/channel", listener.local_addr().unwrap()); + let (stop, stopped) = oneshot::channel(); + let native = tokio::spawn(run( + Config { + url, + origin: "http://localhost".into(), + name: "Participant".into(), + key: first.then(|| "invite".into()), + credential: credential.clone(), + server_udp: None, + }, + vec![RoomFile { + path: path.clone(), + id: "caller-cannot-choose-this".into(), + name: "Participant room".into(), + bootstrap: false, + }], + async { + let _ = stopped.await; + }, + )); + let mut domain = Domain::accept(&listener).await; + if let Some(previous) = authority.take() { + domain.authority = previous; + } + let id = if first { + let Event::RoomCreated { room, .. } = domain + .until(|_, event| matches!(event, Event::RoomCreated { .. })) + .await + else { + unreachable!() + }; + assert_ne!(room.id, "caller-cannot-choose-this"); + saved_id = Some(room.id.clone()); + room.id + } else { + saved_id.clone().unwrap() + }; + domain.bound(&id).await; + domain.room_turn(&id).await; + assert!( + !domain + .commands + .iter() + .any(|command| matches!(command, Command::AdmitRoom { .. })), + "ordinary native creation never uses bootstrap authority" + ); + if !first { + assert!( + !domain + .commands + .iter() + .any(|command| matches!(command, Command::CreateRoom { .. })), + "existing policy is restored, never recreated" + ); + } + assert_eq!(StoredRoomHost::open(&path).unwrap().policy().id, id); + credential = domain.events.iter().find_map(|(_, event)| match event { + Event::Welcome { credential, .. } => Some(credential.clone()), + _ => None, + }); + stop.send(()).unwrap(); + domain.until(|_, event| matches!(event, Event::Ack { request_id } if request_id == "native-leave")).await; + tokio::time::timeout(Duration::from_secs(5), native) + .await + .unwrap() + .unwrap() + .unwrap(); + authority = Some(domain.authority); + } +} + #[tokio::test] async fn rejected_identity_never_creates_room_storage() { let folder = std::env::temp_dir().join(format!("piik-native-rejected-{}", Uuid::new_v4())); @@ -156,6 +313,7 @@ async fn rejected_identity_never_creates_room_storage() { path: folder.join("one.sqlite"), id: "one".into(), name: "one".into(), + bootstrap: true, }], std::future::pending(), )); @@ -199,6 +357,7 @@ fn start( path: folder.join(format!("{id}.sqlite")), id: id.into(), name: id.into(), + bootstrap: true, }) .collect(), async { @@ -299,7 +458,6 @@ async fn real_session_resumes_bindings_and_restarts_from_committed_room_files() .args([ "--room", folder.join("one.sqlite").to_str().unwrap(), - "one", "stolen", ]) .env( @@ -722,9 +880,8 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission let ready: Value = serde_json::from_str(&page.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); assert!(ready.get("result").is_some()); - let room = Uuid::new_v4().to_string(); - let policy = RoomState::new( - room.clone(), + let mut policy = RoomState::new( + "new".into(), "Saved private".into(), Default::default(), user, @@ -733,6 +890,19 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission Some("room-secret".into()), ) .unwrap(); + domain.command(browser, json!({"type":"create_room","room":piik_channel_core::host::RoomSummary::from_policy(&policy),"requestId":"create-app-room"})).await; + policy.id = domain + .events + .iter() + .find_map(|(connection, event)| match event { + Event::RoomCreated { + room, + request_id: Some(id), + } if *connection == browser && id == "create-app-room" => Some(room.id.clone()), + _ => None, + }) + .unwrap(); + let room = policy.id.clone(); let policy = serde_json::to_string(&policy).unwrap(); let open = json!({"id":"open","type":"open","policy":policy}); page.send(Message::Text(open.to_string().into())) @@ -1022,13 +1192,22 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission domain .command( browser, - json!({"type":"host_register","room":{ + json!({"type":"create_room","room":{ "id":format!("reserved-{index}"),"name":format!("Reserved {index}"),"icon":"couch", "creatorId":user,"access":"public","hidden":false,"hasPassword":false, }}), ) .await; } + domain + .command( + browser, + json!({"type":"create_room","room":{ + "id":"new","name":"Beyond limit","icon":"couch","creatorId":user, + "access":"public","hidden":false,"hasPassword":false},"requestId":"limit-before-storage"}), + ) + .await; + assert!(domain.events.iter().any(|(connection, event)| *connection == browser && matches!(event, Event::Error { code, request_id: Some(id) } if code == "room_limit" && id == "limit-before-storage"))); let refused_room = Uuid::new_v4().to_string(); let refused_policy = RoomState::new( refused_room.clone(), @@ -1045,12 +1224,12 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission domain .until(|connection, event| { connection == native_connection - && matches!(event, Event::Error {code,request_id:Some(_)} if code == "room_limit") + && matches!(event, Event::Error {code,request_id:Some(_)} if code == "room_not_in_domain") }) .await; let refused: Value = serde_json::from_str(&page.next().await.unwrap().unwrap().into_text().unwrap()).unwrap(); - assert_eq!(refused["error"], "room_limit"); + assert_eq!(refused["error"], "room_not_in_domain"); let refused_path = room_directory.join(format!("{refused_room}.sqlite")); assert!( refused_path.exists(), @@ -1120,8 +1299,8 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission domain.socket = accept_async(stream).await.unwrap(); domain.connection = Uuid::new_v4(); domain.events.clear(); - domain.until(|_, event| matches!(event, Event::Error {code,request_id:Some(id)} if code == "room_limit" && id == &refused_room)).await; let next_binding = domain.bound(&room).await; + assert!(!domain.commands.iter().rev().take_while(|command| !matches!(command, Command::Join { .. })).any(|command| matches!(command, Command::HostRegister { room, .. } if room.id == refused_room)), "a saved but unadmitted room is not automatically introduced on restart"); assert_ne!(next_binding, binding); let ready: Value = tokio::time::timeout(Duration::from_secs(5), async { loop { @@ -1476,9 +1655,8 @@ async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change() serde_json::from_str(&control.next().await.unwrap().unwrap().into_text().unwrap()) .unwrap(); assert!(ready.get("result").is_some()); - let room = Uuid::new_v4().to_string(); - let policy = piik_channel_core::RoomState::new( - room.clone(), + let mut policy = piik_channel_core::RoomState::new( + "new".into(), "Saved local room".into(), Default::default(), Uuid::parse_str(user).unwrap(), @@ -1487,6 +1665,28 @@ async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change() None, ) .unwrap(); + admin.send(Message::Text(json!({"type":"create_room","room":piik_channel_core::host::RoomSummary::from_policy(&policy),"requestId":"create-app-room"}).to_string().into())).await.unwrap(); + policy.id = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let frame = admin.next().await.unwrap().unwrap(); + let Message::Text(text) = frame else { + continue; + }; + let event: Event = serde_json::from_str(&text).unwrap(); + if let Event::RoomCreated { + room, + request_id: Some(id), + } = event + { + if id == "create-app-room" { + break room.id; + } + } + } + }) + .await + .unwrap(); + let room = policy.id.clone(); control.send(Message::Text(json!({"id":"open","type":"open","policy":serde_json::to_string(&policy).unwrap()}).to_string().into())).await.unwrap(); let opened: Value = serde_json::from_str(&control.next().await.unwrap().unwrap().into_text().unwrap()) diff --git a/src/client/channel/components/ChannelRoomControls.tsx b/src/client/channel/components/ChannelRoomControls.tsx index 1da4d2d01..cc64599d9 100644 --- a/src/client/channel/components/ChannelRoomControls.tsx +++ b/src/client/channel/components/ChannelRoomControls.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { useAnchoredPopover } from "../../components/living/use-anchored-popover"; import { Tooltip } from "../../components/living/Tooltip"; +import { Btn } from "../../components/living/primitives"; import { Glyph } from "../../ui/icons"; import { useCopy } from "../../ui/copy"; import { useClipboardResult } from "../../ui/use-clipboard-result"; @@ -87,28 +88,33 @@ export function ChannelRoomControls({ channel, room, onCreated }: { if (open && room) void channel.roomBackupAvailable(room.id).then(value => { if (current) setBackupAvailable(value); }); return () => { current = false; }; }, [open, room?.id, room?.delivery?.bindingId, channel.sessionId, channel.appConnected, channel.connection, channel.roomBackupAvailable]); - const available = channel.connection === "connected" && (!room || room.available); + const connected = channel.connection === "connected"; + const available = connected && (!room || room.available); const busy = channel.pending.has(room ? `room:${room.id}` : "create-room"); const backupBusy = channel.pending.has("room-backup"); + const removing = !!room && channel.pending.has(`delete:${room.id}`); + const working = busy || backupBusy || removing; const members = room?.members?.filter(userId => userId !== room.creatorId && userId !== channel.state?.channel.ownerId) ?? []; const run = (work: Promise) => { void work.catch(() => {}); }; return <> ; diff --git a/src/client/channel/components/channel-room-controls.css b/src/client/channel/components/channel-room-controls.css index d39e88e43..a0f7e2399 100644 --- a/src/client/channel/components/channel-room-controls.css +++ b/src/client/channel/components/channel-room-controls.css @@ -8,6 +8,7 @@ .c3-check { display: flex; align-items: center; gap: 8px; cursor: pointer; line-height: 1.5; } .c3-check input { flex: none; accent-color: var(--action); cursor: pointer; } .c3-room-invitation { display: grid; gap: 12px; margin-top: 20px; padding-top: 18px; border-top: 1px solid var(--line); } +.c3-room-removal { display: flex; justify-content: flex-end; margin-top: 20px; padding-top: 18px; border-top: 1px solid var(--line); } .c3-invite-copy, .c3-room-members > div { display: flex; align-items: center; gap: 8px; min-width: 0; } .c3-invite-copy .c3-input, .c3-room-members > div > span { flex: 1; min-width: 0; } .c3-room-members { font-size: 12px; } diff --git a/src/client/channel/protocol.ts b/src/client/channel/protocol.ts index 905ad9405..254398cc7 100644 --- a/src/client/channel/protocol.ts +++ b/src/client/channel/protocol.ts @@ -78,6 +78,7 @@ export const eventSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("input_state"), registrations: z.array(z.object({ publicationId: id, controllerSessionId: id, flowId: id, secret: signingKey })) }), z.object({ type: z.literal("room_invite"), roomId: id, key: id, requestId: id.optional() }), z.object({ type: z.literal("host_bound"), roomId: id, bindingId: id }), + z.object({ type: z.literal("room_created"), room: roomSchema.pick({ id: true, name: true, icon: true, creatorId: true, access: true, hidden: true, hasPassword: true, voiceBitrate: true }), requestId: id.optional() }), z.object({ type: z.literal("host_input"), roomId: id, input: z.object({ bindingId: id }).passthrough() }), z.object({ type: z.literal("room_reply"), roomId: id, requestId: id.optional(), result: z.object({ type: z.string(), code: z.string().optional() }).passthrough() }), z.object({ type: z.literal("signal"), pairId: id, fromSessionId: id, payload: signalSchema }), @@ -100,7 +101,7 @@ export type RoomSummary = z.infer; export type ChannelPair = ChannelSnapshot["pairs"][number]; export type ChannelSignal = z.infer; export type ChannelEvent = z.infer; -export type ChannelReply = Extract | Extract; +export type ChannelReply = Extract | Extract; export interface SignedConversationPacket { sender: string; payload: string; signature: number[]; remainingHops: number } export interface ConversationAddress { roomId: string; bindingId: string; sender: string; recipient: string; requestId: string } export type ConversationReply = ConversationAddress & { record: @@ -124,6 +125,9 @@ export type ChannelCommand = | ({ type: "update_domain" } & DomainSettings) | { type: "input_register"; publicationId: string; flowId: string; secret: number[] } | { type: "host_register"; room: RoomSummary; resumeBinding?: string } + | { type: "create_room"; room: RoomSummary } + | { type: "admit_room"; room: RoomSummary } + | { type: "delete_room"; roomId: string; deleteData: boolean } | { type: "host_output"; roomId: string; output: unknown } | { type: "host_stop"; roomId: string; bindingId: string } | { type: "browse"; roomId: string; active: boolean } diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts index 00f564d5d..a95cba764 100644 --- a/src/client/channel/session.ts +++ b/src/client/channel/session.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { ChannelMedia } from "./media"; import { ChannelInput } from "./input"; import { ChannelConversation } from "./conversation"; -import { channelTopologySchema, eventSchema, userSchema, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type DomainSettings, type MessageReactionSnapshot, type RoomSettings } from "./protocol"; +import { channelTopologySchema, eventSchema, roomSummarySchema, userSchema, type ChannelCommand, type ChannelEvent, type ChannelMessage, type ChannelReply, type ChannelSnapshot, type ChannelTopology, type ConversationReply, type DomainSettings, type MessageReactionSnapshot, type RoomSettings, type RoomSummary } from "./protocol"; import { ChannelAttachments, type DraftFile } from "./attachments"; import type { ChannelView, ScreenPresentation, SourceMicrophoneConfiguration, SourceMicrophoneSettings } from "./types"; import { loadRoomHosting, roomDatabaseName, type HostedRoom, type BrowserRoomSnapshot, type BrowserRoomStage } from "./hosting"; @@ -274,6 +274,11 @@ export class ChannelSession { const binding = hosted.bindingId; void hosted.host.dispatch(event.input).then(output => { if (this.hostedRooms.get(event.roomId) === hosted && hosted.bindingId === binding && this.socket === socket) { + const result = (output as { reply?: { result?: { type?: string; dataRemoved?: boolean } } }).reply?.result; + if (result?.type === "deleted" && result.dataRemoved === true) { + this.hostedRooms.delete(event.roomId); + this.hostCleanup = Promise.all([this.hostCleanup, hosted.host.close()]).then(() => {}); + } this.write({ type: "host_output", roomId: event.roomId, output }); } }).catch(error => { @@ -291,6 +296,12 @@ export class ChannelSession { try { request.result?.(event); request.resolve(); } catch (error) { request.reject(error instanceof Error ? error : new Error("invalid_response")); } } + } else if (event.type === "room_created") { + const request = event.requestId ? this.requests.get(event.requestId) : undefined; + if (!request || !event.requestId) return; + clearTimeout(request.timer); this.requests.delete(event.requestId); + try { request.result?.(event); request.resolve(); } + catch (error) { request.reject(error instanceof Error ? error : new Error("invalid_response")); } } else if (event.type === "state") this.applyState(event.state); else if (event.type === "room_invite") { if (event.requestId) this.requests.get(event.requestId)?.result?.(event); @@ -364,6 +375,10 @@ export class ChannelSession { messagesByRoom: Object.fromEntries(Object.entries(this.view.messagesByRoom).filter(([id]) => canRead(id) && !freshBindings.has(id))), historyByRoom: Object.fromEntries(Object.entries(this.view.historyByRoom).filter(([id]) => canRead(id) && !freshBindings.has(id))), }); + for (const [id, hosted] of this.hostedRooms) if (!state.channel.rooms.some(room => room.id === id)) { + this.hostedRooms.delete(id); + this.hostCleanup = Promise.all([this.hostCleanup, hosted.host.close()]).then(() => {}); + } if (this.reading && (!sameChannel || !state.channel.rooms.some(room => room.id === this.reading!.roomId && room.authorized && room.available && room.delivery?.bindingId === this.reading!.bindingId))) { this.closeInteractions(); this.reading = null; @@ -706,9 +721,15 @@ export class ChannelSession { const storage = await this.browserStorage(state.channel.id, self.id); const policies = await storage.storedPolicies(); if (this.view.sessionId !== sessionId || this.closed) return; + const retained = new Set(policies.map(policy => (JSON.parse(policy) as { id: string }).id)); + for (const [id, hosted] of this.hostedRooms) if (!retained.has(id)) { + this.hostedRooms.delete(id); + await hosted.host.close(); + } for (const policy of policies) { const id = (JSON.parse(policy) as { id: string }).id; if (id === skipRoom) continue; + if (!this.view.state?.channel.rooms.some(room => room.id === id && room.creatorId === self.id)) continue; let hosted = this.hostedRooms.get(id); if (!hosted) { const host = await storage.open(policy); @@ -718,7 +739,17 @@ export class ChannelSession { } const room = await hosted.host.summary(); if (this.hostedRooms.get(id) !== hosted || this.view.sessionId !== sessionId || this.closed) return; - await this.request({ type: "host_register", room, resumeBinding: hosted.bindingId }); + try { await this.request({ type: "host_register", room, resumeBinding: hosted.bindingId }); } + catch (error) { + if (!(error instanceof Error) || error.message !== "room_not_in_domain") throw error; + if (this.hostedRooms.get(id) === hosted) this.hostedRooms.delete(id); + await hosted.host.close(); + } + } + for (const room of this.view.state?.channel.rooms ?? []) { + if (room.delivery?.hostSessionId === sessionId && !this.hostedRooms.has(room.id)) { + this.write({ type: "host_stop", roomId: room.id, bindingId: room.delivery.bindingId }); + } } } @@ -888,7 +919,15 @@ export class ChannelSession { const app = this.app?.connected ? this.app : undefined; const state = this.view.state, self = this.view.self, sessionId = this.view.sessionId; if (!state || !self || !sessionId) throw new Error("disconnected"); - const runtime = await loadRoomHosting(), roomId = crypto.randomUUID(); + const current = this.sessionContext(); + let room: RoomSummary | undefined; + await this.request({ type: "create_room", room: roomSummarySchema.parse({ ...settings, id: "new", creatorId: self.id, + hasPassword: settings.access === "private" && Boolean(settings.password) }) }, event => { + if (event.type === "room_created") room = event.room; + }); + current(); + if (!room) throw new Error("invalid_response"); + const runtime = await loadRoomHosting(), roomId = room.id; const policy = await runtime.createRoomPolicy({ ...settings, id: roomId, creatorId: self.id }); if (app) { const room = await app.open(policy); @@ -900,9 +939,9 @@ export class ChannelSession { const host = await storage.open(policy); if (this.view.sessionId !== sessionId || this.closed) { await host.close(); throw new Error("disconnected"); } this.hostedRooms.set(roomId, { host }); - const room = await host.summary(); + const summary = await host.summary(); if (this.hostedRooms.get(roomId)?.host !== host || this.view.sessionId !== sessionId || this.closed) throw new Error("disconnected"); - await this.request({ type: "host_register", room }); + await this.request({ type: "host_register", room: summary }); await this.request({ type: "browse", roomId, active: true }); return roomId; }); @@ -1163,6 +1202,10 @@ export class ChannelSession { if (metadata.kind !== "room" || !stage) throw new Error("invalid_backup"); if (!roomId && this.view.state!.channel.rooms.some(room => room.id === metadata.policy.id && room.available)) throw new Error("room_host_conflict"); if (roomId && metadata.policy.creatorId !== this.view.self!.id) throw new Error("backup_identity_required"); + if (!this.view.state!.channel.rooms.some(room => room.id === metadata.policy.id)) { + await this.request({ type: "admit_room", room: roomSummarySchema.parse({ ...metadata.policy, hasPassword: metadata.policy.passwordHash != null }) }); + initial(); + } rollback = await this.admitBackupIdentity(metadata); const check = this.sessionContext(), target = metadata.policy.id; const app = this.app?.connected ? this.app : undefined; @@ -1215,6 +1258,16 @@ export class ChannelSession { }, false); updateRoom = (roomId: string, settings: RoomSettings): Promise => this.action(`room:${roomId}`, () => this.request({ type: "update_room", roomId, ...settings })); + deleteRoom = (roomId: string, deleteData: boolean): Promise<{ dataRemoved: boolean }> => this.action(`delete:${roomId}`, async () => { + let dataRemoved: boolean | undefined; + await this.request({ type: "delete_room", roomId, deleteData }, event => { + if (event.type !== "room_reply" || event.result.type !== "deleted" || typeof event.result.dataRemoved !== "boolean") throw new Error("invalid_response"); + dataRemoved = event.result.dataRemoved; + }); + if (dataRemoved === undefined) throw new Error("invalid_response"); + if (this.roomId === roomId) this.browse(this.view.state?.channel.rooms.find(room => room.id !== roomId)?.id ?? ""); + return { dataRemoved }; + }); setRoomVoiceBitrate = (roomId: string, voiceBitrate: number): Promise => { const room = this.view.state?.channel.rooms.find(room => room.id === roomId); diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts index 51fd5a94d..0ccb2235f 100644 --- a/src/client/channel/types.ts +++ b/src/client/channel/types.ts @@ -95,6 +95,7 @@ export interface ChannelActions { restoreDomainBackup(archive: Blob): Promise; createRoom(settings: RoomSettings): Promise; updateRoom(roomId: string, settings: RoomSettings): Promise; + deleteRoom(roomId: string, deleteData: boolean): Promise<{ dataRemoved: boolean }>; setRoomVoiceBitrate(roomId: string, bitrate: number): Promise; roomBackupAvailable(roomId: string): Promise; exportRoomBackup(roomId: string): Promise; diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts index 901b92bde..0861ff923 100644 --- a/src/client/channel/use-channel.ts +++ b/src/client/channel/use-channel.ts @@ -44,7 +44,7 @@ export function useChannel(onInvitation?: (roomId: string) => void): ChannelCont roomTopology: session.roomTopology, connectionMetrics: session.connectionMetrics, appConnectionMetrics: session.appConnectionMetrics, setMessageReaction: session.setMessageReaction, exportDomainBackup: session.exportDomainBackup, restoreDomainBackup: session.restoreDomainBackup, - createRoom: session.createRoom, updateRoom: session.updateRoom, enterRoom: session.enterRoom, + createRoom: session.createRoom, updateRoom: session.updateRoom, deleteRoom: session.deleteRoom, enterRoom: session.enterRoom, setRoomVoiceBitrate: session.setRoomVoiceBitrate, roomBackupAvailable: session.roomBackupAvailable, exportRoomBackup: session.exportRoomBackup, restoreRoomBackup: session.restoreRoomBackup, createRoomInvite: session.createRoomInvite, revokeRoomAccess: session.revokeRoomAccess, diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts index 336c36e9e..d5e8ddb87 100644 --- a/tests/channel-session.test.ts +++ b/tests/channel-session.test.ts @@ -48,7 +48,7 @@ beforeEach(() => { afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.useRealTimers(); }); -async function setup(window = 1000, read = true, hash = "", readyInteractions = true) { +async function setup(window = 1000, read = true, hash = "", readyInteractions = true, roomIds = ["first", "second"]) { vi.stubGlobal("location", new URL(`https://channel.test/__channel-preview${hash ? `#${hash}` : ""}`)); vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => {} }); vi.stubGlobal("WebSocket", ChannelSocket); @@ -102,7 +102,7 @@ async function setup(window = 1000, read = true, hash = "", readyInteractions = await socket.onopen?.(); socket.receive({ type: "welcome", credential: "credential", sessionId: "endpoint", state: { channel: { id: "domain", name: "Friends", icon: "future-domain_7", ownerId: "self", historyWindow: window, - rooms: ["first", "second"].map(id => ({ id, name: id, icon: "couch", creatorId: "self", access: "public", + rooms: roomIds.map(id => ({ id, name: id, icon: "couch", creatorId: "self", access: "public", hidden: false, hasPassword: false, authorized: true, canManage: true, participantSessionIds: id === "first" ? ["endpoint"] : [], available: true, reading: id === "first", capabilities: { attachments: true }, @@ -417,12 +417,13 @@ test("App hosting uses its own participant while Browser rooms retain their page close: vi.fn(async () => {}), }; vi.stubGlobal("indexedDB", {}); - const storedPolicies = vi.fn(async () => [JSON.stringify(localRoom)]); + const storedPolicies = vi.fn(async () => [JSON.stringify(localRoom), JSON.stringify({ ...localRoom, id: "removed-from-domain" })]); + const open = vi.fn(async () => host); vi.spyOn(hosting, "loadRoomHosting").mockResolvedValue({ createRoomPolicy: async (input: unknown) => JSON.stringify(input), - BrowserRoomHost: { open: async () => host, storedPolicies }, + BrowserRoomHost: { open, storedPolicies }, } as unknown as Awaited>); - const { session, socket } = await setup(); + const { session, socket } = await setup(1000, true, "", true, ["first", "second", localRoom.id]); const app = ChannelSocket.current; try { expect(app).not.toBe(socket); @@ -436,8 +437,10 @@ test("App hosting uses its own participant while Browser rooms retain their page socket.receive({ type: "host_bound", roomId: localRoom.id, bindingId: "browser-binding" }); socket.receive({ type: "ack", requestId: register.requestId }); expect(storedPolicies).toHaveBeenCalledOnce(); + expect(open).toHaveBeenCalledOnce(); const creating = session.createRoom({ name: "App room", icon: "couch", access: "private", hidden: true, password: "private-room" }); + acceptCreatedRoom(socket); await vi.waitFor(() => expect(app.sent.some(command => command.type === "open")).toBe(true)); const opening = app.sent.find(command => command.type === "open")!; const policy = JSON.parse(opening.policy as string) as { id: string; name: string; icon: string; creatorId: string; access: string; hidden: boolean; password: string }; @@ -2158,6 +2161,38 @@ test("pending Native capture stays page-owned through same-page stop and close", } finally { session.close(); } }); +function acceptCreatedRoom(socket: ChannelSocket): void { + const request = socket.sent.findLast(command => command.type === "create_room")!; + expect(request.type).toBe("create_room"); + socket.receive({ type: "room_created", requestId: request.requestId, + room: { ...(request.room as object), id: "domain-created-room" } }); +} + +test("same-session recovery retires its own host binding when the committed room policy is gone", async () => { + const policy = JSON.stringify({ id: "first", creatorId: "self", name: "First", icon: "couch", access: "public", hidden: false }); + let policies = [policy]; + const host = { roomId: "first", summary: () => ({ ...JSON.parse(policy), hasPassword: false }), bind: vi.fn(async () => {}), close: vi.fn(async () => {}) }; + vi.stubGlobal("indexedDB", {}); + vi.spyOn(hosting, "loadRoomHosting").mockResolvedValue({ BrowserRoomHost: { storedPolicies: async () => policies, open: async () => host } } as unknown as Awaited>); + const { session, socket } = await setup(); + try { + await vi.waitFor(() => expect(socket.sent.some(command => command.type === "host_register")).toBe(true)); + const registration = socket.sent.find(command => command.type === "host_register")!; + socket.receive({ type: "host_bound", roomId: "first", bindingId: "owned-binding" }); + socket.receive({ type: "ack", requestId: registration.requestId }); + const retained = structuredClone(session.getSnapshot().state!); + retained.channel.rooms[0].delivery = { hostSessionId: "endpoint", bindingId: "owned-binding", nextHops: {} }; + policies = []; + session.reconnect(); + const resumed = ChannelSocket.current; + await resumed.onopen?.(); + resumed.receive({ type: "welcome", credential: "credential", sessionId: "endpoint", state: retained }); + await vi.waitFor(() => expect(resumed.sent.some(command => command.type === "host_stop" && command.roomId === "first" && command.bindingId === "owned-binding")).toBe(true)); + expect(host.close).toHaveBeenCalledOnce(); + expect(resumed.sent.some(command => command.type === "host_register")).toBe(false); + } finally { session.close(); } +}); + test("remembered App intent does not prevent Browser hosting when no App is connected", async () => { vi.mocked(launchSession.isClientActivated).mockReturnValue(true); const discovery = vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue(null); @@ -2174,6 +2209,7 @@ test("remembered App intent does not prevent Browser hosting when no App is conn expect(discovery).toHaveBeenCalledOnce(); expect(session.getSnapshot()).toMatchObject({ appConnected: false, error: null }); const creating = session.createRoom({ name: "Browser room", icon: "couch", access: "public", hidden: false }); + acceptCreatedRoom(socket); await vi.waitFor(() => expect(socket.sent.some(command => command.type === "host_register")).toBe(true)); const register = socket.sent.find(command => command.type === "host_register")!; socket.receive({ type: "host_bound", roomId: host.roomId, bindingId: "browser-binding" }); @@ -2205,6 +2241,7 @@ test("an App failure during creation does not turn that request into a Browser r app.receive({ id: app.sent.at(-1)!.id, result: null }); await vi.waitFor(() => expect(session.getSnapshot().appConnected).toBe(true)); const creating = session.createRoom({ name: "App room", icon: "couch", access: "public", hidden: false }); + acceptCreatedRoom(socket); const failed = expect(creating).rejects.toThrow("app_disconnected"); await vi.waitFor(() => expect(prepared).toBeTypeOf("function")); app.close(); @@ -2234,6 +2271,7 @@ test("host binding precedes its first input and a failed binding retires that ho const { session, socket } = await setup(); try { const creating = session.createRoom({ name: "Hosted", icon: "couch", access: "public", hidden: false }); + acceptCreatedRoom(socket); void creating.catch(() => {}); await vi.waitFor(() => expect(socket.sent.some(command => command.type === "host_register")).toBe(true)); const registration = socket.sent.at(-1)!; @@ -2327,6 +2365,15 @@ test("room replies settle only the request belonging to that room", async () => result: { type: "done" } }); await saving; expect(settled).toBe(true); + for (const deleteData of [false, true]) { + const deleting = session.deleteRoom("first", deleteData); + const request = socket.sent.at(-1)!; + expect(request).toMatchObject({ type: "delete_room", roomId: "first", deleteData }); + socket.receive({ type: "room_reply", roomId: "second", requestId: request.requestId, result: { type: "deleted", dataRemoved: true } }); + expect(session.getSnapshot().pending.has("delete:first")).toBe(true); + socket.receive({ type: "room_reply", roomId: "first", requestId: request.requestId, result: { type: "deleted", dataRemoved: deleteData } }); + await expect(deleting).resolves.toEqual({ dataRemoved: deleteData }); + } const updating = session.updateRoom("first", { name: "Unavailable", icon: "couch", access: "public", hidden: false }); const rejected = expect(updating).rejects.toThrow("room_host_offline"); socket.receive({ type: "room_reply", roomId: "first", requestId: socket.sent.at(-1)!.requestId, @@ -5727,7 +5774,7 @@ test("a late Native ownership description cannot export a replaced room binding" }); test("portable import validates the full archive before switching accounts and rejects an unrelated Welcome without persisting it", async () => { - const { session, stage, metadata, read } = await setupRoomBackup(); + const { session, socket, stage, metadata, read } = await setupRoomBackup(); metadata.policy = { ...metadata.policy, id: "imported", creatorId: "archived-user" }; Object.assign(metadata, { ownCredential: { userId: "archived-user", credential: "archived-credential" } }); const persist = vi.fn(); vi.stubGlobal("localStorage", { getItem: () => null, setItem: persist }); @@ -5737,8 +5784,16 @@ test("portable import validates the full archive before switching accounts and r read.mockRejectedValueOnce(new Error("backup_content_mismatch")); await expect(session.restoreRoomBackup(new Blob())).rejects.toThrow("backup_content_mismatch"); expect(ChannelSocket.current.sent.some(command => command.credential === "archived-credential")).toBe(false); + expect(socket.sent.some(command => command.type === "admit_room")).toBe(false); const importing = session.restoreRoomBackup(new Blob()), failed = expect(importing).rejects.toThrow("backup_identity_required"); - await vi.waitFor(() => expect(ChannelSocket.current).not.toBeUndefined()); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("admit_room")); + const admissionRequest = socket.sent.at(-1)!; + expect(admissionRequest.room).toMatchObject({ id: "imported", creatorId: "archived-user" }); + expect(stage.replace).not.toHaveBeenCalled(); expect(persist).not.toHaveBeenCalled(); + const catalog = structuredClone(original); + catalog.channel.rooms.push({ ...catalog.channel.rooms[0], id: "imported", creatorId: "archived-user", available: false, delivery: undefined }); + socket.receive({ type: "state", state: catalog }); + socket.receive({ type: "ack", requestId: admissionRequest.requestId }); await vi.waitFor(() => expect(session.getSnapshot().connection).toBe("connecting")); const admission = ChannelSocket.current; await admission.onopen?.(); expect(admission.sent.find(command => command.type === "join")).toMatchObject({ credential: "archived-credential" }); @@ -5782,7 +5837,7 @@ test("an approved App exports only rooms positively matched to its Native sessio }); test("portable import admits the archived identity through Welcome before committing and omits old owner/resume context", async () => { - const { session, stage, metadata, nextHost, read } = await setupRoomBackup(); + const { session, socket, stage, metadata, nextHost, read } = await setupRoomBackup(); metadata.policy = { ...metadata.policy, id: "imported", creatorId: "archived-user" }; stage.policy = JSON.stringify(metadata.policy); Object.assign(metadata, { ownCredential: { userId: "archived-user", credential: "archived-credential" } }); const runtime = await hosting.loadRoomHosting(); vi.spyOn(runtime.BrowserRoomHost, "storedPolicies").mockResolvedValue([]); @@ -5791,10 +5846,19 @@ test("portable import admits the archived identity through Welcome before commit vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ domainId: "domain", user: { id: "archived-user", name: "Archived", roles: [] } })))); const cache = vi.spyOn(session.attachments, "restoreRetained").mockResolvedValue(true); const state = structuredClone(session.getSnapshot().state!); - state.channel.rooms = []; state.channel.ownerId = null; state.users = [{ id: "archived-user", name: "Archived", roles: [] }]; + const catalog = structuredClone(state); + const imported = { ...state.channel.rooms[0], id: "imported", creatorId: "archived-user", name: "First", available: false, delivery: undefined }; + catalog.channel.rooms.push(imported); + state.channel.rooms = [imported]; state.channel.ownerId = null; state.users = [{ id: "archived-user", name: "Archived", roles: [] }]; state.sessions = [{ id: "new-endpoint", userId: "archived-user", online: true, signingKey: testSigningKey }]; try { const importing = session.restoreRoomBackup(new Blob()); + await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("admit_room")); + const admissionRequest = socket.sent.at(-1)!; + expect(admissionRequest.room).toMatchObject({ id: "imported", creatorId: "archived-user" }); + expect(stage.replace).not.toHaveBeenCalled(); expect(saved).not.toHaveBeenCalled(); + socket.receive({ type: "state", state: catalog }); + socket.receive({ type: "ack", requestId: admissionRequest.requestId }); await vi.waitFor(() => expect(session.getSnapshot().connection).toBe("connecting")); const admission = ChannelSocket.current; await admission.onopen?.(); const join = admission.sent.find(command => command.type === "join")!; @@ -5808,9 +5872,9 @@ test("portable import admits the archived identity through Welcome before commit admission.receive({ type: "host_bound", roomId: "imported", bindingId: "imported-binding" }); admission.receive({ type: "ack", requestId: registration.requestId }); const restored = structuredClone(state); - restored.channel.rooms.push({ id: "imported", name: "First", creatorId: "archived-user", icon: "couch", access: "public", hidden: false, hasPassword: false, + restored.channel.rooms = [{ id: "imported", name: "First", creatorId: "archived-user", icon: "couch", access: "public", hidden: false, hasPassword: false, authorized: true, canManage: true, voiceBitrate: 64_000, participantSessionIds: [], available: true, reading: false, capabilities: { attachments: true }, - delivery: { hostSessionId: "new-endpoint", bindingId: "imported-binding", nextHops: {} } }); + delivery: { hostSessionId: "new-endpoint", bindingId: "imported-binding", nextHops: {} } }]; admission.receive({ type: "state", state: restored }); await vi.waitFor(() => expect(admission.sent.some(command => command.type === "browse" && command.roomId === "imported")).toBe(true)); const browse = admission.sent.find(command => command.type === "browse" && command.roomId === "imported")!;