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
50 changes: 49 additions & 1 deletion src/apps/desktop/src/api/remote_connect_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2121,7 +2121,7 @@ pub async fn remote_connect_start(
};
let result = async {
let current_url = read_account_context().await.ok().map(|(_, url)| url);
if current_url.as_deref() != Some(relay_url.as_str()) {
if relay_requires_account_login(current_url.as_deref(), &relay_url) {
login_account_on_relay(relay_url).await?;
}
account_connect_devices().await?;
Expand Down Expand Up @@ -2383,6 +2383,18 @@ pub async fn account_login(_request: AccountAuthRequest) -> Result<AccountLoginR
login_account_on_relay(openbitfun_product_domains::account::DEFAULT_RELAY_URL.to_string()).await
}

/// Whether showing an invitation must sign in again on `target`.
///
/// A restored session keeps the endpoint base while the prepared official
/// endpoint also announces `?v=`. The version is not part of the endpoint
/// identity, and an unneeded login rotates the token and drops device routing.
fn relay_requires_account_login(current: Option<&str>, target: &str) -> bool {
current.map(openbitfun_product_domains::account::relay_endpoint_base)
!= Some(openbitfun_product_domains::account::relay_endpoint_base(
target,
))
}

async fn login_account_on_relay(relay_url: String) -> Result<AccountLoginResult, String> {
login_account_on_relay_for_generation(relay_url, None).await
}
Expand Down Expand Up @@ -3984,3 +3996,39 @@ pub async fn account_unsubscribe_session(request: UnsubscribeSessionRequest) ->
}
Ok(())
}

#[cfg(test)]
mod relay_account_login_tests {
use super::relay_requires_account_login;

#[test]
fn version_parameter_does_not_change_the_endpoint_identity() {
let official = "https://remote.openbitfun.com/relay?v=1.0.9";
for current in [
"https://remote.openbitfun.com/relay",
"https://remote.openbitfun.com/relay/",
"https://remote.openbitfun.com/relay?v=1.0.8",
official,
] {
assert!(
!relay_requires_account_login(Some(current), official),
"{current}"
);
}
}

#[test]
fn missing_or_different_endpoint_requires_login() {
let official = "https://remote.openbitfun.com/relay?v=1.0.9";
assert!(relay_requires_account_login(None, official));
// The legacy alias migrates to the current endpoint through one login.
assert!(relay_requires_account_login(
Some("https://remote.openbitfun.com/v/1.0.2"),
official
));
assert!(relay_requires_account_login(
Some("http://192.168.1.2:9700"),
official
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,31 @@ async fn official_and_lan_invitations_use_the_same_authenticated_device_protocol
}
}

#[tokio::test]
async fn restored_base_endpoint_keeps_the_announced_version_in_the_invitation() {
let host = Arc::new(RecordingEmbeddedRelayHost::default());
let service = RemoteConnectService::new(RemoteConnectConfig::default(), host).unwrap();
let prepared = service
.prepare_relay(&ConnectionMethod::OpenBitFunServer)
.await
.unwrap();
assert!(prepared.contains("?v="));
*service.authenticated_device_id.write().await = Some("restored-host".into());
*service.device_relay_url.write().await =
Some(openbitfun_product_domains::account::relay_endpoint_base(&prepared).to_string());
let result = service
.start(ConnectionMethod::OpenBitFunServer)
.await
.unwrap();
assert_eq!(
result.qr_url,
Some(openbitfun_product_domains::account::relay_page_url(
&prepared,
"#/pair?did=restored-host"
))
);
}

#[tokio::test]
async fn switching_endpoint_invalidates_the_previous_invitation() {
let host = Arc::new(RecordingEmbeddedRelayHost::default());
Expand Down
20 changes: 16 additions & 4 deletions src/crates/assembly/core/src/service/remote_connect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,12 +361,24 @@ impl RemoteConnectService {
.await
.clone()
.ok_or_else(|| anyhow::anyhow!("No authenticated relay connection"))?;
if self.prepared_relay_url.read().await.as_deref() != Some(relay_url.as_str())
|| self.active_method.read().await.as_ref() != Some(&method)
{
// A restored device connection uses the endpoint base, while the
// prepared endpoint also announces `?v=`; only the base identifies it.
let prepared_relay_url = self
.prepared_relay_url
.read()
.await
.clone()
.filter(|prepared| {
openbitfun_product_domains::account::relay_endpoint_base(prepared)
== openbitfun_product_domains::account::relay_endpoint_base(&relay_url)
});
let Some(prepared_relay_url) = prepared_relay_url else {
anyhow::bail!("Relay endpoint changed; start the connection again");
};
if self.active_method.read().await.as_ref() != Some(&method) {
anyhow::bail!("Relay endpoint changed; start the connection again");
}
let qr_url = QrGenerator::build_device_url(&relay_url, &device_id)?;
let qr_url = QrGenerator::build_device_url(&prepared_relay_url, &device_id)?;
Ok(ConnectionResult {
method,
qr_data: Some(QrGenerator::generate_png_base64_from_url(&qr_url)?),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,25 @@ describe('Remote Connect shared status through the real dialog and sidebar', ()
expect(attachedMobile()).not.toBeNull();
});

it('shows the invitation when the start it is waiting on publishes an account login', async () => {
const pending = deferred<ConnectionResult>();
boundary.startConnection.mockReturnValueOnce(pending.promise);
await render();
await generateInvitation();
await act(async () => {
boundary.backend = status({ relay_connected: true, relay_url: relayA, active_method: 'openbitfun_server' });
for (const listener of boundary.listeners.get('account://login-state') ?? []) {
listener({ logged_in: true, relay_url: relayA });
}
await vi.advanceTimersByTimeAsync(0);
});
await act(async () => { pending.resolve(invitation()); });
await tick();
expect(dialog().textContent).toContain(invitation().qr_url);
expect(dialog().textContent).not.toContain('remoteConnect.connecting');
expect(boundary.stopConnection).not.toHaveBeenCalled();
});

it('keeps the LAN invitation when the official credential expires', async () => {
const lanUrl = 'http://192.168.1.2:9700';
boundary.backend = status({ connections: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -474,12 +474,16 @@ export const RemoteConnectDialog: React.FC<RemoteConnectDialogProps> = ({
const unlisten = api.listen<{ logged_in: boolean; relay_url?: string }>(
'account://login-state',
() => {
// Invitations belong to the active account route.
// Invitations belong to the active account route, so only one issued
// before this event can be stale. A start in flight may publish this
// very login, and its result is issued for the new account context.
const invitationAtEvent = connectionResultRef.current;
remoteConnectStatusSource.invalidate();
void remoteConnectStatusSource.refresh().then((nextStatus) => {
if (!nextStatus) return;
if (!isOpenRef.current) return;
applyStatus(nextStatus);
if (!invitationAtEvent || connectionResultRef.current !== invitationAtEvent) return;
const invitationRoute = selectRemoteNetworkConnection(nextStatus, connectionResultRef.current);
if (!invitationRoute.connected || invitationRoute.relayUrl !== invitationRelayUrl(connectionResultRef.current)) {
pendingOwnerRef.current = null;
Expand Down Expand Up @@ -746,10 +750,9 @@ export const RemoteConnectDialog: React.FC<RemoteConnectDialogProps> = ({
setError(e?.message || String(e));
}
} finally {
if (isCurrent()) {
if (!ownsConnection) pendingOwnerRef.current = null;
setLoading(false);
}
if (isCurrent() && !ownsConnection) pendingOwnerRef.current = null;
// The spinner belongs to this operation even if its owner was released.
if (operationGenerationRef.current === operationGeneration) setLoading(false);
}
}, [accountLoggedIn, activeView, networkTab, botTab, tgToken, feishuAppId, feishuAppSecret, weixinIlinkToken, weixinBaseUrl, weixinBotAccountId, selectedLanIp, startPolling, hasAgreedDisclaimer]);

Expand Down
2 changes: 1 addition & 1 deletion src/web-ui/src/locales/en-US/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@
"stateHandshaking": "Handshaking…",
"stateVerifying": "Verifying…",
"stateConnected": "Connected",
"cancelInvitation": "Cancel invitation",
"cancelInvitation": "Hide invitation",
"accountConnectedHint": "This phone or browser is connected through your account. Cancelling the invitation or closing this window keeps that connection active.",
"statusUnavailable": "Connection status is unavailable",
"statusChecking": "Checking connection…",
Expand Down
2 changes: 1 addition & 1 deletion src/web-ui/src/locales/zh-CN/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@
"stateHandshaking": "握手中…",
"stateVerifying": "验证中…",
"stateConnected": "已连接",
"cancelInvitation": "取消邀请",
"cancelInvitation": "收起邀请",
"accountConnectedHint": "手机或浏览器已通过账号连接。取消邀请或关闭此窗口不会断开该连接。",
"statusUnavailable": "连接状态暂不可用",
"statusChecking": "正在检查连接…",
Expand Down
2 changes: 1 addition & 1 deletion src/web-ui/src/locales/zh-TW/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@
"stateHandshaking": "握手中…",
"stateVerifying": "驗證中…",
"stateConnected": "已連接",
"cancelInvitation": "取消邀請",
"cancelInvitation": "收起邀請",
"accountConnectedHint": "手機或瀏覽器已透過帳號連線。取消邀請或關閉此視窗不會中斷該連線。",
"statusUnavailable": "連線狀態暫時無法取得",
"statusChecking": "正在檢查連線…",
Expand Down
Loading