use std::sync::Arc; use desktop_runtime::{Result, ServiceError, Services, SessionId}; use futures::future::BoxFuture; use reqwest::{Method, StatusCode, Url}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sqlx::Row as _; use zeroize::Zeroizing; use super::{ CloudServices, Core, account, auth::AuthLease, choice, field, target, transport::{Transport, failure, first, text, uuid}, }; use crate::product::{ services::{Action, Mutation, Operation, Scope}, sharing::{AccessEntry, Capability, EntryKind, GeneralAccess, ManagedShare}, }; #[derive(Clone, Serialize, Deserialize)] pub(super) struct Publication { pub share_id: String, pub workspace_id: String, pub revision: u64, pub pending: Option, pub conflict: Option, #[serde(default)] pub attachments: Vec, /// Fingerprint of the local content last published or kept, so sharing actions republish /// only after the note changes. #[serde(default)] pub source: Option, } pub(super) struct ShareSource { pub title: String, pub body: Value, pub workspace: String, pub participants: Vec, pub meeting_at: String, } impl Core { pub(super) async fn share_comments(&self, lease: &AuthLease, share: &str) -> Result { let mut comments = Vec::new(); let mut bytes = 0usize; let mut cursor = (Value::Null, Value::Null); loop { let page = self.rpc(lease, "list_session_share_comments", json!({"p_share_id": share, "p_before_created_at": cursor.0, "p_before_comment_id": cursor.1, "p_limit": 30})).await?; let page = page .as_array() .filter(|rows| rows.len() <= 30) .ok_or_else(|| failure("Invalid comments page"))?; super::transport::check_directory_size(comments.len(), page, &mut bytes)?; comments.extend(page.iter().cloned()); if page.len() < 30 { comments.reverse(); return Ok(Value::Array(comments)); } let last = page .last() .ok_or_else(|| failure("Missing comment cursor"))?; let next = (last["created_at"].clone(), last["comment_id"].clone()); if next == cursor || next.0.as_str().is_none() || next.1.as_str().is_none() { return Err(failure("Invalid comment cursor")); } cursor = next; } } pub(super) async fn share_state( &self, services: &Services, lease: &AuthLease, session: &SessionId, ) -> Result> { let value: Option = sqlx::query_scalar("SELECT value_json FROM app_settings WHERE id = ?") .bind(journal_id(account(lease)?, session)) .fetch_optional(services.db.pool()) .await .map_err(|_| failure("Cannot load share publication journal"))?; value .map(|value| { serde_json::from_str(&value).map_err(|_| { failure("Share publication journal is damaged; original data retained") }) }) .transpose() } pub(super) async fn save_share_state( &self, services: &Services, lease: &AuthLease, session: &SessionId, publication: &Publication, ) -> Result<()> { lease.check()?; sqlx::query("INSERT INTO app_settings (id, value_json) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET value_json = excluded.value_json") .bind(journal_id(account(lease)?, session)) .bind(serde_json::to_string(publication).map_err(|_| failure("Cannot serialize share publication"))?) .execute(services.db.pool()).await.map_err(|_| failure("Cannot save publication state; retry without closing the app"))?; Ok(()) } pub(super) async fn share_source( &self, services: &Services, lease: &AuthLease, scope: &Scope, ) -> Result { let session = scope .session_id .as_ref() .ok_or_else(|| failure("Open a meeting to share"))?; self.host.flush_editor(session.clone()).await?; lease.check()?; let row = sqlx::query( "SELECT s.workspace_id, s.owner_user_id, s.title, d.body, d.body_format, CASE WHEN datetime(s.started_at) IS NOT NULL THEN s.started_at ELSE s.created_at END AS meeting_at FROM sessions s JOIN session_documents d ON d.id = ( SELECT id FROM session_documents WHERE session_id = s.id AND deleted_at IS NULL AND kind IN ('summary', 'template_output') ORDER BY sort_order, id LIMIT 1) WHERE s.id = ? AND s.deleted_at IS NULL", ) .bind(session.0.as_ref()) .fetch_optional(services.db.pool()) .await .map_err(|_| failure("Cannot read meeting"))? .ok_or_else(|| failure("This meeting has no summary to share"))?; let workspace: String = row .try_get("workspace_id") .map_err(|_| failure("Invalid meeting workspace"))?; let owner: String = row .try_get("owner_user_id") .map_err(|_| failure("Invalid meeting owner"))?; // Workspace owners and admins share any note; other active members share their own. let local_access: bool = sqlx::query_scalar( "SELECT EXISTS(SELECT 1 FROM workspace_memberships m JOIN workspaces w ON w.id = m.workspace_id WHERE m.workspace_id = ? AND m.user_id = ? AND (m.role IN ('owner', 'admin') OR (w.kind = 'shared' AND m.role <> '' AND ?)) AND m.deleted_at IS NULL AND w.deleted_at IS NULL)") .bind(&workspace).bind(account(lease)?).bind(owner == account(lease)?).fetch_one(services.db.pool()).await .map_err(|_| failure("Cannot verify workspace membership"))?; let routed = anlg_db_app::local_library_remote_workspace(services.db.pool(), &workspace) .await .map_err(|_| failure("Cannot verify local library routing"))?; let personal = routed == account(lease)?; if !local_access && !(personal && (owner == account(lease)? || owner == "00000000-0000-0000-0000-000000000000")) { return Err(failure("This account does not own this meeting")); } let remote_workspace = scope.workspace_id.as_deref().unwrap_or(&routed).to_owned(); uuid(&remote_workspace)?; if remote_workspace != routed { let can_share: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM workspace_memberships m JOIN workspaces w ON w.id = m.workspace_id WHERE m.workspace_id = ? AND m.user_id = ? AND m.role IN ('owner', 'admin') AND m.deleted_at IS NULL AND w.deleted_at IS NULL)") .bind(&remote_workspace).bind(account(lease)?).fetch_one(services.db.pool()).await.map_err(|_| failure("Cannot verify destination workspace"))?; if !can_share { return Err(failure( "This account cannot publish into the selected workspace", )); } } let body: String = row .try_get("body") .map_err(|_| failure("Invalid meeting body"))?; let format: String = row .try_get("body_format") .map_err(|_| failure("Invalid meeting format"))?; if body.len() > 2 * 1024 * 1024 { return Err(failure("Meeting exceeds sharing size limit")); } let document = match format.as_str() { "prosemirror_json" => { serde_json::from_str(&body).map_err(|_| failure("Meeting document is malformed"))? } "markdown" => anlg_tiptap::md_to_tiptap_json(&body) .map_err(|_| failure("Meeting markdown is malformed"))?, _ => return Err(failure("Meeting document format cannot be shared")), }; validate_document(&document)?; if document["content"].as_array().is_none_or(Vec::is_empty) { return Err(failure("Generate a summary before sharing")); } let title = row .try_get::("title") .map_err(|_| failure("Invalid meeting title"))?; let names: Vec = sqlx::query_scalar( "SELECT COALESCE(NULLIF(h.name, ''), p.display_name) FROM session_participants p LEFT JOIN humans h ON h.id = p.human_id AND h.deleted_at IS NULL WHERE p.session_id = ? AND p.human_id <> '' AND p.source <> 'excluded' AND p.deleted_at IS NULL ORDER BY p.created_at, p.id LIMIT 1025", ).bind(session.0.as_ref()).fetch_all(services.db.pool()).await.map_err(|_| failure("Cannot read meeting participants"))?; if names.len() > 1024 { return Err(failure("Meeting exceeds participant limit")); } let mut participants = Vec::new(); for name in names { let name = name.split_whitespace().collect::>().join(" "); if !name.is_empty() && name.encode_utf16().count() <= 100 && !participants.contains(&name) { participants.push(name); if participants.len() == 32 { break; } } } Ok(ShareSource { title, body: document, workspace: remote_workspace, participants, meeting_at: row .try_get("meeting_at") .map_err(|_| failure("Invalid meeting timestamp"))?, }) } pub(super) async fn share_action( &self, services: &Services, lease: &AuthLease, scope: &Scope, mutation: &Mutation, ) -> Result<()> { let session = scope .session_id .as_ref() .ok_or_else(|| failure("Open a meeting to share"))?; let existing = self.share_state(services, lease, session).await?; if mutation.operation.action == Action::CreateShare { let workspace = self.share_source(services, lease, scope).await?.workspace; let value = self .rpc( lease, "create_session_share", json!({"p_workspace_id": workspace, "p_session_id": session.0.as_ref()}), ) .await?; let share = uuid(text(first(&value)?, "share_id")?)?; if existing .as_ref() .is_some_and(|old| old.share_id != share && old.pending.is_some()) { return Err(failure( "Existing publication has pending changes; resolve it before creating another share", )); } let publication = existing.unwrap_or(Publication { share_id: share.into(), workspace_id: workspace, revision: 0, pending: None, conflict: None, attachments: Vec::new(), source: None, }); self.save_share_state(services, lease, session, &publication) .await?; return self.publish(services, lease, scope, publication).await; } let publication = existing.ok_or_else(|| failure("Create a share first"))?; let share = &publication.share_id; let id = || uuid(target(mutation)?); let (rpc, body) = match mutation.operation.action { Action::PublishShare => return self.publish(services, lease, scope, publication).await, Action::SetShareScope => { let next = choice(mutation, "scope", &["restricted", "workspace", "public"])?; ( "set_session_share_scope", json!({"p_share_id": share, "p_general_scope": next, "p_general_workspace_id": if next == "workspace" { Some(uuid(field(mutation, "workspace")?)?) } else { None }}), ) } Action::SetShareRole => ( "update_session_access_grant", json!({"p_grant_id": id()?, "p_capability": choice(mutation, "role", &["viewer", "commenter", "editor"])?}), ), Action::RespondShareRequest => { let decision = choice(mutation, "decision", &["approved", "denied"])?; ( "review_session_access_request", json!({"p_request_id": id()?, "p_decision": decision, "p_capability": if decision == "approved" { Some(choice(mutation, "role", &["viewer", "commenter", "editor"])?) } else { None }}), ) } Action::AddComment => ( "create_session_share_comment", json!({"p_share_id": share, "p_body": field(mutation, "comment")?, "p_anchor_quote_exact": null, "p_anchor_quote_prefix": null, "p_anchor_quote_suffix": null, "p_anchor_from_hint": null, "p_anchor_to_hint": null}), ), Action::DeleteComment => ( "delete_session_share_comment", json!({"p_comment_id": id()?}), ), Action::RevokeShareLink => ( "set_session_share_scope", json!({"p_share_id": share, "p_general_scope": "restricted", "p_general_workspace_id": null}), ), Action::RevokeInvitation => ( "revoke_session_access_invitation", json!({"p_invitation_id": id()?}), ), Action::DeleteShare => { self.rpc(lease, "delete_session_share_by_session", json!({"p_workspace_id": publication.workspace_id, "p_session_id": session.0.as_ref()})).await?; sqlx::query("DELETE FROM app_settings WHERE id = ?") .bind(journal_id(account(lease)?, session)) .execute(services.db.pool()) .await .map_err(|_| { failure("Share deleted remotely; local journal cleanup needs retry") })?; sqlx::query( "DELETE FROM shared_session_cache WHERE viewer_user_id = ? AND share_id = ?", ) .bind(account(lease)?) .bind(share) .execute(services.db.pool()) .await .map_err(|_| failure("Share deleted remotely; local cache cleanup needs retry"))?; return Ok(()); } Action::EnableShareLink | Action::RotateShareLink | Action::CopyShareLink => { let rpc = if mutation.operation.action == Action::RotateShareLink { "rotate_session_share_link" } else { "enable_session_share_link" }; let response = self.rpc(lease, rpc, json!({"p_share_id": share})).await?; let row = first(&response)?; let link = uuid(text(row, "link_id")?)?; let slot = self .auth .key(&format!("{}:share:{share}:link", account(lease)?)); let url = if let Some(token) = row["link_token"].as_str() { let url = self.capability_url(&format!("/t/{link}/"), token)?; self.auth .store .write(slot.clone(), Zeroizing::new(url.clone())) .await?; url } else { self.auth.store.read(slot).await?.ok_or_else(|| failure("Link token exists on another device. Rotate the link to copy a new one"))?.to_string() }; self.host.copy_text(Zeroizing::new(url)).await?; return Ok(()); } Action::InviteToShare | Action::ResendInvitation => { let mut response = if mutation.operation.action == Action::InviteToShare { self.rpc(lease, "create_session_access_invitation", json!({"p_share_id": share, "p_invitee_email": field(mutation, "email")?.to_lowercase(), "p_capability": choice(mutation, "role", &["viewer", "commenter", "editor"])?})).await? } else { self.rpc( lease, "resend_session_access_invitation", json!({"p_invitation_id": id()?}), ) .await? }; let invitation = uuid(text(first(&response)?, "invitation_id")?)?.to_owned(); if first(&response)?["invite_token"].as_str().is_none() { response = self .rpc( lease, "resend_session_access_invitation", json!({"p_invitation_id":invitation}), ) .await?; } let token = text(first(&response)?, "invite_token")?; let url = self.capability_url(&format!("/share/invite/{invitation}/"), token)?; let title = self.share_source(services, lease, scope).await?.title; let sent = self.api(lease, Method::POST, &format!("/shared-notes/invitations/{invitation}/email"), Some(&json!({"shareId":share,"inviteToken":token,"noteTitle":title,"fromName":lease.identity.email.as_deref().unwrap_or_default()}))).await; if sent.is_err() { lease.check()?; if self.host.copy_text(Zeroizing::new(url)).await.is_err() { self.rpc( lease, "revoke_session_access_invitation", json!({"p_invitation_id": invitation}), ) .await?; return Err(failure("Could not deliver invitation; invitation revoked")); } *self.notice.lock().await = Some("Email unavailable. Invitation link copied instead".into()); } return Ok(()); } _ => return Err(failure("Invalid sharing action")), }; self.rpc(lease, rpc, body).await?; Ok(()) } pub(super) fn capability_url(&self, path: &str, token: &str) -> Result { if token.len() != 43 || !token .bytes() .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') { return Err(failure("Invalid invitation/link capability")); } let mut url = self .auth .transport .config .web .join(path) .map_err(|_| failure("Invalid sharing URL"))?; url.set_fragment(Some(&format!("token={token}"))); if self.auth.transport.config.callback.scheme() != "anarlog" { url.query_pairs_mut() .append_pair("scheme", self.auth.transport.config.callback.scheme()); } Ok(url.to_string()) } /// The snapshot `publish` would send for the note's current local content. pub(super) async fn draft( &self, services: &Services, lease: &AuthLease, scope: &Scope, state: &Publication, ) -> Result { let source = self.share_source(services, lease, scope).await?; let ids = state .attachments .iter() .map(|attachment| text(attachment, "id").and_then(uuid)) .collect::>>()?; Ok( json!({"baseRevision": state.revision, "mutationId": uuid::Uuid::new_v4().to_string(), "title": source.title, "body": source.body, "attachmentIds": ids, "participants": source.participants, "meetingAt": source.meeting_at}), ) } pub(super) async fn publish( &self, services: &Services, lease: &AuthLease, scope: &Scope, mut state: Publication, ) -> Result<()> { let session = scope .session_id .as_ref() .ok_or_else(|| failure("Select a meeting"))?; if state.conflict.is_some() { return Err(failure( "The web copy changed. Review the saved remote snapshot before retrying; your local draft is intact", )); } // A mutation left pending by a failed attempt is retried as it was, then the note's // current content is published if it changed since. loop { let retried = state.pending.is_some(); if !retried { let pending = self.draft(services, lease, scope, &state).await?; if state.source.as_deref() == Some(fingerprint(&pending).as_str()) { return Ok(()); } state.pending = Some(pending); self.save_share_state(services, lease, session, &state) .await?; } self.send_pending(services, lease, session, &mut state) .await?; if !retried { return Ok(()); } } } async fn send_pending( &self, services: &Services, lease: &AuthLease, session: &SessionId, state: &mut Publication, ) -> Result<()> { let url = self .auth .transport .config .api .join(&format!("/sync/shares/{}/snapshot", state.share_id)) .map_err(|_| failure("Invalid share route"))?; let response = self .auth .transport .send( Method::PUT, url, Some(lease.access_token()?), state.pending.as_ref(), &[], ) .await?; lease.check()?; if response.status == StatusCode::CONFLICT { if response.body["code"] != "snapshot_conflict" { return Err(failure("Share conflict response is malformed")); } validate_snapshot(&response.body["snapshot"], &state.share_id)?; state.conflict = Some(response.body["snapshot"].clone()); self.save_share_state(services, lease, session, state) .await?; return Err(desktop_runtime::ServiceError::Conflict); } let snapshot = Transport::checked(response)?; validate_snapshot(&snapshot, &state.share_id)?; persist_snapshot( services, account(lease)?, session, &state.workspace_id, &snapshot, ) .await?; state.revision = snapshot["contentRevision"] .as_u64() .ok_or_else(|| failure("Invalid published revision"))?; state.source = state.pending.take().as_ref().map(fingerprint); state.attachments = snapshot["attachments"] .as_array() .cloned() .ok_or_else(|| failure("Invalid attachment list"))?; self.save_share_state(services, lease, session, state).await } } /// The published fields of a pending snapshot, without its revision base or mutation id. pub(super) fn fingerprint(pending: &Value) -> String { use sha2::{Digest, Sha256}; let fields = json!([ pending["title"], pending["body"], pending["attachmentIds"], pending["participants"], pending["meetingAt"] ]); Sha256::digest(fields.to_string()) .iter() .map(|byte| format!("{byte:02x}")) .collect() } fn journal_id(account: &str, session: &SessionId) -> String { format!("gpui.share.{account}.{}", session.0.as_ref()) } pub(super) fn validate_document(value: &Value) -> Result<()> { if value["type"] != "doc" { return Err(failure("Invalid document root")); } let mut stack = vec![(value, 0usize)]; let mut count = 0; while let Some((node, depth)) = stack.pop() { count += 1; if count > 50_000 || depth > 64 || !node.is_object() || node["type"].as_str().is_none() { return Err(failure("Invalid or excessively complex document")); } if let Some(children) = node.get("content") { let children = children .as_array() .ok_or_else(|| failure("Invalid document content"))?; stack.extend(children.iter().map(|child| (child, depth + 1))); } } Ok(()) } fn validate_snapshot(value: &Value, share: &str) -> Result<()> { if value["shareId"] != share || value["schemaVersion"] != 1 || value["contentRevision"] .as_u64() .is_none_or(|revision| revision == 0) || value["accessVersion"] .as_u64() .is_none_or(|version| version == 0) || value["publishedAt"].as_str().is_none() || value["attachments"] .as_array() .is_none_or(|rows| rows.len() > 64) || value["webEditable"].as_bool().is_none() { return Err(failure("Invalid published snapshot")); } validate_document(&value["body"]) } pub(super) async fn persist_snapshot( services: &Services, account: &str, session: &SessionId, workspace: &str, value: &Value, ) -> Result<()> { let written = sqlx::query("INSERT INTO shared_session_cache (share_id, viewer_user_id, workspace_id, session_id, schema_version, content_revision, title, body_json, capability, manage_access, access_version, published_at, attachments_json, web_editable) VALUES (?, ?, ?, ?, 1, ?, ?, ?, 'editor', 1, ?, ?, ?, ?) ON CONFLICT(viewer_user_id, share_id) DO UPDATE SET content_revision = excluded.content_revision, title = excluded.title, body_json = excluded.body_json, access_version = excluded.access_version, published_at = excluded.published_at, attachments_json = excluded.attachments_json, web_editable = excluded.web_editable WHERE shared_session_cache.content_revision <= excluded.content_revision AND shared_session_cache.web_edit_base_content_revision IS NULL") .bind(text(value, "shareId")?).bind(account).bind(workspace).bind(session.0.as_ref()) .bind(value["contentRevision"].as_i64()).bind(value["title"].as_str().unwrap_or_default()) .bind(serde_json::to_string(&value["body"]).map_err(|_| failure("Cannot persist snapshot"))?) .bind(value["accessVersion"].as_i64()).bind(text(value, "publishedAt")?) .bind(value["attachments"].to_string()).bind(value["webEditable"].as_bool().unwrap_or(false)) .execute(services.db.pool()).await.map_err(|_| failure("Share published but local receipt could not be saved. Retry to reconcile"))?; if written.rows_affected() == 0 { return Err(failure( "A newer or edited shared cache exists. Its draft was retained; reconcile it before publishing again", )); } Ok(()) } /// One change from the note's share popover. #[derive(Clone, Debug)] pub enum ShareCommand { /// Invites each address as a viewer. Invite(Vec), CopyLink, Access(GeneralAccess), SetCapability(AccessEntry, Capability), Remove(AccessEntry), Resend(AccessEntry), Review(AccessEntry, bool), /// Publishes the desktop copy over the web edits that paused sharing. KeepDesktop, /// Opens the shared note's web copy in the browser. OpenWebCopy, /// Emails the published summary to each address (`deliverSessionShareRecapEmail`). EmailRecap(Vec), } impl CloudServices { /// Starts browser sign-in, as the share surfaces' Sign in buttons do. pub fn sign_in(&self) -> BoxFuture<'static, Result<()>> { let this = self.clone(); Box::pin(async move { this.runtime .service(move |_| async move { let url = this.core.auth.begin_sign_in().await?; this.core .host .hand_off(url, super::host::Handoff::SignIn) .await })? .receive() .await }) } /// The note's published share as its owner manages it, or `None` before it is shared. pub fn share_overview(&self, scope: Scope) -> BoxFuture<'static, Result>> { let this = self.clone(); Box::pin(async move { this.runtime .service(move |services| async move { let lease = this.core.lease(&scope).await?; let session = scope .session_id .as_ref() .ok_or_else(|| failure("Open a meeting to share"))?; this.core.managed_share(&services, &lease, session).await })? .receive() .await }) } /// Shipping's draft panel shares the note on its first action; later actions manage it. pub fn share_command( &self, scope: Scope, command: ShareCommand, ) -> BoxFuture<'static, Result>> { let this = self.clone(); Box::pin(async move { this.runtime .service(move |services| async move { let _guard = this .core .mutations .try_lock() .map_err(|_| ServiceError::Busy)?; let lease = this.core.lease(&scope).await?; this.core .share_command(&services, &lease, &scope, command) .await?; let session = scope .session_id .as_ref() .ok_or_else(|| failure("Open a meeting to share"))?; this.core.managed_share(&services, &lease, session).await })? .receive() .await }) } } impl CloudServices { /// Shipping's `revokeManagedShare`: deletes the published shares and cached copies of /// deleted notes, once their undo window has ended. Admitted now, behind the notes' queued /// database work, so quitting still waits for it. Nothing is revoked while signed out or for /// a note that is no longer deleted. Every note is tried; the first failure is returned. pub fn revoke_deleted_shares( &self, sessions: Vec, ) -> Result> { let deleted = self.runtime.flush()?; let this = self.clone(); self.runtime.service(move |services| async move { deleted.receive().await?; if this.scope().account_id.is_none() { return Ok(()); } let mut result = Ok(()); for session in sessions { let revoked = this.revoke_deleted_share(&services, session).await; result = result.and(revoked); } result }) } async fn revoke_deleted_share(&self, services: &Services, session: SessionId) -> Result<()> { let workspace: Option = sqlx::query_scalar( "SELECT workspace_id FROM sessions WHERE id = ? AND deleted_at IS NOT NULL", ) .bind(session.0.as_ref()) .fetch_optional(services.db.pool()) .await .map_err(|_| failure("Cannot read the deleted note"))?; let Some(workspace) = workspace else { return Ok(()); }; let scope = Scope { session_id: Some(session.clone()), ..self.scope() }; let _guard = self.core.mutations.lock().await; let lease = self.core.lease(&scope).await?; if self .core .share_state(services, &lease, &session) .await? .is_some() { let delete = Mutation { operation: super::panels::operation(Action::DeleteShare, "Delete share"), fields: Arc::from([]), }; return self .core .share_action(services, &lease, &scope, &delete) .await; } // Only the publishing device keeps a journal, so the server finds a share published from // another device by its note. A note outside a cloud workspace was never shared. let workspace = anlg_db_app::local_library_remote_workspace(services.db.pool(), &workspace) .await .map_err(|_| failure("Cannot verify local library routing"))?; if uuid(&workspace).is_err() { return Ok(()); } // Best effort: without a journal this device doesn't know the note was ever shared (shipping // wouldn't ask the server at all), so a failure, such as being offline, is only logged // rather than warning on every deletion. if let Err(error) = self .core .rpc( &lease, "delete_session_share_by_session", json!({"p_workspace_id": workspace, "p_session_id": session.0.as_ref()}), ) .await { tracing::warn!(%error, "a deleted note's share could not be revoked by its note"); return Ok(()); } sqlx::query("DELETE FROM shared_session_cache WHERE viewer_user_id = ? AND session_id = ?") .bind(account(&lease)?) .bind(session.0.as_ref()) .execute(services.db.pool()) .await .map_err(|_| failure("Share deleted remotely; local cache cleanup needs retry"))?; Ok(()) } } impl Core { async fn managed_share( &self, services: &Services, lease: &AuthLease, session: &SessionId, ) -> Result> { let Some(publication) = self.share_state(services, lease, session).await? else { return Ok(None); }; let share = json!({"p_share_id": publication.share_id}); let management = self .rpc(lease, "get_session_share_management", share.clone()) .await?; let management = first(&management)?; let general = GeneralAccess::parse( text(management, "general_scope")?, management["general_workspace_id"].as_str(), ) .ok_or_else(|| failure("Invalid share access"))?; let access = self.rpc(lease, "list_session_share_access", share).await?; let access = access .as_array() .ok_or_else(|| failure("Invalid share access list"))? .iter() .map(AccessEntry::parse) .collect::>>() .ok_or_else(|| failure("Invalid share access entry"))?; Ok(Some(ManagedShare { share_id: publication.share_id.as_str().into(), general, has_active_link: management["has_active_link"].as_bool() == Some(true), access: access.into(), conflict: publication.conflict.is_some(), })) } async fn share_command( &self, services: &Services, lease: &AuthLease, scope: &Scope, command: ShareCommand, ) -> Result<()> { let session = scope .session_id .as_ref() .ok_or_else(|| failure("Open a meeting to share"))?; let run = |action: Action, target: Option<&str>, fields: &[(&str, &str)]| Mutation { operation: Operation { id: "share-popover".into(), label: "Share".into(), action, target_id: target.map(Into::into), disabled_reason: None, confirmation: None, }, fields: fields .iter() .map(|(key, value)| (Arc::from(*key), Arc::from(*value))) .collect(), }; if self.share_state(services, lease, session).await?.is_none() { self.share_action(services, lease, scope, &run(Action::CreateShare, None, &[])) .await?; } let mut publication = self .share_state(services, lease, session) .await? .ok_or_else(|| failure("Create a share first"))?; // Like shipping's `publishLatest`: whoever gains access sees the note as it is now. // Narrowing access and opening the web copy skip it, so they still work while a web // edit conflict pauses publishing. let publishes = match &command { ShareCommand::Remove(_) | ShareCommand::Review(_, false) | ShareCommand::Access(GeneralAccess::Restricted | GeneralAccess::Public) | ShareCommand::KeepDesktop | ShareCommand::OpenWebCopy => false, ShareCommand::SetCapability(entry, capability) => { entry.kind != EntryKind::Grant || *capability > entry.capability } _ => true, }; if publishes { self.publish(services, lease, scope, publication).await?; publication = self .share_state(services, lease, session) .await? .ok_or_else(|| failure("Create a share first"))?; } let share = publication.share_id.as_str(); let mutation = match command { ShareCommand::Invite(emails) => { if emails.is_empty() || emails.len() > 32 { return Err(failure("Invite between 1 and 32 people at a time")); } for email in emails { self.share_action( services, lease, scope, &run( Action::InviteToShare, None, &[("email", &email), ("role", "viewer")], ), ) .await?; } return Ok(()); } ShareCommand::CopyLink => return self.copy_share_url(lease, share).await, ShareCommand::EmailRecap(recipients) => { return self.email_recap(services, lease, share, &recipients).await; } ShareCommand::OpenWebCopy => { let url = self.share_url(lease, share, "anarlog").await?; let url = Url::parse(&url).map_err(|_| failure("Share URL is unavailable"))?; return self.host.open_url(url).await; } ShareCommand::KeepDesktop => { let revision = publication .conflict .as_ref() .and_then(|remote| remote["contentRevision"].as_u64()) .ok_or(ServiceError::Conflict)?; return self .resolve_share_conflict( services, lease, scope, revision, super::ConflictDecision::PublishLocal, ) .await; } ShareCommand::Access(GeneralAccess::Link) => { let management = self .rpc( lease, "get_session_share_management", json!({"p_share_id": share}), ) .await?; let linked = async { if first(&management)?["has_active_link"].as_bool() != Some(true) { self.rpc( lease, "enable_session_share_link", json!({"p_share_id": share}), ) .await?; } self.copy_share_url(lease, share).await } .await; if linked.is_err() { let _ = self.rpc(lease, "set_session_share_scope", json!({"p_share_id": share, "p_general_scope": "restricted", "p_general_workspace_id": null})).await; } return linked; } ShareCommand::Access(GeneralAccess::Restricted) => { run(Action::SetShareScope, None, &[("scope", "restricted")]) } ShareCommand::Access(GeneralAccess::Workspace(workspace)) => run( Action::SetShareScope, None, &[("scope", "workspace"), ("workspace", &workspace)], ), ShareCommand::Access(GeneralAccess::Public) => { return Err(failure("Public access is managed on the web")); } ShareCommand::SetCapability(entry, capability) => match entry.kind { EntryKind::Grant => run( Action::SetShareRole, Some(&entry.id), &[("role", capability.as_str())], ), EntryKind::Invitation => run( Action::InviteToShare, None, &[ ("email", entry.email.as_deref().unwrap_or_default()), ("role", capability.as_str()), ], ), EntryKind::Request => return Err(failure("Review the request first")), }, ShareCommand::Remove(entry) => match entry.kind { EntryKind::Grant => { self.rpc( lease, "revoke_session_access_grant", json!({"p_grant_id": uuid(&entry.id)?}), ) .await?; return Ok(()); } EntryKind::Invitation => run(Action::RevokeInvitation, Some(&entry.id), &[]), EntryKind::Request => return Err(failure("Deny the request instead")), }, ShareCommand::Resend(entry) => run(Action::ResendInvitation, Some(&entry.id), &[]), ShareCommand::Review(entry, approve) => run( Action::RespondShareRequest, Some(&entry.id), &[ ("decision", if approve { "approved" } else { "denied" }), ("role", entry.capability.as_str()), ], ), }; self.share_action(services, lease, scope, &mutation).await } /// `deliverSessionShareRecapEmail`: the published title and summary, as Markdown, sent by /// the API from the account's address. async fn email_recap( &self, services: &Services, lease: &AuthLease, share: &str, recipients: &[String], ) -> Result<()> { if recipients.is_empty() || recipients.len() > 20 { return Err(failure("Email between 1 and 20 people at a time")); } let (title, body): (String, String) = sqlx::query_as( "SELECT title, body_json FROM shared_session_cache WHERE viewer_user_id = ? AND share_id = ?", ) .bind(account(lease)?) .bind(share) .fetch_optional(services.db.pool()) .await .map_err(|_| failure("Cannot read the published note"))? .ok_or_else(|| failure("Publish the note before emailing it"))?; let body = serde_json::from_str(&body) .ok() .and_then(|body| anlg_tiptap::tiptap_json_to_md(&body).ok()) .ok_or_else(|| failure("The published note cannot be emailed"))?; let body = body.trim(); if body.is_empty() || body.len() > 100 * 1024 { return Err(failure("The published note cannot be emailed")); } self.api( lease, Method::POST, &format!("/shared-notes/{share}/recap/email"), Some(&json!({"recipients": recipients, "senderName": lease.identity.email.as_deref().unwrap_or("An Anarlog user"), "noteTitle": title, "noteBody": body, "deliveryId": uuid::Uuid::new_v4().to_string()})), ) .await?; Ok(()) } /// `copySessionShareUrl`: the account URL people with access open. async fn copy_share_url(&self, lease: &AuthLease, share: &str) -> Result<()> { let scheme = self.auth.transport.config.callback.scheme().to_owned(); let url = self.share_url(lease, share, &scheme).await?; self.host.copy_text(Zeroizing::new(url)).await } async fn share_url(&self, lease: &AuthLease, share: &str, scheme: &str) -> Result { let response = self .rpc( lease, "get_session_share_workspace_slug", json!({"p_share_id": share}), ) .await?; let slug = first(&response)?["workspace_share_slug"].as_str(); account_share_url(&self.auth.transport.config.web, share, slug, scheme) } } /// `buildAccountSessionShareUrl`: `/share//`, on the workspace's subdomain of anarlog.so, /// with the desktop scheme for non-production builds. pub(super) fn account_share_url( web: &Url, share: &str, slug: Option<&str>, scheme: &str, ) -> Result { uuid(share)?; let mut base = web.clone(); if let Some(slug) = slug { const RESERVED: &[&str] = &[ "admin", "api", "app", "assets", "auth", "cdn", "dev", "docs", "mail", "staging", "static", "status", "support", "www", ]; let bytes = slug.as_bytes(); let valid = (3..=63).contains(&bytes.len()) && bytes .iter() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-') && bytes[0] != b'-' && bytes[bytes.len() - 1] != b'-' && !RESERVED.contains(&slug); if !valid { return Err(failure("Share URL is unavailable")); } if matches!(base.host_str(), Some("anarlog.so" | "www.anarlog.so")) { base.set_host(Some(&format!("{slug}.anarlog.so"))) .map_err(|_| failure("Share URL is unavailable"))?; } } let mut url = base .join(&format!("/share/{share}/")) .map_err(|_| failure("Share URL is unavailable"))?; url.set_query(None); url.set_fragment(None); if scheme != "anarlog" { url.query_pairs_mut().append_pair("scheme", scheme); } Ok(url.to_string()) }