Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions desktop/ox-mobile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ mod running;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod session_end;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod session_link;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod session_usage;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod starred_models;
Expand Down
108 changes: 84 additions & 24 deletions desktop/ox-mobile/src/mobile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ use crate::{
file_change,
preferences::EnterKey,
reconnect::Recovery,
session_link,
};

#[cfg(target_os = "ios")]
Expand Down Expand Up @@ -211,7 +212,7 @@ enum SessionOpen {
},
}

const INVITATION_OPEN_NOTE: &str = "Paired with this host, but that conversation could not be opened. It may have moved or closed. You can open it from Activity.";
const OPEN_SESSION_NOTE: &str = "That conversation could not be opened. It may have moved or closed. You can open it from Activity.";

#[derive(Clone)]
struct MoveSource {
Expand Down Expand Up @@ -557,9 +558,9 @@ pub(crate) struct Mobile {
/// displayed.
damaged_pairing: Option<remote::DamagedPairing>,
pub(crate) notice: Option<String>,
/// Pairing succeeded but the invited conversation could not be opened.
/// Kept separate from a host error because nothing about the pairing failed.
invitation_note: Option<String>,
/// A pairing invitation or pasted session link could not open a conversation.
/// Kept separate from a host error because the host and its pairing are fine.
open_note: Option<String>,
/// A new pairing's conversation target, consumed after the directory read.
invitation_pending: crate::pairing_open::Pending,
invitation_opening: bool,
Expand Down Expand Up @@ -1021,7 +1022,7 @@ impl Mobile {
unreadable_storage: false,
damaged_pairing: None,
notice: None,
invitation_note: None,
open_note: None,
invitation_pending: Default::default(),
invitation_opening: false,
request: None,
Expand Down Expand Up @@ -2358,7 +2359,7 @@ impl Mobile {
self.navigation_locked = true;
self.error = None;
self.notice = None;
self.invitation_note = None;
self.open_note = None;
window.blur(cx);
let task = cx.background_spawn(async move { remote::pair(address, code) });
self.request = Some(cx.spawn_in(window, async move |this, cx| {
Expand Down Expand Up @@ -2540,6 +2541,7 @@ impl Mobile {
let Some(client) = self.client.clone() else {
return;
};
self.open_note = None;
let epoch = self.pairing_epoch;
let pairing = client.local_pairing_id().to_owned();
let resolving_origin = origin.clone();
Expand Down Expand Up @@ -2574,7 +2576,7 @@ impl Mobile {
cx,
),
Err(_) => {
app.invitation_note = Some(INVITATION_OPEN_NOTE.into());
app.open_note = Some(OPEN_SESSION_NOTE.into());
cx.notify();
}
}
Expand All @@ -2583,6 +2585,58 @@ impl Mobile {
cx.notify();
}

/// Read a session link from the clipboard after the user asked to paste it.
///
/// The clipboard is never read at any other point. A link for another host
/// is reported without switching hosts, because the person must select
/// that paired host first; the resolution path is the same one a pairing
/// invitation uses once its directory read has finished.
fn paste_session_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.busy {
return;
}
// A new attempt replaces whatever the previous one reported.
self.open_note = None;
let Some(text) = Self::read_clipboard(cx) else {
self.open_note = Some("The clipboard has no text to open.".into());
cx.notify();
return;
};
match session_link::classify(&text, &self.origin) {
session_link::Paste::Current(link) => {
self.open_invitation(link.target.as_str().to_owned(), link.origin, window, cx);
}
session_link::Paste::OtherHost(origin) => {
self.open_note = Some(format!(
"That session link is for {origin}. Select that paired host in Hosts first, then paste it again."
));
cx.notify();
}
session_link::Paste::Invalid => {
self.open_note = Some(
"That is not a session link. Copy the link shown for a session on its host, then paste it again."
.into(),
);
cx.notify();
}
}
}

/// The user-triggered clipboard read for [`Self::paste_session_link`].
fn read_clipboard(cx: &mut Context<Self>) -> Option<String> {
#[cfg(target_os = "android")]
{
let _ = cx;
// GPUI's Android store is in-process; the package reads the system
// clipboard a link was copied to.
gpui_mobile::packages::clipboard::get_text().ok().flatten()
}
#[cfg(target_os = "ios")]
{
cx.read_from_clipboard().and_then(|item| item.text())
}
}

fn adopt_host(
&mut self,
pairing: String,
Expand Down Expand Up @@ -2635,7 +2689,7 @@ impl Mobile {
self.clear_move_offer();
self.key_transfer.reset();
self.cancel_invitation_open();
self.invitation_note = None;
self.open_note = None;
self.flush_drafts();
self.draft_save = None;
self.draft_storage = None;
Expand Down Expand Up @@ -3154,7 +3208,7 @@ impl Mobile {
app.catalog.clear_pending();
}
if invitation.is_some() {
app.invitation_note = Some(INVITATION_OPEN_NOTE.into());
app.open_note = Some(OPEN_SESSION_NOTE.into());
cx.notify();
return;
}
Expand Down Expand Up @@ -3323,7 +3377,7 @@ impl Mobile {
};
let invitation_snapshot = if invitation.is_some() {
let Ok(first) = incoming.try_recv() else {
app.invitation_note = Some(INVITATION_OPEN_NOTE.into());
app.open_note = Some(OPEN_SESSION_NOTE.into());
cx.notify();
return;
};
Expand Down Expand Up @@ -5510,22 +5564,28 @@ impl Render for Mobile {
.when_some(tap_notice, |root, notice| {
root.child(arcade::banner(palette, Tone::Warning, "ALERT", notice, cx))
})
.when_some(self.invitation_note.as_ref(), |root, note| {
.when_some(self.open_note.as_ref(), |root, note| {
root.child(
arcade::banner(palette, Tone::Warning, "PAIRED", note.clone(), cx)
.child(
div().flex().items_center().pr(px(8.)).child(
button("dismiss-invitation-note", "Dismiss")
.ghost()
.on_click(cx.listener(|app, _, _, cx| {
arcade::haptics::trigger(
arcade::haptics::Haptic::Light,
);
app.invitation_note = None;
cx.notify();
})),
),
arcade::banner(
palette,
Tone::Warning,
"OPEN SESSION",
note.clone(),
cx,
)
.child(
div().flex().items_center().pr(px(8.)).child(
button("dismiss-open-session-note", "Dismiss")
.ghost()
.on_click(cx.listener(|app, _, _, cx| {
arcade::haptics::trigger(
arcade::haptics::Haptic::Light,
);
app.open_note = None;
cx.notify();
})),
),
),
)
})
.when_some(
Expand Down
15 changes: 15 additions & 0 deletions desktop/ox-mobile/src/mobile/projects_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,21 @@ impl Mobile {
),
),
)
.when(self.client.is_some(), |card| {
card.child(
row().child(
button("paste-session-link", "Paste session link")
.flex_1()
.disabled(self.busy)
.accessibility_label(
"Read the clipboard and open a session link for this paired host",
)
.on_click(window.listener_for(entity, |app, _, window, cx| {
app.paste_session_link(window, cx)
})),
),
)
})
}

fn project_card(
Expand Down
165 changes: 165 additions & 0 deletions desktop/ox-mobile/src/session_link.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//! A session link pasted into an already paired host.
//!
//! The desktop's "Copy session link" prints one canonical HTTPS `.ts.net`
//! origin and exactly one `#thread=<target>` fragment. This parser accepts
//! nothing else: no pairing code, no other or duplicate fragment key, no
//! query or path, and no credentials. Keeping the check here lets the phone
//! reject a link before it signs anything.
use ox_host_web::{client::canonical_origin, phone_link::SessionTarget};

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Link {
pub(crate) origin: String,
pub(crate) target: SessionTarget,
}

/// What a pasted clipboard value means for the host the phone shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Paste {
/// A canonical link for the exact origin already selected.
Current(Link),
/// A canonical link for some other origin. The phone keeps its host.
OtherHost(String),
/// Anything that is not a session link this phone accepts.
Invalid,
}

pub(crate) fn classify(text: &str, current_origin: &str) -> Paste {
let Some(link) = parse(text) else {
return Paste::Invalid;
};
if link.origin == current_origin {
Paste::Current(link)
} else {
Paste::OtherHost(link.origin)
}
}

fn parse(text: &str) -> Option<Link> {
let (address, fragment) = text.trim().split_once('#')?;
if fragment.is_empty() || fragment.contains('#') {
return None;
}
let mut pairs = url::form_urlencoded::parse(fragment.as_bytes());
let (name, value) = pairs.next()?;
if name != "thread" || pairs.next().is_some() {
return None;
}
// Re-encoding must reproduce the fragment byte for byte. That rejects a
// trailing `&`, a raw `=`, a non-canonical percent escape and an encoded
// key, all of which the desktop's serializer would have written another
// way.
let mut canonical = url::form_urlencoded::Serializer::new(String::new());
canonical.append_pair("thread", &value);
if canonical.finish() != fragment {
return None;
}
Some(Link {
origin: canonical_origin(address)?,
target: SessionTarget::parse(&value)?,
})
}

#[cfg(test)]
mod tests {
use super::*;
use ox_desk_core::{host_protocol::Scope, runtime::Route};
use ox_host_web::phone_link::{session_target, session_url};

const ORIGIN: &str = "https://studio.fixture.ts.net";

fn target() -> String {
session_target(
&Scope {
project: "/fixture".into(),
route: Route::CODEX_SUBSCRIPTION,
},
"thread-1",
)
.unwrap()
}

/// The exact link the desktop's "Copy session link" prints.
fn link(origin: &str, target: &str) -> String {
session_url(&format!("{origin}/"), target).unwrap()
}

/// The one accepted fragment, encoded the way the desktop writes it.
fn fragment(target: &str) -> String {
let mut encoded = url::form_urlencoded::Serializer::new(String::new());
encoded.append_pair("thread", target);
encoded.finish()
}

#[test]
fn accepts_a_canonical_link_for_the_current_host() {
let target = target();
let Paste::Current(parsed) = classify(&link(ORIGIN, &target), ORIGIN) else {
panic!("canonical link was rejected");
};
assert_eq!(parsed.origin, ORIGIN);
assert_eq!(parsed.target.as_str(), target);
assert_eq!(parsed.target.thread(), "thread-1");
// The digest itself is URL-safe and decodes to a canonical target.
assert!(parsed.target.as_str().contains('~'));
// A trailing newline is what a phone clipboard usually carries.
assert!(matches!(
classify(&format!("{}\n", link(ORIGIN, &target)), ORIGIN),
Paste::Current(_)
));
}

#[test]
fn a_link_for_another_host_is_named_and_the_current_host_is_kept() {
let other = "https://other.fixture.ts.net";
assert_eq!(
classify(&link(other, &target()), ORIGIN),
Paste::OtherHost(other.into())
);
}

#[test]
fn rejects_anything_but_a_canonical_https_ts_net_thread_fragment() {
let target = target();
let encoded = fragment(&target);
let texts = [
String::new(),
link(ORIGIN, &target).replace("https://", "http://"),
link(ORIGIN, &target).replace("studio.fixture.ts.net", "studio.example.test"),
link("https://user:[email protected]", &target),
link("https://[email protected]", &target),
format!("https://studio.fixture.ts.net:443/#{encoded}"),
link(&format!("{ORIGIN}/project"), &target),
link(&format!("{ORIGIN}/?view=1"), &target),
format!("{ORIGIN}/#pair=0123456789AB&{encoded}"),
format!("{ORIGIN}/#thread=thread-1"),
format!("{ORIGIN}/#{encoded}&{encoded}"),
format!("{ORIGIN}/#{encoded}&unknown=1"),
format!("{ORIGIN}/#{encoded}&"),
format!("{ORIGIN}/#unknown={target}"),
format!("{ORIGIN}/#pair=0123456789AB"),
format!("{ORIGIN}/#"),
format!("{ORIGIN}/#thread="),
format!(
"{ORIGIN}/#{}",
fragment(&format!("thread-1~{}", "a".repeat(42)))
),
format!("{ORIGIN}/#{}", fragment(&format!("~{}", "a".repeat(43)))),
format!("{ORIGIN}/#thread=~{}", "a".repeat(43)),
// The serializer writes `=` as `%3D`; a raw one is not canonical.
format!("{ORIGIN}/#thread=a=b~{}", "a".repeat(43)),
// `%41` decodes to `A` but the serializer writes `A` literally.
format!(
"{ORIGIN}/#{}",
encoded.replacen("thread=thread", "thread=%74hread", 1)
),
];
for (index, text) in texts.into_iter().enumerate() {
assert_eq!(
classify(&text, ORIGIN),
Paste::Invalid,
"accepted {text} at {index}"
);
}
}
}