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
feat: leave an account from the terminal, and finish a join pairing missed
leepokai387bceb473e6
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex dfbadd2a..45d09fa6 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -59,7 +59,7 @@ host_tests() {host/src/chat/memory/*|host/crates/memory/*) add="memory_e2e memory_files_e2e compaction_e2e" ;;host/src/voice.rs|host/src/chat/calls*) add="calls_e2e" ;;host/src/tui/*|host/src/screen/*|host/src/update/*|host/src/usage/*|host/src/remote/*|host/src/analytics*|\- host/src/service/*|host/src/cloud_cli.rs|host/src/compat.rs|host/src/secret_prompt.rs|\+ host/src/service/*|host/src/cloud_cli.rs|host/src/compat.rs|host/src/prompt.rs|\packaging/updates/*|docs/reference/fixtures/*) add="" ;;host/tests/common/*) echo all; return ;;host/tests/*.py|host/tests/fixtures/*)diff --git a/README.md b/README.mdindex 52f22780..fd56ddac 100644--- a/README.md+++ b/README.md@@ -170,7 +170,7 @@ and computer identity; do not use **Reset all data**, a cleanup utility, or Home| `codync-host serve [--port 19222]` | run in the foreground || `codync-host statusline [-- <your command>]` | Claude Code status line command (wraps yours) || `codync-host reset-token` | rotate the local loopback bearer token |-| `codync-host cloud [--assistants on\|off]` | cloud enablement, URL and status; whether ChatGPT, Claude and other connected assistants may message this computer's bots |+| `codync-host cloud [--assistants on\|off] [--leave]` | cloud enablement, URL and status; whether ChatGPT, Claude and other connected assistants may message this computer's bots; `--leave` takes this computer out of its account || `codync-host network` | codync-network, your computers' network: create, invite, join, status, promote, remove, recover || `codync-host devices` | list/revoke authorized remote devices || `codync-host access` | review device access requests |diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex 60e13d33..961d0b16 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -12,7 +12,9 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- 介面新增巴西葡萄牙文:可在設定選擇「Português (Brasil)」,或跟隨系統的葡萄牙文語言。- 新增俄文介面:在設定選擇「Русский」,或跟隨系統的俄文語言。+- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如網路中斷),下次連上時會自動補上。### en-US- Choose Português (Brasil) in Settings, or follow your Portuguese system language.- Choose Русский in Settings, or follow your Russian system language.+- A computer you pair with a QR code that couldn't join your account at the time (a dropped connection, say) joins it the next time it connects.diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.ktindex 5b425d27..c5964d95 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt@@ -28,6 +28,8 @@ class AccountStore(application: Application) : AndroidViewModel(application) {internal var cloud: CloudClient? = null/** The account proof pairing sends, kept for this account context while it lasts. */internal var deviceCertificate: DeviceCertificate? = null+ /** Computers joining this account ([joinAccount]). */+ internal val joining: MutableSet<String> = java.util.concurrent.ConcurrentHashMap.newKeySet()private var sessionJob: Job? = nullinternal var linkJob: Job? = nullinternal var pairingJob: Job? = null@@ -152,7 +154,9 @@ class AccountStore(application: Application) : AndroidViewModel(application) {for (other in stores.value) if (other !== opened) other.openBot(null)mutableState.update { it.copy(removedChat = false) }noteActive(opened.id)- }, usageRead = ::publishUsage)+ }, usageRead = ::publishUsage, joinAccount = { sign ->+ joinAccount(computer.id) { client -> client.createClaim().let { claim -> claim to sign(claim) } }+ })store.open()mutableStores.update { list -> list.filter { it.id != computer.id } + store }sortStores()diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.ktindex deac092b..04681a53 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt@@ -8,6 +8,7 @@ import com.codync.android.core.*import kotlinx.coroutines.*import kotlinx.coroutines.flow.*import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.json.JsonObject// Pairing and the links notifications, widgets and other apps open.@@ -29,25 +30,20 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {mutableState.update { it.copy(pairingCheck = pairing.checkCode(identity)) }val certificate = accountProof()val client = cloud- // Without a claim a computer in no account still lets the phone in; it just doesn't join the account.+ // Without a claim a computer in no account still lets the phone in; it joins the account on a later connection.val claim = client?.let { bestEffort("start a claim") { it.createClaim() } }val paired = HostConnector.pair(pairing, identity, Build.MODEL.take(100), certificate, claim)- // Picked on this phone: pairing again keeps them (iOS `AccountStore.pair`).- val computer = paired.computer.keepingDevicePicks(old)+ // Picked on this phone: pairing again keeps them, and may bring the computer into the account again+ // (iOS `AccountStore.pair`).+ val computer = paired.computer.keepingDevicePicks(old).copy(joinedAccount = false)transitions.withLock { addComputer(computer) }withContext(Dispatchers.IO) { local.completeSetup() }mutableState.update { it.copy(setupComplete = true) }Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))Analytics.completeOnboarding(OnboardingVia.Paired)- // The computer joined this account: the account takes it in (or it stays paired, outside the account).+ // The computer signed this account's claim: the account takes it in.val signed = paired.claim- // In the background, as on iOS: the computer is already paired.- if (client != null && claim != null && signed != null) {- contextScope.launch {- bestEffort("complete the claim") { client.completeClaim(claim.claimId, signed) }- refreshCloud()- }- }+ if (claim != null && signed != null) joinAccount(computer.id) { claim to signed }} catch (error: CancellationException) { throw error }catch (error: Exception) {val reason = PairingFailure.of(error)@@ -80,6 +76,29 @@ private suspend fun AccountStore.accountProof(): DeviceCertificate {private const val NO_PROOF = "Connect to the internet to pair, so Codync can confirm your account."+/**+ * The computer signs this account's claim ([sign]: while letting this phone in, or later through `joinAccount` when its+ * hello asks), and the phone, which holds the account's session, completes it in the background (iOS+ * `AccountStore.joinAccount`). One at a time per computer; a join that fails here is tried again on the next connection,+ * and one that worked is noted on the computer ([Computer.joinedAccount]).+ */+internal fun AccountStore.joinAccount(id: String, sign: suspend (CloudClient) -> Pair<PairingClaim, JsonObject>) {+ val client = cloud ?: return+ if (!joining.add(id)) return+ contextScope.launch {+ try {+ val joined = bestEffort("join the account") {+ val (claim, signed) = sign(client)+ client.completeClaim(claim.claimId, signed)+ }+ if (joined != null) {+ store(id)?.changeComputer { it.copy(joinedAccount = true) }+ refreshCloud()+ }+ } finally { joining.remove(id) }+ }+}+/** [step] of joining the account, which pairing goes on without: a failure is only logged. */private suspend fun <T> bestEffort(what: String, step: suspend () -> T): T? = try { step() }catch (error: CancellationException) { throw error }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.ktindex 598390bb..15587e56 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt@@ -28,6 +28,8 @@ class AppStore internal constructor(internal val opened: (AppStore) -> Unit,/** A usage read finished (the account refreshes the Usage widget). */internal val usageRead: suspend (AppStore) -> Unit = {},+ /** Its hello says this phone paired without the computer joining the account: finish the join with this signer. */+ internal val joinAccount: (sign: suspend (PairingClaim) -> JsonObject) -> Unit = {},) {val id: String = computer.idprivate val job = SupervisorJob(parent)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.ktindex 6ac0232d..878b73aa 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt@@ -111,6 +111,9 @@ fun AppStore.connect() {// Dropped chats page their earlier messages again.mutableState.update { it.copy(historyComplete = if (dropped) emptySet() else it.historyComplete) }noteHello(hello)+ if (asksToJoinAccount(hello, state.value.computer)) joinAccount { claim ->+ active.call("joinAccount", claim.json).jsonObject+ }// The event catch-up is ordered by revision; bot revisions can// follow hundreds of historical entries. Load the current roster// without moving the event cursor before consuming that stream.@@ -226,6 +229,13 @@ private fun AppStore.noteHello(hello: JsonObject) = mutableState.update {it.copy(hello = hello, unreadable = it.unreadable && same, hostUpdate = it.hostUpdate.takeIf { same })}+/**+ * The computer's [hello] asks this phone to finish bringing it into the account, and this phone hasn't brought it in+ * before: one it did was taken out since, and stays out (iOS `BotStore.refreshHello`).+ */+internal fun asksToJoinAccount(hello: JsonObject, computer: Computer): Boolean =+ hello["joinAccount"]?.jsonPrimitive?.booleanOrNull == true && !computer.joinedAccount+private fun AppStore.showConnection(link: LinkState) {mutableState.update { it.copy(actualConnection = link) }val immediate = link is LinkState.Ready || link is LinkState.Failed && link.status in listOf(403, 426)diff --git a/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.ktnew file mode 100644index 00000000..869d6a2d--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt@@ -0,0 +1,24 @@+package com.codync.android++import com.codync.android.core.Computer+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import org.junit.Assert.*+import org.junit.Test++/** A computer whose hello says this phone paired without it joining the account asks to finish (iOS `JoinAccountTests`). */+class JoinAccountTest {+ private val computer = Computer("id", "Mac", "key")++ @Test fun helloAsksToFinishJoiningTheAccount() {+ assertTrue(asksToJoinAccount(buildJsonObject { put("joinAccount", true) }, computer))+ assertFalse(asksToJoinAccount(buildJsonObject { put("joinAccount", false) }, computer))+ assertFalse("an older host doesn't say", asksToJoinAccount(buildJsonObject { }, computer))+ }++ @Test fun aComputerThisPhoneBroughtInIsNotBroughtBackAfterItWasTakenOut() {+ val joined = computer.copy(joinedAccount = true)+ assertFalse(asksToJoinAccount(buildJsonObject { put("joinAccount", true) }, joined))+ assertTrue("a newer copy from the computer's hello keeps it", computer.keepingDevicePicks(joined).joinedAccount)+ }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.ktindex 4fdf4b70..439fd409 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt@@ -44,7 +44,10 @@ data class DeviceCertificate(val payload: String, val sig: String) {}/** What a computer that joins this phone's account by pairing signs, so the account takes it in. */-data class PairingClaim(val claimId: String, val nonce: String)+data class PairingClaim(val claimId: String, val nonce: String) {+ /** As the host reads it (`pair`'s `claim`, `joinAccount`). */+ val json: JsonObject get() = buildJsonObject { put("claimId", claimId); put("nonce", nonce) }+}class CloudError(val status: Int, val code: String, detail: String? = null) : IOException(when (code) {"requestExpired" -> "The request expired. Ask again."diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.ktindex 906a1622..52ded6ba 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt@@ -16,10 +16,19 @@ data class Computer(val color: String? = null,/** Whether this computer sends push alerts to this phone, switched on its card. */val notifications: Boolean = true,+ /**+ * This phone brought the computer into its account (it completed the claim). One taken out of the account before+ * it heard of that join still asks to join (`hello`'s `joinAccount`); this phone leaves it out.+ */+ val joinedAccount: Boolean = false,) {- /** Keeps what this phone picked (color, route, push) over a newer copy from pairing or the account (iOS `keepDevicePicks`). */- fun keepingDevicePicks(previous: Computer?): Computer =- previous?.let { copy(color = it.color, route = it.route, notifications = it.notifications) } ?: this+ /**+ * Keeps what this phone picked (color, route, push) or did ([joinedAccount]) over a newer copy from pairing or the+ * account (iOS `keepDevicePicks`).+ */+ fun keepingDevicePicks(previous: Computer?): Computer = previous?.let {+ copy(color = it.color, route = it.route, notifications = it.notifications, joinedAccount = it.joinedAccount)+ } ?: thisfun validate() {require(RelayCrypto.computerId(signKey.decodeBase64Url(32)) == id) { "This computer's identity changed. Pair it again." }diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.ktindex 86090215..9e498a96 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt@@ -31,7 +31,7 @@ object HostConnector {channel.call("pair", buildJsonObject {put("code", pairing.code); put("name", deviceName); put("platform", "android")put("certificate", certificate.json)- claim?.let { put("claim", buildJsonObject { put("claimId", it.claimId); put("nonce", it.nonce) }) }+ claim?.let { put("claim", it.json) }}, timeoutMillis = 150_000)} catch (error: HostError) {// Hosts from before Android support turn the platform down: say what to do, not the wire error.diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 1493bb02..32055fc0 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -156,6 +156,12 @@ public extension HostClient {let _: Empty = try await call("installHostUpdate")}+ /// The computer signs `claim` for the account this phone paired from (`Hello.joinAccount`), as JSON to+ /// pass on to `CloudClient.completeClaim` as it came.+ func joinAccount(_ claim: CloudClaim) async throws -> Data {+ try await transport.call("joinAccount", body: try Self.encoder.encode(claim), timeout: 20)+ }+func history(botId: String, beforeSeq: Int64, limit: Int = 100) async throws -> [Entry] {struct Body: Encodable { var botId: String; var beforeSeq: Int64; var limit: Int }struct Res: Decodable { var entries: [Entry] }diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swiftindex decfea30..1974a198 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift@@ -23,6 +23,9 @@ public struct Computer: Codable, Hashable, Sendable, Identifiable {public var route: ConnectionRoute?/// Whether the computer sends push alerts to this device, picked per computer; nil = on.public var notifications: Bool?+ /// This device brought the computer into its account (it completed the claim); nil = it never did. One taken out+ /// of the account before it heard of that join still asks to join (`Hello.joinAccount`); this device leaves it out.+ public var joinedAccount: Bool?public init(id: ComputerID, name: String, signKey: String, boxKey: String? = nil, urls: [String] = [],cloud: URL? = nil, device: String? = nil, color: String? = nil) {@@ -36,11 +39,13 @@ public struct Computer: Codable, Hashable, Sendable, Identifiable {self.color = color}- /// Keeps what this device picked (color, route, push) over a newer copy from pairing, the account or `hello`.+ /// Keeps what this device picked (color, route, push) or did (`joinedAccount`) over a newer copy from pairing,+ /// the account or `hello`.public mutating func keepDevicePicks(from previous: Computer) {color = previous.colorroute = previous.routenotifications = previous.notifications+ joinedAccount = previous.joinedAccount}/// `true` when `id` really is the computer ID of `signKey`.diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex 7320f302..c0328fb9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -243,6 +243,8 @@ public struct Hello: Codable, Sendable {public var canUpdate: Bool?/// The latest release the computer found; nil while unknown (development builds, older hosts).public var latestVersion: String?+ /// This phone paired without the computer joining its account: it calls `joinAccount` to finish (older hosts: nil).+ public var joinAccount: Bool?}public struct RecentWorkspace: Codable, Sendable, Identifiable {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftindex 38bafe84..70512438 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift@@ -65,6 +65,8 @@ public final class AccountStore {private var asks: [ComputerID: Task<AccessTicket, any Error>] = [:]/// The account's word for this device's key, kept in memory for this context.private var certificate: DeviceCertificate?+ /// Computers joining this account (`joinAccount`).+ private var joining: Set<ComputerID> = []private var isActive = trueprivate var retired = false@@ -108,7 +110,7 @@ public final class AccountStore {let identity = try DeviceIdentity.load(context: storage)guard let cloud else { throw Self.noCertificate }let certificate = try await pairingCertificate(cloud, deviceName: deviceName, platform: platform)- // Without a claim the computer still pairs; it just doesn't join the account.+ // Without a claim the computer still pairs; it joins the account on a later connection (`Hello.joinAccount`).let claim: CloudClaim?do { claim = try await cloud.createClaim() } catch {log.info("pairing without a claim: \(error.localizedDescription, privacy: .public)")@@ -121,10 +123,12 @@ public final class AccountStore {guard !retired else { throw CancellationError() }var computer = paired.computerif let previous = saved.first(where: { $0.id == computer.id }) { computer.keepDevicePicks(from: previous) }+ // Pairing again may bring it into the account again.+ computer.joinedAccount = nilsave(computer)open(computer)if let claim, let signed = paired.claim {- Task { await joinAccount(claimId: claim.claimId, signed: signed, cloud: cloud) }+ joinAccount(computer.id) { _ in (claim, signed) }}return computer}@@ -155,16 +159,25 @@ public final class AccountStore {}}- /// The computer signed this account's claim while letting this phone in: the phone, which holds the- /// account's session, completes it. Best effort: without it the computer stays paired, outside the account.- private func joinAccount(claimId: String, signed: Data, cloud: CloudClient) async {- do {- try await cloud.completeClaim(claimId: claimId, claim: signed)- } catch {- log.error("paired computer didn't join the account: \(error.localizedDescription, privacy: .public)")- return+ /// The computer signs this account's claim (`sign`: while letting this phone in, or later through+ /// `joinAccount` when its `hello` asks), and the phone, which holds the account's session, completes it.+ /// One at a time per computer; a join that fails here is tried again on the next connection, and one that+ /// worked is noted on the computer (`Computer.joinedAccount`).+ private func joinAccount(_ id: ComputerID, sign: @escaping @MainActor (CloudClient) async throws -> (CloudClaim, Data)) {+ guard let cloud, !retired, joining.insert(id).inserted else { return }+ Task {+ defer { joining.remove(id) }+ do {+ let (claim, signed) = try await sign(cloud)+ try await cloud.completeClaim(claimId: claim.claimId, claim: signed)+ } catch {+ log.error("paired computer didn't join the account: \(error.localizedDescription, privacy: .public)")+ return+ }+ guard !retired else { return }+ updateSaved(id) { $0.joinedAccount = true }+ await refreshCloud()}- await refreshCloud()}public func forget(_ id: ComputerID) {@@ -432,6 +445,12 @@ public final class AccountStore {}store.onComputerChanged = { [weak self] computer in self?.computerChanged(computer) }store.onRosterChanged = { [weak self] in self?.rosterChanged() }+ store.onJoinAccount = { [weak self] client in+ self?.joinAccount(id) { cloud in+ let claim = try await cloud.createClaim()+ return (claim, try await client.joinAccount(claim))+ }+ }stores[id] = storeif isActive { store.setActive(true) }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swiftindex 79f29ce7..2632957a 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift@@ -21,6 +21,7 @@ extension BotStore {onSent = nilonRosterChanged = nilonComputerChanged = nil+ onJoinAccount = nilclient = nilselection = nilscreenRequest = nildiff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swiftindex 262c89cb..d7518823 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift@@ -66,6 +66,8 @@ extension BotStore {hello = happlyIcons(h.icons ?? [:], revision: h.iconsRevision ?? 0)noteHostVersion(HostVersion(version: h.version, minApp: h.minApp))+ // One this phone brought in before was taken out since: it stays out.+ if h.joinAccount == true, computer.joinedAccount != true { onJoinAccount?(client) }}private func noteHostVersion(_ new: HostVersion) {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex f4e17181..798d43e6 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -101,6 +101,8 @@ public final class BotStore {var onRosterChanged: (@MainActor () -> Void)?/// The computer's addresses or keys changed (merged from its `hello`); persist it.var onComputerChanged: (@MainActor (Computer) -> Void)?+ /// Its `hello` says this phone paired without the computer joining the account (`Hello.joinAccount`).+ var onJoinAccount: (@MainActor (HostClient) -> Void)?public let storage: SharedStore.Context/// Opens a channel to the computer as it is now: its route, and the addresses and keys merged since.diff --git a/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swiftnew file mode 100644index 00000000..88bea711--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift@@ -0,0 +1,86 @@+import Foundation+import os+import Testing+@testable import CodyncKit+@testable import CodyncUI++private let askingHello = #"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0,"joinAccount":true}"#++/// A computer whose `hello` says this phone paired without it joining the account asks the account to finish the+/// join; one that doesn't say so (or an older host) doesn't.+@MainActor @Test(arguments: [false, true]) func helloAsksToFinishJoiningTheAccount(asks: Bool) async throws {+ let suite = "JoinAccountTests.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let remote = FakeRemote(.ready(.direct))+ if asks { await remote.setHello(askingHello) }+ let computer = Computer(id: UUID().uuidString, name: "Mac", signKey: "unused", boxKey: "unused")+ let store = BotStore(computer: computer, storage: SharedStore.Context(accountID: "account", suite: suite)) { _ in remote }+ defer { store.retire() }+ var asked = 0+ store.onJoinAccount = { _ in asked += 1 }+ store.setActive(true)+ #expect(await until { store.hello != nil })+ #expect(asked == (asks ? 1 : 0))+}++/// Answers the claim calls (counting them) and every other request as an empty account.+private final class ClaimCloudStub: URLProtocol {+ static let created = OSAllocatedUnfairLock(initialState: 0)+ static let completed = OSAllocatedUnfairLock(initialState: 0)++ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }+ override func stopLoading() {}++ override func startLoading() {+ let path = request.url?.path ?? ""+ let json: String+ switch path {+ case "/v1/claims":+ Self.created.withLock { $0 += 1 }+ json = #"{"claimId":"clm_1","nonce":"n1"}"#+ case "/v1/claims/clm_1/complete":+ Self.completed.withLock { $0 += 1 }+ json = "{}"+ case "/v1/computers": json = #"{"computers":[]}"#+ default: json = "{}"+ }+ let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Data(json.utf8))+ client?.urlProtocolDidFinishLoading(self)+ }+}++/// The account finishes the join its `hello` asks for once (claim, the computer's signature, completion) and notes it+/// on the computer, so the same computer asking again later (taken out before it heard of the join) stays out.+@MainActor @Test func theAccountFinishesTheJoinOnceAndDoesNotBringTheComputerBack() async throws {+ let suite = "JoinAccountTests.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [ClaimCloudStub.self]+ let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),+ session: URLSession(configuration: config)) { "token" }+ let storage = SharedStore.Context(accountID: "account", suite: suite)+ let computer = randomComputer("Mac")+ storage.computers = [computer]+ let remote = FakeRemote(.ready(.direct))+ await remote.setHello(askingHello)+ let accounts = AccountStore(storage: storage, cloud: cloud) { computer in+ BotStore(computer: computer, storage: storage) { _ in remote }+ }+ defer { accounts.retire() }++ #expect(await until { storage.computers.first?.joinedAccount == true })+ #expect(ClaimCloudStub.created.withLock { $0 } == 1)+ #expect(ClaimCloudStub.completed.withLock { $0 } == 1)+ #expect(await remote.calls.filter { $0 == "joinAccount" }.count == 1)++ let store = try #require(accounts.store(for: computer.id))+ #expect(store.computer.joinedAccount == true)+ store.restartStream()+ #expect(await until { await remote.calls.filter { $0 == "hello" }.count >= 2 })+ try await Task.sleep(for: .milliseconds(100))+ #expect(ClaimCloudStub.created.withLock { $0 } == 1)+ #expect(await remote.calls.filter { $0 == "joinAccount" }.count == 1)+}diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex e55f5a79..1e0facef 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -11,7 +11,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 介面新增巴西葡萄牙文:可在設定選擇「Português (Brasil)」,或跟隨系統的葡萄牙文語言。- 新增俄文介面:在設定選擇「Русский」,或跟隨系統的俄文語言。+- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如網路中斷),下次連上時會自動補上。### en-US- Choose Português (Brasil) in Settings, or follow your Portuguese system language.- Choose Русский in Settings, or follow your Russian system language.+- A computer you pair with a QR code that couldn't join your account at the time (a dropped connection, say) joins it the next time it connects.diff --git a/docs/architecture/connections.md b/docs/architecture/connections.mdindex 758c4938..8c5a83de 100644--- a/docs/architecture/connections.md+++ b/docs/architecture/connections.md@@ -54,6 +54,7 @@ The phone finds and pairs every computer itself. A computer the phone hasn't pai- Only a signed-in phone scans, and the host checks the phone's account from a proof the cloud signed, never from what the phone says. The check works offline (a signature), so computers with the cloud off or on a private relay still pair in person.- A QR pairing records the phone's account on the computer. When a host changes the account it belongs to, it drops every device of the old account, QR-paired ones too.- Joining an account on the first scan is how a headless computer "signs in": there is no `codync-host login`. A computer may also join through a manager's **Add to account**, which uses the manager app's account.+- A phone let in while the join itself failed (no claim, or the cloud didn't take it) finishes it on a later connection: the host's `hello` says `joinAccount: true` while it is in no account on the Codync cloud (this connection's state pulled), the phone recorded an account, and no device of another account is on it; the phone then makes a claim, the host's `joinAccount` signs it for that recorded account, and the phone completes it (`owner::joinable_by`). Leaving an account drops every device, and a phone that completed a join notes it on its copy of the computer (`joinedAccount`), so a computer taken out never comes back this way, even one taken out before it heard it had joined (it still asks).## Accounts on a phone@@ -95,7 +96,7 @@ A computer with only the host (SSH-only server, VPS) never signs in. It joins an- A manager's desktop app adds it over SSH: add the SSH computer, install the host in one click, then it joins the manager app's account on its own.- A signed-in phone scans `codync-host pair` (or types its short code) and the terminal confirms.-`codync-host cloud` says which account the computer is in, or how to add it to one; the terminal UI's pair sheet says when a scanning phone would bring it into its account.+`codync-host cloud` says which account the computer is in, or how to add it to one, and `--leave` takes it out (`unclaim`, after a yes in a terminal); the terminal UI's pair sheet says when a scanning phone would bring it into its account.### Using a Linux VPSdiff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.mdindex 8f0975c4..3773c787 100644--- a/docs/guides/accounts-and-ssh.md+++ b/docs/guides/accounts-and-ssh.md@@ -234,8 +234,8 @@ directly (the encrypted channel wasn't ported to the desktop app), so theirconfirmed first), so a computer that was reset or given away can be cleaned up even when itsname changed. Offline may only mean asleep, so the dialog says what removal does: account-approveddevices lose access, and the computer's own app doesn't add it back by itself. The phones have no-such action: adding a computer to the account or removing it is desktop-only, and phones manage-only their own access (pair or forget, revoke, ask). See [desktop app](../architecture/desktop-app.md).+such action: removing a computer from the account takes the desktop app (or `codync-host cloud --leave`+on that computer), and phones manage only their own access (pair or forget, revoke, ask). See [desktop app](../architecture/desktop-app.md).**Computers & devices** (Settings) shows, for this computer and each SSH computer:*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud),diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.mdindex 6bc12f10..2f4a3325 100644--- a/docs/plans/require-sign-in.md+++ b/docs/plans/require-sign-in.md@@ -177,7 +177,7 @@ After either case the signed-out context is erased (on iOS except a mirror cache| 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 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 |+| 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. A later connection on the Codync cloud finishes a join that didn't happen here ([connections](../architecture/connections.md#pairing-a-phone)) |**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/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex a1a9384a..31467f4c 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -155,6 +155,8 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair4. host 先驗憑證與帳號,再花掉 code([require sign-in](../plans/require-sign-in.md#phase-2-same-account-pairing)):沒有憑證 → `reject unsupportedVersion`;憑證不是這把 device key 的 → 403;電腦在別的帳號 → 403,訊息帶 owner 遮罩過的 email;電腦在手機的帳號 → 直接放行;電腦不在任何帳號 → 在電腦上問(loopback 的 `pairingRequests` 事件/方法、`decidePairing`,最多 2 分鐘,兩邊顯示同一組 6 位數 `sha256("codync/pair-check/v1" ‖ dk ‖ hostSignKey)`),同意後 host 簽手機的 claim,回應帶 `claim`,手機自己 `POST /v1/claims/{id}/complete`。接著驗 code(常數時間比較、未過期、未用過)→ 刪除該 code → 新增裝置列(`source=local`,`grant_id=NULL`,`account=<userId>`,`scopes=["control","screen"]`,無 lease)→ 回 `{"id":1,"ok":{"computerId":"…","name":"…","claim":{…}|null}}` → **關閉這條 channel,close code `4100 paired`**(中繼:host 依序送 `data`(回應)→ `close {link, code:4100}` → 新 ACL(移除 offer、加入 dk);同一條 host socket 保序,所以回應一定先到)。5. client 收到 `4100` 立即以一般模式重連(§7.5,不帶 `pair`)。直連與中繼行為相同;DO 不需要「升級」pairing socket。+**之後補完加入帳號**:手機進來了但電腦沒加入帳號(手機沒拿到 claim、host 簽 claim 失敗、`complete` 失敗,或當時雲端關著/用 private relay)時,host 之後回給這台裝置的 `hello` 帶 `joinAccount: true`,條件是 `owner::joinable_by`:用 Codync 雲端(不是 private relay)、這次連線已拉過 state(`cloud_synced`)、電腦不在任何帳號、這台裝置記了帳號(`devices.account`),而且電腦上沒有別的帳號的裝置。手機接著 `POST /v1/claims`,呼叫 control scope 的 `joinAccount {claimId, nonce}`;host 再查一次同樣的條件,替這台裝置記的帳號簽 claim(`owner::sign_claim`,回傳內容與 `claimSign` 相同),手機再 `POST /v1/claims/{id}/complete`。手機完成後在自己存的電腦上記 `joinedAccount`(重新 QR 配對時清掉):電腦被移出帳號時若還沒拉到自己加入過,它之後仍會問,這支手機不會再把它加回去。+`Caller::Pairing` 的 channel 只接受 `pair`:第一個 inner 訊息不是 `pair`、或 `pair` 之後還有任何訊息 → 關閉 `4002 protocolError`。錯誤與限流:@@ -171,6 +173,8 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair3. 桌面 App `POST /v1/claims/{claimId}/complete`(Clerk)帶上 host 回傳的內容。Worker 驗 Clerk、claim、簽章,原子化設定 owner。4. Worker 通知 DO `cloud.changed` → host 拉 state 得知 owner。+手機也會讓 host 簽 claim:配對時(§4.1 第 4 步),以及配對沒加入帳號時之後的 control scope `joinAccount`(§4.1「之後補完加入帳號」)。+**B. 手機取得存取權**(commit-then-reveal SAS,ZRTP/BLE numeric comparison 同型):1. 手機登入後 `POST /v1/devices`(Clerk + 該 device key 的 `Codync-Sig`)。2. `GET /v1/computers`(帶 `Codync-Sig` 則回傳每台的 `access`)。 手機在「電腦與設定」(Computers)列出帳號裡的電腦,不需掃 QR Code;存取申請只在使用者點該電腦的 **Ask for access** 後才開始(登入或重新整理都不會自動申請),點下後才顯示 6 位數代碼;關閉申請畫面後,等待中的申請仍以橫幅顯示代碼,直到電腦回應。核准後顯示該電腦的 bots。首次裝置授權仍由電腦上的使用者確認。@@ -321,7 +325,7 @@ blob = epk(32) ‖ sig(64) ‖ ct| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `pairingRequests`, `decidePairing`, `pairingCodeOpen`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token);`pairingRequests` 事件也只送給 loopback || 配對中 | `pair` | 只在 pairing 狀態的 channel;配對完成後不可再呼叫 || screen scope | `screenPrepare`, `screenOffer`, `screenCandidate`, `screenClose`, `screenTakeover` | Local,或 scopes 含 `screen` 的裝置 |-| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `forgetDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |+| control scope | 其餘所有既有方法(`hello`, `joinAccount`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `forgetDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |The `screenCandidates` subscription also requires `screen` scope and belongs to its device’s screen session. It carries ordered candidates and completion separately from chat events; see [remote screen](../features/remote-screen.md).diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex 15cffda3..7d14d2c8 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -58,6 +58,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value"hello" => {let port = hub.port;let icons = crate::icons::snapshot(&hub.store)?;+ let join_account = crate::remote::owner::joinable_by(hub, caller.device_key()).unwrap_or_else(|e| {+ tracing::warn!(error = format!("{e:#}"), "couldn't check whether this phone can finish joining");+ None+ });json!({"hostId": hub.host_id,"computerId": hub.identity.computer_id(),@@ -80,6 +84,8 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value"rev": hub.store.current_rev(),"screen": hub.screen.state(),"analytics": hub.analytics.state(),+ // This phone paired without the computer joining its account: it calls `joinAccount` to finish.+ "joinAccount": join_account.is_some(),// Shells out to `tailscale`: keep it off the async workers."urls": tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?,})diff --git a/host/src/api/remote.rs b/host/src/api/remote.rsindex 21c61b9c..b848477c 100644--- a/host/src/api/remote.rs+++ b/host/src/api/remote.rs@@ -127,6 +127,12 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuelet (claim_id, nonce, user_id) = (str_arg(&b, "claimId")?, str_arg(&b, "nonce")?, str_arg(&b, "userId")?);crate::remote::owner::sign_claim(hub, claim_id, nonce, user_id).await?}+ // A phone finishing a join its pairing didn't complete (hello's `joinAccount`).+ "joinAccount" => {+ let user_id = crate::remote::owner::joinable_by(hub, caller.device_key())?+ .ok_or_else(|| anyhow!("This computer can't join this phone's account now."))?;+ crate::remote::owner::sign_claim(hub, str_arg(&b, "claimId")?, str_arg(&b, "nonce")?, &user_id).await?+ }_ => return Ok(ControlFlow::Continue(b)),}))}diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rsindex f1fdba63..893f2a3d 100644--- a/host/src/cloud_cli.rs+++ b/host/src/cloud_cli.rs@@ -1,8 +1,10 @@-//! `codync-host cloud`: the relay this computer uses, its registration token and account approval.+//! `codync-host cloud`: the relay this computer uses, its registration token, its account and account approval.-use crate::local_api::local_call;-use anyhow::Result;-use serde_json::json;+use crate::local_api::{local_call, local_call_for};+use anyhow::{Result, bail};+use serde_json::{Value, json};+use std::io::IsTerminal as _;+use std::time::Duration;#[derive(clap::Args)]#[allow(clippy::struct_excessive_bools, reason = "independent command-line flags")]@@ -13,6 +15,10 @@ pub struct CloudArgs {enable: bool,#[arg(long)]disable: bool,+ /// Take this computer out of its Codync account (asks first). Every device paired with it+ /// loses access and pairs again with a new code.+ #[arg(long, conflicts_with = "disable")]+ leave: bool,/// How devices on this computer's account get in: `code` (compare the 6-digit code,/// the default) or `auto` (no check: anyone who gets into the account, or controls/// the cloud, can then add a device).@@ -37,14 +43,14 @@ pub struct CloudArgs {/// `codync-host cloud`: shows or changes the cloud this computer uses.pub async fn run(args: CloudArgs) -> Result<()> {- let CloudArgs { port, enable, disable, approval, assistants, url, clear_url, token } = args;+ let CloudArgs { port, enable, disable, leave, approval, assistants, url, clear_url, token } = args;let mut status = None;if clear_url {status = Some(local_call(port, "setCloudUrl", json!({ "url": "" })).await?);} else if let Some(url) = url {let mut body = json!({ "url": url });if token {- let token = crate::secret_prompt::read("Relay token: ")?;+ let token = crate::prompt::read_secret("Relay token: ")?;// An empty answer would clear the saved token; `--clear-url` is the way to forget it.if token.is_empty() {anyhow::bail!("No relay token was given.");@@ -57,6 +63,9 @@ pub async fn run(args: CloudArgs) -> Result<()> {if enable || disable {status = Some(local_call(port, "setCloud", json!({"enabled": !disable})).await?);}+ if leave {+ status = Some(leave_account(port).await?);+ }if let Some(approval) = approval {status = Some(local_call(port, "setApproval", json!({ "approval": approval })).await?);}@@ -68,7 +77,7 @@ pub async fn run(args: CloudArgs) -> Result<()> {None => local_call(port, "cloudStatus", json!({})).await?,};let text = |k: &str| status[k].as_str().unwrap_or("-").to_owned();- let owner = status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str()).unwrap_or("none");+ let owner = owner(&status).unwrap_or("none");println!("enabled: {}\nurl: {}\nrelay: {}\ntoken: {}\nregistered: {}\nconnected: {}\naccount: {owner}\napproval: {}\nassistants: {}\nlast error: {}",status["enabled"],@@ -87,8 +96,30 @@ pub async fn run(args: CloudArgs) -> Result<()> {Ok(())}+/// `--leave`: after a yes in a terminal, the desktop app's Remove from account (`unclaim`). Returns the status.+async fn leave_account(port: u16) -> Result<Value> {+ let status = local_call(port, "cloudStatus", json!({})).await?;+ let Some(owner) = owner(&status) else { bail!("This computer isn't in an account.") };+ if !std::io::stdin().is_terminal() {+ bail!("Run `codync-host cloud --leave` in a terminal to confirm.");+ }+ let prompt =+ format!("Take this computer out of {owner}'s account? Every device paired with it loses access. [y/N] ");+ if !crate::prompt::ask_yes_no(&prompt).await? {+ return Ok(status);+ }+ // The cloud call and the state pull after it: the desktop app allows them 30 seconds too.+ local_call_for(port, "unclaim", json!({}), Duration::from_secs(30)).await?;+ local_call(port, "cloudStatus", json!({})).await+}++/// The account this computer is in, by email when the cloud gave one.+fn owner(status: &Value) -> Option<&str> {+ status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str())+}+/// How a computer with no desktop app gets into an account (docs/architecture/connections.md, headless computers).-fn account_hint(status: &serde_json::Value) -> Option<&'static str> {+fn account_hint(status: &Value) -> Option<&'static str> {if !status["owner"].is_null() {return None;}diff --git a/host/src/main.rs b/host/src/main.rsindex c47475f3..fea92fde 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -18,10 +18,10 @@ mod mcp;mod network;mod network_cli;mod pair_cli;+mod prompt;mod remote;mod routines;mod screen;-mod secret_prompt;mod send_cli;mod service;mod shell;diff --git a/host/src/pair_cli.rs b/host/src/pair_cli.rsindex 933cf5fd..c3e81be6 100644--- a/host/src/pair_cli.rs+++ b/host/src/pair_cli.rs@@ -5,7 +5,7 @@use crate::local_api::local_call;use anyhow::{Result, bail};use serde_json::{Value, json};-use std::io::{IsTerminal as _, Write as _};+use std::io::IsTerminal as _;use std::time::Duration;#[derive(clap::Subcommand)]@@ -85,7 +85,7 @@ async fn wait(port: u16, url: &str, expires_at: i64) -> Result<()> {r["email"].as_str().unwrap_or("a Codync account"),spaced(r["code"].as_str().unwrap_or_default()),);- let approve = ask_yes_no("Let it in? [y/N] ").await?;+ let approve = crate::prompt::ask_yes_no("Let it in? [y/N] ").await?;let answered = local_call(port, "decidePairing", json!({"requestId": r["requestId"], "approve": approve}));if answered.await.is_err() {println!("The phone stopped waiting, or it was answered elsewhere.");@@ -111,17 +111,6 @@ fn spaced(code: &str) -> String {}}-async fn ask_yes_no(prompt: &str) -> Result<bool> {- print!("{prompt}");- std::io::stdout().flush()?;- let line = tokio::task::spawn_blocking(|| {- let mut line = String::new();- std::io::stdin().read_line(&mut line).map(|_| line)- })- .await??;- Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))-}-/// Requests waiting for this computer's answer, each with the method that answers it.async fn requests(port: u16) -> Result<Vec<(Value, &'static str)>> {let mut all = vec![];diff --git a/host/src/secret_prompt.rs b/host/src/prompt.rssimilarity index 67%rename from host/src/secret_prompt.rsrename to host/src/prompt.rsindex 49aee496..377f2337 100644--- a/host/src/secret_prompt.rs+++ b/host/src/prompt.rs@@ -1,4 +1,5 @@-//! Reads a secret for a CLI command: typed without echo on a terminal, or one line of piped stdin.+//! Reads answers for CLI commands: a secret (typed without echo on a terminal, or one line of piped stdin) or a+//! yes or no.use anyhow::{Result, bail};use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};@@ -6,7 +7,7 @@ use crossterm::terminal;use std::io::{BufRead, IsTerminal, Write};/// One line of secret input, trimmed. Typed keys are never shown.-pub fn read(prompt: &str) -> Result<String> {+pub fn read_secret(prompt: &str) -> Result<String> {if !std::io::stdin().is_terminal() {let mut line = String::new();std::io::stdin().lock().read_line(&mut line)?;@@ -40,3 +41,15 @@ fn read_keys() -> Result<String> {}}}++/// `true` for `y` or `yes` (any case); anything else is a no.+pub async fn ask_yes_no(prompt: &str) -> Result<bool> {+ print!("{prompt}");+ std::io::stdout().flush()?;+ let line = tokio::task::spawn_blocking(|| {+ let mut line = String::new();+ std::io::stdin().read_line(&mut line).map(|_| line)+ })+ .await??;+ Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))+}diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rsindex 97e2c4a3..fd1ac09a 100644--- a/host/src/remote/channel/tests/accounts.rs+++ b/host/src/remote/channel/tests/accounts.rs@@ -119,3 +119,30 @@ async fn a_phone_let_in_after_the_computer_joined_another_account_stays_out() {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");}++#[tokio::test]+async fn a_phone_let_in_without_joining_finishes_the_join_later() {+ let hub = unowned_hub();+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();+ // Paired without a claim: the phone couldn't start one, so the computer stayed out of the account.+ 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;+ crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), true).unwrap();+ assert!(p.recv().await.unwrap()["ok"]["claim"].is_null());+ hub.cloud_synced.store(true, std::sync::atomic::Ordering::Release);++ let mut p = Phone::direct(&hub, p.key.clone());+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));+ assert_eq!(p.call(1, "hello", json!({})).await["ok"]["joinAccount"], true);+ let claim = p.call(2, "joinAccount", json!({"claimId": "clm_2", "nonce": "n2"})).await;+ let input = crypto::claim_input("clm_2", "n2", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());+ let sig = crypto::unb64_n::<64>(claim["ok"]["sig"].as_str().unwrap()).unwrap();+ crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();++ // Once it is in the account, there is nothing left to join.+ let owner = crate::remote::cloud::Owner { user_id: "user_2".into(), email: None };+ crate::remote::owner::remember(&hub, Some(&owner)).unwrap();+ assert_eq!(p.call(3, "hello", json!({})).await["ok"]["joinAccount"], false);+ assert!(p.call(4, "joinAccount", json!({"claimId": "clm_3", "nonce": "n3"})).await["err"].is_object());+}diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rsindex 16e68666..f05ebf44 100644--- a/host/src/remote/owner.rs+++ b/host/src/remote/owner.rs@@ -10,6 +10,7 @@ use crate::hub::Hub;use crate::store::Store;use anyhow::{Result, bail};use serde_json::{Value, json};+use std::sync::atomic::Ordering;const OWNER: &str = "account_owner";@@ -67,8 +68,21 @@ pub fn out_of_account(hub: &Hub) -> Result<()> {Ok(())}+/// The account the device `key` may bring this computer into (`joinAccount`), when a pairing let the phone in+/// without the computer joining its account (the claim failed or never went out). Only on the Codync cloud, with+/// this connection's state pulled and no account yet, for the account the phone paired from, and only when no+/// device of another account would lose access by it.+pub fn joinable_by(hub: &Hub, key: &str) -> Result<Option<String>> {+ if cloud::codync_url(hub).is_err() || !hub.cloud_synced.load(Ordering::Acquire) || owner(&hub.store).is_some() {+ return Ok(None);+ }+ let Some(account) = hub.store.device(key).and_then(|d| d.account) else { return Ok(None) };+ let devices = hub.store.devices()?;+ Ok(devices.iter().all(|d| d.account.as_ref().is_none_or(|a| *a == account)).then_some(account))+}+/// 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.+/// Add to account, a phone pairing with a computer in no account, or a phone finishing that join later.pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -> Result<Value> {cloud::require_accounts(&hub.store)?;for (k, v) in [("claimId", claim_id), ("nonce", nonce), ("userId", user_id)] {@@ -167,6 +181,31 @@ mod tests {assert_eq!(keys(&hub), ["legacy", "mine"]);}+ #[test]+ fn a_phone_brings_a_computer_in_no_account_into_the_account_it_paired_from() {+ let hub = hub();+ device(&hub, "mine", Some("user_a"));+ device(&hub, "legacy", None);+ assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "not before this connection's state pull");+ hub.cloud_synced.store(true, Ordering::Release);+ assert_eq!(joinable_by(&hub, "mine").unwrap().as_deref(), Some("user_a"));+ assert_eq!(+ joinable_by(&hub, "legacy").unwrap(),+ None,+ "a phone that paired before devices recorded their account"+ );+ assert_eq!(joinable_by(&hub, "local").unwrap(), None);+ device(&hub, "theirs", Some("user_b"));+ assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "another account's phone would lose access");+ hub.store.remove_device("theirs").unwrap();+ remember(&hub, Some(&account("user_a"))).unwrap();+ assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "already in an account");+ remember(&hub, None).unwrap();+ device(&hub, "mine", Some("user_a"));+ hub.store.kv_set("cloud_enabled", "false").unwrap();+ assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "no account with the cloud off");+ }+#[test]fn with_the_cloud_off_or_a_private_relay_the_computer_is_in_no_account() {let hub = hub();diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex 558af0b6..5abd9fe0 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -205,6 +205,7 @@"hello.hostId": "string","hello.icons": "object","hello.iconsRevision": "number",+ "hello.joinAccount": "bool","hello.latestVersion": "null","hello.minApp": "string","hello.name": "string",diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdxindex 85e98755..b42fe32a 100644--- a/web/content/docs/linux-servers.mdx+++ b/web/content/docs/linux-servers.mdx@@ -42,7 +42,7 @@ codync-host status## Pair your phone-With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, signed in, scan the QR code from the welcome screen or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**), or type the short code into the field under the scanner. A server that isn't in an account yet asks in the terminal whether to let the phone in and join your account: check the phone shows the same 6-digit code, then answer `y` within 90 seconds. With `codync-host pair --json`, or SSH without a terminal, answer with `codync-host access approve <code>` instead. `codync-host cloud` says which account the server is in.+With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, signed in, scan the QR code from the welcome screen or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**), or type the short code into the field under the scanner. A server that isn't in an account yet asks in the terminal whether to let the phone in and join your account: check the phone shows the same 6-digit code, then answer `y` within 90 seconds. With `codync-host pair --json`, or SSH without a terminal, answer with `codync-host access approve <code>` instead. A server that lets the phone in but can't join your account at that moment (its cloud is off, or the connection dropped) joins it the next time the phone connects with the Codync cloud on. `codync-host cloud` says which account the server is in, and `codync-host cloud --leave` takes the server out of it: every phone paired with it loses access and pairs again with a new code.The code works once and expires after 10 minutes. More about pairing and accounts: [Remote access](/docs/remote-access).diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdxindex 2e1c0148..c1c76bf1 100644--- a/web/content/docs/remote-access.mdx+++ b/web/content/docs/remote-access.mdx@@ -34,7 +34,8 @@ Pairing checks your account, so a phone and a computer pair only when they're in- **The computer is in your account:** the phone is let in right away.- **The computer is in someone else's account:** the phone says whose (for example *k•••@example.com*). Move the computer to your account on that computer, or sign in to that account.-- **The computer isn't in an account yet:** the computer asks first, for 90 seconds. The desktop app asks whether to let the phone in, and the terminal UI and `codync-host pair` ask you to answer `y`. Without any of them (`codync-host pair --json`, a script, SSH with no terminal), run `codync-host access approve <code>` with the 6 digits the phone shows. Check that the phone shows the same 6-digit code, then let it in. The computer joins your account; with its cloud off or on a private relay, the phone gets in and the computer stays out of any account.+- **The computer isn't in an account yet:** the computer asks first, for 90 seconds. The desktop app asks whether to let the phone in, and the terminal UI and `codync-host pair` ask you to answer `y`. Without any of them (`codync-host pair --json`, a script, SSH with no terminal), run `codync-host access approve <code>` with the 6 digits the phone shows. Check that the phone shows the same 6-digit code, then let it in. The computer joins your account. While its cloud is off or it uses a private relay, the phone gets in and the computer stays out of any account.+- **The computer let the phone in but didn't join your account** (the connection dropped while pairing, or its cloud was off or on a private relay): the next time the phone connects while the computer is on the Codync cloud, the computer joins your account on its own, as long as no phone of another account is paired with it. A computer taken out of your account isn't brought back this way.Changing the account a computer belongs to (moving it, or **Remove from account**) takes away access from every device of the old account. A computer joining its first account keeps the phones that were already paired.@@ -158,5 +159,5 @@ Webhook deliveries are **not** end-to-end encrypted. The relay receives them ove- **On the computer:** in **Settings → Computers**, the list **Devices that can use** the computer has **Revoke access** for each device. Without the desktop app, use `codync-host devices` to list devices and `codync-host devices revoke <key>` to remove one. The device disconnects right away and has to pair or ask again.- **On the iPhone:** in **Manage computers**, remove a paired computer, or revoke this phone's account access to one. The computer keeps its bots and chats.-- **Remove from account** on a computer's card disconnects every device of the account, phones paired with a QR code included. They have to pair again.-- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. Any offline computer has it, so first make sure it's gone rather than asleep: every device of the account loses access, and it rejoins only when you add it again on that computer. Only the desktop app removes a computer from the account; on a phone you can only forget a computer you paired with a QR code.+- **Remove from account** on a computer's card disconnects every device of the account, phones paired with a QR code included. They have to pair again. On a computer without the desktop app, run `codync-host cloud --leave` in a terminal there; it asks before it removes anything.+- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. Any offline computer has it, so first make sure it's gone rather than asleep: every device of the account loses access, and it rejoins only when you add it again on that computer. Only the desktop app removes a computer that's gone, from another computer; on a phone you can only forget a computer you paired with a QR code.