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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ This log records user-visible changes. GitHub releases contain package downloads

## Unreleased

### Changed

- Start onboarding with one pairing-link entry for local or remote environments and show Settings after pairing. Settings shows a compact local status with a separate Manage connection page.
- Exclude Local from remote pairing controls so an unpaired local server cannot submit through the remote-only pairing command.
- Identify the link's environment before pairing, select it after connecting, and support remote-only installations without local T3 Code state.
- Make importing T3 Code's encrypted environment catalog opt-in; preserve Bar's own pairing credentials and independent manual and T3 Connect connections.
- Distinguish a running local server from an authorized Bar connection instead of showing unpaired installations as connected.

### Fixed

- Forget access and Remove connection work for a Tailscale HTTP route after its peer leaves the tailnet or Tailscale stops, instead of failing and leaving the saved grant in the credential store.
Expand Down
33 changes: 33 additions & 0 deletions desktop/crates/bar-connection/src/manual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ pub fn input_has_pairing_key(input: &ConnectionInput) -> Result<bool, String> {
Ok(parse_input(input)?.code.is_some())
}

pub fn pairing_key_from_link(input: &ConnectionInput) -> Result<PairingKey, String> {
let parsed = parse_input(input)?;
let code = parsed.code.ok_or("Copy a complete pairing link from T3 Code, including its one-time code.")?;
if code.len() != 12 || !code.chars().all(|character| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(character.to_ascii_uppercase())) {
return Err("This pairing link has an invalid code. Create and copy a fresh link in T3 Code.".into());
}
Ok(PairingKey::new(code.to_ascii_uppercase()))
}

struct ParsedInput {
route: Route,
code: Option<Zeroizing<String>>,
Expand Down Expand Up @@ -130,6 +139,9 @@ fn parse_input(input: &ConnectionInput) -> Result<ParsedInput, String> {
url.set_path("/");
}
url.set_fragment(None);
if url.scheme() == "http" && url.host_str() == Some("localhost") {
url.set_host(Some("127.0.0.1")).map_err(|_| invalid_input())?;
}
let base = crate::normalized_origin(url.as_str()).map_err(|_| invalid_input())?;
Ok(ParsedInput {
route: Route::Bearer {
Expand Down Expand Up @@ -737,6 +749,27 @@ mod tests {
.is_err());
}

#[test]
fn unified_pairing_requires_a_complete_link_and_normalizes_localhost() {
for address in [
"https://remote.example/",
"https://remote.example/pair#token=invalid",
"https://remote.example/pair#token=ABCD2345EFGH&token=ABCD2345EFGH",
"ABCD2345EFGH",
] {
let input = ConnectionInput::Direct { address: address.into() };
assert!(pairing_key_from_link(&input).is_err());
}
for address in [
"http://localhost:3773/pair#token=abcd2345efgh",
"t3code://pair?pairingUrl=http%3A%2F%2Flocalhost%3A3773%2Fpair%23token%3DABCD2345EFGH",
] {
let input = ConnectionInput::Direct { address: address.into() };
assert_eq!(pairing_key_from_link(&input).unwrap().as_str(), "ABCD2345EFGH");
assert_eq!(destination_label(&input_route(&input).unwrap()), "http://127.0.0.1:3773/");
}
}

#[test]
fn manual_and_desktop_routes_deduplicate_and_removal_leaves_desktop_untouched() {
let dir = FixtureDir::new();
Expand Down
26 changes: 26 additions & 0 deletions desktop/crates/bar-core/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{fs, io, path::PathBuf};
#[serde(rename_all = "camelCase", default)]
pub struct Settings {
pub environment_selection: EnvironmentSelection,
pub imports_desktop_environments: bool,
pub notifications_muted: bool,
pub shows_previews: bool,
pub automatically_checks_for_updates: bool,
Expand All @@ -15,6 +16,7 @@ impl Default for Settings {
fn default() -> Self {
Self {
environment_selection: EnvironmentSelection::All,
imports_desktop_environments: false,
notifications_muted: false,
shows_previews: true,
automatically_checks_for_updates: true,
Expand All @@ -26,6 +28,7 @@ impl Default for Settings {
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SettingKey {
ImportsDesktopEnvironments,
NotificationsMuted,
ShowsPreviews,
AutomaticallyChecksForUpdates,
Expand Down Expand Up @@ -73,6 +76,7 @@ impl SettingsStore {
pub fn set(&mut self, key: SettingKey, enabled: bool) -> io::Result<()> {
let mut next = self.value.clone();
match key {
SettingKey::ImportsDesktopEnvironments => next.imports_desktop_environments = enabled,
SettingKey::NotificationsMuted => next.notifications_muted = enabled,
SettingKey::ShowsPreviews => next.shows_previews = enabled,
SettingKey::AutomaticallyChecksForUpdates => {
Expand Down Expand Up @@ -150,12 +154,34 @@ mod tests {
let mut store = SettingsStore::load(path.clone()).unwrap();
assert!(store.value().notifications_muted);
assert!(store.value().shows_previews);
assert!(!store.value().imports_desktop_environments);
store.set(SettingKey::ShowsPreviews, false).unwrap();
let read = SettingsStore::load(path).unwrap();
assert!(!read.value().shows_previews);
assert!(read.value().notifications_muted);
}
#[test]
fn desktop_environment_import_is_opt_in_and_survives_restart() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let mut store = SettingsStore::load(path.clone()).unwrap();
assert!(!store.value().imports_desktop_environments);
store
.set(SettingKey::ImportsDesktopEnvironments, true)
.unwrap();
let mut restored = SettingsStore::load(path.clone()).unwrap();
assert!(restored.value().imports_desktop_environments);
restored
.set(SettingKey::ImportsDesktopEnvironments, false)
.unwrap();
assert!(
!SettingsStore::load(path)
.unwrap()
.value()
.imports_desktop_environments
);
}
#[test]
fn selection_defaults_and_survives_restart_with_other_preferences() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
Expand Down
76 changes: 74 additions & 2 deletions desktop/crates/bar-limits/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,80 @@ fn is_pairing_code(token: &str) -> bool {
.all(|c| PAIRING_ALPHABET.contains(c.to_ascii_uppercase()))
}

fn local_pairing_input(port: u16, input: &str) -> Result<String, ConnectionError> {
Credential::new(port, input)?.validate()?;
let input = input.trim();
if !input.contains("://")
&& !input.starts_with("http:")
&& !input.starts_with("https:")
&& !input.starts_with("t3code:")
{
return Ok(input.to_owned());
}
let mut url = url::Url::parse(input).map_err(|_| ConnectionError::InvalidPairingLink)?;
if url.scheme() == "t3code" {
if url.host_str() != Some("pair")
|| !url.username().is_empty()
|| url.password().is_some()
|| url.port().is_some()
|| !matches!(url.path(), "" | "/")
|| url.fragment().is_some()
{
return Err(ConnectionError::InvalidPairingLink);
}
let fields: Vec<_> = url.query_pairs().collect();
if fields.len() != 1 || fields[0].0 != "pairingUrl" {
return Err(ConnectionError::InvalidPairingLink);
}
url = url::Url::parse(&fields[0].1).map_err(|_| ConnectionError::InvalidPairingLink)?;
}
if url.scheme() == "https" && url.host_str() == Some("app.t3.codes") && url.path() == "/pair" {
if !url.username().is_empty() || url.password().is_some() || url.port().is_some() {
return Err(ConnectionError::InvalidPairingLink);
}
let fields: Vec<_> = url.query_pairs().collect();
if fields.len() != 1 || fields[0].0 != "host" {
return Err(ConnectionError::InvalidPairingLink);
}
let mut destination =
url::Url::parse(&fields[0].1).map_err(|_| ConnectionError::InvalidPairingLink)?;
if !matches!(destination.path(), "" | "/")
|| destination.query().is_some()
|| destination.fragment().is_some()
{
return Err(ConnectionError::InvalidPairingLink);
}
destination.set_path("/pair");
destination.set_fragment(url.fragment());
url = destination;
}
if url.scheme() != "http"
|| !matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))
|| url.port_or_known_default() != Some(port)
{
return Err(ConnectionError::PairingDestination);
}
if !url.username().is_empty()
|| url.password().is_some()
|| url.path() != "/pair"
|| url.query().is_some()
{
return Err(ConnectionError::InvalidPairingLink);
}
let fields: Vec<_> =
url::form_urlencoded::parse(url.fragment().unwrap_or_default().as_bytes()).collect();
if fields.len() != 1 || fields[0].0 != "token" || !is_pairing_code(&fields[0].1) {
return Err(ConnectionError::InvalidPairingLink);
}
Ok(fields[0].1.to_ascii_uppercase())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectionError {
Destination,
InvalidToken,
InvalidPairingLink,
PairingDestination,
Authorization,
PairingRejected,
Expired,
Expand All @@ -53,6 +123,8 @@ impl fmt::Display for ConnectionError {
f.write_str(match self {
Self::Destination => "Enter a local T3 Code port from 1 to 65535.",
Self::InvalidToken => "Enter a T3 Code access token of up to 16 KiB.",
Self::InvalidPairingLink => "This pairing link is incomplete or invalid. Copy a fresh link from T3 Code, or use Copy code only.",
Self::PairingDestination => "This link does not match the running local T3 Code server. Create a link for this computer, or use Add environment for another machine. No pairing code was sent.",
Self::Authorization => "The access token was rejected by T3 Code.",
Self::PairingRejected => "T3 Code rejected this pairing key. It may have expired or already been used. Create a new pairing key and try again.",
Self::Expired => {
Expand Down Expand Up @@ -478,10 +550,10 @@ impl LimitsConnection {
Ok(())
}
pub async fn connect(&self, port: u16, token: &str) -> Result<(), ConnectionError> {
Credential::new(port, token)?.validate()?;
let token = local_pairing_input(port, token)?;
let access_token = timeout(
Duration::from_secs(15),
self.transport.exchange_pairing(port, token),
self.transport.exchange_pairing(port, &token),
)
.await
.map_err(|_| ConnectionError::Transport)??;
Expand Down
85 changes: 77 additions & 8 deletions desktop/crates/bar-limits/src/live_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,60 @@ use std::{
sync::atomic::{AtomicUsize, Ordering},
};

#[test]
fn local_pairing_links_accept_only_the_configured_loopback_destination() {
let port = 3773;
for address in ["127.0.0.1", "localhost", "[::1]"] {
let link = format!(" http://{address}:{port}/pair#token=abcd2345efgh ");
assert_eq!(local_pairing_input(port, &link).unwrap(), "ABCD2345EFGH");
}
let direct = "http://127.0.0.1:3773/pair#token=ABCD2345EFGH";
let desktop = format!(
"t3code://pair?pairingUrl={}",
url::form_urlencoded::byte_serialize(direct.as_bytes()).collect::<String>()
);
let hosted = "https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773#token=ABCD2345EFGH";
for link in [&desktop, hosted] {
assert_eq!(local_pairing_input(port, link).unwrap(), "ABCD2345EFGH");
}
for input in ["ABCD2345EFGH", "existing-access-token"] {
assert_eq!(local_pairing_input(port, input).unwrap(), input);
}
for link in [
"http://127.0.0.1:3774/pair#token=ABCD2345EFGH",
"https://127.0.0.1:3773/pair#token=ABCD2345EFGH",
"https://remote.example/pair#token=ABCD2345EFGH",
"http://localhost.example:3773/pair#token=ABCD2345EFGH",
"https://app.t3.codes/pair?host=https%3A%2F%2Fremote.example#token=ABCD2345EFGH",
] {
assert_eq!(
local_pairing_input(port, link),
Err(ConnectionError::PairingDestination)
);
}
}

#[test]
fn malformed_pairing_links_are_rejected_without_echoing_the_code() {
for link in [
"http://127.0.0.1:3773/pair",
"http://127.0.0.1:3773/pair?token=ABCD2345EFGH",
"http://127.0.0.1:3773/pair#token=ABCD2345EFGH&token=ABCD2345EFGH",
"http://127.0.0.1:3773/pair#token=invalid",
"http://127.0.0.1:3773/oauth/token#token=ABCD2345EFGH",
"http://user:password@127.0.0.1:3773/pair#token=ABCD2345EFGH",
"t3code://pair?pairingUrl=invalid",
"t3code://pair?pairingUrl=one&pairingUrl=two",
"https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773&host=other#token=ABCD2345EFGH",
"https://app.t3.codes/pair?host=http%3A%2F%2F127.0.0.1%3A3773%2Fother#token=ABCD2345EFGH",
"http://",
] {
let error = local_pairing_input(3773, link).unwrap_err();
assert_eq!(error, ConnectionError::InvalidPairingLink);
assert!(!error.to_string().contains("ABCD2345EFGH"));
}
}

#[test]
fn pairing_code_shape_matches_t3_code_and_bearer_tokens_pass_through() {
assert!(is_pairing_code("ABCD2345EFGH"));
Expand Down Expand Up @@ -200,15 +254,20 @@ fn write_frame(s: &mut std::net::TcpStream, value: &str) {
}
#[test]
fn loopback_bootstrap_subscribe_ack_and_snapshot() {
loopback_connection(false);
loopback_connection(false, false);
}

#[test]
fn loopback_pairing_saves_access_token_and_streams_limits() {
loopback_connection(true);
loopback_connection(true, false);
}

#[test]
fn loopback_pairing_link_saves_only_the_exchanged_access_token() {
loopback_connection(true, true);
}

fn loopback_connection(pairing: bool) {
fn loopback_connection(pairing: bool, link: bool) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let server = std::thread::spawn(move || {
Expand Down Expand Up @@ -273,9 +332,12 @@ fn loopback_connection(pairing: bool) {
runtime().block_on(async {
let store = Arc::new(Memory::default());
let c = LimitsConnection::with_default_transport(store.clone());
let pairing_link = format!("http://127.0.0.1:{port}/pair#token=ABCD2345EFGH");
c.connect(
port,
if pairing {
if link {
&pairing_link
} else if pairing {
"ABCD2345EFGH"
} else {
"test-token"
Expand Down Expand Up @@ -348,10 +410,7 @@ fn saved_pairing_is_restored_offline_without_a_transport_request() {
fn restore_storage_errors_are_explicit_and_do_not_fake_pairing() {
let c = LimitsConnection::with_default_transport(Arc::new(BrokenStore));
assert_eq!(c.restore_saved(), Err(ConnectionError::Storage));
assert_eq!(
c.snapshot().status,
LiveStatus::StorageUnavailable
);
assert_eq!(c.snapshot().status, LiveStatus::StorageUnavailable);
assert!(!c.snapshot().has_credential);
}
struct Mock {
Expand Down Expand Up @@ -424,6 +483,16 @@ fn invalid_replacement_preserves_active_connection_and_saved_key() {
};

assert_eq!(c.connect(43, "").await, Err(ConnectionError::InvalidToken));
assert_eq!(
c.connect(43, "http://127.0.0.1:44/pair#token=ABCD2345EFGH")
.await,
Err(ConnectionError::PairingDestination)
);
assert_eq!(
c.connect(43, "http://127.0.0.1:43/pair#token=invalid")
.await,
Err(ConnectionError::InvalidPairingLink)
);
assert_eq!(
c.connect(43, "ABCD2345EFGH").await,
Err(ConnectionError::PairingRejected)
Expand Down
Loading
Loading