Skip to content

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.

fix: a computer taken out of its account never joins it again by itself

leepokaidda7bd4a9d37
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 3b7b79ed..39918e87 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -11,9 +11,9 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
### zh-Hant
- 介面新增巴西葡萄牙文:可在設定選擇「Português (Brasil)」,或跟隨系統的葡萄牙文語言。
- 新增俄文介面:在設定選擇「Русский」,或跟隨系統的俄文語言。
-- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如網路中斷),下次連上時會自動補上。
+- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如手機連不上 Codync 雲端,或電腦的雲端關著),下次連上時會自動補上。
### 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.
+- A computer you pair with a QR code that couldn't join your account at the time (the phone couldn't reach the Codync cloud, or the computer's cloud was off, say) joins it the next time it connects.
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.kt
index 04681a53..514b0942 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
@@ -33,9 +33,8 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {
// 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, and may bring the computer into the account again
- // (iOS `AccountStore.pair`).
- val computer = paired.computer.keepingDevicePicks(old).copy(joinedAccount = false)
+ // Picked on this phone: pairing again keeps them (iOS `AccountStore.pair`).
+ val computer = paired.computer.keepingDevicePicks(old)
transitions.withLock { addComputer(computer) }
withContext(Dispatchers.IO) { local.completeSetup() }
mutableState.update { it.copy(setupComplete = true) }
@@ -79,8 +78,8 @@ private const val NO_PROOF = "Connect to the internet to pair, so Codync can con
/**
* 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]).
+ * `AccountStore.joinAccount`). One at a time per computer; the computer decides whether a join that failed here is asked
+ * for again.
*/
internal fun AccountStore.joinAccount(id: String, sign: suspend (CloudClient) -> Pair<PairingClaim, JsonObject>) {
val client = cloud ?: return
@@ -91,10 +90,7 @@ internal fun AccountStore.joinAccount(id: String, sign: suspend (CloudClient) ->
val (claim, signed) = sign(client)
client.completeClaim(claim.claimId, signed)
}
- if (joined != null) {
- store(id)?.changeComputer { it.copy(joinedAccount = true) }
- refreshCloud()
- }
+ if (joined != null) refreshCloud()
} finally { joining.remove(id) }
}
}
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.kt
index 878b73aa..aa181882 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,7 +111,7 @@ 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 ->
+ if (asksToJoinAccount(hello)) joinAccount { claim ->
active.call("joinAccount", claim.json).jsonObject
}
// The event catch-up is ordered by revision; bot revisions can
@@ -229,12 +229,8 @@ 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
+/** The computer's [hello] asks this phone to finish bringing it into the account (iOS `BotStore.refreshHello`). */
+internal fun asksToJoinAccount(hello: JsonObject): Boolean = hello["joinAccount"]?.jsonPrimitive?.booleanOrNull == true
private fun AppStore.showConnection(link: LinkState) {
mutableState.update { it.copy(actualConnection = link) }
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.kt
index 869d6a2d..5b72b952 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import com.codync.android.core.Computer
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.*
@@ -8,17 +7,9 @@ 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)
+ assertTrue(asksToJoinAccount(buildJsonObject { put("joinAccount", true) }))
+ assertFalse(asksToJoinAccount(buildJsonObject { put("joinAccount", false) }))
+ assertFalse("an older host doesn't say", asksToJoinAccount(buildJsonObject { }))
}
}
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.kt
index 52ded6ba..906a1622 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,19 +16,10 @@ 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) 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)
- } ?: this
+ /** 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
fun validate() {
require(RelayCrypto.computerId(signKey.decodeBase64Url(32)) == id) { "This computer's identity changed. Pair it again." }
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift
index 1974a198..decfea30 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swift
@@ -23,9 +23,6 @@ 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) {
@@ -39,13 +36,11 @@ public struct Computer: Codable, Hashable, Sendable, Identifiable {
self.color = color
}
- /// Keeps what this device picked (color, route, push) or did (`joinedAccount`) over a newer copy from pairing,
- /// the account or `hello`.
+ /// Keeps what this device picked (color, route, push) over a newer copy from pairing, the account or `hello`.
public mutating func keepDevicePicks(from previous: Computer) {
color = previous.color
route = previous.route
notifications = previous.notifications
- joinedAccount = previous.joinedAccount
}
/// `true` when `id` really is the computer ID of `signKey`.
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index 70512438..854a5caf 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -123,8 +123,6 @@ public final class AccountStore {
guard !retired else { throw CancellationError() }
var computer = paired.computer
if let previous = saved.first(where: { $0.id == computer.id }) { computer.keepDevicePicks(from: previous) }
- // Pairing again may bring it into the account again.
- computer.joinedAccount = nil
save(computer)
open(computer)
if let claim, let signed = paired.claim {
@@ -161,8 +159,7 @@ public final class AccountStore {
/// 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`).
+ /// One at a time per computer; the computer decides whether a join that failed here is asked for again.
private func joinAccount(_ id: ComputerID, sign: @escaping @MainActor (CloudClient) async throws -> (CloudClaim, Data)) {
guard let cloud, !retired, joining.insert(id).inserted else { return }
Task {
@@ -175,7 +172,6 @@ public final class AccountStore {
return
}
guard !retired else { return }
- updateSaved(id) { $0.joinedAccount = true }
await refreshCloud()
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
index d7518823..c0cd50d9 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
@@ -66,8 +66,7 @@ extension BotStore {
hello = h
applyIcons(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) }
+ if h.joinAccount == true { onJoinAccount?(client) }
}
private func noteHostVersion(_ new: HostVersion) {
diff --git a/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
index 88bea711..a3c7eaaa 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
@@ -52,9 +52,8 @@ private final class ClaimCloudStub: URLProtocol {
}
}
-/// 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 {
+/// The account finishes the join its `hello` asks for: a claim, the computer's signature, then the completion.
+@MainActor @Test func theAccountFinishesTheJoinTheComputerAsksFor() async throws {
let suite = "JoinAccountTests.\(UUID().uuidString)"
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
let config = URLSessionConfiguration.ephemeral
@@ -62,8 +61,7 @@ private final class ClaimCloudStub: URLProtocol {
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]
+ storage.computers = [randomComputer("Mac")]
let remote = FakeRemote(.ready(.direct))
await remote.setHello(askingHello)
let accounts = AccountStore(storage: storage, cloud: cloud) { computer in
@@ -71,16 +69,7 @@ private final class ClaimCloudStub: URLProtocol {
}
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(await until { ClaimCloudStub.completed.withLock { $0 } == 1 })
#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.md
index cd4d15fc..53b3f170 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,9 +10,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- 介面新增巴西葡萄牙文:可在設定選擇「Português (Brasil)」,或跟隨系統的葡萄牙文語言。
- 新增俄文介面:在設定選擇「Русский」,或跟隨系統的俄文語言。
-- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如網路中斷),下次連上時會自動補上。
+- 用 QR Code 配對時,如果電腦當下沒能加入你的帳號(例如手機連不上 Codync 雲端,或電腦的雲端關著),下次連上時會自動補上。
### 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.
+- A computer you pair with a QR code that couldn't join your account at the time (the phone couldn't reach the Codync cloud, or the computer's cloud was off, say) joins it the next time it connects.
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index 8c5a83de..13b2b19f 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -54,7 +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).
+- A phone let in without the host signing a claim for its account (the phone couldn't start one, or the cloud was off or a private relay) finishes the join 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, no device of another account is on it, and the host signed no claim for that account since its own account last changed; the phone then makes a claim, the host's `joinAccount` signs it for that recorded account, and the phone completes it (`owner::joinable_by`). The host notes every account it signs a claim for (`owner::note_signed`, any path: pairing, `joinAccount`, the desktop's Add to account) until its account changes, because a claim may complete and the computer be taken out again before it pulls its state, which then still says no account. So a computer taken out never comes back this way: one seen leaving dropped every device, and one taken out before it heard it had joined signed for that account. The cost: a claim the host signed that then failed to complete isn't retried; pairing again joins.
## Accounts on a phone
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 31467f4c..d268de9d 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -155,7 +155,9 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair
4. 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 配對時清掉):電腦被移出帳號時若還沒拉到自己加入過,它之後仍會問,這支手機不會再把它加回去。
+**之後補完加入帳號**:手機進來了但 host 沒替它的帳號簽 claim(手機沒拿到 claim,或當時雲端關著/用 private relay)時,host 之後回給這台裝置的 `hello` 帶 `joinAccount: true`,條件是 `owner::joinable_by`:用 Codync 雲端(不是 private relay)、這次連線已拉過 state(`cloud_synced`)、電腦不在任何帳號、這台裝置記了帳號(`devices.account`)、電腦上沒有別的帳號的裝置,而且 host 從自己的帳號上次改變以來沒替這個帳號簽過 claim。手機接著 `POST /v1/claims`,呼叫 control scope 的 `joinAccount {claimId, nonce}`;host 再查一次同樣的條件,替這台裝置記的帳號簽 claim(`owner::sign_claim`,回傳內容與 `claimSign` 相同),手機再 `POST /v1/claims/{id}/complete`。
+
+`sign_claim` 簽之前把帳號記進 kv `account_claims_signed`(`owner::note_signed`,配對、`joinAccount`、桌面 App 的 Add to account 都走這裡),帳號改變時(`owner::remember` 看到 user id 不同)清掉。原因:claim 完成後、host 還沒拉到 state 前,電腦可能又被移出帳號,下一次 pull 仍是「沒有帳號」,`remember` 不會刪任何裝置;有這筆紀錄,任何一支手機都不能再用 `joinAccount` 把它加回去。代價是 host 簽過、但 `complete` 失敗的 claim 不會自動重試,重新配對即可。
`Caller::Pairing` 的 channel 只接受 `pair`:第一個 inner 訊息不是 `pair`、或 `pair` 之後還有任何訊息 → 關閉 `4002 protocolError`。
diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rs
index fd1ac09a..ecd20501 100644
--- a/host/src/remote/channel/tests/accounts.rs
+++ b/host/src/remote/channel/tests/accounts.rs
@@ -95,6 +95,11 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {
crypto::claim_input("clm_1", "n1", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());
let sig = crypto::unb64_n::<64>(claim["sig"].as_str().unwrap()).unwrap();
crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();
+ // Taken out again before it pulled that it joined: a state pull that still says no account brings no
+ // later join for the account it signed for.
+ hub.cloud_synced.store(true, std::sync::atomic::Ordering::Release);
+ crate::remote::owner::remember(&hub, None).unwrap();
+ assert_eq!(crate::remote::owner::joinable_by(&hub, &p.dk()).unwrap(), None);
} else {
assert_eq!(reply["err"]["status"], 403);
assert!(hub.store.device(&p.dk()).is_none());
@@ -140,9 +145,9 @@ async fn a_phone_let_in_without_joining_finishes_the_join_later() {
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();
+ // Signed once: whether that claim completed (and the computer was taken out again) or not, a state pull that
+ // still says no account brings no second join.
+ crate::remote::owner::remember(&hub, None).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.rs
index f05ebf44..e2665986 100644
--- a/host/src/remote/owner.rs
+++ b/host/src/remote/owner.rs
@@ -13,6 +13,8 @@ use serde_json::{Value, json};
use std::sync::atomic::Ordering;
const OWNER: &str = "account_owner";
+/// The accounts this computer signed a claim for since its account last changed (`note_signed`).
+const SIGNED: &str = "account_claims_signed";
/// 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).
@@ -24,7 +26,8 @@ pub fn owner(store: &Store) -> Option<Owner> {
/// Records the account the cloud reports. When it is another one than before (joining one, moving, or leaving),
/// every device let in for another account goes; joining a first account keeps the phones paired before devices
/// recorded their account. The first record after an upgrade only records. The devices go first, so a failure
-/// leaves the old account recorded and the next pull tries again.
+/// leaves the old account recorded and the next pull tries again. Any change of account also forgets the accounts
+/// claims were signed for before it (`note_signed`).
pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
let saved = serde_json::to_string(&now)?;
let _change = hub.cloud.account.locked();
@@ -32,11 +35,12 @@ pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
if before.as_deref() == Some(saved.as_str()) {
return Ok(());
}
- if let Some(before) = before {
- let before = serde_json::from_str::<Option<Owner>>(&before).ok().flatten().map(|o| o.user_id);
- let now = now.map(|o| o.user_id.as_str());
- if before.as_deref() != now {
- let gone = hub.store.keep_devices_of(now, before.is_none())?;
+ let before_user =
+ before.as_deref().and_then(|b| serde_json::from_str::<Option<Owner>>(b).ok().flatten()).map(|o| o.user_id);
+ let now_user = now.map(|o| o.user_id.as_str());
+ if before_user.as_deref() != now_user {
+ if before.is_some() {
+ let gone = hub.store.keep_devices_of(now_user, before_user.is_none())?;
tracing::info!(
devices = gone.len(),
"the computer changed its account; the old account's devices are gone"
@@ -45,6 +49,7 @@ pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
hub.auth_changed();
}
}
+ hub.store.kv_delete(SIGNED)?;
}
hub.store.kv_set(OWNER, &saved)
}
@@ -69,16 +74,35 @@ pub fn out_of_account(hub: &Hub) -> Result<()> {
}
/// 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.
+/// without the computer signing a claim for its account (the phone couldn't start one, or the cloud was off or a
+/// private relay). Only on the Codync cloud, with this connection's state pulled and no account yet, for the account
+/// the phone paired from, only when no device of another account would lose access by it, and never for an account
+/// this computer signed a claim for since its account last changed (`note_signed`).
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))
+ let alone = devices.iter().all(|d| d.account.as_ref().is_none_or(|a| *a == account));
+ Ok((alone && !signed_for(&hub.store)?.contains(&account)).then_some(account))
+}
+
+/// Notes the account a claim is about to be signed for. That claim may complete and the computer be taken out of
+/// the account again before it pulls its state, which then still says no account: until its account changes, the
+/// computer doesn't offer that account a later join, so it never comes back into an account it was taken out of.
+fn note_signed(hub: &Hub, user_id: &str) -> Result<()> {
+ let _change = hub.cloud.account.locked();
+ let mut signed = signed_for(&hub.store)?;
+ if !signed.iter().any(|u| u == user_id) {
+ signed.push(user_id.to_owned());
+ hub.store.kv_set(SIGNED, &serde_json::to_string(&signed)?)?;
+ }
+ Ok(())
+}
+
+fn signed_for(store: &Store) -> Result<Vec<String>> {
+ store.kv_read(SIGNED)?.map_or(Ok(vec![]), |s| Ok(serde_json::from_str(&s)?))
}
/// Signs this computer into an account claim (§4.2 A) for a signed-in app to complete: the desktop app's
@@ -91,6 +115,7 @@ pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -
bail!("`{k}` is invalid");
}
}
+ note_signed(hub, user_id)?;
let computer_id = hub.identity.computer_id();
let box_key = hub.identity.box_pub_b64();
let input = crypto::claim_input(claim_id, nonce, user_id, &computer_id, &box_key);
@@ -206,6 +231,27 @@ mod tests {
assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "no account with the cloud off");
}
+ #[test]
+ fn a_computer_taken_out_before_it_heard_it_joined_stays_out() {
+ let hub = hub();
+ remember(&hub, None).unwrap();
+ hub.cloud_synced.store(true, Ordering::Release);
+ device(&hub, "a", Some("user_a"));
+ device(&hub, "b", Some("user_a"));
+ // Phone a's claim completes and the computer is taken out again, both between two state pulls.
+ note_signed(&hub, "user_a").unwrap();
+ remember(&hub, None).unwrap();
+ assert_eq!(joinable_by(&hub, "a").unwrap(), None);
+ assert_eq!(joinable_by(&hub, "b").unwrap(), None, "nor through another phone of that account");
+
+ // Seen in the account and taken out, its phones go: one let in again may bring it back.
+ remember(&hub, Some(&account("user_a"))).unwrap();
+ remember(&hub, None).unwrap();
+ assert!(hub.store.device("a").is_none());
+ device(&hub, "a", Some("user_a"));
+ assert_eq!(joinable_by(&hub, "a").unwrap().as_deref(), Some("user_a"));
+ }
+
#[test]
fn with_the_cloud_off_or_a_private_relay_the_computer_is_in_no_account() {
let hub = hub();
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index b42fe32a..0795ee00 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. 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.
+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 phone couldn't reach the Codync cloud) joins it the next time the phone connects with the Codync cloud on. If it still isn't in your account after that, pair it again. `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.mdx
index c1c76bf1..da150c38 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -35,7 +35,7 @@ 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. 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.
+- **The computer let the phone in but didn't join your account** (the phone couldn't reach the Codync cloud while pairing, or the computer's 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. If it still isn't in your account after that, pair it again. 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.