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.

feat: signing out of a phone keeps its computers and only stops notifications

leepokai39d3740d0693
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 7595aa50..d56330ab 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -10,14 +10,14 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
## 2.36.0
### zh-Hant
- Codync 現在需要用 Apple、Google 或 GitHub 登入。以前沒登入就配對的電腦,第一次登入時會一起移進你的賬戶,不用再掃一次。
-- 登出時,這支手機會從它連得到的電腦和你的賬戶中移除。
+- 登出後,這支手機不再收到通知,但會保留它的電腦,重新登入不用再掃描。
- 可以在 App 裡刪除賬戶:點 Bots 分頁左上角的賬戶按鈕,再點「刪除賬戶」。
- 配對會確認賬戶:在別人賬戶裡的電腦會告訴你它在誰的賬戶;還不在任何賬戶的電腦,會先在電腦上問一聲,再加入你的賬戶。
- 也可以輸入 `codync-host pair` 印出的短代碼來配對,不用掃 QR code。
### en-US
- Codync now asks you to sign in with Apple, Google or GitHub. Computers you paired before come along, no new scan.
-- Signing out removes this phone from its computers and your account.
+- Signing out stops notifications and keeps your computers: sign back in, no scan.
- Delete your account in the app: account button (top left of Bots), then Delete account.
- Pairing checks your account: a computer in another account says whose; one in no account asks first, then joins yours.
- Or type the short code `codync-host pair` prints instead of scanning.
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
index 09ba4268..a949abce 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
@@ -108,7 +108,7 @@ class AccountScreenTest {
compose.setContent { Hosted { AccountSwitcherView(fixture(), viewModel()) {} } }
compose.onNodeWithText("Sign out").performClick()
compose.onNodeWithText("Sign out of ${first.email}?").assertIsDisplayed()
- compose.onNodeWithText("This phone forgets the account's computers. Your bots stay on them.").assertIsDisplayed()
+ compose.onNodeWithText("This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.").assertIsDisplayed()
compose.onNodeWithText("Cancel").performClick()
compose.onNodeWithText("Sign out of ${first.email}?").assertDoesNotExist()
compose.onNodeWithText(first.email).assertIsDisplayed()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
index 6a72d8c0..b14ca019 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt
@@ -26,8 +26,9 @@ internal fun AccountStore.signIn(provider: SignInProvider) = sessionAction {
fun AccountStore.switchAccount(account: SavedAccount) = sessionAction { NativeAccounts.switch(account) }
fun AccountStore.retryAccounts() { NativeAccounts.retry() }
/**
- * Clerk first, so a sign-out that fails keeps the key. Then this phone's key goes back ([handBack]) while the account's
- * stores are still open (the context switch waits for `transitions`), and the account is forgotten here.
+ * Clerk first, so a sign-out that fails changes nothing. This phone keeps the account's key, computers and drafts, so
+ * signing back in needs no scan or check; only its alerts stop: closing the account's computers unregisters them on each
+ * one connected (`AppStore.retire`), and the account tells the others (iOS `signOut`; connections.md, accounts on a phone).
*/
fun AccountStore.signOut() = sessionAction {
val old = state.value.account.accounts.firstOrNull { it.userId == state.value.account.userId } ?: return@sessionAction
@@ -37,8 +38,8 @@ fun AccountStore.signOut() = sessionAction {
val account = cloud?.pinningToken()
transitions.withLock {
NativeAccounts.signOut(old.sessionId)
- handBack(account)
- leave(old.userId)
+ account?.let { bestEffort("tell the account this phone signed out") { it.signOutThisDevice() } }
+ switchAway(old.userId)
}
}
@@ -53,31 +54,40 @@ fun AccountStore.deleteAccount() = sessionAction {
catch (error: CancellationException) { throw error }
catch (error: Exception) { throw IOException("Couldn't delete your account. Check your connection and try again.", error) }
handBack(null)
- leave(old)
+ forget(old)
}
}
/**
- * Hands this phone's key back as an account is left, before its data goes: every computer it's connected to drops it, and [account] (the
- * account's cloud) revokes the device with its grants and requests. Best effort with short timeouts: leaving never waits on them.
+ * Hands this phone's key back as an account is deleted or the phone starts over, before its data goes: every computer it's
+ * connected to drops it, and [account] (the account's cloud) revokes the device with its grants and requests. Best effort with
+ * short timeouts: leaving never waits on them.
*/
private suspend fun AccountStore.handBack(account: CloudClient?) = coroutineScope {
for (store in stores.value) launch { store.forgetDevice() }
- if (account != null) launch {
- withTimeoutOrNull(5_000) {
- try { account.revokeThisDevice() }
- catch (error: CancellationException) { throw error }
- catch (error: Exception) { android.util.Log.i("Codync", "Couldn't revoke this device in the account: ${error.message}") }
- }
+ if (account != null) launch { bestEffort("revoke this device in the account") { account.revokeThisDevice() } }
+}
+
+/** A cloud call made while leaving an account: five seconds at most, and a failure is only logged. */
+private suspend fun bestEffort(what: String, call: suspend () -> Unit) {
+ withTimeoutOrNull(5_000) {
+ try { call() }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { android.util.Log.i("Codync", "Couldn't $what: ${error.message}") }
}
}
-/** After signing out of [userId] or deleting it (under `transitions`): the next account or the welcome loads, and [userId]'s data here goes. */
-private suspend fun AccountStore.leave(userId: String) {
+/** After signing out of [userId] (under `transitions`): the next account or the welcome loads. */
+private suspend fun AccountStore.switchAway(userId: String) {
// The SDK updates its session synchronously; its observer may be queued behind us.
val next = com.clerk.api.Clerk.activeSession?.user?.id?.takeIf { it != userId }
retireContext()
loadContext(next)
+}
+
+/** After deleting [userId] (under `transitions`): as [switchAway], then [userId]'s data here goes. */
+private suspend fun AccountStore.forget(userId: String) {
+ switchAway(userId)
val remaining = com.clerk.api.Clerk.auth.sessions.any { it.user?.id == userId && it.status == com.clerk.api.session.Session.SessionStatus.ACTIVE }
if (!remaining) withContext(Dispatchers.IO) {
LocalStore(getApplication(), userId).erase()
@@ -248,7 +258,8 @@ fun AccountStore.taskNotifications(enabled: Boolean) = action("taskSettings") {
fun AccountStore.startOver() = sessionAction {
transitions.withLock {
- // The open account's computers and cloud drop this phone, as signing out does; its keys go regardless.
+ // The open account's computers and cloud drop this phone; every account's keys go regardless, those signed out
+ // here too (signing out keeps them).
handBack(cloud)
retireContext()
withContext(NonCancellable) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt
index c7d69e11..9ae4baa3 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt
@@ -92,7 +92,7 @@ import com.kyant.shapes.RoundedRectangle
}
}
CodyncDialog("Sign out of ${current?.email ?: "this account"}?", confirmSignOut, { confirmSignOut = false },
- "This phone forgets the account's computers. Your bots stay on them.") {
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.") {
listOf(DialogAction("Sign out", destructive = true, action = store::signOut))
}
CodyncDialog("Delete your Codync account?", confirmDelete, { confirmDelete = false },
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.kt
index 48ab0e3b..e236164c 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
@@ -117,7 +117,7 @@ class AppStore internal constructor(
}
/**
- * Leaving the account: the computer drops this device (`forgetDevice`; one older than that only stops its alerts).
+ * Deleting the account or starting over: the computer drops this device (`forgetDevice`; one older than that only stops its alerts).
* Best effort, three seconds at most: the key is erased right after, so a row left behind can't be used.
*/
internal suspend fun forgetDevice() {
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.kt
index 2f848af4..4fdf4b70 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
@@ -147,7 +147,15 @@ class CloudClient private constructor(base: String, private val identity: Device
}
}
- /** Signing out: this device leaves the account, and with it every grant and pending request (iOS `revokeThisDevice`). */
+ /**
+ * Signing out: this device keeps its key and access, but the account's computers stop its alerts until it registers
+ * again, signing back in (iOS `signOutThisDevice`).
+ */
+ suspend fun signOutThisDevice() {
+ request("POST", listOf("v1", "devices", "sign-out"), buildJsonObject { }, signed = true)
+ }
+
+ /** Starting over: this device leaves the account, and with it every grant and pending request (iOS `revokeThisDevice`). */
suspend fun revokeThisDevice() {
request("DELETE", listOf("v1", "devices", deviceId() ?: return))
}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
index 08a7ea76..d8049a52 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
@@ -219,4 +219,20 @@ class CloudClientTest {
assertEquals(null, client.pinningToken())
} finally { server.shutdown() }
}
+
+ @Test fun `signing out tells the account this device signed out, on the token taken before`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("{}"))
+ var signedIn = true
+ val client = CloudClient(server.url("/").toString(), identity, { check(signedIn); "session" }, OkHttpClient(), 1, Unit)
+ val pinned = requireNotNull(client.pinningToken())
+ signedIn = false
+ pinned.signOutThisDevice()
+ val request = server.takeRequest()
+ assertEquals(listOf("POST", "/v1/devices/sign-out", "Bearer session"), listOf(request.method, request.path, request.getHeader("Authorization")))
+ assertEquals(true, request.getHeader("Codync-Sig") != null)
+ } finally { server.shutdown() }
+ }
}
diff --git a/apps/ios/App/AppStore+Account.swift b/apps/ios/App/AppStore+Account.swift
index 2cd57b59..4aba2dd7 100644
--- a/apps/ios/App/AppStore+Account.swift
+++ b/apps/ios/App/AppStore+Account.swift
@@ -10,8 +10,9 @@ extension AppStore {
Analytics.shared.capture(.signedOutPairingsMoved(computers: adoption.computers, keys: adoption.keys))
}
- /// Signing out: Clerk first, so a sign-out that fails keeps the key. Then this iPhone's key goes back (the
- /// computers it reaches and the account drop it) and the account is forgotten here (spec §3.2).
+ /// Signing out: Clerk first, so a sign-out that fails changes nothing. This iPhone keeps the account's key,
+ /// computers and drafts, so signing back in needs no scan or check; only its alerts stop: the computers it reaches
+ /// drop them now, the others when the account tells them (connections.md, accounts on a phone).
func signOut() async {
guard let userID = account.userID else { return }
// Sent first so it still counts toward the account.
@@ -20,12 +21,14 @@ extension AppStore {
let cloud = await cloud?.pinningToken()
leaving = true
await account.signOut()
- if hasLeft(userID) { await handBack(cloud: cloud) }
- forget(userID)
+ if hasLeft(userID) {
+ await tell(computers: { try await $0.unregisterDevice() }, cloud: cloud, account: { try await $0.signOutThisDevice() })
+ }
+ finishLeaving()
}
/// Delete account: the user goes in Clerk first, and nothing changes when that fails. Then this iPhone leaves the
- /// computers it reaches and forgets the account, as signing out does. The cloud removes the account's devices,
+ /// computers it reaches and forgets the account. The cloud removes the account's devices,
/// grants and computers itself, on Clerk's `user.deleted`.
func deleteAccount() async {
guard let userID = account.userID else { return }
@@ -39,14 +42,18 @@ extension AppStore {
forget(userID)
}
- /// After leaving `userID`: the switch held off while `leaving` runs (a retiring store saves its cache one last
- /// time), then its device keys, computers and caches go, unless it's still signed in here.
+ /// After deleting `userID`: as `finishLeaving()`, then its device keys, computers and caches go, unless it's
+ /// still signed in here.
private func forget(_ userID: String) {
+ finishLeaving()
+ if hasLeft(userID) { SharedStore.Context(accountID: userID).erase() }
+ }
+
+ /// The switch held off while `leaving` runs (a retiring store saves its cache one last time); the last account
+ /// gone, the sign-in screen takes over.
+ private func finishLeaving() {
leaving = false
switchAccount(to: account.userID)
- guard hasLeft(userID) else { return }
- SharedStore.Context(accountID: userID).erase()
- // The last account gone: the sign-in screen takes over.
if !account.isSignedIn { account.showSwitcher = false }
}
@@ -54,15 +61,21 @@ extension AppStore {
account.userID != userID && !account.accounts.contains(where: { $0.id == userID })
}
- /// This iPhone's key goes back: each computer it's connected to removes it (older hosts only stop its alerts),
- /// and with `cloud` the account revokes it. Best effort, a few seconds at most: leaving never waits on an
- /// unreachable computer or cloud, and the key is erased right after.
+ /// This iPhone's key goes back (deleting the account, starting over): each computer it's connected to removes it
+ /// (older hosts only stop its alerts), and with `cloud` the account revokes it. The key is erased right after.
func handBack(cloud: CloudClient?) async {
+ await tell(computers: { try await $0.forgetDevice() }, cloud: cloud, account: { try await $0.revokeThisDevice() })
+ }
+
+ /// `computers` on each computer this iPhone is connected to, and `account` on `cloud`, at once. Best effort, a
+ /// few seconds at most: leaving never waits on an unreachable computer or cloud.
+ private func tell(computers: @escaping @Sendable (HostClient) async throws -> Void, cloud: CloudClient?,
+ account: @escaping @Sendable (CloudClient) async throws -> Void) async {
let clients = accounts.computers.compactMap { accounts.store(for: $0.id) }
.filter { $0.connection == .online }.compactMap(\.client)
await withTaskGroup(of: Void.self) { group in
- for client in clients { group.addTask { await Self.bestEffort(.seconds(3)) { try await client.forgetDevice() } } }
- if let cloud { group.addTask { await Self.bestEffort(.seconds(5)) { try await cloud.revokeThisDevice() } } }
+ for client in clients { group.addTask { await Self.bestEffort(.seconds(3)) { try await computers(client) } } }
+ if let cloud { group.addTask { await Self.bestEffort(.seconds(5)) { try await account(cloud) } } }
}
}
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index d90c0121..6fb46390 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -186,16 +186,15 @@ final class AppStore {
/// Settings → Start over: signs out of every account and forgets every computer, key and cache
/// on this iPhone, then shows the welcome again. The computers keep their bots and chats.
func startOver() async {
- let userIDs = account.accounts.map(\.id)
- // The open account's computers and cloud drop this iPhone, as signing out does; its keys go regardless.
+ // The open account's computers and cloud drop this iPhone; every account's keys go regardless, those signed
+ // out here too (signing out keeps them).
await handBack(cloud: cloud)
await account.signOutAll()
accounts.retire()
PushRegistrar.shared.deactivate()
LiveActivities.shared.endAll()
- for id in userIDs { SharedStore.Context(accountID: id).erase() }
+ SharedStore.eraseAll()
let storage = SharedStore.Context(accountID: nil)
- storage.erase()
storage.bots = []
SharedStore.activeAccountID = nil
UserDefaults.standard.set(false, forKey: "onboardingCompleted")
@@ -295,19 +294,8 @@ final class AppStore {
guard let store = accounts?.store(for: ref.computerId) else { return }
LiveActivities.shared.sent(ref, bot: bot, progress: progress, store: store)
}
- if let cloud {
- // Signed in: make this iPhone known to the account, then list its computers.
- Task { [weak accounts] in
- do {
- try await cloud.registerDevice(name: UIDevice.current.name, platform: "ios")
- } catch let error as CloudError where !error.isTransient {
- accounts?.lastError = error.localizedDescription
- } catch {
- // Transient (network, busy cloud, token not ready): the next launch registers again.
- }
- await accounts?.refreshCloud()
- }
- }
+ // Signed in: make this iPhone known to the account, then list its computers.
+ if cloud != nil { Task { [weak accounts] in await accounts?.refreshCloud() } }
return (accounts, cloud)
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
index 9873ec19..6a0f5c34 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
@@ -71,7 +71,14 @@ public struct CloudClient: Sendable {
return res.devices
}
- /// Signing out: this device leaves the account, and with it every grant and pending request.
+ /// Signing out: this device keeps its key and access, but the account's computers stop its alerts until it
+ /// registers again (signing back in).
+ public func signOutThisDevice() async throws {
+ guard identity != nil else { return }
+ try await send("POST", "v1/devices/sign-out", signed: true)
+ }
+
+ /// Start over: this device leaves the account, and with it every grant and pending request.
public func revokeThisDevice() async throws {
guard let device = try await thisDevice() else { return }
try await send("DELETE", "v1/devices/\(device.deviceId)")
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift b/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
index a9b99aa0..99fbb08e 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
@@ -34,12 +34,17 @@ public struct DeviceIdentity: Sendable {
return DeviceIdentity(signing: signing, push: push)
}
- /// Signing out or removing an account: hosts and the cloud can no longer tie anything to it.
+ /// Deleting an account: hosts and the cloud can no longer tie anything to it.
public static func delete(context: SharedStore.Context) {
Keychain.delete(service: deviceService, account: context.id)
Keychain.delete(service: pushService, account: context.id)
}
+ /// Start over: every account context's keys.
+ static func deleteAll() {
+ for service in [deviceService, pushService] { Keychain.deleteAll(service: service) }
+ }
+
/// Whether `context` has a device key yet (`load` creates one).
static func exists(context: SharedStore.Context) -> Bool {
(try? Keychain.read(service: deviceService, account: context.id)) != nil
@@ -178,6 +183,16 @@ enum Keychain {
#endif
SecItemDelete(query(service: service, account: account) as CFDictionary)
}
+
+ /// Every key of `service`, whichever account context holds it.
+ static func deleteAll(service: String) {
+ #if DEBUG
+ if memory.withLock({ $0 != nil }) { memory.withLock { $0 = $0?.filter { !$0.key.hasPrefix("\(service)/") } }; return }
+ #endif
+ var q = query(service: service, account: "")
+ q.removeValue(forKey: kSecAttrAccount)
+ SecItemDelete(q as CFDictionary)
+ }
}
protocol RawKey {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 25b24b43..1493bb02 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -347,13 +347,13 @@ public extension HostClient {
let _: Empty = try await call("registerDevice", Body(ticket: ticket, relay: relay, name: name, pushKey: pushKey, ctx: ctx))
}
- /// Stops this device's alerts; used when notifications are switched off in the app.
+ /// Stops this device's alerts: notifications switched off in the app, or the phone signed out.
func unregisterDevice() async throws {
let _: Empty = try await call("unregisterDevice")
}
- /// Removes this device from the computer (signing out): its access and alerts go. A computer
- /// older than `forgetDevice` only stops the alerts; the key is erased right after either way.
+ /// Removes this device from the computer (deleting the account, starting over): its access and alerts go.
+ /// A computer older than `forgetDevice` only stops the alerts; the key is erased right after either way.
func forgetDevice() async throws {
do {
let _: Empty = try await call("forgetDevice")
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
index 03570036..bb4c4cf9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
@@ -22,6 +22,18 @@ public enum SharedStore {
public static var activeContext: Context { Context(accountID: activeAccountID) }
+ /// Start over: every account context on this iPhone, those signed out here included (signing out keeps their keys
+ /// and computers so the same account comes back without a check), and the signed-out context.
+ public static func eraseAll(suite: String = appGroup) {
+ let defaults = Context(accountID: nil, suite: suite).defaults
+ for key in defaults.dictionaryRepresentation().keys where key.hasPrefix("account.") || Context.names.contains(key) {
+ defaults.removeObject(forKey: key)
+ }
+ DeviceIdentity.deleteAll()
+ do { try ActivityIconCache.eraseAll() } catch { log.error("Cannot erase activity icons: \(error.localizedDescription)") }
+ for file in Context.mirrorCaches(id: nil) { try? FileManager.default.removeItem(at: file) }
+ }
+
public struct Context: Sendable {
/// The raw Clerk user ID; nil = the local (signed-out) context.
public let accountID: String?
@@ -110,7 +122,8 @@ public enum SharedStore {
return BotReference(accountId: accountID, computerId: computer, botId: botId)
}
- /// Signing out or removing the account: device keys, computers, widget snapshot and caches go.
+ /// Deleting the account, or the signed-out context once adopted: device keys, computers, widget snapshot and
+ /// caches go.
public func erase() { erase(keeping: []) }
/// `erase()`, except for the mirror caches in `kept` (`adopt(from:)`).
@@ -119,14 +132,14 @@ public enum SharedStore {
DeviceIdentity.delete(context: self)
do { try ActivityIconCache.erase(context: id) }
catch { Logger(subsystem: "com.pokai.Codync", category: "CustomIcon").error("Cannot erase activity icons: \(error.localizedDescription)") }
- for file in mirrorCaches() where !kept.contains(file) { try? FileManager.default.removeItem(at: file) }
+ for file in Self.mirrorCaches(id: id) where !kept.contains(file) { try? FileManager.default.removeItem(at: file) }
}
- /// This context's mirror caches (`BotStore.saveCache`): `codync-mirror-<app>-<id>-<computer>.json`.
- fileprivate func mirrorCaches() -> [URL] {
+ /// Mirror caches (`BotStore.saveCache`), `codync-mirror-<app>-<id>-<computer>.json`: context `id`'s, or every one.
+ fileprivate static func mirrorCaches(id: String?) -> [URL] {
let caches = URL.cachesDirectory
return ((try? FileManager.default.contentsOfDirectory(atPath: caches.path())) ?? [])
- .filter { $0.hasPrefix("codync-mirror-") && $0.contains("-\(id)-") }
+ .filter { name in name.hasPrefix("codync-mirror-") && id.map { name.contains("-\($0)-") } ?? true }
.map { caches.appending(path: $0) }
}
}
@@ -171,7 +184,7 @@ public extension SharedStore.Context {
/// nothing loads them again (Start over removes them).
private func moveMirrorCaches(from local: Self) -> [URL] {
var unmoved: [URL] = []
- for file in local.mirrorCaches() {
+ for file in Self.mirrorCaches(id: local.id) {
let name = file.lastPathComponent
guard let marker = name.range(of: "-\(local.id)-") else { continue }
let moved = file.deletingLastPathComponent().appending(path: name.replacingCharacters(in: marker, with: "-\(id)-"))
diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift
index 3165381d..fa5db76d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift
@@ -12,6 +12,12 @@ public enum ActivityIconCache {
if !FileManager.default.fileExists(atPath: file.path) { try data.write(to: file, options: .atomic) }
}
+ /// Start over: every account's icons.
+ static func eraseAll() throws {
+ guard let root, FileManager.default.fileExists(atPath: root.path) else { return }
+ try FileManager.default.removeItem(at: root)
+ }
+
public static func erase(context: String) throws {
guard let directory = directory(context), FileManager.default.fileExists(atPath: directory.path) else { return }
try FileManager.default.removeItem(at: directory)
@@ -61,9 +67,12 @@ public enum ActivityIconCache {
return UIImage(contentsOfFile: directory.appendingPathComponent(filename).path)
}
- private static func directory(_ context: String) -> URL? {
+ private static var root: URL? {
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: SharedStore.appGroup)?
.appendingPathComponent("CustomIcons", isDirectory: true)
- .appendingPathComponent(SHA256.hash(data: Data(context.utf8)).map { String(format: "%02x", $0) }.joined(), isDirectory: true)
+ }
+
+ private static func directory(_ context: String) -> URL? {
+ root?.appendingPathComponent(SHA256.hash(data: Data(context.utf8)).map { String(format: "%02x", $0) }.joined(), isDirectory: true)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 67c0afc3..0a380aaf 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -295,7 +295,6 @@
"Text size": "Textgröße",
"This Mac": "Dieser Mac",
"This computer": "Dieser Computer",
- "This iPhone forgets the account's computers. Your bots stay on them.": "Dieses iPhone vergisst die Computer des Kontos. Deine Bots bleiben auf ihnen erhalten.",
"Through Cloudflare": "Über Cloudflare",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Auto: Wi-Fi oder Tailscale, dann privates Relay ({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "Privates Relay ({host}), dann Wi-Fi oder Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "Dieser Computer ist in einem anderen Konto",
"This computer isn't in an account: its cloud is off": "Dieser Computer ist in keinem Konto: seine Cloud ist aus",
"This computer isn't in an account: it uses a private relay": "Dieser Computer ist in keinem Konto: er nutzt ein privates Relay",
- "This computer isn't in your account": "Dieser Computer ist nicht in deinem Konto"
+ "This computer isn't in your account": "Dieser Computer ist nicht in deinem Konto",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses iPhone bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen.",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses Telefon bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index fd80d1b0..4e441239 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -295,7 +295,6 @@
"Text size": "Tamaño del texto",
"This Mac": "Este Mac",
"This computer": "Esta computadora",
- "This iPhone forgets the account's computers. Your bots stay on them.": "Este iPhone se olvida de los ordenadores de la cuenta. Tus robots permanecen en ellos.",
"Through Cloudflare": "A través de Cloudflare",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Automático: Wi-Fi o Tailscale, luego relé privado ({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "Relé privado ({host}), luego Wi-Fi o Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "Este ordenador está en otra cuenta",
"This computer isn't in an account: its cloud is off": "Este ordenador no está en ninguna cuenta: su nube está desactivada",
"This computer isn't in an account: it uses a private relay": "Este ordenador no está en ninguna cuenta: usa un relé privado",
- "This computer isn't in your account": "Este ordenador no está en tu cuenta"
+ "This computer isn't in your account": "Este ordenador no está en tu cuenta",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este iPhone deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes.",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este teléfono deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 0594c776..bfba10e0 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -295,7 +295,6 @@
"Text size": "Taille du texte",
"This Mac": "Ce Mac",
"This computer": "Cet ordinateur",
- "This iPhone forgets the account's computers. Your bots stay on them.": "Cet iPhone oublie les ordinateurs du compte. Vos bots restent sur ces ordinateurs.",
"Through Cloudflare": "Via Cloudflare",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Auto : Wi-Fi ou Tailscale, puis relais privé ({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "Relais privé ({host}), puis Wi-Fi ou Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "Cet ordinateur est dans un autre compte",
"This computer isn't in an account: its cloud is off": "Cet ordinateur n'est dans aucun compte : son cloud est désactivé",
"This computer isn't in an account: it uses a private relay": "Cet ordinateur n'est dans aucun compte : il utilise un relais privé",
- "This computer isn't in your account": "Cet ordinateur n'est pas dans votre compte"
+ "This computer isn't in your account": "Cet ordinateur n'est pas dans votre compte",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Cet iPhone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages.",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Ce téléphone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 516c3369..0d498141 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -295,7 +295,6 @@
"Text size": "文字サイズ",
"This Mac": "このMac",
"This computer": "このコンピュータ",
- "This iPhone forgets the account's computers. Your bots stay on them.": "この iPhone はアカウントのコンピュータを忘れます。ボットはそこに留まります。",
"Through Cloudflare": "Cloudflareを通じて",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自動: Wi-Fi または Tailscale、次にプライベートリレー({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "プライベートリレー({host})、次に Wi-Fi または Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "このコンピュータは別のアカウントにあります",
"This computer isn't in an account: its cloud is off": "このコンピュータはどのアカウントにもありません: クラウドがオフです",
"This computer isn't in an account: it uses a private relay": "このコンピュータはどのアカウントにもありません: プライベートリレーを使っています",
- "This computer isn't in your account": "このコンピュータはあなたのアカウントにありません"
+ "This computer isn't in your account": "このコンピュータはあなたのアカウントにありません",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "この iPhone はアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "このスマートフォンはアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 9775fc3e..2e474499 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -295,7 +295,6 @@
"Text size": "텍스트 크기",
"This Mac": "이 Mac",
"This computer": "이 컴퓨터",
- "This iPhone forgets the account's computers. Your bots stay on them.": "이 iPhone는 계정의 컴퓨터를 잊어버립니다. 당신의 봇은 그 위에 머물러 있습니다.",
"Through Cloudflare": "Cloudflare를 통해",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "자동: Wi-Fi 또는 Tailscale, 프라이빗 릴레이({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "프라이빗 릴레이({host}), 그 다음 Wi-Fi 또는 Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "이 컴퓨터는 다른 계정에 있습니다",
"This computer isn't in an account: its cloud is off": "이 컴퓨터는 어떤 계정에도 없습니다: 클라우드가 꺼져 있습니다",
"This computer isn't in an account: it uses a private relay": "이 컴퓨터는 어떤 계정에도 없습니다: 개인 릴레이를 사용합니다",
- "This computer isn't in your account": "이 컴퓨터는 내 계정에 없습니다"
+ "This computer isn't in your account": "이 컴퓨터는 내 계정에 없습니다",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 iPhone은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요.",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 휴대폰은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index d5429c26..7648b0c2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -295,7 +295,6 @@
"Text size": "文字大小",
"This Mac": "这台 Mac",
"This computer": "这台电脑",
- "This iPhone forgets the account's computers. Your bots stay on them.": "这台 iPhone 会忘掉账户里的电脑。Bot 仍留在那些电脑上。",
"Through Cloudflare": "经 Cloudflare",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自动:先 Wi-Fi 或 Tailscale,再私人中继({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "先私人中继({host}),再 Wi-Fi 或 Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "这台电脑在另一个账户里",
"This computer isn't in an account: its cloud is off": "这台电脑不在任何账户里:它的云端已关闭",
"This computer isn't in an account: it uses a private relay": "这台电脑不在任何账户里:它用私人中继",
- "This computer isn't in your account": "这台电脑不在你的账户里"
+ "This computer isn't in your account": "这台电脑不在你的账户里",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台 iPhone 不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台手机不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index 52435e59..14a82aee 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -295,7 +295,6 @@
"Text size": "文字大小",
"This Mac": "這臺 Mac",
"This computer": "這臺電腦",
- "This iPhone forgets the account's computers. Your bots stay on them.": "這臺 iPhone 會忘掉賬戶裡的電腦。Bot 仍留在那些電腦上。",
"Through Cloudflare": "經 Cloudflare",
"Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自動:先 Wi-Fi 或 Tailscale,再私人中繼({host})",
"Private relay ({host}), then Wi-Fi or Tailscale": "先私人中繼({host}),再 Wi-Fi 或 Tailscale",
@@ -1510,5 +1509,7 @@
"This computer is in another account": "這臺電腦在另一個賬戶裡",
"This computer isn't in an account: its cloud is off": "這臺電腦不在任何賬戶裡:它的雲端已關閉",
"This computer isn't in an account: it uses a private relay": "這臺電腦不在任何賬戶裡:它用私人中繼",
- "This computer isn't in your account": "這臺電腦不在你的賬戶裡"
+ "This computer isn't in your account": "這臺電腦不在你的賬戶裡",
+ "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這臺 iPhone 不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。",
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這支手機不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index 30422992..38bafe84 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -1,6 +1,7 @@
import CodyncKit
import Foundation
import Observation
+import UIKit
import os
private let log = Logger(subsystem: "com.pokai.Codync", category: "Account")
@@ -212,6 +213,9 @@ public final class AccountStore {
cloudListVersion += 1
let version = cloudListVersion
do {
+ // Every refresh, as on Android: signing back in clears the account's signed-out mark, or its computers
+ // drop this iPhone's push tickets again on their next state pull.
+ try await cloud.registerDevice(name: UIDevice.current.name, platform: "ios")
let list = try await cloud.computers()
guard !retired, version == cloudListVersion else { return }
if list != cloudComputers { Motion.animate { cloudComputers = list } }
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift
index 793ae355..80cc6f91 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift
@@ -44,4 +44,22 @@ private final class DevicesStub: URLProtocol {
#expect(DevicesStub.state.withLock { $0.calls } == ["GET /v1/devices Bearer token", "DELETE /v1/devices/this-phone Bearer token"])
#expect(await cloud.pinningToken() == nil, "signed out: no token to take")
}
+
+ @Test func signingOutTellsTheAccountOnTheTokenTakenBefore() async throws {
+ let config = URLSessionConfiguration.ephemeral
+ config.protocolClasses = [DevicesStub.self]
+ let identity = DeviceIdentity(signing: .init(), push: .init())
+ DevicesStub.state.withLock { $0 = (identity.publicKey, []) }
+ let signedIn = OSAllocatedUnfairLock(initialState: true)
+ let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: identity, session: URLSession(configuration: config)) {
+ guard signedIn.withLock({ $0 }) else { throw CloudError(status: 401, code: "signedOut") }
+ return "token"
+ }
+
+ let pinned = try #require(await cloud.pinningToken())
+ signedIn.withLock { $0 = false }
+ try await pinned.signOutThisDevice()
+
+ #expect(DevicesStub.state.withLock { $0.calls } == ["POST /v1/devices/sign-out Bearer token"], "the device stays in the account")
+ }
}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
index c9c25295..a9f639e7 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
@@ -85,4 +85,23 @@ import Testing
#expect(try Data(contentsOf: cache) == Data("unsent".utf8), "the only copy of those messages isn't deleted")
#expect(local.computers.isEmpty && !DeviceIdentity.exists(context: local))
}
+
+ @Test func startingOverErasesAccountsSignedOutHereToo() throws {
+ let (local, account, suite) = contexts()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let signedOutHere = SharedStore.Context(accountID: "user_\(UUID().uuidString)", suite: suite)
+ for context in [local, account, signedOutHere] {
+ _ = try DeviceIdentity.load(context: context)
+ context.computers = [v.computer]
+ }
+ let cache = URL.cachesDirectory.appending(path: "codync-mirror-tests-\(signedOutHere.id)-\(v.computer.id).json")
+ try Data("unsent".utf8).write(to: cache)
+
+ SharedStore.eraseAll(suite: suite)
+
+ for context in [local, account, signedOutHere] {
+ #expect(context.computers.isEmpty && !DeviceIdentity.exists(context: context))
+ }
+ #expect(!FileManager.default.fileExists(atPath: cache.path()))
+ }
}
diff --git a/apps/ios/NotificationService/NotificationService.swift b/apps/ios/NotificationService/NotificationService.swift
index 74ac337d..e9e29203 100644
--- a/apps/ios/NotificationService/NotificationService.swift
+++ b/apps/ios/NotificationService/NotificationService.swift
@@ -9,12 +9,14 @@ import os
final class NotificationService: UNNotificationServiceExtension {
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
let info = request.content.userInfo
+ let store = SharedStore.activeContext
guard let sealed = info["sealed"] as? String,
let computerId = info["computerId"] as? String,
- let ctx = info["ctx"] as? String,
- let alert = DeviceIdentity.openPush(sealed: sealed, computerId: computerId, contextID: ctx) else {
+ // Only the selected account's alerts open: one signed out here keeps its push key.
+ info["ctx"] as? String == store.id,
+ let alert = DeviceIdentity.openPush(sealed: sealed, computerId: computerId, contextID: store.id) else {
Logger(subsystem: "com.pokai.Codync.ios", category: "NotificationService")
- .error("Showing notification fallback: sealed content or shared key unavailable")
+ .error("Showing notification fallback: sealed content, shared key or selected account unavailable")
contentHandler(request.content)
return
}
@@ -25,16 +27,15 @@ final class NotificationService: UNNotificationServiceExtension {
content.title = alert.title
content.subtitle = alert.subtitle ?? ""
content.body = alert.body
- contentHandler(Self.fromBot(content, alert: alert, botId: info["botId"] as? String, computerId: computerId, ctx: ctx))
+ contentHandler(Self.fromBot(content, alert: alert, botId: info["botId"] as? String, computerId: computerId, store: store))
}
/// A communication notification shows the bot's face in place of the app icon; a group
/// message shows the group's face with the speaking member's on it. Faces come with the alert,
/// or (from an older host) from this account's snapshot; without either, or if the system
/// refuses, the plain notification stays.
- private static func fromBot(_ content: UNMutableNotificationContent, alert: PushAlert, botId: String?, computerId: String, ctx: String) -> UNNotificationContent {
- let store = SharedStore.activeContext
- let snapshot = store.id == ctx ? store.bots.filter { $0.computerId == computerId }.map(\.bot) : []
+ private static func fromBot(_ content: UNMutableNotificationContent, alert: PushAlert, botId: String?, computerId: String, store: SharedStore.Context) -> UNNotificationContent {
+ let snapshot = store.bots.filter { $0.computerId == computerId }.map(\.bot)
let bots = (alert.faces ?? []).map { face in
var face = face
face.customIcon = snapshot.first { $0.id == face.id }?.customIcon
diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swift
index fdd092e1..a55a6f82 100644
--- a/apps/ios/Views/AccountSwitcherView.swift
+++ b/apps/ios/Views/AccountSwitcherView.swift
@@ -96,7 +96,7 @@ struct AccountSwitcherView: View {
.onChange(of: account.userID) { _, _ in withAnimation(Motion.layout) { addingAccount = false } }
.codyncSheet(isPresented: $pairing) { PairingView(inModal: true) }
.codyncDialog("Sign out of \(account.email ?? "this account")?", isPresented: $confirmSignOut,
- message: "This iPhone forgets the account's computers. Your bots stay on them.") {
+ message: "This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.") {
[DialogAction("Sign out", destructive: true) { Task { await app.signOut() } }]
}
.codyncDialog("Delete your Codync account?", isPresented: $confirmDelete,
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 4f7fd649..c3288306 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -9,14 +9,14 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
## 2.36.0
### zh-Hant
- Codync 現在需要用 Apple、Google 或 GitHub 登入。以前沒登入就配對的電腦,第一次登入時會一起移進你的賬戶,不用再掃一次。
-- 登出時,這支手機會從它連得到的電腦和你的賬戶中移除。
+- 登出後,這支手機不再收到通知,但會保留它的電腦,重新登入不用再掃描。
- 可以在 App 裡刪除賬戶:點 Bots 分頁左上角的賬戶按鈕,再點「刪除賬戶」。
- 配對會確認賬戶:在別人賬戶裡的電腦會告訴你它在誰的賬戶;還不在任何賬戶的電腦,會先在電腦上問一聲,再加入你的賬戶。
- 也可以輸入 `codync-host pair` 印出的短代碼來配對,不用掃 QR code。
### en-US
- Codync now asks you to sign in with Apple, Google or GitHub. Computers you paired without signing in move into your account the first time you sign in, with no new scan.
-- Signing out now also removes this phone from the computers it can reach and from your account.
+- Signing out stops this phone's notifications and keeps its computers, so signing back in needs no scan.
- You can delete your account in the app: tap the account button at the top left of the Bots tab, then Delete account.
- Pairing checks your account: a computer in someone else's account tells you whose, and a computer in no account asks on the computer first, then joins your account.
- You can also type the short code `codync-host pair` prints instead of scanning the QR code.
diff --git a/cloud/README.md b/cloud/README.md
index c48edd36..f9d34162 100644
--- a/cloud/README.md
+++ b/cloud/README.md
@@ -55,7 +55,7 @@ Development deployment (see [environment readiness](../docs/guides/environments-
```bash
# Only if the database does not exist: npx wrangler d1 create codync-dev
# Confirm its database_id in [env.dev] before applying migrations.
-npx wrangler d1 migrations apply codync-dev --env dev --remote # includes 0005 (short pairing codes)
+npx wrangler d1 migrations apply codync-dev --env dev --remote # includes 0005 (short pairing codes), 0006 (signed-out devices)
npx wrangler secret put CLERK_SECRET_KEY --env dev
npx wrangler secret put CLERK_WEBHOOK_SECRET --env dev
# The device certificate key: without it phones can't pair (503 notConfigured).
diff --git a/cloud/migrations/0006_signed_out_devices.sql b/cloud/migrations/0006_signed_out_devices.sql
new file mode 100644
index 00000000..860dabd1
--- /dev/null
+++ b/cloud/migrations/0006_signed_out_devices.sql
@@ -0,0 +1,3 @@
+-- A phone that signed out keeps its key and its access, but its notifications stop: the account's computers drop
+-- its push tickets on their next state pull (`signedOut` in GET /v1/host/state). Registering it again clears this.
+ALTER TABLE devices ADD COLUMN signed_out_at INTEGER;
diff --git a/cloud/src/index.ts b/cloud/src/index.ts
index 172c4f38..a1560a43 100644
--- a/cloud/src/index.ts
+++ b/cloud/src/index.ts
@@ -61,6 +61,7 @@ const routes: [string, RegExp, Handler][] = [
["POST", /^\/v1\/devices$/, api.registerDevice],
["GET", /^\/v1\/devices$/, api.listDevices],
["POST", /^\/v1\/devices\/certificate$/, api.deviceCertificate],
+ ["POST", /^\/v1\/devices\/sign-out$/, api.signOutDevice],
["DELETE", new RegExp(`^/v1/devices/${ID}$`), api.revokeDevice],
["POST", /^\/v1\/claims$/, api.createClaim],
["POST", new RegExp(`^/v1/claims/${ID}/complete$`), api.completeClaim],
diff --git a/cloud/src/routes/account.ts b/cloud/src/routes/account.ts
index 35523d71..dac38e99 100644
--- a/cloud/src/routes/account.ts
+++ b/cloud/src/routes/account.ts
@@ -65,7 +65,8 @@ export async function registerDevice(c: Ctx) {
.first<DeviceRow>();
if (existing?.revoked_at) throw new ApiError("forbidden", "This device key was revoked; create a new one");
if (existing) {
- await c.env.DB.prepare("UPDATE devices SET name = ?, platform = ?, last_used_at = ? WHERE id = ?")
+ // Signing in again: its computers may push to it again.
+ await c.env.DB.prepare("UPDATE devices SET name = ?, platform = ?, last_used_at = ?, signed_out_at = NULL WHERE id = ?")
.bind(name, platform, c.now, existing.id)
.run();
return { device: deviceView({ ...existing, name, platform }) };
@@ -121,6 +122,19 @@ export async function deviceCertificate(c: Ctx) {
return { certificate };
}
+/** Signing out of a phone: it keeps its key and access, but the account's computers drop its push tickets on their
+ * next state pull, told to pull now. Registering the device again (signing back in) undoes it. */
+export async function signOutDevice(c: Ctx) {
+ const u = await user(c);
+ const d = await device(c, u.userId);
+ await c.env.DB.prepare("UPDATE devices SET signed_out_at = ? WHERE id = ?").bind(c.now, d.id).run();
+ const { results } = await c.env.DB.prepare("SELECT id FROM computers WHERE owner_user_id = ?")
+ .bind(u.userId)
+ .all<{ id: string }>();
+ await Promise.all(results.map((r) => notify(c.env, r.id)));
+ return {};
+}
+
export async function revokeDevice(c: Ctx, [deviceId]: string[]) {
const u = await user(c);
const d = await c.env.DB.prepare("SELECT id, revoked_at FROM devices WHERE id = ? AND owner_user_id = ?")
diff --git a/cloud/src/routes/host.ts b/cloud/src/routes/host.ts
index 64262e14..b718638f 100644
--- a/cloud/src/routes/host.ts
+++ b/cloud/src/routes/host.ts
@@ -134,8 +134,17 @@ export async function hostState(c: Ctx) {
created_at: number;
expires_at: number;
}>();
+ // The account's phones that signed out: the host drops their push tickets.
+ const signedOut = comp.owner_user_id
+ ? await c.env.DB.prepare(
+ "SELECT sign_pub FROM devices WHERE owner_user_id = ? AND signed_out_at IS NOT NULL AND revoked_at IS NULL",
+ )
+ .bind(comp.owner_user_id)
+ .all<{ sign_pub: string }>()
+ : { results: [] };
return {
owner: owner ? { userId: owner.user_id, email: owner.email } : null,
+ signedOut: signedOut.results.map((d) => d.sign_pub),
grants: grants.results.map((g) => ({
grantId: g.id,
deviceKey: g.sign_pub,
diff --git a/cloud/test/android.test.ts b/cloud/test/android.test.ts
index 4ead288e..9554dddd 100644
--- a/cloud/test/android.test.ts
+++ b/cloud/test/android.test.ts
@@ -34,7 +34,7 @@ describe("Android devices", () => {
]);
const tables = ["devices", "grants", "access_requests"];
const before = await Promise.all(tables.map(table => db.prepare(`SELECT * FROM ${table} ORDER BY id`).all()));
- await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(androidMigration));
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(androidMigration, androidMigration + 1));
const after = await Promise.all(tables.map(table => db.prepare(`SELECT * FROM ${table} ORDER BY id`).all()));
expect(after.map(result => result.results)).toEqual(before.map(result => result.results));
const old = await db.prepare("SELECT platform,created_at,last_used_at,revoked_at FROM devices ORDER BY platform").all();
diff --git a/cloud/test/api.test.ts b/cloud/test/api.test.ts
index 212fd191..5fba26e9 100644
--- a/cloud/test/api.test.ts
+++ b/cloud/test/api.test.ts
@@ -254,6 +254,29 @@ describe("devices", () => {
expect(r.status).toBe(401);
});
+ it("signs a device out: its account's computers drop its notifications until it registers again", async () => {
+ const u = await newUser();
+ const other = await newUser("other");
+ const host = await newHost();
+ const elsewhere = await newHost();
+ expect((await claim(u, host)).status).toBe(200);
+ expect((await claim(other, elsewhere)).status).toBe(200);
+ const signedOut = async (h: TestHost) => (await call("GET", "/v1/host/state", { key: h.sign })).body.signedOut;
+ expect(await signedOut(host)).toEqual([]);
+ const [hostWs, elsewhereWs] = await Promise.all([hostSocket(host), hostSocket(elsewhere)]);
+ expect((await call("POST", "/v1/devices/sign-out", { token: u.token, key: u.key })).status).toBe(200);
+ // The account's computers pull now, not at their next poll; another account's hear nothing.
+ await hostWs.nextT("cloud.changed");
+ await elsewhereWs.none((m) => m.t === "cloud.changed");
+ expect(await signedOut(host)).toEqual([u.dk]);
+ expect(await signedOut(elsewhere)).toEqual([]);
+ // Still in the account, so signing back in needs no new access: registering again clears it.
+ expect((await call("POST", "/v1/devices/certificate", { token: u.token, key: u.key })).status).toBe(200);
+ expect((await call("POST", "/v1/devices", { token: u.token, key: u.key, body: { name: "iPhone", platform: "ios" } })).status).toBe(200);
+ expect(await signedOut(host)).toEqual([]);
+ expect((await call("POST", "/v1/devices/sign-out", { token: u.token, key: ref.signKey() })).status).toBe(404);
+ });
+
it("hides other accounts' devices", async () => {
const a = await newUser();
const b = await newUser("b");
@@ -490,7 +513,7 @@ describe("revocation reaches the relay", () => {
await grantAccess(u, host);
expect((await call("POST", "/v1/host/unclaim", { key: host.sign, body: {} })).status).toBe(200);
const state = await call("GET", "/v1/host/state", { key: host.sign });
- expect(state.body).toEqual({ owner: null, grants: [], requests: [] });
+ expect(state.body).toEqual({ owner: null, grants: [], requests: [], signedOut: [] });
expect((await call("GET", "/v1/computers", { token: u.token })).body.computers).toEqual([]);
});
@@ -559,7 +582,7 @@ describe("Clerk webhook", () => {
const id = `msg_${ref.b64url(ref.random(8))}`;
expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
expect((await call("GET", "/v1/me", { token: u.token })).body.error.code).toBe("accountDeleted");
- expect((await call("GET", "/v1/host/state", { key: host.sign })).body).toEqual({ owner: null, grants: [], requests: [] });
+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body).toEqual({ owner: null, grants: [], requests: [], signedOut: [] });
expect((await deliver(id, { type: "user.deleted", data: { id: u.userId } })).status).toBe(200);
const n = await env.DB.prepare("SELECT COUNT(*) AS n FROM processed_events WHERE event_id = ?").bind(id).first<{ n: number }>();
expect(n?.n).toBe(1);
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index f871c820..b784d71f 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -40,7 +40,7 @@ The terminal UI and the CLI are the computer's own console, not apps in this sen
3. **One account per link.** A device may use a computer only when both are in the same account.
4. **A computer is in at most one account.** Changing accounts means leaving one and joining the other.
5. **Manage comes from the OS account.** Whoever sits at a computer can read `~/.codync/token`; Codync doesn't pretend to stop them. A managed computer keeps every setting of its own.
-6. **Signing out affects only that app.** It hands its key back (cloud grant revoked, push stopped, the device removed on computers it can reach) and erases that account's data on the device. The computer stays in its account; leaving takes **Remove from account**.
+6. **Signing out affects only that app.** A phone keeps its key, computers and drafts and only stops getting alerts, so signing back in needs no scan or check; **Start over** and **Delete account** hand the key back and erase the data ([accounts on a phone](#accounts-on-a-phone)). The computer stays in its account; leaving takes **Remove from account**.
## Pairing a phone
@@ -62,18 +62,19 @@ Decided 2026-11-02. A computer is in one account at most; a phone may know sever
| What happens | On the phone | Computers and cloud |
| --- | --- | --- |
| The Clerk session ends on its own (expired, revoked elsewhere) | The sign-in screen; the account's key, computers and drafts stay. Signing in to the same account connects as before: no scan, no 6-digit check | Unchanged |
-| **Sign out** | The key is handed back and the account's data erased | The computers it reaches drop the phone (`forgetDevice`), the cloud revokes the device, push stops |
-| Using another account | Only after signing out: both Clerk instances stay single-session (`single_session_mode`) | As signing out. Back on the first account, each computer takes a scan (same account, no question) or **Ask for access** with the 6-digit check |
+| **Sign out** | The key, computers and drafts stay; signing back in to the same account connects as before, no scan, no check | The phone stays a device. Its alerts stop: the computers it reaches drop its push tickets (`unregisterDevice`), the account marks it signed out (`POST /v1/devices/sign-out`) and the other computers drop them on their next state pull (`signedOut`). Registering again at sign-in clears the mark |
+| Using another account | Only after signing out: both Clerk instances stay single-session (`single_session_mode`) | As signing out: the first account's computers keep the phone, without alerts, until it comes back |
+| **Start over**, **Delete account** | Start over erases every account's keys and data, accounts signed out here included; Delete account erases that account's | The open account's computers drop the phone (`forgetDevice`), the cloud revokes it (Delete account: Clerk's webhook does) |
-Signing out hands the key back because it is the phone's one "this phone is done" button (selling, lending, someone else's account), and a key left behind keeps the computers pushing to it. Considered and not taken: a sign-out that keeps the key and only stops push, so the same account comes back without a check. The computers would keep listing a phone that left, and its key would stay on a phone that may have changed hands.
+Signing out is the everyday "not now", so it keeps the key (decided 2026-11-02). Handing the key back made a sign-out and sign-in cost every computer a new scan or a 6-digit check, which switching accounts in single-session mode turned into a regular cost. The price: a computer keeps listing a phone that signed out, until someone removes it there, and the key stays on the phone. **Start over** is the "this phone is done" button (selling, lending), and a lost phone is removed from the computer or another device. Start over hands back only the open account's key: accounts signed out here lose theirs on the phone only, and their computers keep listing it, so the sign-out dialog says to start over instead. A computer that never hears of the sign-out keeps pushing to the phone until it signs back in: one offline at the time with the Codync cloud off or on a private relay, a host older than 2.36.0, or any computer when the phone's call to the cloud failed (it isn't retried). The iPhone shows those alerts with the generic text only (it opens only the selected account's), Android drops them.
-**Multi-session stays off.** Turned on in Clerk, a phone would keep several accounts and switch without handing a key back. The apps already show the switcher and **Add account** then (iOS `authConfig.singleSessionMode`, Android `multiSessionModeIsEnabledFlow`), but no instance has run it. Before turning it on:
+**Multi-session stays off.** Turned on in Clerk, a phone would keep several accounts signed in and switch between them without signing out. The apps already show the switcher and **Add account** then (iOS `authConfig.singleSessionMode`, Android `multiSessionModeIsEnabledFlow`), but no instance has run it. Before turning it on:
-- **Only the selected account's notifications show, the same on iOS and Android.** Signed in to B, nothing from A's computers. Android already drops them (`PushService.receive`: `ctx` isn't the active account). iOS shows them, text included: the Notification Service Extension opens any account's push with that account's key, and an extension can't drop a visible notification without Apple's filtering entitlement (`com.apple.developer.usernotifications.filtering`). Get the entitlement and drop it there when `ctx` isn't the active context. Unregistering the old account's push tickets at each switch (`unregisterDevice`) would miss computers offline at that moment.
+- **Only the selected account's notifications show, the same on iOS and Android.** Signed in to B, nothing from A's computers. Android already drops them (`PushService.receive`: `ctx` isn't the active account). iOS shows them with the generic text: the Notification Service Extension opens only the active context's push (`ctx`), and an extension can't drop a visible notification without Apple's filtering entitlement (`com.apple.developer.usernotifications.filtering`). Get the entitlement and drop it there when `ctx` isn't the active context. Unregistering the old account's push tickets at each switch (`unregisterDevice`) would miss computers offline at that moment.
- Tapping another account's notification keeps doing nothing (iOS checks `ctx` in `userNotificationCenter(_:didReceive:)`); none should show anyway.
- End to end with two accounts on the iOS Simulator and the Android emulator: add one, switch, switch back without a check, notifications only from the selected one.
-**Open:** after a session ends on its own no account is selected, so Android drops that account's notifications while iOS still shows them with their text.
+**Open:** after a session ends on its own no account is selected, so Android drops that account's notifications while iOS still shows them, with the generic text.
## When the app and its computer disagree
@@ -156,7 +157,7 @@ Phases, file-level steps, tests and risks: [require sign-in](../plans/require-si
| Order | Change | Status |
| --- | --- | --- |
| 1 | Delete the account from inside the apps (App Store 5.1.1(v), Google Play). The cloud already cleans up on Clerk's `user.deleted` | Built (2.35.0) |
-| 2 | Sign-out hands the key back (iPhone, Android; the desktop revokes its cloud device) | Built (2.35.0) |
+| 2 | Sign-out stops the phone's alerts and keeps its key (the desktop revokes its cloud device); Start over and Delete account hand it back | Built (2.36.0) |
| 3 | Sign-in required in every app; the phone's signed-out pairings move into the account on first sign-in (with their device and push keys when the account context is new on that phone, otherwise a list to scan again). Builds without Clerk keep the signed-out context | Built (2.35.0) |
| 4 | Same-account QR: the cloud-signed account proof, the host recording each device's account, joining an unowned computer on first scan with a confirmation, short codes, the refusal message | Built (2.36.0) |
| 5 | Changing accounts drops every old-account device; the move dialog's text says so | Built (2.36.0); joining a first account keeps the phones paired before 2.36.0 |
diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md
index d2a014b7..ba7def5d 100644
--- a/docs/architecture/overview.md
+++ b/docs/architecture/overview.md
@@ -68,7 +68,7 @@ When a client needs data or behavior the host doesn't offer, add a host method o
- On iPhone, `AccountSession` owns Clerk integration; `AccountStore` owns one account context's computer stores.
- `BotReference(accountId, computerId, botId)` identifies a destination. Widgets and pushes carry account/computer scope.
- `BotStore` mirrors one computer and consumes a `HostTransport`: loopback or encrypted channel.
-- Account changes retire the old stores; late responses must not update the new context. Signing out erases that context's local credentials and caches.
+- Account changes retire the old stores; late responses must not update the new context. Signing out keeps that context (its key, computers and caches) and only stops its alerts; Start over and Delete account erase it.
- The desktop app (`apps/desktop/`) has its own TypeScript `BotStore` and attaches its local host and configured SSH hosts through loopback only ([desktop app](desktop-app.md)). iPhone connections use device identities.
Several computers per account are supported: the iPhone and Android apps pair several, with a heading per computer in the roster, Computer management for each, and each computer's push, usage and widgets; the desktop app attaches its local host and configured SSH hosts. Account-scoped aggregation and SSH build on the same structure (`AccountStore`, `BotReference`).
diff --git a/docs/features/custom-icons.md b/docs/features/custom-icons.md
index 15434199..3174fe5e 100644
--- a/docs/features/custom-icons.md
+++ b/docs/features/custom-icons.md
@@ -58,7 +58,7 @@ snapshot and removals clear the reference. No client renders arbitrary remote SV
## Live Activity and Dynamic Island
Custom images remain static. Built-in characters keep their existing animation mechanism.
-iOS stores content-addressed PNGs in an account-scoped App Group directory (erased on sign-out); ActivityKit carries only the filename.
+iOS stores content-addressed PNGs in an account-scoped App Group directory (kept on sign-out; erased by Start over or Delete account); ActivityKit carries only the filename.
A small per-computer/bot local pointer lets a running activity follow replacement/removal.
Local state revisions trigger redraws without putting image bytes into APNs payloads.
An offline activity keeps its last cached image until the app reconnects and receives the new snapshot.
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index d4ec5f07..8f0975c4 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -212,9 +212,11 @@ iPhone (`SharedStore.Context`). Computers paired with a code while signed out
with the device and push keys when that account's context is new on the phone,
otherwise as computers to pair again. Each account context gets its own
`AccountStore`, retired when changing accounts; once Clerk has signed out,
-signing out hands the device key back (`forgetDevice` on reachable computers,
-`DELETE /v1/devices/{id}` on a token taken before), then erases that account's
-computers, device and push keys and caches from the iPhone. **Delete account** deletes the Clerk user first, then does the same.
+signing out keeps the account's device key, computers and caches and only stops
+its alerts (`unregisterDevice` on reachable computers, `POST /v1/devices/sign-out`
+on a token taken before). **Start over** and **Delete account** (which deletes the
+Clerk user first) hand the key back (`forgetDevice`, the cloud revokes the device)
+and erase the data.
Signed in, the Computers screen also lists the account's computers from the cloud;
asking one for access shows the 6-digit code to compare on the computer.
diff --git a/docs/guides/composer.md b/docs/guides/composer.md
index 0ed0b857..6a25435b 100644
--- a/docs/guides/composer.md
+++ b/docs/guides/composer.md
@@ -58,8 +58,8 @@ text. Deleting a bot removes its drafts.
Desktop stores text in a versioned localStorage record per account context and
computer, independently of transcript caches. iOS uses its account-scoped
-SharedStore defaults with a separate map per computer. Signing out on iOS erases
-these values with the rest of the account data. Retired desktop/iOS stores cannot
+SharedStore defaults with a separate map per computer. Start over and Delete account on iOS erase
+these values with the rest of the account data; signing out keeps them. Retired desktop/iOS stores cannot
write late edits over a newly opened store.
The terminal saves text under `CODYNC_HOME` (normally `~/.codync`), in a private,
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index 68e7f46f..5bf59e08 100644
--- a/docs/plans/require-sign-in.md
+++ b/docs/plans/require-sign-in.md
@@ -37,24 +37,24 @@ App Store 5.1.1(v) and Google Play require in-app deletion for any app that crea
- iOS: `clerk.user.delete()` (ClerkKit `User.delete()`).
- Android: `User.delete()` from `com.clerk.api.user`.
- Desktop: FAPI `DELETE /v1/me`, through `apps/desktop/src/main/account.ts`.
- 2. Hand the key back to the computers this phone reaches, as signing out does (section 2). The account's stores stay open until then, even though Clerk has already ended the session (`AppStore.leaving` on iOS). The cloud side needs no call: the webhook revokes every device.
- 3. Erase this account's local data, the same as signing out.
+ 2. Hand the key back to the computers this phone reaches, as Start over does (section 2). The account's stores stay open until then, even though Clerk has already ended the session (`AppStore.leaving` on iOS). The cloud side needs no call: the webhook revokes every device.
+ 3. Erase this account's local data.
- **Cloud: no change.** Clerk's `user.deleted` webhook already revokes every grant, cancels pending requests, removes the account's computers from it and deletes their icons (`cloud/src/routes/webhooks.ts`).
- **Clerk setting:** "users can delete themselves" (`user_settings.actions.delete_self`) is on in the development instance. Check it is on in production before the release.
- **Google Play** also wants a web address for deletion requests: add `codync.dev/delete-account`, listing the in-app steps and a contact address.
-### 2. Sign-out hands the key back (iPhone, Android)
+### 2. Sign-out stops the alerts and keeps the key (iPhone, Android)
-Today iPhone erases only local data, and Android tells only the computer it is connected to. New order, in `AppStore.signOut()` (iOS) and `AccountStore.signOut()` (Android):
+Built in 2.35.0 as handing the key back; changed before release (2026-11-02) to keep it, so signing back in needs no scan or check ([accounts on a phone](../architecture/connections.md#accounts-on-a-phone)). In `AppStore.signOut()` (iOS) and `AccountStore.signOut()` (Android):
-1. **Clerk:** sign out first. When that fails the phone stays signed in and keeps its key, so nothing below runs. The cloud call below needs a session token, so one is taken before (`CloudClient.pinningToken()`); it stays valid until it expires. The account's stores stay open until the steps below finish (`AppStore.leaving` on iOS, `transitions` on Android).
-2. **Computers this phone can reach:** call the new host method `forgetDevice`. It removes the caller's own device row and push tickets.
- - Hosts older than this release answer "unknown method"; then call `unregisterDevice`, which stops the push tickets only.
- - The device key is erased right after, so a row left on an older host is unusable.
-3. **Cloud:** `DELETE /v1/devices/{id}` for this phone's own device. Find the id the way `CloudClient.revokeDeviceAccess` already does. This revokes every grant and pending request, and hosts drop the device on their next sync. Add `CloudClient.revokeThisDevice()` and its Android twin.
-4. Switch context and erase (as today).
+1. **Clerk:** sign out first. When that fails nothing below runs. The cloud call below needs a session token, so one is taken before (`CloudClient.pinningToken()`); it stays valid until it expires. The account's stores stay open until the steps below finish (`AppStore.leaving` on iOS, `transitions` on Android).
+2. **Computers this phone can reach:** `unregisterDevice` drops its push tickets (Android: closing each computer's store does it, `AppStore.retire`). The device stays.
+3. **Cloud:** `POST /v1/devices/sign-out` (Clerk + `Codync-Sig`) marks the device signed out and tells the account's computers to pull their state, whose `signedOut` lists it: each drops its push tickets. `POST /v1/devices`, which the phone sends with every refresh of the account's computers (opening the account, coming back to the foreground), clears the mark, so a failed one is retried. `CloudClient.signOutThisDevice()` and its Android twin.
+4. Switch context. The account's key, computers and drafts stay on the phone.
-The two calls are best effort, with a short timeout each. Signing out never fails because a computer or the cloud is unreachable. **Start over** hands the open account's key back the same way before it erases everything.
+The two calls are best effort, with a short timeout each. Signing out never fails because a computer or the cloud is unreachable.
+
+**Start over** and **Delete account** still hand the key back: `forgetDevice` on the computers the phone reaches (it removes the caller's device row and push tickets; hosts older than it answer "unknown method", then `unregisterDevice`), the cloud revokes the device (`DELETE /v1/devices/{id}`, `CloudClient.revokeThisDevice()`; for Delete account, Clerk's webhook), and the data goes. Start over erases every account on the phone, those signed out here included (iOS `SharedStore.eraseAll()`, Android `LocalStore.eraseAll`).
**Host (`host/src/api/remote.rs`):** `forgetDevice` is for a device caller only. It removes `caller.device_key()` from devices and push tickets. It sends no event: a desktop showing the device list sees the change the next time the list loads. It is additive, so `minApp` doesn't change.
@@ -152,7 +152,7 @@ After either case the signed-out context is erased (on iOS except a mirror cache
| Fresh install | The welcome shows only sign-in. Signing in leads to pairing, and a QR pair works |
| Upgrade | With the previous build signed out, pair by QR. Install this build: the gate counts the computer. Sign in: the computer is there and connects without scanning, and push still arrives |
| Merge case | Unit tests only: with sign-in required, a phone can't pair signed out any more, so this only happens to someone who was signed in on an older build and had also paired signed out (the older builds can't take the test sign-in ticket) |
-| Sign out | The computer's device list drops the phone, and the cloud lists the device as revoked |
+| Sign out | The computer keeps the phone but has no push ticket for it; the cloud's host state lists it in `signedOut`. Sign back in: it connects without a scan and registers push again |
| Delete account | The test user is gone in Clerk, and the computers leave the account (`--prune` cleans up) |
| Desktop | Signed out shows the welcome with no skip. Sign out returns to it. Signed in to a second test account, the footer notice shows and reopens the move choice |
@@ -197,7 +197,7 @@ After either case the signed-out context is erased (on iOS except a mirror cache
Phase 2 and 3 need these once per cloud, before the hosts that ask for them ship (the cloud is deployed by hand):
1. `DEVICE_CERT_KEY`: `grep '^CODYNC_DEVICE_CERT_KEY=' .env.development | cut -d= -f2- | npx wrangler secret put DEVICE_CERT_KEY --env dev` from `cloud/` (and the same from `.env.production` without `--env` for main).
-2. The pairing codes table: `npx wrangler d1 migrations apply codync-dev --env dev --remote` (main: `codync`).
+2. The pairing codes table and the signed-out mark (migrations `0005`, `0006`): `npx wrangler d1 migrations apply codync-dev --env dev --remote` (main: `codync`).
3. `npm run deploy:dev`, then `npm run deploy:main` right after the release merges.
## Later
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 9bcf87ec..2ae476ee 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -88,7 +88,7 @@ See [architecture](../architecture/overview.md) and [file structure](../architec
- 桌面 App(`apps/desktop/src/main/cloud.ts`):每個帳號一把 Ed25519 device key,seed 以 Electron `safeStorage`(OS keychain)加密後存在 app 的 userData 目錄;只用於雲端 `/v1` API 的 `Codync-Sig`。
- iOS App、Widgets、NotificationService 共用 access group `$(AppIdentifierPrefix)com.pokai.Codync`(`project.yml` 對這三個 target 加 `keychain-access-groups` entitlement;`CodyncKit` 從 Info.plist `CodyncKeychainGroup` 讀 group,缺值則不設 group)。
- 私鑰永不離開 Keychain/process;雲端只存公鑰。
-- 帳號登出/移除帳號:先在 Clerk 登出(失敗就保留金鑰、維持登入),成功後才交還金鑰(連得到的電腦呼叫 `forgetDevice`,舊版 host 改呼叫 `unregisterDevice`;雲端 `DELETE /v1/devices/{id}`,用登出前先取的 session token),各自最多數秒、失敗不擋登出,再刪除該 context 的 device key、computers 快取、mailbox 草稿、widget snapshot。刪除帳號則先在 Clerk 刪除使用者,成功後才交還給電腦,雲端那側由 `user.deleted` webhook 處理。
+- 帳號登出:先在 Clerk 登出(失敗就什麼都不變)。成功後只停通知、保留金鑰:連得到的電腦呼叫 `unregisterDevice` 刪掉 push tickets;雲端 `POST /v1/devices/sign-out`(用登出前先取的 session token)標記這台裝置已登出,帳號的其他電腦下次拉 `/v1/host/state` 時依 `signedOut` 刪掉它的 push tickets。各自最多數秒、失敗不擋登出。該 context 的 device key、computers、草稿都留著,同一帳號登回來直接連上(`POST /v1/devices` 清掉標記)。**Start over**/刪除帳號才交還金鑰:連得到的電腦呼叫 `forgetDevice`(舊版 host 改呼叫 `unregisterDevice`),雲端 `DELETE /v1/devices/{id}`(刪除帳號由 `user.deleted` webhook 處理),再刪除 device key、computers 快取、mailbox 草稿、widget snapshot;Start over 連這支手機上登出過的帳號一起刪。刪除帳號先在 Clerk 刪除使用者,成功後才交還給電腦。
- 有 Clerk 的 build 一律要求登入([require sign-in](../plans/require-sign-in.md)):`local` context 只留給沒有 Clerk 的 build,以及登入前遷移的來源。某個帳號 context 第一次使用時,若 `local` 有電腦或金鑰:該 context 在這支手機上是新的(沒有金鑰、沒有電腦)就整包搬過去,金鑰一起搬,電腦不用重新掃;已有自己的金鑰就只合併電腦清單,那些電腦會顯示需要重新配對。之後清掉 `local`(iOS `SharedStore.Context.adopt(from:)`、Android `LocalStore.adopt`)。
### 3.3 Per-(device, host) E2E 金鑰
@@ -106,7 +106,8 @@ See [architecture](../architecture/overview.md) and [file structure](../architec
| 動作 | 效果 |
|---|---|
-| 裝置自己登出(`forgetDevice`,只能移除呼叫者自己) | 與在電腦上撤銷相同;帳號來源的 grant 一併撤銷 |
+| 裝置自己離開(Start over/刪除帳號:`forgetDevice`,只能移除呼叫者自己) | 與在電腦上撤銷相同;帳號來源的 grant 一併撤銷 |
+| 裝置登出(`unregisterDevice` + `POST /v1/devices/sign-out`) | 不撤權:只刪 push tickets,裝置列與 grant 都留著 |
| 在電腦上撤銷裝置(桌面 App/`codync-host devices revoke`) | host 刪除裝置列與其 push tickets、Live Activity tickets → 立即關閉該裝置所有 channel → 發佈新 ACL → DO 關閉其 WebSocket;帳號來源的另呼叫 `DELETE` 對應 grant(見 §8.4 `POST /v1/host/grants/{id}/revoke`) |
| 雲端撤銷 grant/裝置/解除綁定/刪帳號 | Worker 寫 D1 → 呼叫 DO `/internal/block`(`[{dk, grantId}]`,立即關閉並封鎖)→ DO 通知 host `cloud.changed` → host 拉 `/v1/host/state` 並刪除裝置列 |
| host 連不到雲端 | 帳號來源裝置的 lease 最長 15 分鐘後失效,host 關閉 channel;本機(QR)來源裝置不受影響 |
@@ -497,6 +498,7 @@ The route table below summarizes the contract. Executable schema and validation
- `POST /v1/host/pairing-codes`(Sig(host))`{"link","expiresAt"}` → `{"code":"QRTX-4821","expiresAt"}`;`GET /v1/pairing-codes/{code}`(Clerk)→ `{"link"}`,只能用一次、10 分鐘。`codync-host pair` 的短代碼。
- `GET /v1/devices` → `{"devices":[{"deviceId","deviceKey","name","platform","createdAt","lastUsedAt","revoked":bool}]}`
- `DELETE /v1/devices/{deviceId}` → `{}`;撤銷裝置與其所有 grants(`deviceRevoked`),對相關 computers 呼叫 DO `/internal/block` + `cloud.changed`。
+- `POST /v1/devices/sign-out`(Clerk + Sig(dev))→ `{}`:手機登出。設 `devices.signed_out_at`(migration `0006`),對帳號的每台電腦送 `cloud.changed`;不撤權。同一把 key 再 `POST /v1/devices`(登回來)就清掉。
- `POST /v1/claims` → `{"claimId","nonce","expiresAt"}`(nonce = 16 random bytes b64url)
- `POST /v1/claims/{claimId}/complete` `{"computerId","signKey","boxKey","name","platform","device","version","sig"}` → `{"computer":<Computer>}`。驗:`computerId == derive(signKey)`、sig(§4.2 A,輸入含 `boxKey`)、claim 有效;computer 列不存在時一併建立,`box_pub` 一律取自簽過的 `boxKey`。
- `GET /v1/computers`(Clerk,選配 Sig(dev))→ `{"computers":[Computer]}`,
@@ -516,9 +518,10 @@ The route table below summarizes the contract. Executable schema and validation
```json
{"owner":{"userId":"user_…","email":"[email protected]"} | null,
"grants":[{"grantId","deviceKey","deviceName","platform","scopes":["control","screen"]}],
- "requests":[{"requestId","deviceKey","deviceName","platform","email","commit","hostNonce"?,"deviceNonce"?,"createdAt","expiresAt"}]}
+ "requests":[{"requestId","deviceKey","deviceName","platform","email","commit","hostNonce"?,"deviceNonce"?,"createdAt","expiresAt"}],
+ "signedOut":["<deviceKey>"]}
```
- grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。
+ grants 只含:grant active、device 未撤銷、device.owner == computer.owner。host 只把它當成「可續約/應刪除」的清單(§4.3)。`signedOut` 是電腦所屬帳號裡登出的裝置(未撤銷),host 刪掉它們的 push tickets,不動裝置列。
- `POST /v1/host/access-requests/{id}/nonce` `{"nonce"}` → `{}`(`cloud/src/routes/host.ts`;已設過 → `409`)
- `POST /v1/host/grants/{grantId}/revoke` `{}` → `{}`(host 在本機撤銷帳號來源裝置時同步 D1,`revoked_reason='owner'`;失敗記錄並存入 `grant_revokes` 重試,本機撤銷已生效)
- `POST /v1/host/access-requests/{id}/decision` `{"decision":"approve"|"deny"}` → `{"status","grantId"?}`(`cloud/src/routes/host.ts` 的原子更新;request 過期 → `410 requestExpired`;approve 要求 `device_nonce IS NOT NULL`,否則 `409`)
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index 8f49affd..21c61b9c 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -80,7 +80,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
json!({"devices": devices})
}
"revokeDevice" => revoke(hub, str_arg(&b, "key")?)?,
- // A device leaving on its own (signing out): the same as revoking it at the computer.
+ // A device leaving on its own (deleting the account, starting over): the same as revoking it at the computer.
"forgetDevice" => revoke(hub, caller.device_key())?,
"accessRequests" => json!({"requests": hub.cloud.requests_json()}),
"pairingRequests" => json!({"requests": hub.pairing_requests.json()}),
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index d5b99397..d76ee0e9 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -301,6 +301,9 @@ struct State {
grants: Vec<Grant>,
#[serde(default)]
requests: Vec<StateRequest>,
+ /// The account's phones that signed out: they keep their access, but get no alerts until they sign back in.
+ #[serde(default)]
+ signed_out: Vec<String>,
}
#[derive(Deserialize)]
@@ -338,6 +341,9 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {
let state: State = serde_json::from_value(call(hub, base, Method::GET, "/v1/host/state", None).await?)
.context("reading the cloud state")?;
apply_grants(hub, &state.grants)?;
+ for device in &state.signed_out {
+ hub.store.remove_push_tickets(device)?;
+ }
super::owner::remember(hub, state.owner.as_ref())?;
let in_account = state.owner.is_some();
// A pull that works also settles an earlier failed one.
@@ -802,6 +808,20 @@ mod tests {
assert_eq!(hub.cloud.status().last_error, None, "Settings stops showing a relay error that's gone");
}
+ #[tokio::test]
+ async fn a_phone_that_signed_out_gets_no_more_alerts() {
+ let hub = temp_hub();
+ let fake = Arc::new(FakeCloud::default());
+ let base = fake_cloud(fake.clone()).await;
+ hub.store.add_push_ticket("t1", "signed out", None, Some("ctx"), "iPhone").unwrap();
+ hub.store.add_push_ticket("t2", "still in", None, Some("ctx"), "Pixel").unwrap();
+ *fake.state.lock().unwrap() =
+ json!({"owner": {"userId": "user_1"}, "grants": [], "requests": [], "signedOut": ["signed out"]});
+ pull(&hub, &base).await.unwrap();
+ let tickets: Vec<String> = hub.store.push_tickets().into_iter().map(|t| t.ticket).collect();
+ assert_eq!(tickets, ["t2"]);
+ }
+
#[tokio::test]
async fn leaving_the_account_turns_cloud_assistants_off_and_the_check_on() {
let hub = temp_hub();
diff --git a/host/src/store/devices.rs b/host/src/store/devices.rs
index ddabed26..93869ccd 100644
--- a/host/src/store/devices.rs
+++ b/host/src/store/devices.rs
@@ -180,7 +180,7 @@ impl Store {
Ok(())
}
- /// Stops alerts to a device (its notification switch is off); Live Activity tickets stay.
+ /// Stops alerts to a device (its notification switch is off, or it signed out); Live Activity tickets stay.
pub fn remove_push_tickets(&self, device_key: &str) -> Result<()> {
let c = self.db.locked();
c.execute("DELETE FROM push_tickets WHERE device_key = ?1", [device_key])?;
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index 1dae4552..2e1c0148 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -55,7 +55,7 @@ When the computer and the desktop app's account differ, an amber notice at the b
- **This computer is in *[email protected]*'s account:** click it to be asked again whether to move the computer here.
- **This computer isn't in an account: its cloud is off**, **…: it uses a private relay**, or **This computer isn't in your account** (you took it out): click it to open **Settings → Computers**, where **Add to account** puts it in yours.
-Signing out of a phone takes that phone off the computers it can reach and out of your account, and it forgets them. Sign in and pair again to come back. Computers a phone paired before sign-in was required come along: the first sign-in moves them into the account, with no new scan.
+Signing out of a phone stops its notifications from your computers, and it keeps them: sign back in with the same account and it connects again, with no scan. To take the phone off your computers, for example before giving it away, use **Start over** on the **Settings** tab instead of signing out. Computers a phone paired before sign-in was required come along: the first sign-in moves them into the account, with no new scan.
## Deleting your account