Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix: keep pairing to the computer's account and bring back unanswered pairing questions
leepokai524fa5536a17
diff --git a/apps/desktop/src/renderer/lib/refresh.test.ts b/apps/desktop/src/renderer/lib/refresh.test.tsindex a4816c00..571c88ec 100644--- a/apps/desktop/src/renderer/lib/refresh.test.ts+++ b/apps/desktop/src/renderer/lib/refresh.test.ts@@ -105,3 +105,17 @@ test('an unresponsive host cannot leave manual refresh spinning forever', asyncawait rejectedstore.retire()})++test('a pairing answer the host never got brings the question back', async () => {+ const app = new AppModel(false)+ const store = { isLoopback: true, computer: { id: 'mac' }, pairingRequests: [{ requestId: 'r1' }],+ ready: async () => ({ call: () => Promise.reject(new Error('Offline')) }) } as unknown as BotStore+ app.stores.set('mac', store)+ const [ask] = app.pairingAsks+ const answer = app.decidePairing(ask, true)+ assert.equal(app.pairingAsks.length, 0, 'off the screen at once')+ assert.equal(await answer, false)+ assert.equal(app.lastError, 'Offline')+ assert.equal(app.pairingAsks.length, 1, 'the question comes back')+ app.stores.clear()+})diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.tsindex baebfba2..db91cd2c 100644--- a/apps/desktop/src/renderer/store/app-model.ts+++ b/apps/desktop/src/renderer/store/app-model.ts@@ -3,6 +3,7 @@ import type { HostSnapshot, LocalHost } from '@shared/ipc'import type { AccessRequest, Bot, Computer, PairingRequest } from '@shared/models'import { HostError, LoopbackTransport } from '../client/host-client'import { Observable } from '../lib/observable'+import { undoOnFailure } from '../lib/undo-on-failure'import { account } from './account'import { analytics } from './analytics'import { BotStore } from './bot-store'@@ -241,11 +242,15 @@ export class AppModel extends Observable {.filter((ask) => !this.answeredPairings.has(ask.id))}- async decidePairing(ask: PairingAsk, approve: boolean) {+ decidePairing(ask: PairingAsk, approve: boolean) {this.answeredPairings.add(ask.id)this.changed()- const client = await ask.store.ready()- await client.call('decidePairing', { requestId: ask.request.requestId, approve }, 30_000)+ const answer = ask.store.ready().then((client) => client.call('decidePairing', { requestId: ask.request.requestId, approve }, 30_000))+ // The host may not have the answer: the question comes back.+ return undoOnFailure(answer, () => {+ this.answeredPairings.delete(ask.id)+ this.changed()+ }, (message) => this.setError(message))}get needsAttention() {diff --git a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsxindex ea045ba5..81fe3b91 100644--- a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx+++ b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx@@ -4,7 +4,6 @@ import { pairingAskText } from '../lib/account-copy'import { useModel, useModels } from '../lib/observable'import { useTr } from '../lib/use-language'import { useApp } from '../store/context'-import { errorText } from './settings/parts'/*** A signed-in phone scanned a computer this app manages that is in no account: let it in, and the computer joins@@ -23,7 +22,7 @@ export function PairingRequestPrompt() {const decide = (approve: boolean) => {if (!ask) return- app.decidePairing(ask, approve).catch((error: unknown) => app.setError(errorText(error)))+ void app.decidePairing(ask, approve)}const text = ask ? pairingAskText(tr, ask.request) : nullreturn (diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftindex 3e15fa96..b35b0f34 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift@@ -2,6 +2,8 @@ import CryptoKitimport Foundationimport os+private let log = Logger(subsystem: "com.pokai.Codync", category: "Account")+/// Values shared between the app, its widgets and its notification extension through the App Group,/// one namespace per account context so a signed-out account's data never shows in another.public enum SharedStore {@@ -149,21 +151,32 @@ public extension SharedStore.Context {do {try DeviceIdentity.move(from: local, to: self)} catch {- Logger(subsystem: "com.pokai.Codync", category: "Account").error("Cannot move the device key: \(error.localizedDescription)")+ log.error("Cannot move the device key: \(error.localizedDescription)")return merge(moving)}for name in Self.names { defaults.set(local.defaults.object(forKey: local.key(name)), forKey: key(name)) }- // Unsent and failed messages live only in the mirror caches: they come along rather than go with `erase()`.- for file in local.mirrorCaches() {- let name = file.lastPathComponent- guard let marker = name.range(of: "-\(local.id)-") else { continue }- try? FileManager.default.moveItem(at: file, to: file.deletingLastPathComponent().appending(path: name.replacingCharacters(in: marker, with: "-\(id)-")))- }+ moveMirrorCaches(from: local)return Adoption(computers: moving.count, keys: .moved)}return merge(moving)}+ /// Unsent and failed messages live only in the mirror caches: they come along rather than go with `erase()`.+ /// A rename in one folder: only a cache left at the account's name (it has no computers yet) is in the way.+ private func moveMirrorCaches(from local: Self) {+ for file in local.mirrorCaches() {+ let name = file.lastPathComponent+ guard let marker = name.range(of: "-\(local.id)-") else { continue }+ let moved = file.deletingLastPathComponent().appending(path: name.replacingCharacters(in: marker, with: "-\(id)-"))+ do {+ if FileManager.default.fileExists(atPath: moved.path()) { try FileManager.default.removeItem(at: moved) }+ try FileManager.default.moveItem(at: file, to: moved)+ } catch {+ log.error("Cannot move unsent messages: \(error.localizedDescription)")+ }+ }+ }+private func merge(_ moving: [Computer]) -> Adoption {let known = Set(computers.map(\.id))computers += moving.filter { !known.contains($0.id) }diff --git a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swiftindex 0a4dc6d3..20615726 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift@@ -22,12 +22,13 @@ import Testinglocal.composerDrafts = [v.computer.id: ["b1": "draft"]]let cache = URL.cachesDirectory.appending(path: "codync-mirror-tests-\(local.id)-\(v.computer.id).json")try Data("unsent".utf8).write(to: cache)+ let movedCache = URL.cachesDirectory.appending(path: "codync-mirror-tests-\(account.id)-\(v.computer.id).json")+ try Data("stale".utf8).write(to: movedCache)#expect(account.adopt(from: local) == .init(computers: 1, keys: .moved))#expect(account.computers == [v.computer])#expect(account.composerDrafts[v.computer.id]?["b1"] == "draft")- let movedCache = URL.cachesDirectory.appending(path: "codync-mirror-tests-\(account.id)-\(v.computer.id).json")- #expect(try Data(contentsOf: movedCache) == Data("unsent".utf8), "unsent messages come along")+ #expect(try Data(contentsOf: movedCache) == Data("unsent".utf8), "unsent messages come along, over a stale cache")#expect(!FileManager.default.fileExists(atPath: cache.path()))let moved = try DeviceIdentity.load(context: account)#expect(moved.publicKey == key.publicKey, "hosts see the same device")diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.mdindex 5ac82e79..250b0ad9 100644--- a/docs/plans/require-sign-in.md+++ b/docs/plans/require-sign-in.md@@ -169,7 +169,7 @@ After either case the signed-out context is erased, and when computers moved an- Hosts compile in the public half for their environment (`host/src/environment.rs` `device_cert_key`; `CODYNC_DEVICE_CERT_KEY` overrides it for a self-hosted cloud). Checking a certificate is a signature check with no network, so it works from the first run, with the cloud off or on a private relay. There is no `/v1/keys` route.- The private keys live in the git-ignored `.env.development` / `.env.production` (`CODYNC_DEVICE_CERT_KEY`).-**`pair` takes the certificate** (`host/src/remote/channel/pairing.rs`). The code is checked first without spending it, so nothing about the computer's account reaches a phone without a live code; then the certificate and the account. The code is spent only once the phone may come in (after the computer's answer), so a phone that can't come in doesn't use it up, and the relay keeps the offer, and the phone's socket, while the computer asks. The account the computer belongs to is kept on the computer (`remote/owner.rs`, kv `account_owner`) and compared offline; with the cloud off or a private relay the computer is in no account, as its status says.+**`pair` takes the certificate** (`host/src/remote/channel/pairing.rs`). The code is checked first without spending it, so nothing about the computer's account reaches a phone without a live code; then the certificate and the account. The code is spent only once the phone may come in (after the computer's answer), so a phone that can't come in doesn't use it up, and the relay keeps the offer, and the phone's socket, while the computer asks. The account the computer belongs to is kept on the computer (`remote/owner.rs`, kv `account_owner`) and compared offline; with the cloud off or a private relay the computer is in no account, as its status says. The phone's account is checked against it, the code spent and the phone saved while the account can't change (`owner::while_unchanged`, which `owner::remember` waits for), so a change of account never misses a phone saved for the old one.| The computer | Result || --- | --- |@@ -177,7 +177,7 @@ After either case the signed-out context is erased, and when computers moved an| Certificate not valid for this device key | 403 "Couldn't confirm your Codync account. Sign in again, then scan a new code." || In the phone's account | The phone is let in at once || In another account | 403 "This computer is in k•••@example.com's account. Move it to your account in Codync on that computer, or sign in with that account." |-| In no account | The computer asks for up to 90 seconds, inside the relay's 2-minute pairing socket (`remote/pairing_requests.rs`: the loopback-only `pairingRequests` event and method, `decidePairing`): the desktop app and the terminal UI show a dialog, `codync-host pair` asks `y/N` in a terminal, and `codync-host access approve <code>` answers anywhere. A phone that leaves takes the question off the screens. Both screens show the same 6-digit code, `sha256("codync/pair-check/v1" ‖ deviceKey ‖ hostSignKey)` (`crypto::pair_check_code`, vector `pairCheck`). Declined or unanswered: 403 "The computer didn't let this phone in." Let in: the computer signs the claim the phone made (`POST /v1/claims`) and the phone completes it (`POST /v1/claims/{id}/complete`), so joining needs no new cloud route. With the cloud off or a private relay there is no claim; the phone is let in and the computer stays out of any account |+| In no account | The computer asks for up to 90 seconds, inside the relay's 2-minute pairing socket (`remote/pairing_requests.rs`: the loopback-only `pairingRequests` event and method, `decidePairing`): the desktop app and the terminal UI show a dialog, `codync-host pair` asks `y/N` in a terminal, and `codync-host access approve <code>` answers anywhere. A phone that leaves takes the question off the screens. Both screens show the same 6-digit code, `sha256("codync/pair-check/v1" ‖ deviceKey ‖ hostSignKey)` (`crypto::pair_check_code`, vector `pairCheck`). Declined or unanswered: 403 "The computer didn't let this phone in." Let in, the account is checked again: a computer that joined another account while it asked gives the "In another account" 403 and leaves the code unspent. Otherwise the computer signs the claim the phone made (`POST /v1/claims`) and the phone completes it (`POST /v1/claims/{id}/complete`), so joining needs no new cloud route. With the cloud off or a private relay there is no claim; the phone is let in and the computer stays out of any account |**Each device records its account** (`devices.account`, schema 7). When the host changes the account it belongs to (joining one, moving, or leaving with **Remove from account**), devices of any other account are dropped. Joining a first account keeps the phones paired before devices recorded their account, so updating doesn't cost anyone a phone. The desktop's move and remove dialogs say: "Every device of {email}'s account loses access." Networks stay as they are: a computer handed to someone else is taken out of a network by the network's creator or an admin, like its SSH key is taken off the manager.diff --git a/host/src/remote/channel/pairing.rs b/host/src/remote/channel/pairing.rsindex cd921623..0c507203 100644--- a/host/src/remote/channel/pairing.rs+++ b/host/src/remote/channel/pairing.rs@@ -10,6 +10,16 @@ use crate::remote::{owner, pairing_requests};const PROTOCOL: CloseWith = (close::PROTOCOL, "protocolError");const EXPIRED: &str = "This pairing code expired. Show a new one on the computer.";+/// Why `let_in` left the phone out.+enum Kept {+ /// The computer is in no account and hasn't asked its user yet.+ Unasked,+ /// Turned away: the message and the close reason.+ Out(String, &'static str),+ /// Let in, but it couldn't be saved.+ Unsaved,+}+impl Channel {pub(super) async fn pair(&mut self,@@ -28,37 +38,26 @@ impl Channel {return PROTOCOL;};let code = b["code"].as_str().unwrap_or_default();- let (account, owner) = match self.admit(id, &b, code, source).await {- Ok(admitted) => admitted,+ let account = match self.admit(id, &b, code, source).await {+ Ok(account) => account,Err(close) => return close,};- if owner.is_none()- && let Err(close) = self.ask(id, name, platform, account.email.as_deref(), incoming).await- {- return close;- }- // Spent only now: a phone turned away leaves the code to the right one, and while the computer asks the- // relay keeps the offer, and with it this socket.- if !self.hub.pairing.locked().redeem(code) {- return self.refuse(id, EXPIRED, "unauthorized").await;+ let mut let_in = owner::while_unchanged(&self.hub, || self.let_in(&account, false, code, name, platform));+ if matches!(let_in, Err(Kept::Unasked)) {+ if let Err(close) = self.ask(id, name, platform, account.email.as_deref(), incoming).await {+ return close;+ }+ let_in = owner::while_unchanged(&self.hub, || self.let_in(&account, true, code, name, platform));}- let device = Device {- key: self.key.clone(),- name: name.to_owned(),- platform: platform.to_owned(),- source: DeviceSource::Local,- grant_id: None,- scopes: vec![Scope::Control, Scope::Screen],- lease_until: None,- created_at: now_ms(),- last_seen_at: None,- account: Some(account.user_id.clone()),+ let owner = match let_in {+ Ok(owner) => owner,+ Err(Kept::Out(message, reason)) => return self.refuse(id, &message, reason).await,+ // `Unasked` only comes before the computer asked.+ Err(Kept::Unsaved | Kept::Unasked) => {+ self.send(err(id, 500, "couldn't save this device")).await;+ return (close::NORMAL, "");+ }};- if let Err(e) = self.hub.store.put_device(&device) {- tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");- self.send(err(id, 500, "couldn't save this device")).await;- return (close::NORMAL, "");- }tracing::info!(device = self.key, platform, "device paired");crate::analytics::device_paired(&self.hub, crate::analytics::Via::Qr, platform, false);let mut ok = json!({"computerId": self.hub.identity.computer_id(), "name": crate::service::host_name()});@@ -71,40 +70,73 @@ impl Channel {(close::PAIRED, "paired")}- /// Who may come in, before the code is spent: a live code first, so nothing about this computer's account- /// reaches a phone without one; then the phone's account, which must be this computer's when it is in one.- /// Returns the phone's account and this computer's.- async fn admit(- &self,- id: u64,- b: &Value,- code: &str,- source: &str,- ) -> Result<(Certified, Option<Owner>), CloseWith> {+ /// Before anything about this computer's account reaches the phone: a live code, then the phone's account.+ async fn admit(&self, id: u64, b: &Value, code: &str, source: &str) -> Result<Certified, CloseWith> {if !self.hub.pairing.locked().attempt(source) {return Err(self.reject(RejectCode::RateLimited).await);}if !self.hub.pairing.locked().valid(code) {return Err(self.refuse(id, EXPIRED, "unauthorized").await);}- let account = match certificate::check(&b["certificate"], &self.key, now_ms()) {- Ok(account) => account,- Err(Refusal::Missing) => return Err(self.reject(RejectCode::UnsupportedVersion).await),+ match certificate::check(&b["certificate"], &self.key, now_ms()) {+ Ok(account) => Ok(account),+ Err(Refusal::Missing) => Err(self.reject(RejectCode::UnsupportedVersion).await),Err(Refusal::Invalid) => {let message = "Couldn't confirm your Codync account. Sign in again, then scan a new code.";- return Err(self.refuse(id, message, "unauthorized").await);+ Err(self.refuse(id, message, "unauthorized").await)}+ }+ }++ /// Run under `owner::while_unchanged`, so the account the phone is checked against is the one it is saved+ /// under: a computer in an account lets in phones of that account only, one in no account only once it asked+ /// (`asked`). Returns this computer's account. The code is spent only now: a phone turned away leaves it to the+ /// right one, and while the computer asks the relay keeps the offer, and with it this socket.+ fn let_in(+ &self,+ account: &Certified,+ asked: bool,+ code: &str,+ name: &str,+ platform: &str,+ ) -> Result<Option<Owner>, Kept> {+ let owner = self.owner_for(account).map_err(|message| Kept::Out(message, "otherAccount"))?;+ if owner.is_none() && !asked {+ return Err(Kept::Unasked);+ }+ if !self.hub.pairing.locked().redeem(code) {+ return Err(Kept::Out(EXPIRED.into(), "unauthorized"));+ }+ let device = Device {+ key: self.key.clone(),+ name: name.to_owned(),+ platform: platform.to_owned(),+ source: DeviceSource::Local,+ grant_id: None,+ scopes: vec![Scope::Control, Scope::Screen],+ lease_until: None,+ created_at: now_ms(),+ last_seen_at: None,+ account: Some(account.user_id.clone()),};+ if let Err(e) = self.hub.store.put_device(&device) {+ tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");+ return Err(Kept::Unsaved);+ }+ Ok(owner)+ }++ /// This computer's account, or what to tell a phone of another account.+ fn owner_for(&self, account: &Certified) -> Result<Option<Owner>, String> {let owner = owner::owner(&self.hub.store);if let Some(owner) = owner.as_ref().filter(|o| o.user_id != account.user_id) {let whose =owner.email.as_deref().map_or_else(|| "another".into(), |e| format!("{}'s", certificate::masked(e)));- let message = format!(+ return Err(format!("This computer is in {whose} account. Move it to your account in Codync on that computer, or sign in with that account."- );- return Err(self.refuse(id, &message, "otherAccount").await);+ ));}- Ok((account, owner))+ Ok(owner)}/// A computer in no account asks its user before the phone comes in; a phone that leaves meanwhile takes thediff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rsindex 97b76c87..97e2c4a3 100644--- a/host/src/remote/channel/tests/accounts.rs+++ b/host/src/remote/channel/tests/accounts.rs@@ -9,6 +9,15 @@ async fn pairing_phone(hub: &Arc<Hub>) -> (Phone, String) {(p, code)}+/// Sends `pair` to a computer in no account and waits for it to ask: the question on its screens.+async fn asked(hub: &Hub, p: &mut Phone, body: Value) -> Value {+ p.send(json!({"id": 1, "m": "pair", "b": body})).await;+ while hub.pairing_requests.json().is_empty() {+ tokio::task::yield_now().await;+ }+ hub.pairing_requests.json()[0].clone()+}+#[tokio::test]async fn an_app_without_a_certificate_is_told_to_update_and_the_code_stays() {let hub = temp_hub();@@ -50,10 +59,8 @@ async fn without_a_live_code_a_phone_learns_nothing_about_the_account() {async fn a_phone_that_leaves_while_the_computer_asks_is_not_let_in() {let hub = unowned_hub();let (mut p, code) = pairing_phone(&hub).await;- p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "Pixel", "android", "user_2")})).await;- while hub.pairing_requests.json().is_empty() {- tokio::task::yield_now().await;- }+ let body = pair_body(&p, &code, "Pixel", "android", "user_2");+ asked(&hub, &mut p, body).await;// The computer still has the offer while it asks: the relay keeps the phone's socket.assert!(hub.pairing.locked().open());let dk = p.dk();@@ -72,11 +79,7 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {let (mut p, code) = pairing_phone(&hub).await;let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");body["claim"] = json!({"claimId": "clm_1", "nonce": "n1"});- p.send(json!({"id": 1, "m": "pair", "b": body})).await;- while hub.pairing_requests.json().is_empty() {- tokio::task::yield_now().await;- }- let request = hub.pairing_requests.json()[0].clone();+ let request = asked(&hub, &mut p, body).await;assert_eq!(request["email"], "[email protected]");let device_key = crypto::unb64_n::<32>(&p.dk()).unwrap();let expected = crypto::pair_check_code(&device_key, &hub.identity.sign_pub());@@ -98,3 +101,21 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {}}}++#[tokio::test]+async fn a_phone_let_in_after_the_computer_joined_another_account_stays_out() {+ let hub = unowned_hub();+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();+ let (mut p, code) = pairing_phone(&hub).await;+ let body = pair_body(&p, &code, "Pixel", "android", "user_2");+ let request = asked(&hub, &mut p, body).await;+ // While the computer asks, another phone brings it into user_3's account.+ let owner = crate::remote::cloud::Owner { user_id: "user_3".into(), email: Some("[email protected]".into()) };+ crate::remote::owner::remember(&hub, Some(&owner)).unwrap();+ crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), true).unwrap();+ let reply = p.recv().await.unwrap();+ assert_eq!(reply["err"]["status"], 403);+ assert!(reply["err"]["message"].as_str().unwrap().contains("a•••@example.com's account"));+ assert!(hub.store.device(&p.dk()).is_none(), "user_2's phone stays out of user_3's computer");+ assert!(hub.pairing.locked().valid(&code), "a refused phone leaves the code");+}diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rsindex dff995da..d5b99397 100644--- a/host/src/remote/cloud.rs+++ b/host/src/remote/cloud.rs@@ -4,7 +4,6 @@//! SAS. Which cloud this host uses lives in `cloud_url`, the relay socket in `relay`.use crate::LockExt;-use crate::chat::team::assistant;use crate::hub::Hub;use crate::remote::crypto::{self, b64};use crate::store::{Device, DeviceSource, Scope, Store, now_ms};@@ -116,6 +115,8 @@ pub struct Cloud {requests: Mutex<Vec<Request>>,/// One state pull at a time.pulling: tokio::sync::Mutex<()>,+ /// Held while the account changes and while pairing saves a phone against it (`owner::while_unchanged`).+ pub(super) account: Mutex<()>,/// Bumped when the cloud is turned on or off or pointed elsewhere: the relay restarts.pub config: watch::Sender<u64>,}@@ -126,6 +127,7 @@ impl Default for Cloud {status: Mutex::default(),requests: Mutex::default(),pulling: tokio::sync::Mutex::new(()),+ account: Mutex::default(),config: watch::Sender::new(0),}}@@ -343,13 +345,8 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {s.owner = state.owner;s.last_error = None;});- // Out of an account, cloud assistants go off and the 6-digit check comes back on: the account- // this computer joins next is asked again.- if !in_account && assistant::enabled(&hub.store) {- assistant::set_enabled(hub, false)?;- }- if !in_account && approval(&hub.store) == Approval::Auto {- set_approval(hub, Approval::Code)?;+ if !in_account {+ super::owner::out_of_account(hub)?;}sync_requests(hub, base, state.requests).await;if approval(&hub.store) == Approval::Auto {@@ -646,6 +643,7 @@ pub fn set_approval(hub: &Hub, approval: Approval) -> Result<CloudStatus> {mod tests {#![allow(clippy::unwrap_used, clippy::expect_used)]use super::*;+ use crate::chat::team::assistant;use crate::remote::identity::Identity;fn temp_hub() -> Arc<Hub> {diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rsindex 247a5567..16e68666 100644--- a/host/src/remote/owner.rs+++ b/host/src/remote/owner.rs@@ -2,8 +2,10 @@//! even with the cloud unreachable, and a change of account drops the old account's devices//! (docs/architecture/connections.md: "the host changed its account").-use super::cloud::{Owner, RelayKind};+use super::cloud::{self, Approval, Owner, RelayKind};use super::crypto;+use crate::LockExt;+use crate::chat::team::assistant;use crate::hub::Hub;use crate::store::Store;use anyhow::{Result, bail};@@ -14,7 +16,7 @@ const OWNER: &str = "account_owner";/// The account as last seen from the cloud; `None` when the computer isn't in one (or never heard yet), and/// with the Codync cloud off or a private relay, where it is in no account either (as its status says).pub fn owner(store: &Store) -> Option<Owner> {- super::cloud::current(store).filter(|address| address.kind == RelayKind::Codync)?;+ cloud::current(store).filter(|address| address.kind == RelayKind::Codync)?;store.kv_get(OWNER).and_then(|v| serde_json::from_str::<Option<Owner>>(&v).ok()).flatten()}@@ -24,6 +26,7 @@ pub fn owner(store: &Store) -> Option<Owner> {/// leaves the old account recorded and the next pull tries again.pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {let saved = serde_json::to_string(&now)?;+ let _change = hub.cloud.account.locked();let before = hub.store.kv_get(OWNER);if before.as_deref() == Some(saved.as_str()) {return Ok(());@@ -45,10 +48,29 @@ pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {hub.store.kv_set(OWNER, &saved)}+/// Runs `f` while the account can't change (`remember` waits), so a phone `f` saves against the account it reads+/// can't come in after a change of account dropped the other accounts' devices.+pub fn while_unchanged<T>(hub: &Hub, f: impl FnOnce() -> T) -> T {+ let _change = hub.cloud.account.locked();+ f()+}++/// Out of an account, cloud assistants go off and the 6-digit check comes back on: the account this computer+/// joins next is asked again.+pub fn out_of_account(hub: &Hub) -> Result<()> {+ if assistant::enabled(&hub.store) {+ assistant::set_enabled(hub, false)?;+ }+ if cloud::approval(&hub.store) == Approval::Auto {+ cloud::set_approval(hub, Approval::Code)?;+ }+ Ok(())+}+/// Signs this computer into an account claim (§4.2 A) for a signed-in app to complete: the desktop app's/// Add to account, or a phone pairing with a computer in no account.pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -> Result<Value> {- super::cloud::require_accounts(&hub.store)?;+ cloud::require_accounts(&hub.store)?;for (k, v) in [("claimId", claim_id), ("nonce", nonce), ("userId", user_id)] {// Fields are newline-separated in the signed string: a newline would forge another field.if v.is_empty() || v.contains('\n') {diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex 64f9cbd3..a58e671d 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -167,7 +167,7 @@ impl App {self.network_reply(n, r);return;}- if matches!(after, After::Pairing | After::Cloud | After::PairingRequests) {+ if matches!(after, After::Pairing | After::Cloud | After::PairingRequests | After::PairingDecided) {self.pair_reply(&after, r);return;}@@ -218,7 +218,8 @@ impl App {| After::Connection(_, _)| After::Pairing| After::Cloud- | After::PairingRequests => {}+ | After::PairingRequests+ | After::PairingDecided => {}After::Installed => {self.error = None;self.flash("Host installed; connecting…");diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex e4f017dc..55fcae48 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -43,6 +43,8 @@ pub enum After {/// The pair sheet's `cloudStatus` and `pairingRequests`.Cloud,PairingRequests,+ /// The pair sheet's answer to a waiting phone.+ PairingDecided,Backends,Update,Saved,diff --git a/host/src/tui/app/pair.rs b/host/src/tui/app/pair.rsindex be9e70b4..921244bf 100644--- a/host/src/tui/app/pair.rs+++ b/host/src/tui/app/pair.rs@@ -37,7 +37,13 @@ impl App {}(After::Cloud, Ok(v)) => self.cloud = v,(After::PairingRequests, Ok(v)) => self.pairing_requests = requests(&v),- // Hosts before accounts have neither: the sheet shows the code alone.+ // The host may not have the answer: its list brings the phone back while it still waits.+ (After::PairingDecided, Err(e)) => {+ self.flash(&e);+ self.call("pairingRequests", json!({}), After::PairingRequests);+ }+ // An answer the host took (its event follows), or a host before accounts, which has neither list: the+ // sheet shows the code alone._ => {}}}@@ -54,7 +60,8 @@ impl App {}// Off the sheet at once; the host's event follows.let request = self.pairing_requests.remove(0);- self.call("decidePairing", json!({"requestId": request["requestId"], "approve": approve}), After::Nothing);+ let answer = json!({"requestId": request["requestId"], "approve": approve});+ self.call("decidePairing", answer, After::PairingDecided);}/// Known to be in no account while it could join one (the host's `canJoinAccount`): a signed-in phone that@@ -87,6 +94,8 @@ mod tests {app.decide_pairing(true);assert_eq!(app.pairing_requests.len(), 1, "an answered phone leaves the sheet at once");assert_eq!(app.pairing_requests[0]["requestId"], "b");+ app.pair_reply(&After::PairingDecided, Err("The host took too long to answer.".into()));+ assert!(app.hint.is_some(), "a failed answer says why, and the host's list comes again");app.pair_reply(&After::PairingRequests, Err("unknown method".into()));assert_eq!(app.pairing_requests.len(), 1, "an older host's refusal changes nothing");app.pairing_requests_changed(&json!({"requests": []}));