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: require sign-in in every app

leepokaib833b1051922
diff --git a/README.md b/README.md
index 63c915de..cf10f562 100644
--- a/README.md
+++ b/README.md
@@ -201,7 +201,7 @@ Data lives in `~/.codync`. The local bearer token authorizes loopback helpers an
**Where does my data go?** Bots, chats and memory stay on your computer. The phone reaches it directly on the same network, or through an end-to-end encrypted relay that can't read your messages.
-**Do I need an account?** No. Pair your phone by scanning a QR code. Signing in with Apple or Google is optional.
+**Do I need an account?** Yes, a free one: the apps ask you to sign in with Apple or Google. An account alone never unlocks a computer: you still pair by scanning a QR code, or approve a 6-digit code on the computer.
**Which computers can run it?** A Mac, a Windows PC, or a Linux desktop or headless server. The iPhone app and the terminal UI over SSH talk to the same host.
diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxproj
index dc9ad2bc..86e4b6eb 100644
--- a/apps/Codync.xcodeproj/project.pbxproj
+++ b/apps/Codync.xcodeproj/project.pbxproj
@@ -11,6 +11,7 @@
0137767F43A65AB592869ADD /* ShortcutLeadSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6ABB70475ABEE88EFAFBA1BB /* ShortcutLeadSettings.swift */; };
01A1F820EFEE49A8FCCFC3F3 /* BotListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0582B6169BFC36E4BCD51C0D /* BotListView.swift */; };
0631979397E0D6822747E03A /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6E13F8EA6C7B0DA4D899FEE /* RootView.swift */; };
+ 0C0673CAE7FE759E7F549C7C /* AppStore+Account.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A792AA5A57EFCD63F254BB8 /* AppStore+Account.swift */; };
0C920E4962F182ADF75670C5 /* CodyncBot-tablet-Ink.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 120FD9DBA315A6DD543463D8 /* CodyncBot-tablet-Ink.ttf */; };
0D6E2869DC5A1BC7D6385444 /* CodyncOrb-Dot.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 0C44BCF971511A5E94D073D5 /* CodyncOrb-Dot.ttf */; };
107232310A15C4D9A3BCF466 /* AppStore+Shortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = C518FF3FFD22C3A114B6D1B8 /* AppStore+Shortcuts.swift */; };
@@ -148,6 +149,7 @@
445DB0A03CFBB5CC7A830139 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
46538A6E6E6B7C5E212F5CDF /* SessionCandidates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionCandidates.swift; sourceTree = "<group>"; };
4815867922559696EDCA47FD /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 4A792AA5A57EFCD63F254BB8 /* AppStore+Account.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppStore+Account.swift"; sourceTree = "<group>"; };
4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSwitcherView.swift; sourceTree = "<group>"; };
4FA78A055791BBBA79DF8C8B /* Permissions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Permissions.swift; sourceTree = "<group>"; };
52A96030D47F1B9678095909 /* iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iOS.entitlements; sourceTree = "<group>"; };
@@ -436,6 +438,7 @@
isa = PBXGroup;
children = (
31BFDAD6DCCE1CC98642ACDD /* AccountSession.swift */,
+ 4A792AA5A57EFCD63F254BB8 /* AppStore+Account.swift */,
C518FF3FFD22C3A114B6D1B8 /* AppStore+Shortcuts.swift */,
300202AE0BDAB4961D1E4423 /* BotShortcuts.swift */,
A65FE0504B741D0B44DB2516 /* CodyncApp.swift */,
@@ -723,6 +726,7 @@
7E5F670CFFA0E4373F44DB41 /* AccountSession.swift in Sources */,
9BBB2FAEDBD35A83EAB02981 /* AccountSwitcherView.swift in Sources */,
00F78E3DAAF66E8E0933D091 /* ActivityGalleryView.swift in Sources */,
+ 0C0673CAE7FE759E7F549C7C /* AppStore+Account.swift in Sources */,
107232310A15C4D9A3BCF466 /* AppStore+Shortcuts.swift in Sources */,
16C24A622E33414C24B0C148 /* AppearanceSettings.swift in Sources */,
01A1F820EFEE49A8FCCFC3F3 /* BotListView.swift in Sources */,
@@ -846,7 +850,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.34.2;
+ MARKETING_VERSION = 2.35.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -944,7 +948,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.34.2;
+ MARKETING_VERSION = 2.35.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -1203,7 +1207,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.34.2;
+ MARKETING_VERSION = 2.35.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -1353,7 +1357,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
MACOSX_DEPLOYMENT_TARGET = 14.0;
- MARKETING_VERSION = 2.34.2;
+ MARKETING_VERSION = 2.35.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index b6af3444..2613a2e0 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -7,9 +7,13 @@ released version's section; a version without one gets the PRs' "What's New: And
else a generic "Bug fixes and improvements" line. Delete old sections.
-->
-## 2.34.2
+## 2.35.0
### zh-Hant
-- 有很多 Docker 或虛擬機網路的電腦,現在也能配對與連線,不會再顯示配對碼已損毀。
+- Codync 現在需要用 Apple 或 Google 登入。以前沒登入就配對的電腦,第一次登入時會一起移進你的賬戶,不用再掃一次。
+- 登出時,這支手機會從它連得到的電腦和你的賬戶中移除。
+- 可以在 App 裡刪除賬戶:點 Bots 分頁左上角的賬戶按鈕,再點「刪除賬戶」。
### en-US
-- Computers with many Docker or virtual machine networks now pair and connect, instead of reporting a damaged pairing code.
+- Codync now asks you to sign in with Apple or Google. 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.
+- You can delete your account in the app: tap the account button at the top left of the Bots tab, then Delete account.
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 1443997c..74ac2368 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
@@ -50,6 +50,8 @@ class AccountScreenTest {
val signOut = compose.onNodeWithText("Sign out").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
assertTrue(scan.bottom < identity.top)
assertTrue(identity.bottom < signOut.top)
+ val delete = compose.onNodeWithText("Delete account").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(signOut.bottom <= delete.top)
compose.onNodeWithContentDescription(first.email).assertIsSelected().assertIsNotEnabled()
compose.onNodeWithContentDescription(second.email).assertIsNotSelected().assertIsEnabled()
compose.onNodeWithContentDescription("Add account").assertIsDisplayed()
@@ -89,6 +91,7 @@ class AccountScreenTest {
assertEquals(apple.right, google.right, 1f)
compose.onNodeWithText("Other sign-in options").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Sign out").assertDoesNotExist()
+ compose.onNodeWithText("Delete account").assertDoesNotExist()
compose.runOnUiThread { state.value = state.value.copy(account = state.value.account.copy(ready = false, error = "Couldn't restore sign-in.")) }
compose.onNodeWithText("Continue with Apple").assertIsNotEnabled()
compose.onNodeWithText("Continue with Google").assertIsNotEnabled()
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt
index 16307dd0..a58df914 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt
@@ -2,7 +2,9 @@ package com.codync.android
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.Computer
import com.codync.android.core.DeviceIdentity
+import com.codync.android.core.RelayCrypto
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
@@ -10,6 +12,7 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@@ -31,6 +34,48 @@ class LocalStoreTest {
} finally { store.erase() }
}
+ /** A computer whose id matches its key, as saved computers must. */
+ private fun computer(seed: Int, name: String): Computer {
+ val key = DeviceIdentity(ByteArray(32) { seed.toByte() }, ByteArray(32)).publicKey
+ return Computer(RelayCrypto.computerId(java.util.Base64.getUrlDecoder().decode(key)), name, key)
+ }
+
+ @Test fun aNewAccountTakesTheSignedOutKeysAndComputers() {
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val scope = "test-${java.util.UUID.randomUUID()}"
+ val signedOut = LocalStore(context, "$scope-local")
+ val account = LocalStore(context, scope)
+ try {
+ val identity = signedOut.identity()
+ signedOut.saveComputers(listOf(computer(1, "Mac mini")))
+ signedOut.saveLastComputer("last")
+ assertEquals(LocalStore.Adoption(1, MovedKeys.Moved), account.adopt(signedOut))
+ assertEquals(identity.publicKey, account.identity().publicKey)
+ assertEquals(listOf("Mac mini"), account.computers().map { it.name })
+ assertEquals("last", account.lastComputer())
+ assertFalse(signedOut.hasIdentity())
+ assertTrue(signedOut.computers().isEmpty())
+ assertNull("nothing left to move", account.adopt(signedOut))
+ } finally { signedOut.erase(); account.erase() }
+ }
+
+ @Test fun anAccountInUseKeepsItsKeyAndMergesTheComputers() {
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val scope = "test-${java.util.UUID.randomUUID()}"
+ val signedOut = LocalStore(context, "$scope-local")
+ val account = LocalStore(context, scope)
+ try {
+ val own = account.identity()
+ account.saveComputers(listOf(computer(1, "Account copy")))
+ signedOut.identity()
+ signedOut.saveComputers(listOf(computer(1, "Signed-out copy"), computer(2, "Linux box")))
+ assertEquals(LocalStore.Adoption(2, MovedKeys.Rescan), account.adopt(signedOut))
+ assertEquals(own.publicKey, account.identity().publicKey)
+ assertEquals(listOf("Account copy", "Linux box"), account.computers().map { it.name })
+ assertFalse(signedOut.hasIdentity())
+ } finally { signedOut.erase(); account.erase() }
+ }
+
@Test fun theShortcutsLeadIsSavedPerAccountAndAutomaticIsNone() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val store = LocalStore(context, "test-${java.util.UUID.randomUUID()}")
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
index d3653f7b..2e03015a 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
@@ -3,6 +3,7 @@ package com.codync.android
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.lifecycle.viewmodel.compose.viewModel
+import com.codync.android.core.Computer
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
@@ -11,10 +12,23 @@ import org.junit.Test
class OnboardingTest {
@get:Rule val compose = createComposeRule()
+ @Test fun signedOutWithAccountsTheWelcomeOnlySignsInAndCountsTheWaitingComputers() {
+ compose.mainClock.autoAdvance = false
+ val signedOut = AccountContext(loading = false, account = AccountState(ready = true, configured = true),
+ computers = listOf(Computer("waiting-computer-000001", "Mac mini", "fixture-key"), Computer("waiting-computer-000002", "Linux", "fixture-key")))
+ compose.setContent { Hosted { CodyncApp(signedOut, emptyMap(), viewModel()) } }
+ step()
+ compose.onNodeWithText("Continue with Apple").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Continue with Google").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Sign in to keep using your 2 computers", substring = true).performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Get started").assertDoesNotExist()
+ }
+
@Test fun welcomeLeadsToInstallAndBackReturnsToWelcome() {
// The welcome crew never stops moving: step the clock by hand so the test can settle.
compose.mainClock.autoAdvance = false
- compose.setContent { Hosted { CodyncApp(AccountContext(loading = false), emptyMap(), viewModel()) } }
+ // Only builds without accounts pair signed out.
+ compose.setContent { Hosted { CodyncApp(AccountContext(loading = false, account = AccountState(ready = true, configured = false)), emptyMap(), viewModel()) } }
step()
compose.onNodeWithText("Your coding agents", substring = true).assertIsDisplayed()
compose.onNodeWithText("Get started").performClick()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
index 81764b69..69027080 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
@@ -55,14 +55,14 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
NativeAccounts.observe(viewModelScope) { account ->
mutableState.update { it.copy(account = account) }
if (account.ready) transitions.withLock {
- // Read the latest state after a concurrent logout/reset finishes.
- val current = state.value.account
- val desired = current.userId ?: "local"
- if (desired != local.contextId) {
+ // Clerk's account now, not this (maybe older) update: a sign-out or deletion that held the lock
+ // already left that account, and loading it again would bring its data back.
+ val userId = NativeAccounts.activeUserId()
+ if ((userId ?: "local") != local.contextId) {
retireContext()
- loadContext(current.userId)
- } else if (cloud == null && current.userId != null) {
- configureCloud(current.userId)
+ loadContext(userId)
+ } else if (cloud == null && userId != null) {
+ configureCloud(userId)
refreshCloud()
}
}
@@ -76,6 +76,7 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
try {
WidgetRefreshWorker.stop(getApplication())
local = LocalStore(getApplication(), userId ?: "local")
+ if (userId != null) adoptSignedOut()
widgetOwner = withContext(Dispatchers.IO) { WidgetStore.activate(getApplication(), local.contextId) }
PushDelivery.activate(getApplication(), userId)
val computers = withContext(Dispatchers.IO) { local.computers() }
@@ -84,7 +85,7 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
val lead = withContext(Dispatchers.IO) { local.shortcutLead() }
mutableState.update { AccountContext(contextId = local.referenceId, generation = it.generation + 1, account = it.account,
computers = computers, lastComputerId = last, shortcutLeadComputer = lead, tasks = PushPreferences.tasks(getApplication()),
- setupComplete = complete || computers.isNotEmpty() || userId != null) }
+ setupComplete = complete || computers.isNotEmpty()) }
// A computer that can't open (damaged drafts) is reported; the others, the cloud and the widgets go on.
for (computer in computers) try { open(computer) }
catch (error: CancellationException) { throw error }
@@ -100,6 +101,21 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
catch (error: Exception) { showError(error) }
}
+ /**
+ * Sign-in is required: the signed-out context's pairings move into this account (`LocalStore.adopt`), with their
+ * device keys when the account is new on this phone. A failure leaves them where they are; the account still opens.
+ */
+ private suspend fun adoptSignedOut() {
+ try {
+ val adopted = withContext(Dispatchers.IO) {
+ val signedOut = LocalStore(getApplication(), "local")
+ local.adopt(signedOut)?.also { AccountImages.cacheDir(getApplication(), signedOut.referenceId).deleteRecursively() }
+ } ?: return
+ if (adopted.computers > 0) Analytics.capture(AnalyticsEvent.SignedOutPairingsMoved(adopted.computers, adopted.keys))
+ } catch (error: CancellationException) { throw error }
+ catch (error: Exception) { android.util.Log.w("Codync", "Couldn't move the signed-out pairings", error) }
+ }
+
private suspend fun configureCloud(userId: String) {
val identity = withContext(Dispatchers.IO) { local.identity() }
cloud = CloudClient(BuildConfig.CLOUD_URL, identity) { NativeAccounts.token(userId) }
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 1a4d166a..40a1e939 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
@@ -25,31 +25,77 @@ 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.
+ */
fun AccountStore.signOut() = sessionAction {
val old = state.value.account.accounts.firstOrNull { it.userId == state.value.account.userId } ?: return@sessionAction
// Sent first so it still counts toward the account.
Analytics.capture(AnalyticsEvent.SignedOut)
- NativeAccounts.signOut(old.sessionId)
+ // The cloud call goes out after Clerk signed out, on a token taken now (it outlives the session).
+ val account = cloud?.pinningToken()
transitions.withLock {
- // The SDK updates its session synchronously; its observer may be queued behind us.
- val userId = com.clerk.api.Clerk.activeSession?.user?.id
- retireContext()
- loadContext(userId)
- val remaining = com.clerk.api.Clerk.auth.sessions.any { it.user?.id == old.userId && it.status == com.clerk.api.session.Session.SessionStatus.ACTIVE }
- if (!remaining) withContext(Dispatchers.IO) {
- LocalStore(getApplication(), old.userId).erase()
- File(getApplication<Application>().cacheDir, "codync-images-${LocalStore.referenceId(old.userId)}").deleteRecursively()
+ NativeAccounts.signOut(old.sessionId)
+ handBack(account)
+ leave(old.userId)
+ }
+}
+
+/**
+ * Deletes the signed-in account (App Store and Google Play require it in the app). Clerk goes first, so a failure changes
+ * nothing; the cloud cleans up on Clerk's `user.deleted`. The context switch waits for the computers to drop this phone.
+ */
+fun AccountStore.deleteAccount() = sessionAction {
+ val old = state.value.account.userId ?: return@sessionAction
+ transitions.withLock {
+ try { NativeAccounts.deleteUser() }
+ 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)
+ }
+}
+
+/**
+ * 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.
+ */
+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}") }
}
}
}
+/** 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) {
+ // 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)
+ 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()
+ AccountImages.cacheDir(getApplication(), LocalStore.referenceId(userId)).deleteRecursively()
+ }
+}
+
fun AccountStore.refreshCloud() = action("cloud") {
val client = cloud ?: return@action
try {
client.registerDevice(Build.MODEL.take(100))
val computers = client.computers()
mutableState.update { it.copy(cloudComputers = computers) }
- // Signed in to an account with computers, before pairing any (iOS: the same moment).
+ // Signed in to an account with computers, before pairing any (iOS: the same moment): setup is done.
+ if (computers.isNotEmpty() && !state.value.setupComplete) {
+ withContext(Dispatchers.IO) { local.completeSetup() }
+ mutableState.update { it.copy(setupComplete = true) }
+ }
if (computers.isNotEmpty() && state.value.computers.isEmpty()) Analytics.completeOnboarding(OnboardingVia.Account)
} catch (error: IOException) {
if (error is CloudError && !error.isTransient) throw error
@@ -202,6 +248,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.
+ handBack(cloud)
retireContext()
withContext(NonCancellable) {
NativeAccounts.reset()
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 590ad34b..c7d69e11 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
@@ -48,6 +48,7 @@ import com.kyant.shapes.RoundedRectangle
val current = account.accounts.firstOrNull { it.userId == account.userId }
val busy = "session" in state.busy
var confirmSignOut by remember { mutableStateOf(false) }
+ var confirmDelete by remember { mutableStateOf(false) }
var addingAccount by remember { mutableStateOf(false) }
LaunchedEffect(account.userId) { addingAccount = false }
Column(Modifier.fillMaxSize().background(Palette.background)) {
@@ -83,6 +84,9 @@ import com.kyant.shapes.RoundedRectangle
RowLabel("Sign out", "rectangle.portrait.and.arrow.right", Palette.danger,
modifier = Modifier.plainButton(enabled = !busy) { confirmSignOut = true })
}
+ row {
+ RowLabel("Delete account", "trash", Palette.danger, modifier = Modifier.plainButton(enabled = !busy) { confirmDelete = true })
+ }
}
account.error?.let { IconLabel(it, "exclamationmark.triangle.fill", Palette.danger) }
}
@@ -91,6 +95,10 @@ import com.kyant.shapes.RoundedRectangle
"This phone forgets the account's computers. Your bots stay on them.") {
listOf(DialogAction("Sign out", destructive = true, action = store::signOut))
}
+ CodyncDialog("Delete your Codync account?", confirmDelete, { confirmDelete = false },
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.") {
+ listOf(DialogAction("Delete account", destructive = true, action = store::deleteAccount))
+ }
}
/** Every account on this phone as a face; tap one to switch, + to add another. */
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
index 619f9250..6cd4d600 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
@@ -42,6 +42,10 @@ internal sealed class AnalyticsEvent(val name: String) {
override val properties get() = mapOf("provider" to provider.json)
}
data object SignedOut : AnalyticsEvent("signed_out")
+ /** Signing in took the signed-out pairings ([MovedKeys]). */
+ data class SignedOutPairingsMoved(val computers: Int, val keys: MovedKeys) : AnalyticsEvent("signed_out_pairings_moved") {
+ override val properties get() = mapOf("computers" to JsonPrimitive(computers), "keys" to keys.json)
+ }
data class PairingFailed(val reason: PairingFailure) : AnalyticsEvent("pairing_failed") {
override val properties get() = mapOf("reason" to reason.json)
}
@@ -107,6 +111,9 @@ internal enum class OnboardingVia(override val wire: String) : CatalogValue { Pa
internal enum class SignInProvider(override val wire: String) : CatalogValue { Apple("apple"), Google("google"), Hosted("hosted") }
+/** The signed-out pairings' keys at sign-in: [Moved] with them, or listed to be scanned again ([Rescan]). */
+internal enum class MovedKeys(override val wire: String) : CatalogValue { Moved("moved"), Rescan("rescan") }
+
internal enum class SignInFailure(override val wire: String) : CatalogValue {
Cancelled("cancelled"), Timeout("timeout"), Verification("verification"), Error("error")
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
index 04c6efdd..48ab0e3b 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
@@ -116,6 +116,19 @@ class AppStore internal constructor(
withContext(Dispatchers.IO) { feed.clear(); database?.close(); database = null }
}
+ /**
+ * Leaving the account: 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() {
+ val ready = channel?.takeIf { it.state.value is LinkState.Ready } ?: return
+ withTimeoutOrNull(3_000) {
+ for (method in listOf("forgetDevice", "unregisterDevice")) try { ready.call(method); return@withTimeoutOrNull }
+ catch (error: CancellationException) { throw error }
+ catch (_: Exception) { }
+ }
+ }
+
/** Saves the computer's latest copy (`changeComputer`), then shows it. */
internal suspend fun save(computer: Computer) {
saveComputer(computer)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index 93bb442e..578202c7 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -80,10 +80,12 @@ private data class Editing<T>(val computerId: String, val draft: T)
}
}
val signedIn = app.account.userId != null
- // Signed in, setup counts as complete (`loadContext`): the account's computers are asked for access from Computers.
+ // Every build with accounts requires sign-in (iOS `mustSignIn`); only builds without them pair signed out.
+ val required = app.account.configured
val onboarding = !app.setupComplete && app.computers.isEmpty() && app.cloudComputers.isEmpty()
val root = when {
- app.loading -> Root.Loading
+ app.loading || app.account.restoring -> Root.Loading
+ required && !signedIn -> Root.Welcome
onboarding && !welcomed && !signedIn -> Root.Welcome
onboarding -> Root.Pairing
else -> Root.Tabs
@@ -106,7 +108,8 @@ private data class Editing<T>(val computerId: String, val draft: T)
}, label = "Root") { shown ->
when (shown) {
Root.Loading -> Box(Modifier.fillMaxSize())
- Root.Welcome -> WelcomeView(app, accounts) { welcomed = true }
+ // Computers paired before sign-in was required wait in the signed-out context; signing in moves them.
+ Root.Welcome -> WelcomeView(app, accounts, signedOutComputers = if (required) app.computers.size else 0) { welcomed = true }
Root.Pairing -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {
PairingView(app, accounts, onSkip = accounts::skipSetup) {
if (signedIn) AccountSwitcherButton(app) { showAccount = true } else BackButton { welcomed = false }
@@ -122,7 +125,7 @@ private data class Editing<T>(val computerId: String, val draft: T)
}
}
}
- CodyncSheet(showAccount && (app.setupComplete || signedIn) && !app.loading, { showAccount = false }) {
+ CodyncSheet(showAccount && (signedIn || (!required && app.setupComplete)) && !app.loading, { showAccount = false }) {
AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Account))
AccountSwitcherView(app, accounts) { showPairing = true }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt
index 29954384..913d8881 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt
@@ -27,28 +27,69 @@ class LocalStore(context: Context, val contextId: String = "local") {
@Synchronized
fun identity(): DeviceIdentity {
- val file = AtomicFile(File(directory, "identity"))
- val seeds = if (file.baseFile.exists()) {
- val sealed = file.readFully()
- require(sealed.size == 12 + 64 + 16) { "Device identity is damaged. Start over to pair again." }
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- cipher.init(Cipher.DECRYPT_MODE, wrappingKey(), GCMParameterSpec(128, sealed.copyOf(12)))
- cipher.updateAAD(scopeId.toByteArray())
- cipher.doFinal(sealed.copyOfRange(12, sealed.size))
- } else {
- val fresh = ByteArray(64).also(SecureRandom()::nextBytes)
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- cipher.init(Cipher.ENCRYPT_MODE, wrappingKey())
- cipher.updateAAD(scopeId.toByteArray())
- write(file, cipher.iv + cipher.doFinal(fresh))
- fresh
- }
+ val seeds = openSeeds() ?: ByteArray(64).also(SecureRandom()::nextBytes).also(::sealSeeds)
try {
require(seeds.size == 64)
return DeviceIdentity(seeds.copyOfRange(0, 32), seeds.copyOfRange(32, 64))
} finally { seeds.fill(0) }
}
+ /** The device's key seeds, opened with this scope's Keystore key; null before the first [identity]. */
+ private fun openSeeds(): ByteArray? {
+ val file = AtomicFile(File(directory, "identity"))
+ if (!file.baseFile.exists()) return null
+ val sealed = file.readFully()
+ require(sealed.size == 12 + 64 + 16) { "Device identity is damaged. Start over to pair again." }
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, wrappingKey(), GCMParameterSpec(128, sealed.copyOf(12)))
+ cipher.updateAAD(scopeId.toByteArray())
+ return cipher.doFinal(sealed.copyOfRange(12, sealed.size))
+ }
+
+ private fun sealSeeds(seeds: ByteArray) {
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, wrappingKey())
+ cipher.updateAAD(scopeId.toByteArray())
+ write(AtomicFile(File(directory, "identity")), cipher.iv + cipher.doFinal(seeds))
+ }
+
+ /** What [adopt] did: how many computers came over, and whether the device keys came with them. */
+ internal data class Adoption(val computers: Int, val keys: MovedKeys)
+
+ /**
+ * Sign-in is required: [from] (the signed-out context) moves into this account context, then is erased (iOS
+ * `SharedStore.Context.adopt(from:)`). New here (no identity, no computers), this context takes everything, its device
+ * keys too (sealed again under this scope), so computers keep seeing the same device. Otherwise, or when that move
+ * fails, only the computer list merges (this context's entry wins), and those computers ask to be paired again. Null
+ * when there was nothing to move; a failure to merge leaves [from] as it was. Run before this context's stores and identity load.
+ */
+ @Synchronized
+ internal fun adopt(from: LocalStore): Adoption? {
+ val moving = from.computers()
+ if (moving.isEmpty() && !from.hasIdentity()) return null
+ val own = computers()
+ val keys = if (!hasIdentity() && own.isEmpty() && takeAll(from)) MovedKeys.Moved else {
+ val known = own.map { it.id }.toSet()
+ saveComputers(own + moving.filter { it.id !in known })
+ MovedKeys.Rescan
+ }
+ from.erase()
+ return Adoption(moving.size, keys)
+ }
+
+ /** [from]'s device keys and files, for [adopt]; false when they couldn't move (the computers merge instead). */
+ private fun takeAll(from: LocalStore): Boolean = try {
+ from.openSeeds()?.let { seeds -> try { sealSeeds(seeds) } finally { seeds.fill(0) } }
+ // Not the sealed identity or AtomicFile's leftovers of it: only [sealSeeds] writes this scope's.
+ for (file in from.directory.listFiles().orEmpty().filter { !it.name.startsWith("identity") }) {
+ file.copyRecursively(File(directory, file.name), overwrite = true)
+ }
+ true
+ } catch (error: Exception) {
+ android.util.Log.w("Codync", "Couldn't move the signed-out device key", error)
+ false
+ }
+
private fun wrappingKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val existing = keyStore.getKey(alias, null) as? SecretKey
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
index a7968006..2f42bdf1 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
@@ -95,7 +95,9 @@ class MainActivity : ComponentActivity() {
}
}
CodyncTheme(dark = dark) { OverlayRoot { CodyncApp(state, computers, accounts)
- LaunchLayer(state.loading, state.computers.all { computers[it.id]?.widgetBotsCurrent == true }) } }
+ // Held while sign-in restores too: signed out, the app is only the welcome.
+ LaunchLayer(state.loading || state.account.restoring,
+ state.computers.all { computers[it.id]?.widgetBotsCurrent == true }) } }
}
}
}
@@ -155,11 +157,13 @@ internal object AccountImages {
@Synchronized fun open(context: android.content.Context, id: String): ImageLoader {
retire()
val images = ImageLoader.Builder(context).diskCache {
- DiskCache.Builder().directory(File(context.cacheDir, "codync-images-$id").toOkioPath()).maxSizeBytes(64L * 1024 * 1024).build()
+ DiskCache.Builder().directory(cacheDir(context, id).toOkioPath()).maxSizeBytes(64L * 1024 * 1024).build()
}.build()
current = images
return images
}
@Synchronized fun close(images: ImageLoader) { images.shutdown(); if (current === images) current = null }
@Synchronized fun retire() { current?.shutdown(); current = null }
+ /** Where a context's images are cached ([referenceId]: `LocalStore.referenceId`). */
+ fun cacheDir(context: android.content.Context, referenceId: String) = File(context.cacheDir, "codync-images-$referenceId")
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt
index a99acb9d..331ebcda 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt
@@ -10,6 +10,7 @@ import com.clerk.api.network.serialization.errorMessage
import com.clerk.api.session.Session
import com.clerk.api.sso.OAuthProvider
import com.clerk.api.sso.SSOCancellationException
+import com.clerk.api.user.delete
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -27,7 +28,10 @@ internal class SignInError(val reason: SignInFailure, message: String, cause: Th
data class SavedAccount(val userId: String, val sessionId: String, val email: String, val avatar: String?)
data class AccountState(val ready: Boolean = false, val configured: Boolean = NativeAccounts.configured,
val userId: String? = null, val accounts: List<SavedAccount> = emptyList(),
- val multiple: Boolean = false, val error: String? = null)
+ val multiple: Boolean = false, val error: String? = null) {
+ /** Clerk is still restoring the saved sign-in: the launch layer and the root wait, rather than show the welcome. */
+ val restoring: Boolean get() = configured && !ready && error == null
+}
/** Clerk owns browser authentication, encrypted credentials and session restoration. */
object NativeAccounts {
@@ -114,6 +118,12 @@ object NativeAccounts {
requireSuccess(result)
}
+ /** Deletes the signed-in user; Clerk's `user.deleted` then takes the account's computers and devices off the cloud. */
+ suspend fun deleteUser() {
+ val user = requireNotNull(Clerk.activeUser) { "Sign in again to delete your account." }
+ requireSuccess(user.delete())
+ }
+
suspend fun reset() {
if (!configured) return
// The all-session API clears the SDK's local credentials even when the network is down.
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt
index 6a276f79..6e149e00 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt
@@ -53,8 +53,12 @@ import com.kyant.shapes.RoundedRectangle
import kotlinx.coroutines.delay
import kotlin.math.sin
-/** First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward (iOS `WelcomeView`). */
-@Composable internal fun WelcomeView(state: AccountContext, store: AccountStore, start: () -> Unit) {
+/**
+ * Before any setup, and whenever signed out: who the bots are, a glimpse of talking to one, one way forward (iOS `WelcomeView`).
+ * With accounts that way is signing in; builds without them go on to pairing. [signedOutComputers] were paired before
+ * sign-in was required and move into the account at sign-in.
+ */
+@Composable internal fun WelcomeView(state: AccountContext, store: AccountStore, signedOutComputers: Int = 0, start: () -> Unit) {
AnalyticsOnAppear(AnalyticsEvent.OnboardingStepViewed(OnboardingStep.Welcome))
val still = reduceMotion()
// 0 = nothing yet … 4 = everything shown. Each beat enters in turn.
@@ -80,9 +84,12 @@ import kotlin.math.sin
}
}
Column(Modifier.padding(top = 32.dp).rise(beat >= 4), verticalArrangement = Arrangement.spacedBy(10.dp)) {
- WideButton("Get started", action = start)
- // Signed in, the computers on the account show up without scanning a code.
- if (state.account.configured) SignInButtons(state, store)
+ if (signedOutComputers > 0) Text(if (signedOutComputers == 1)
+ tr("Sign in to keep using your computer. It moves into your account, so you won't need to scan again.")
+ else tr("Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.")
+ .replace("{count}", signedOutComputers.toString()),
+ Modifier.fillMaxWidth().padding(bottom = 4.dp), style = Type.footnote, color = Palette.secondary)
+ if (state.account.configured) SignInButtons(state, store) else WideButton("Get started", action = start)
state.account.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
}
}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
index 06ed8bda..c9ac3a4b 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
@@ -25,6 +25,8 @@ class AnalyticsTest {
assertEquals("""{"setting":"live_activities","on":false}""", json(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, false)))
assertEquals("""{"via":"link","computer":"fbfcd4f4fe9f876c"}""", json(AnalyticsEvent.ComputerPaired(PairedVia.Link, "tZ1WMzsVltt-fj7mUDwZsg")))
assertEquals("{}", json(AnalyticsEvent.SignedOut))
+ assertEquals("""{"computers":2,"keys":"moved"}""", json(AnalyticsEvent.SignedOutPairingsMoved(2, MovedKeys.Moved)))
+ assertEquals("""{"computers":1,"keys":"rescan"}""", json(AnalyticsEvent.SignedOutPairingsMoved(1, MovedKeys.Rescan)))
assertEquals("""{"engine":"gemini","reconnects":1,"stuck":"none","failure":"connection","ready_ms":1200}""",
json(AnalyticsEvent.VoiceCallQuality(VoiceEngineKind.Gemini, CallQuality.Report(1_200, 1, VoiceStuck.None, VoiceFailureKind.Connection))))
// An engine that was never ready leaves `ready_ms` out.
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 18487667..cf61bedf 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
@@ -100,14 +100,31 @@ class CloudClient private constructor(base: String, private val identity: Device
/** Takes back this device's grants on a computer, including one approved for an earlier install. */
suspend fun revokeAccess(computerId: String) {
- val devices = request("GET", listOf("v1", "devices")).getValue("devices").jsonArray.map { it.jsonObject }
- val device = devices.firstOrNull { it.text("deviceKey") == identity.publicKey }?.text("deviceId") ?: return
+ val device = deviceId() ?: return
val grants = request("GET", listOf("v1", "computers", computerId, "grants")).getValue("grants").jsonArray.map { it.jsonObject }
for (grant in grants.filter { it.text("deviceId") == device }) {
request("DELETE", listOf("v1", "computers", computerId, "grants", requireNotNull(grant.text("grantId")) { "Invalid grant" }))
}
}
+ /** Signing out: 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))
+ }
+
+ /**
+ * This client on the session token it would send now, for a call that goes out after signing out: a session token
+ * stays valid until it expires (about a minute). Null when there's no token to take (iOS `pinningToken`).
+ */
+ suspend fun pinningToken(): CloudClient? {
+ val now = try { token() } catch (error: CancellationException) { throw error } catch (_: Exception) { return null }
+ return CloudClient(baseUrl.toString(), identity, { now }, http, pollInterval)
+ }
+
+ /** This device's id in the account; null when it was never registered. */
+ private suspend fun deviceId(): String? = request("GET", listOf("v1", "devices")).getValue("devices").jsonArray
+ .map { it.jsonObject }.firstOrNull { it.text("deviceKey") == identity.publicKey }?.text("deviceId")
+
suspend fun accessStatus(id: String): AccessStatus {
val result = request("GET", listOf("v1", "access-requests", id))
return json.decodeFromJsonElement(result)
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 79f6c757..918c8d65 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
@@ -132,4 +132,23 @@ class CloudClientTest {
assertEquals("/v1/devices", server.takeRequest().path)
} finally { server.shutdown() }
}
+
+ @Test fun `signing out deletes only this device from the account, on the token taken before`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("""{"devices":[{"deviceId":"other","deviceKey":"elsewhere"},{"deviceId":"mine","deviceKey":"${identity.publicKey}"}]}"""))
+ 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.revokeThisDevice()
+ val list = server.takeRequest()
+ assertEquals("/v1/devices" to "Bearer session", list.path to list.getHeader("Authorization"))
+ val delete = server.takeRequest()
+ assertEquals("DELETE" to "/v1/devices/mine", delete.method to delete.path)
+ assertEquals(null, client.pinningToken())
+ } finally { server.shutdown() }
+ }
}
diff --git a/apps/desktop/package-lock.json b/apps/desktop/package-lock.json
index 1076b87b..a2560f16 100644
--- a/apps/desktop/package-lock.json
+++ b/apps/desktop/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "codync-desktop",
- "version": "2.34.2",
+ "version": "2.35.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "codync-desktop",
- "version": "2.34.2",
+ "version": "2.35.0",
"license": "Apache-2.0",
"dependencies": {
"electron-updater": "^6.8.9"
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 045f01be..fb3930ca 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "codync-desktop",
"productName": "Codync",
- "version": "2.34.2",
+ "version": "2.35.0",
"description": "Codync for macOS, Linux and Windows: your coding agents as teammates.",
"author": {
"name": "leepokai",
diff --git a/apps/desktop/src/main/account.ts b/apps/desktop/src/main/account.ts
index a81a49b0..6cb88888 100644
--- a/apps/desktop/src/main/account.ts
+++ b/apps/desktop/src/main/account.ts
@@ -5,6 +5,7 @@ import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'
import type { SignInFailure, SignInProvider } from '../shared/analytics'
import type { AccountState } from '../shared/ipc'
import { authenticate, AuthenticationEnded } from './auth'
+import { dropDeviceKey, revokeThisDevice } from './cloud'
import { buildConfig, identity } from './environment'
/**
@@ -108,6 +109,7 @@ export class AccountService extends EventEmitter {
ipcMain.handle('account:state', () => this.state)
ipcMain.handle('account:signIn', (_e, provider: SignInProvider) => this.signIn(provider))
ipcMain.handle('account:signOut', () => this.signOut())
+ ipcMain.handle('account:delete', () => this.deleteAccount())
ipcMain.handle('account:token', () => this.sessionToken())
this.on('change', () => {
for (const w of windows()) w.webContents.send('account:change', this.state)
@@ -127,10 +129,16 @@ export class AccountService extends EventEmitter {
const sealed = await fs.readFile(this.storePath)
this.deviceToken = safeStorage.isEncryptionAvailable() ? safeStorage.decryptString(sealed) : sealed.toString('utf8')
} catch {}
- try {
- if (this.deviceToken) await this.refreshClient()
- } catch {
- // Offline at launch: the saved session still counts; the next call refreshes it.
+ // A saved session counts until Clerk turns it down, so the app isn't shown signed out (the welcome waits
+ // for `ready`) while offline, behind a captive portal or while Clerk is failing: asked again every 30 seconds.
+ while (this.deviceToken) {
+ try {
+ await this.refreshClient()
+ break
+ } catch (error) {
+ if (error instanceof ClerkError && [401, 403, 404].includes(error.status)) break
+ await new Promise((resolve) => setTimeout(resolve, 30_000))
+ }
}
await this.signInWithDevTicket()
this.set({ ready: true })
@@ -170,7 +178,15 @@ export class AccountService extends EventEmitter {
payload = new URLSearchParams(Object.entries(body).map(([k, v]) => [k, String(v)])).toString()
}
const res = await fetch(url, { method, headers, body: payload, signal: AbortSignal.timeout(20_000) })
- const json = (await res.json().catch(() => ({}))) as { response?: T; client?: ClerkClient | null; errors?: { code?: string; long_message?: string; message?: string }[] } & T
+ const text = await res.text()
+ let parsed: unknown = {}
+ try {
+ if (text) parsed = JSON.parse(text)
+ } catch {
+ // Not Clerk answering (a captive portal's page, a proxy's error): nothing in it may change the session.
+ throw new ClerkError(0, "Can't reach sign-in. Check your connection.")
+ }
+ const json = parsed as { response?: T; client?: ClerkClient | null; errors?: { code?: string; long_message?: string; message?: string }[] } & T
const response = json.response ?? json
const accepted = res.ok && (!accept || accept(response))
// Keep normal token rotation (including sign-out responses), but a rejected browser nonce
@@ -292,9 +308,16 @@ export class AccountService extends EventEmitter {
const session = this.activeSession
if (this.state.busy || !session) return
this.set({ busy: true, error: null })
+ // Taken now: the cloud call that revokes this install goes out once Clerk has signed out (the token outlives the session).
+ const cloud = this.state.cloudURL
+ const token = cloud ? await this.sessionToken().catch(() => null) : null
try {
await this.request('POST', `/v1/client/sessions/${session.id}/remove`)
this.cachedToken = null
+ if (session.user) {
+ if (cloud && token) await revokeThisDevice(cloud, token, session.user.id).catch(() => {})
+ await dropDeviceKey(session.user.id)
+ }
await this.refreshClient()
} catch {
this.set({ error: "Couldn't sign out. Check your connection and try again." })
@@ -303,6 +326,30 @@ export class AccountService extends EventEmitter {
}
}
+ /**
+ * Deletes the signed-in user in Clerk (`DELETE /v1/me`); the cloud cleans up on Clerk's `user.deleted`.
+ * False when Clerk refused or couldn't be reached: then nothing changed here.
+ */
+ async deleteAccount(): Promise<boolean> {
+ const session = this.activeSession
+ if (this.state.busy || !session?.user) return false
+ const userId = session.user.id
+ this.set({ busy: true, error: null })
+ try {
+ await this.request('DELETE', '/v1/me', undefined, { _clerk_session_id: session.id })
+ } catch {
+ this.set({ busy: false })
+ return false
+ }
+ this.cachedToken = null
+ await dropDeviceKey(userId)
+ // The user is gone; a client that can't be read now drops it all the same.
+ await this.refreshClient().catch(() => this.applyClient(null))
+ if (this.activeSession?.user?.id === userId) this.applyClient(null)
+ this.set({ busy: false })
+ return true
+ }
+
/** Every account on this device, for starting over. */
async signOutAll() {
try {
diff --git a/apps/desktop/src/main/cloud.ts b/apps/desktop/src/main/cloud.ts
index a6459c72..98812e1b 100644
--- a/apps/desktop/src/main/cloud.ts
+++ b/apps/desktop/src/main/cloud.ts
@@ -18,10 +18,12 @@ interface Identity {
const identities = new Map<string, Identity>()
+const keyPath = (userId: string) => join(app.getPath('userData'), `device-key-${createHash('sha256').update(userId).digest('hex').slice(0, 16)}.bin`)
+
async function identity(userId: string): Promise<Identity> {
const cached = identities.get(userId)
if (cached) return cached
- const path = join(app.getPath('userData'), `device-key-${createHash('sha256').update(userId).digest('hex').slice(0, 16)}.bin`)
+ const path = keyPath(userId)
let seed: Buffer | null = null
try {
const sealed = await fs.readFile(path)
@@ -66,32 +68,59 @@ export interface CloudFailure {
message: string | null
}
+type CloudResult = { ok: true; value: Record<string, unknown> } | { ok: false; error: CloudFailure }
+
+/** One `/v1` call with `token` (a session JWT), signed with `signer`'s device key when given. */
+async function cloudCall(base: string, token: string, method: string, path: string, body: unknown, signer: string | null, timeoutMs = 20_000): Promise<CloudResult> {
+ const url = new URL(path.replace(/^\//, ''), `${base}/`)
+ const payload = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body))
+ const headers: Record<string, string> = { Authorization: `Bearer ${token}` }
+ if (body !== undefined) headers['Content-Type'] = 'application/json'
+ if (signer) headers['Codync-Sig'] = signatureHeader(await identity(signer), method, url, payload)
+ try {
+ const res = await fetch(url, { method, headers, body: body === undefined ? undefined : payload, signal: AbortSignal.timeout(timeoutMs) })
+ const text = await res.text()
+ const json = text ? (JSON.parse(text) as Record<string, unknown>) : {}
+ if (!res.ok) {
+ const e = (json.error ?? {}) as { code?: string; message?: string }
+ return { ok: false, error: { status: res.status, code: e.code ?? `http${res.status}`, message: e.message ?? null } }
+ }
+ return { ok: true, value: json }
+ } catch {
+ return { ok: false, error: { status: 0, code: 'unreachable', message: "Can't reach the Codync cloud. Check your connection." } }
+ }
+}
+
+/**
+ * Signing out: the account drops this install's device, with its grants and requests (iOS and Android
+ * `revokeThisDevice`). `token` was taken before Clerk signed out: it stays valid until it expires. Best effort, a short wait.
+ */
+export async function revokeThisDevice(base: string, token: string, userId: string) {
+ if (!identities.has(userId) && !(await fs.stat(keyPath(userId)).catch(() => null))) return
+ const publicKey = (await identity(userId)).publicKey
+ const list = await cloudCall(base, token, 'GET', 'v1/devices', undefined, null, 5_000)
+ const devices = list.ok ? ((list.value.devices ?? []) as { deviceId: string; deviceKey: string }[]) : []
+ const device = devices.find((d) => d.deviceKey === publicKey)
+ if (device) await cloudCall(base, token, 'DELETE', `v1/devices/${device.deviceId}`, undefined, null, 5_000)
+}
+
+/** Leaving an account here (signing out, deleting it): its device key goes, since the cloud never takes a revoked key back. */
+export async function dropDeviceKey(userId: string) {
+ identities.delete(userId)
+ await fs.rm(keyPath(userId), { force: true }).catch(() => {})
+}
+
export function registerCloud(account: AccountService) {
- ipcMain.handle('cloud:request', async (_e, method: string, path: string, body: unknown, signed: boolean) => {
+ ipcMain.handle('cloud:request', async (_e, method: string, path: string, body: unknown, signed: boolean): Promise<CloudResult> => {
const base = account.state.cloudURL
const user = account.state.user
- if (!base || !user) return { ok: false, error: { status: 0, code: 'signedOut', message: 'Sign in again to reach your account.' } satisfies CloudFailure }
- const url = new URL(path.replace(/^\//, ''), `${base}/`)
- const payload = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body))
- const headers: Record<string, string> = {}
+ if (!base || !user) return { ok: false, error: { status: 0, code: 'signedOut', message: 'Sign in again to reach your account.' } }
+ let token: string
try {
- headers.Authorization = `Bearer ${await account.sessionToken()}`
+ token = await account.sessionToken()
} catch (error) {
return { ok: false, error: { status: 401, code: 'signedOut', message: error instanceof Error ? error.message : 'Sign in again.' } }
}
- if (body !== undefined) headers['Content-Type'] = 'application/json'
- if (signed) headers['Codync-Sig'] = signatureHeader(await identity(user.userId), method, url, payload)
- try {
- const res = await fetch(url, { method, headers, body: body === undefined ? undefined : payload, signal: AbortSignal.timeout(20_000) })
- const text = await res.text()
- const json = text ? (JSON.parse(text) as Record<string, unknown>) : {}
- if (!res.ok) {
- const e = (json.error ?? {}) as { code?: string; message?: string }
- return { ok: false, error: { status: res.status, code: e.code ?? `http${res.status}`, message: e.message ?? null } }
- }
- return { ok: true, value: json }
- } catch {
- return { ok: false, error: { status: 0, code: 'unreachable', message: "Can't reach the Codync cloud. Check your connection." } }
- }
+ return cloudCall(base, token, method, path, body, signed ? user.userId : null)
})
}
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index b8ae69b3..c5725470 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -75,6 +75,7 @@ const bridge: CodyncBridge = {
onChange: (cb) => listen('account:change', cb),
signIn: (provider) => ipcRenderer.invoke('account:signIn', provider),
signOut: () => ipcRenderer.invoke('account:signOut'),
+ deleteAccount: () => ipcRenderer.invoke('account:delete'),
token: () => ipcRenderer.invoke('account:token'),
},
speech: {
diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.ts
index 2f2a6460..0a8720ea 100644
--- a/apps/desktop/src/renderer/demo/bridge.ts
+++ b/apps/desktop/src/renderer/demo/bridge.ts
@@ -55,6 +55,7 @@ const bridge: CodyncBridge = {
onChange: none,
signIn: unavailable,
signOut: async () => {},
+ deleteAccount: async () => false,
token: unavailable,
},
speech: { available: false, locales: () => [], start() {}, stop() {}, onEvent: none, shortcut: async () => 'off', setShortcut: async () => 'off', setCalling() {} },
diff --git a/apps/desktop/src/renderer/lib/auto-claim.test.ts b/apps/desktop/src/renderer/lib/auto-claim.test.ts
index cfd6eda7..b1e57484 100644
--- a/apps/desktop/src/renderer/lib/auto-claim.test.ts
+++ b/apps/desktop/src/renderer/lib/auto-claim.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { mayAutoClaim, mayOfferMove } from './auto-claim.ts'
+import { accountMismatch, mayAutoClaim, mayOfferMove } from './auto-claim.ts'
const host = { id: 'new', online: true, cloud: { enabled: true, owner: null } }
@@ -34,3 +34,17 @@ test('a computer in another account offers to move into the signed-in one', () =
assert.equal(mayOfferMove({ ...owned('a'), online: false }, 'b', []), false)
assert.equal(mayOfferMove({ ...host, cloud: { enabled: true, owner: { userId: 'a' }, relay: 'private' } }, 'b', []), false)
})
+
+test('the sidebar line says when this computer and the signed-in account differ', () => {
+ const owned = { ...host, cloud: { enabled: true, owner: { userId: 'a', email: '[email protected]' } } }
+ assert.deepEqual(accountMismatch(owned, 'b', [], []), { kind: 'other', email: '[email protected]' })
+ assert.equal(accountMismatch(owned, 'a', [], []), null, 'the same account')
+ assert.deepEqual(accountMismatch(owned, 'b', ['new'], []), { kind: 'other', email: '[email protected]' }, 'still shown after keep it there')
+ assert.equal(accountMismatch(host, 'b', [], []), null, 'joining on its own')
+ assert.deepEqual(accountMismatch({ ...host, cloud: { enabled: false } }, 'b', [], []), { kind: 'none', reason: 'cloudOff' })
+ assert.deepEqual(accountMismatch({ ...host, cloud: { enabled: true, relay: 'private' } }, 'b', [], []), { kind: 'none', reason: 'privateRelay' })
+ assert.deepEqual(accountMismatch(host, 'b', ['new'], []), { kind: 'none', reason: 'keptOut' })
+ assert.deepEqual(accountMismatch(host, 'b', [], ['new']), { kind: 'none', reason: 'keptOut' }, 'removed from the account elsewhere')
+ assert.equal(accountMismatch({ ...owned, online: false }, 'b', [], []), null, "an offline host can't say")
+ assert.equal(accountMismatch({ ...host, cloud: null }, 'b', [], []), null)
+})
diff --git a/apps/desktop/src/renderer/lib/auto-claim.ts b/apps/desktop/src/renderer/lib/auto-claim.ts
index d6674713..4a74b544 100644
--- a/apps/desktop/src/renderer/lib/auto-claim.ts
+++ b/apps/desktop/src/renderer/lib/auto-claim.ts
@@ -33,3 +33,22 @@ export function mayOfferMove(host: ClaimCandidate, userId: string, keptOut: read
const owner = host.cloud?.owner
return joinable(host, keptOut) && !!owner && owner.userId !== userId
}
+
+/** Why this computer and the account signed in here differ, for the line in the sidebar (`accountMismatch`). */
+export type AccountMismatch =
+ | { kind: 'other'; email: string | null }
+ | { kind: 'none'; reason: 'cloudOff' | 'privateRelay' | 'keptOut' }
+
+/**
+ * Whether this computer is in another account than the one signed in here, or in none and not about to
+ * join (`mayAutoClaim`): with its cloud off, on a private relay, or taken out by the user. Null when they
+ * match, it's joining on its own, or the host can't say (offline).
+ */
+export function accountMismatch(host: ClaimCandidate, userId: string, keptOut: readonly string[], seen: readonly string[]): AccountMismatch | null {
+ const cloud = host.cloud
+ if (!host.online || !cloud) return null
+ if (cloud.owner) return cloud.owner.userId === userId ? null : { kind: 'other', email: cloud.owner.email ?? null }
+ if (!cloud.enabled) return { kind: 'none', reason: 'cloudOff' }
+ if (cloud.relay === 'private') return { kind: 'none', reason: 'privateRelay' }
+ return mayAutoClaim(host, keptOut, seen) ? null : { kind: 'none', reason: 'keptOut' }
+}
diff --git a/apps/desktop/src/renderer/lib/welcome-gate.test.ts b/apps/desktop/src/renderer/lib/welcome-gate.test.ts
new file mode 100644
index 00000000..dc5a162a
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/welcome-gate.test.ts
@@ -0,0 +1,17 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { showsWelcome } from './welcome-gate.ts'
+
+test('with accounts, the welcome covers the window whenever no one is signed in', () => {
+ const signedOut = { onboarded: true, configured: true, ready: true, signedIn: false }
+ assert.equal(showsWelcome(signedOut), true, 'signing out comes back to it')
+ assert.equal(showsWelcome({ ...signedOut, signedIn: true }), false)
+ assert.equal(showsWelcome({ ...signedOut, ready: false }), false, 'a saved session still restoring keeps the app')
+ assert.equal(showsWelcome({ ...signedOut, signedIn: true, onboarded: false }), true, 'the first run still chooses')
+})
+
+test('without accounts, the first choice is the only welcome', () => {
+ const local = { onboarded: false, configured: false, ready: true, signedIn: false }
+ assert.equal(showsWelcome(local), true)
+ assert.equal(showsWelcome({ ...local, onboarded: true }), false)
+})
diff --git a/apps/desktop/src/renderer/lib/welcome-gate.ts b/apps/desktop/src/renderer/lib/welcome-gate.ts
new file mode 100644
index 00000000..dea7062a
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/welcome-gate.ts
@@ -0,0 +1,8 @@
+/**
+ * Whether the welcome covers the window: before the first run's choice and, in a build with accounts, whenever no
+ * one is signed in once the saved session has been checked (signing out comes back here). Builds without accounts
+ * show it once.
+ */
+export function showsWelcome({ onboarded, configured, ready, signedIn }: { onboarded: boolean; configured: boolean; ready: boolean; signedIn: boolean }) {
+ return !onboarded || (configured && ready && !signedIn)
+}
diff --git a/apps/desktop/src/renderer/store/account.ts b/apps/desktop/src/renderer/store/account.ts
index 2349e102..f7ae3689 100644
--- a/apps/desktop/src/renderer/store/account.ts
+++ b/apps/desktop/src/renderer/store/account.ts
@@ -53,6 +53,19 @@ export class AccountSession extends Observable {
await window.codync.account.signOut()
}
+ /** The account menu's Delete account, waiting for the user to confirm (`DeleteAccountPrompt`). */
+ confirmingDelete = false
+
+ askToDelete(ask = true) {
+ this.confirmingDelete = ask
+ this.changed()
+ }
+
+ /** Deletes the signed-in account; false when it couldn't, and nothing changed. */
+ deleteAccount() {
+ return window.codync.account.deleteAccount()
+ }
+
sessionToken() {
return window.codync.account.token()
}
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 44e1c537..8ca9bd15 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -1,5 +1,5 @@
import type { CloudStatus, ClaimSignature } from '@shared/models'
-import { mayAutoClaim, mayOfferMove, type ClaimCandidate } from '../lib/auto-claim'
+import { accountMismatch, mayAutoClaim, mayOfferMove, type AccountMismatch, type ClaimCandidate } from '../lib/auto-claim'
import { Observable } from '../lib/observable'
import { isOlderCopy } from '../lib/older-copy'
import { relayAddressToSave } from '../lib/relay-address'
@@ -227,6 +227,24 @@ export class CloudModel extends Observable {
return { store, from: store.cloud?.owner?.email ?? null }
}
+ /** This computer and the account signed in here differ (`accountMismatch`): the sidebar's one line. */
+ get mismatch(): AccountMismatch | null {
+ const user = this.userId
+ const store = this.app.local
+ if (!user || !store || this.moving) return null
+ return accountMismatch(candidate(store), user, keptOut(user).get(), claimedIds(user).get())
+ }
+
+ /** The sidebar line: asks again whether to move this computer here, even after "Keep it there". */
+ reconsiderMove() {
+ const user = this.userId
+ const store = this.app.local
+ if (!user || !store) return
+ const out = keptOut(user)
+ out.set(out.get().filter((x) => x !== store.computer.id))
+ this.changed()
+ }
+
/** No to `moveOffer`: this computer stays in its account and isn't offered again (Remove, then Add to account, still moves it). */
keepInOtherAccount(store: BotStore) {
const user = this.userId
diff --git a/apps/desktop/src/renderer/views/AccountWelcomeView.tsx b/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
index 0894a298..36b98219 100644
--- a/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
+++ b/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, type CSSProperties } from 'react'
+import { useCallback, useEffect, useState, type CSSProperties } from 'react'
import { CharacterAvatar, type Mood } from '../components/Avatar'
import { Button, Spinner } from '../components/Controls'
import { Icon } from '../components/Icon'
@@ -6,13 +6,28 @@ import { HStack, Spacer, VStack } from '../components/Stack'
import { Text } from '../components/Text'
import { useReduceMotion } from '../lib/theme'
import { useTr } from '../lib/use-language'
-import { useAccount } from '../store/account'
+import { showsWelcome } from '../lib/welcome-gate'
+import { prefs, usePref } from '../lib/prefs'
+import { account, useAccount } from '../store/account'
+import { analytics } from '../store/analytics'
import googleLogo from '../assets/google.svg'
import './account-welcome.css'
const deviceName = window.codync.platform === 'darwin' ? 'Mac' : 'computer'
-/** First-run account choice. A restored session skips this screen as soon as it is back. */
+/** Whether the welcome covers the window (`showsWelcome`). `finish`: the first run's choice was made. */
+export function useWelcomeGate() {
+ const [onboarded, setOnboarded] = usePref(prefs.onboardingDone)
+ const { isConfigured, isReady, isSignedIn } = useAccount()
+ const finish = useCallback(() => {
+ if (prefs.onboardingDone.get()) return
+ setOnboarded(true)
+ analytics.track({ event: 'onboarding_completed', signed_in: account.isSignedIn })
+ }, [setOnboarded])
+ return { shown: showsWelcome({ onboarded, configured: isConfigured, ready: isReady, signedIn: isSignedIn }), finish }
+}
+
+/** The welcome: signing in, or, in a build without accounts, going on without one. A restored session skips it as soon as it is back. */
export function AccountWelcomeView({ onContinue }: { onContinue: () => void }) {
const account = useAccount()
const reduce = useReduceMotion()
@@ -36,9 +51,11 @@ export function AccountWelcomeView({ onContinue }: { onContinue: () => void }) {
<VStack align="center" justify="center" gap={14} className="welcome-restoring">
<Spinner size={24} />
<Text as="div" size="callout" tone="secondary">{tr(`Checking for a saved account…`)}</Text>
- <button className="welcome-skip" onClick={onContinue}>
- {onThis}
- </button>
+ {account.isConfigured ? null : (
+ <button className="welcome-skip" onClick={onContinue}>
+ {onThis}
+ </button>
+ )}
</VStack>
)
}
@@ -64,9 +81,11 @@ export function AccountWelcomeView({ onContinue }: { onContinue: () => void }) {
</VStack>
<Spacer min={32} />
<VStack gap={10} style={rise(beat >= 4)}>
- <Button onClick={onContinue} className="welcome-button">
- {onThis}
- </Button>
+ {account.isConfigured ? null : (
+ <Button onClick={onContinue} className="welcome-button">
+ {onThis}
+ </Button>
+ )}
<Button onClick={() => void account.signIn('apple')} disabled={!account.isConfigured || account.isBusy} className="welcome-button">
{account.isBusy ? (
<Spinner size={18} />
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 2bc74b11..b833f30e 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -10,14 +10,13 @@ import { Text } from '../components/Text'
import { useModels } from '../lib/observable'
import { prefs, stepTextSize, usePref, DEFAULT_TEXT_SIZE } from '../lib/prefs'
import { useApp, StoreContext } from '../store/context'
-import { account } from '../store/account'
import { analytics } from '../store/analytics'
import { refKey, sameRef, parseRef } from '../store/app-model'
import type { BotStore } from '../store/bot-store'
import { useComputerRoster } from '../store/computer-roster'
import { BotRoster } from './BotRoster'
import { ExtensionsMovedTip } from './ExtensionsMovedTip'
-import { SidebarFooter } from './SidebarFooter'
+import { RailAccountNotice, SidebarFooter } from './SidebarFooter'
import { UpdateBadge } from './UpdateButton'
import { ComputerFilterHeader, computerSelection } from './ComputerFilterHeader'
import { ThreadView } from './thread/ThreadView'
@@ -29,7 +28,7 @@ import { MarketplaceView } from './marketplace/MarketplaceView'
import { SettingsView, type SettingsPage } from './settings/SettingsView'
import { ApprovalSheet } from './settings/ApprovalSheet'
import { SearchPalette } from './SearchPalette'
-import { AccountWelcomeView } from './AccountWelcomeView'
+import { AccountWelcomeView, useWelcomeGate } from './AccountWelcomeView'
import { ComputerAccessView } from './computer-access/ComputerAccessView'
import { AccessOnboarding } from './computer-access/AccessOnboarding'
import { HostStateView } from './HostStateView'
@@ -38,6 +37,7 @@ export { EmptyState } from './HostStateView'
import { RefreshIndicator } from './RefreshIndicator'
import { StarPrompt } from './StarPrompt'
import { MoveComputerPrompt } from './MoveComputerPrompt'
+import { DeleteAccountPrompt } from './DeleteAccountPrompt'
import { OpenVoiceSettings } from './call/CallView'
import { AccountPanelLayer, ProfileAvatar } from './PanelMenus'
import { DesktopActionMenu, type ActionItem } from './DesktopActionMenu'
@@ -56,7 +56,7 @@ import { useTr } from '../lib/use-language'
export function ChatWindow() {
const tr = useTr()
const app = useApp()
- const [onboarded, setOnboarded] = usePref(prefs.onboardingDone)
+ const welcome = useWelcomeGate()
const [accessSetup, setAccessSetup] = usePref(prefs.computerAccessSetup)
const [showAccess, setShowAccess] = useState(false)
const [confirmReset, setConfirmReset] = useState(false)
@@ -124,7 +124,7 @@ export function ChatWindow() {
<div className="chat-window">
<Summaries />
<RefreshIndicator />
- {onboarded ? (
+ {!welcome.shown ? (
accessSetup === null ? (
<AccessOnboarding onContinue={(ready) => finishAccess(ready, true)} />
) : showsChat ? (
@@ -133,15 +133,10 @@ export function ChatWindow() {
<HostStateView />
)
) : (
- <AccountWelcomeView
- onContinue={() => {
- setOnboarded(true)
- analytics.track({ event: 'onboarding_completed', signed_in: account.isSignedIn })
- }}
- />
+ <AccountWelcomeView onContinue={welcome.finish} />
)}
- {onboarded && accessSetup !== null && showsChat ? null : <div className="window-drag drag" />}
- {onboarded && accessSetup !== null ? <><StarPrompt /><MoveComputerPrompt /></> : null}
+ {!welcome.shown && accessSetup !== null && showsChat ? null : <div className="window-drag drag" />}
+ {!welcome.shown && accessSetup !== null ? <><StarPrompt /><MoveComputerPrompt /><DeleteAccountPrompt /></> : null}
<Sheet open={showAccess} onClose={() => setShowAccess(false)} width={660} height={Math.min(820, window.innerHeight - 80)}>
<ModalHeader icon="hand.raised" title={tr(`Computer access`)} />
<ComputerAccessView onContinue={(ready) => { finishAccess(ready, false); setShowAccess(false) }} />
@@ -416,13 +411,14 @@ function ChatSplitView() {
<AnchoredMenu open={railNewMenu} onClose={() => setRailNewMenu(false)} anchor={railNewButton} items={newItems} />
<IconButton title="Extensions" icon="square.grid.2x2" size={36} onClick={openMarketplace} />
<UpdateBadge size={32} />
+ <RailAccountNotice onComputers={() => setSettings('computers')} />
<button className={`rail-profile ${showAccount ? 'open' : ''}`} aria-label="Open account menu for Account" title="Account" onClick={() => setShowAccount((s) => !s)}>
<ProfileAvatar />
</button>
</div>
) : (
// With several computers each heading opens its own Extensions instead.
- <SidebarFooter accountOpen={showAccount} onAccount={() => setShowAccount((s) => !s)} onExtensions={roster.grouped ? undefined : openMarketplace} />
+ <SidebarFooter accountOpen={showAccount} onAccount={() => setShowAccount((s) => !s)} onExtensions={roster.grouped ? undefined : openMarketplace} onComputers={() => setSettings('computers')} />
)}
</aside>
<ResizeHandle label="Resize sidebar" width={width} min={76} max={sidebarMax} edge="trailing" onResize={resizeSidebar} onDragging={setResizing} />
diff --git a/apps/desktop/src/renderer/views/DeleteAccountPrompt.tsx b/apps/desktop/src/renderer/views/DeleteAccountPrompt.tsx
new file mode 100644
index 00000000..b3cebbfc
--- /dev/null
+++ b/apps/desktop/src/renderer/views/DeleteAccountPrompt.tsx
@@ -0,0 +1,23 @@
+import { Dialog } from '../components/Overlay'
+import { useTr } from '../lib/use-language'
+import { account, useAccount } from '../store/account'
+import { useApp } from '../store/context'
+
+/** The account menu's Delete account, confirmed. The computers keep their bots; the cloud forgets the account. */
+export function DeleteAccountPrompt() {
+ const tr = useTr()
+ const app = useApp()
+ const { confirmingDelete } = useAccount()
+ const remove = async () => {
+ if (!(await account.deleteAccount())) app.setError(tr(`Couldn't delete your account. Check your connection and try again.`))
+ }
+ return (
+ <Dialog
+ open={confirmingDelete}
+ title={tr('Delete your Codync account?')}
+ message={tr(`Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.`)}
+ actions={[{ title: 'Delete account', destructive: true, action: () => void remove() }]}
+ onClose={() => account.askToDelete(false)}
+ />
+ )
+}
diff --git a/apps/desktop/src/renderer/views/PanelMenus.tsx b/apps/desktop/src/renderer/views/PanelMenus.tsx
index 964a1899..7b6d32f7 100644
--- a/apps/desktop/src/renderer/views/PanelMenus.tsx
+++ b/apps/desktop/src/renderer/views/PanelMenus.tsx
@@ -56,7 +56,10 @@ export function AccountPanelLayer({ compact, approvals, onDismiss, onUsage, onSe
useScreenViewed('account')
const signedIn = user !== null
const auth: PanelItem[] = signedIn
- ? [{ title: isBusy ? 'Please wait…' : 'Sign out', icon: 'rectangle.portrait.and.arrow.right', disabled: isBusy, action: () => { onDismiss(); void account.signOut() } }]
+ ? [
+ { title: isBusy ? 'Please wait…' : 'Sign out', icon: 'rectangle.portrait.and.arrow.right', disabled: isBusy, action: () => { onDismiss(); void account.signOut() } },
+ { title: 'Delete account', icon: 'trash', destructive: true, disabled: isBusy, action: () => { onDismiss(); account.askToDelete() } },
+ ]
: [
{ title: 'Continue with Apple', icon: 'apple.logo', disabled: isBusy, action: () => { onDismiss(); void account.signIn('apple') } },
{ title: 'Continue with Google', icon: 'person.crop.circle.badge.plus', image: googleLogo, disabled: isBusy, action: () => { onDismiss(); void account.signIn('google') } },
diff --git a/apps/desktop/src/renderer/views/SidebarFooter.tsx b/apps/desktop/src/renderer/views/SidebarFooter.tsx
index 964d9340..fd00573d 100644
--- a/apps/desktop/src/renderer/views/SidebarFooter.tsx
+++ b/apps/desktop/src/renderer/views/SidebarFooter.tsx
@@ -1,4 +1,12 @@
+import { useLayoutEffect, useRef } from 'react'
+import { IconButton } from '../components/Controls'
+import { Icon } from '../components/Icon'
+import { Text } from '../components/Text'
+import type { AccountMismatch } from '../lib/auto-claim'
+import { useModel } from '../lib/observable'
import { useTr } from '../lib/use-language'
+import { useAccount } from '../store/account'
+import { useApp } from '../store/context'
import { ProfileAvatar } from './PanelMenus'
import { UpdateBadge } from './UpdateButton'
import gmail from '../assets/gmail.png'
@@ -7,15 +15,39 @@ import drive from '../assets/google-drive.png'
import './sidebar-footer.css'
/** Account and app connections float above the scrolling roster; Extensions only when given. */
-export function SidebarFooter({ accountOpen, onAccount, onExtensions }: {
+export function SidebarFooter({ accountOpen, onAccount, onExtensions, onComputers }: {
accountOpen: boolean
onAccount: () => void
onExtensions?: () => void
+ /** Settings → Computers, where a computer out of the account is added. */
+ onComputers: () => void
}) {
const tr = useTr()
+ const notice = useAccountNotice(onComputers)
+ const footer = useRef<HTMLDivElement>(null)
+ // The roster scrolls under the footer: its height (taller with the notice, wrapped or not) is the roster's bottom padding.
+ useLayoutEffect(() => {
+ const el = footer.current
+ const sidebar = el?.parentElement
+ if (!el || !sidebar) return
+ const observer = new ResizeObserver(([e]) => sidebar.style.setProperty('--sidebar-footer-height', `${Math.ceil(e!.borderBoxSize[0]!.blockSize)}px`))
+ observer.observe(el)
+ return () => {
+ observer.disconnect()
+ sidebar.style.removeProperty('--sidebar-footer-height')
+ }
+ }, [])
return (
- <div className="sidebar-footer">
+ <div className="sidebar-footer" ref={footer}>
<div className="sidebar-footer-fade" aria-hidden />
+ {notice ? (
+ // This computer and the account signed in here differ: a notice in full, the choice behind it.
+ <button className="sidebar-account-notice" onClick={notice.open}>
+ <Icon name="exclamationmark.circle.fill" size={13} color="var(--attention)" />
+ <Text size="caption" grow>{notice.text}</Text>
+ <Icon name="chevron.right" size={10} color="var(--tertiary)" />
+ </button>
+ ) : null}
<button
className={`sidebar-account ${accountOpen ? 'active' : ''}`}
aria-label="Open account menu for Account"
@@ -37,3 +69,35 @@ export function SidebarFooter({ accountOpen, onAccount, onExtensions }: {
</div>
)
}
+
+/** The narrow rail's notice: an icon with the notice's text as its tooltip, the same choice behind it. */
+export function RailAccountNotice({ onComputers }: { onComputers: () => void }) {
+ const notice = useAccountNotice(onComputers)
+ return notice ? <IconButton title={notice.text} icon="exclamationmark.circle.fill" size={36} className="rail-account-notice" onClick={notice.open} /> : null
+}
+
+/**
+ * This computer and the account signed in here differ (`CloudModel.mismatch`): what to say, and the choice behind it.
+ * In another account, the move prompt again; in none, Settings → Computers.
+ */
+function useAccountNotice(onComputers: () => void) {
+ const tr = useTr()
+ const app = useApp()
+ useAccount()
+ useModel(app.cloud)
+ useModel(app.local)
+ const mismatch = app.cloud.mismatch
+ if (!mismatch) return null
+ return { text: mismatchLine(mismatch, tr), open: () => (mismatch.kind === 'other' ? app.cloud.reconsiderMove() : onComputers()) }
+}
+
+function mismatchLine(mismatch: AccountMismatch, tr: (text: string) => string) {
+ if (mismatch.kind === 'other') {
+ return mismatch.email ? tr(`This computer is in {name}'s account`).replaceAll('{name}', mismatch.email) : tr('This computer is in another account')
+ }
+ switch (mismatch.reason) {
+ case 'cloudOff': return tr(`This computer isn't in an account: its cloud is off`)
+ case 'privateRelay': return tr(`This computer isn't in an account: it uses a private relay`)
+ case 'keptOut': return tr(`This computer isn't in your account`)
+ }
+}
diff --git a/apps/desktop/src/renderer/views/sidebar-footer.css b/apps/desktop/src/renderer/views/sidebar-footer.css
index 19407346..6d43a447 100644
--- a/apps/desktop/src/renderer/views/sidebar-footer.css
+++ b/apps/desktop/src/renderer/views/sidebar-footer.css
@@ -1,6 +1,7 @@
+/* The footer floats over the roster: its measured height (`SidebarFooter`) keeps the last rows clear. */
.sidebar:not(.compact) .roster {
- padding-bottom: 72px;
- scroll-padding-bottom: 72px;
+ padding-bottom: calc(var(--sidebar-footer-height, 58px) + 14px);
+ scroll-padding-bottom: calc(var(--sidebar-footer-height, 58px) + 14px);
}
.sidebar-footer {
@@ -10,6 +11,7 @@
left: 0;
right: 0;
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 10px 14px 14px;
@@ -100,3 +102,24 @@
.sidebar-footer-fade { background: var(--surface); inset: 0; }
.sidebar-footer-fade::before, .sidebar-footer-fade::after { backdrop-filter: none; -webkit-backdrop-filter: none; }
}
+
+/* This computer and the signed-in account differ: a notice of its own above the buttons, shown in full. */
+.sidebar-account-notice {
+ order: -1;
+ flex-basis: 100%;
+ min-width: 0;
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 10px 12px;
+ text-align: left;
+ color: var(--text);
+ border-radius: var(--radius-s);
+ background: color-mix(in srgb, var(--attention) 24%, transparent);
+ transition: background-color var(--hover);
+}
+.sidebar-account-notice > :first-child, .sidebar-account-notice > :last-child { margin-top: 2px; flex-shrink: 0; }
+.sidebar-account-notice:hover,
+.rail-account-notice.icon-button:hover { background: color-mix(in srgb, var(--attention) 32%, transparent); }
+/* The narrow rail has no room for the text: the same notice as a tinted icon, its text in the tooltip. */
+.rail-account-notice.icon-button { color: var(--attention); background: color-mix(in srgb, var(--attention) 24%, transparent); }
diff --git a/apps/desktop/src/shared/account-sign-in.test.ts b/apps/desktop/src/shared/account-sign-in.test.ts
index 5a7a937c..4429838a 100644
--- a/apps/desktop/src/shared/account-sign-in.test.ts
+++ b/apps/desktop/src/shared/account-sign-in.test.ts
@@ -6,6 +6,9 @@ import { AuthenticationEnded, BrowserAuthentication } from '../main/browser-auth
import { loadMainModule } from './test-support/main-module.ts'
const opened: string[] = []
+const revoked: string[] = []
+const dropped: string[] = []
+const retries: (() => void)[] = []
const platform = { open: async (url: string) => { opened.push(url) } }
const browser = new BrowserAuthentication((url) => platform.open(url))
const handleURL = (url: string) => browser.handleURL(url)
@@ -13,11 +16,18 @@ const { AccountService } = loadMainModule<typeof import('../main/account.ts')>('
'node:events': { EventEmitter }, 'node:fs': { promises: {} }, 'node:path': path,
electron: { app: { getVersion: () => '2.33.1' }, ipcMain: {}, safeStorage: {} },
'./auth': { authenticate: browser.authenticate.bind(browser), AuthenticationEnded },
+ './cloud': {
+ revokeThisDevice: async (_base: string, token: string, userId: string) => { revoked.push(`${userId} ${token}`) },
+ dropDeviceKey: async (userId: string) => { dropped.push(userId) },
+ },
'./environment': {
identity: { appId: 'test.codync', scheme: 'codync', environment: 'dev' },
buildConfig: { clerkPublishableKey: `pk_test_${Buffer.from('clerk.example.test$').toString('base64')}`, cloudURL: 'https://cloud.example.test' },
},
-}, { URL, URLSearchParams, Buffer, process: { env: {}, platform: 'win32' }, fetch: (...args: Parameters<typeof fetch>) => globalThis.fetch(...args) })
+}, {
+ URL, URLSearchParams, Buffer, process: { env: {}, platform: 'win32' }, fetch: (...args: Parameters<typeof fetch>) => globalThis.fetch(...args),
+ setTimeout: (retry: () => void) => { retries.push(retry) },
+})
const until = async (check: () => boolean) => {
for (let i = 0; i < 50 && !check(); i++) await new Promise<void>((done) => setImmediate(done))
assert.ok(check())
@@ -83,3 +93,89 @@ test('browser launch and callback network failures reset loading and allow a ret
assert.equal(account.state.busy, false)
assert.match(account.state.error ?? '', /Couldn't sign in/)
})
+
+test('deleting the account removes the user in Clerk; a failure changes nothing', async () => {
+ const account = new AccountService()
+ let deleted = false
+ let reachable = false
+ globalThis.fetch = async (input, init) => {
+ const url = new URL(String(input))
+ if (url.pathname === '/v1/me' && init?.method === 'DELETE') {
+ if (!reachable) throw new Error('Network unavailable')
+ deleted = true
+ return response({ response: { deleted: true }, client: { sessions: [] } })
+ }
+ return response({ response: deleted ? { sessions: [] } : { last_active_session_id: 'session', sessions: [{ id: 'session', status: 'active', user: { id: 'user' } }] } })
+ }
+ await (account as unknown as { refreshClient(): Promise<void> }).refreshClient()
+ assert.equal(account.state.user?.userId, 'user')
+ assert.equal(await account.deleteAccount(), false)
+ assert.equal(account.state.user?.userId, 'user', 'still signed in')
+ assert.equal(account.state.busy, false)
+ assert.deepEqual(dropped, [])
+ reachable = true
+ assert.equal(await account.deleteAccount(), true)
+ assert.equal(account.state.user, null)
+ assert.equal(account.state.busy, false)
+ assert.deepEqual(dropped, ['user'], "this install's key for the account goes")
+ assert.deepEqual(revoked, [], "Clerk's user.deleted revokes it in the cloud")
+})
+
+const activeUser = { last_active_session_id: 'session', sessions: [{ id: 'session', status: 'active', user: { id: 'user' } }] }
+
+test('signing out hands the key back only once Clerk signed out, on the token taken before', async () => {
+ revoked.length = 0
+ dropped.length = 0
+ const account = new AccountService()
+ let signedIn = true
+ let reachable = false
+ globalThis.fetch = async (input) => {
+ const url = new URL(String(input))
+ if (url.pathname === '/v1/client/sessions/session/tokens') return signedIn ? response({ jwt: 'jwt' }) : response({}, 404)
+ if (url.pathname === '/v1/client/sessions/session/remove') {
+ if (!reachable) throw new Error('Network unavailable')
+ signedIn = false
+ return response({ response: {}, client: { sessions: [] } })
+ }
+ return response({ response: signedIn ? activeUser : { sessions: [] } })
+ }
+ await (account as unknown as { refreshClient(): Promise<void> }).refreshClient()
+ await account.signOut()
+ assert.equal(account.state.user?.userId, 'user', 'still signed in')
+ assert.match(account.state.error ?? '', /Couldn't sign out/)
+ assert.deepEqual([revoked, dropped], [[], []], 'a sign-out that failed keeps the key')
+ reachable = true
+ await account.signOut()
+ assert.equal(account.state.user, null)
+ assert.equal(account.state.busy, false)
+ assert.deepEqual(revoked, ['user jwt'])
+ assert.deepEqual(dropped, ['user'])
+})
+
+test('a saved session stays restoring until Clerk answers; only Clerk turning it down signs out', async () => {
+ const answers: (() => Response)[] = [
+ () => response({ errors: [{ message: 'busy' }] }, 503),
+ () => new Response('<html>Hotel Wi-Fi</html>', { status: 200 }),
+ () => { throw new Error('Network unavailable') },
+ () => response({ response: activeUser }),
+ ]
+ globalThis.fetch = async () => answers.shift()!()
+ type Restoring = { deviceToken: string | null; restore(): Promise<void>; state: InstanceType<typeof AccountService>['state'] }
+ const restoring = new AccountService() as unknown as Restoring
+ restoring.deviceToken = 'saved'
+ const restored = restoring.restore()
+ for (let tries = 1; tries <= 3; tries++) {
+ await until(() => retries.length === 1)
+ assert.equal(restoring.state.ready, false, 'not shown signed out while Clerk can\'t say')
+ retries.shift()!()
+ }
+ await restored
+ assert.equal(restoring.state.ready, true)
+ assert.equal(restoring.state.user?.userId, 'user')
+
+ globalThis.fetch = async () => response({ errors: [{ message: 'Signed out' }] }, 401)
+ const declined = new AccountService() as unknown as Restoring
+ declined.deviceToken = 'saved'
+ await declined.restore()
+ assert.deepEqual([declined.state.ready, declined.state.user], [true, null])
+})
diff --git a/apps/desktop/src/shared/cloud-device.test.ts b/apps/desktop/src/shared/cloud-device.test.ts
new file mode 100644
index 00000000..89cbd826
--- /dev/null
+++ b/apps/desktop/src/shared/cloud-device.test.ts
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict'
+import * as crypto from 'node:crypto'
+import path from 'node:path'
+import { test } from 'node:test'
+import { loadMainModule } from './test-support/main-module.ts'
+
+// The key files, in memory; `safeStorage` is unavailable, so a file holds the seed as base64url text.
+const files = new Map<string, Buffer>()
+const missing = () => Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+const fs = {
+ readFile: async (file: string) => files.get(file) ?? missing(),
+ writeFile: async (file: string, data: Buffer) => { files.set(file, Buffer.from(data)) },
+ mkdir: async () => {},
+ stat: async (file: string) => (files.has(file) ? {} : missing()),
+ rm: async (file: string) => { files.delete(file) },
+}
+const calls: string[] = []
+const { revokeThisDevice, dropDeviceKey } = loadMainModule<typeof import('../main/cloud.ts')>('cloud', {
+ 'node:crypto': crypto, 'node:fs': { promises: fs }, 'node:path': path,
+ electron: { app: { getPath: () => '/data' }, ipcMain: {}, safeStorage: { isEncryptionAvailable: () => false } },
+}, {
+ URL, Buffer,
+ fetch: async (input: URL, init: RequestInit) => {
+ calls.push(`${init.method} ${input.pathname} ${(init.headers as Record<string, string>).Authorization}`)
+ return new Response(input.pathname === '/v1/devices'
+ ? JSON.stringify({ devices: [{ deviceId: 'other', deviceKey: 'elsewhere' }, { deviceId: 'mine', deviceKey: publicKey }] })
+ : '{}')
+ },
+})
+const { d: seed, x: publicKey } = crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'jwk' }) as { d: string; x: string }
+
+test("signing out revokes only this install's device, then its key goes", async () => {
+ await revokeThisDevice('https://cloud.test', 'jwt', 'user')
+ assert.deepEqual(calls, [], 'no key here: nothing to revoke')
+
+ const keyFile = `/data/device-key-${crypto.createHash('sha256').update('user').digest('hex').slice(0, 16)}.bin`
+ files.set(keyFile, Buffer.from(seed))
+ await revokeThisDevice('https://cloud.test', 'jwt', 'user')
+ assert.deepEqual(calls, ['GET /v1/devices Bearer jwt', 'DELETE /v1/devices/mine Bearer jwt'])
+
+ await dropDeviceKey('user')
+ assert.equal(files.has(keyFile), false)
+ calls.length = 0
+ await revokeThisDevice('https://cloud.test', 'jwt', 'user')
+ assert.deepEqual(calls, [], 'the dropped key is gone from memory too')
+})
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index fdf8fe80..7f0b8a63 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -174,6 +174,8 @@ export interface CodyncBridge {
/** Why it ended without an account; null once signed in (or while another sign-in runs). */
signIn(provider: SignInProvider): Promise<SignInFailure | null>
signOut(): Promise<void>
+ /** Deletes the signed-in Codync account in Clerk; false when it couldn't (nothing changed). */
+ deleteAccount(): Promise<boolean>
/** The signed-in session's JWT for the Codync cloud. */
token(): Promise<string>
}
diff --git a/apps/ios/App/AccountSession.swift b/apps/ios/App/AccountSession.swift
index 2da722f0..d677dad3 100644
--- a/apps/ios/App/AccountSession.swift
+++ b/apps/ios/App/AccountSession.swift
@@ -119,10 +119,7 @@ final class AccountSession {
func signIn(provider: SignInProvider = .google) async {
guard !isBusy else { return }
- guard let clerk else {
- errorMessage = "Sign-in setup isn't finished yet. You can continue using local pairing."
- return
- }
+ guard let clerk else { return }
let tracked: AnalyticsEvent.SignInProvider = provider == .apple ? .apple : .google
Analytics.shared.capture(.signInStarted(tracked))
isBusy = true
@@ -177,6 +174,18 @@ final class AccountSession {
}
}
+ /// Deletes the signed-in user in Clerk (App Store 5.1.1(v)); the cloud cleans up after Clerk's `user.deleted`.
+ /// Throws when Clerk refused or couldn't be reached, and then nothing changed.
+ func deleteUser() async throws {
+ guard let clerk, let user = clerk.user, let sessionID = clerk.session?.id else { throw SessionError.signedOut }
+ isBusy = true
+ errorMessage = nil
+ defer { isBusy = false }
+ try await user.delete()
+ // Clerk ends the session with the user; make sure it's gone here too.
+ if userID == user.id { try? await clerk.auth.signOut(sessionId: sessionID) }
+ }
+
/// Every account on this device, for starting over.
func signOutAll() async {
guard let clerk else { return }
diff --git a/apps/ios/App/AppStore+Account.swift b/apps/ios/App/AppStore+Account.swift
new file mode 100644
index 00000000..2cd57b59
--- /dev/null
+++ b/apps/ios/App/AppStore+Account.swift
@@ -0,0 +1,77 @@
+import CodyncKit
+import CodyncUI
+
+/// Leaving an account (signing out, deleting it) and moving signed-out pairings into one.
+extension AppStore {
+ /// Sign-in is required: computers paired while signed out move into the account the first time one is
+ /// used here, before its stores and keys load. Builds without Clerk stay in the signed-out context.
+ static func adoptSignedOutPairings(into storage: SharedStore.Context) {
+ guard let adoption = storage.adopt(from: SharedStore.Context(accountID: nil)), adoption.computers > 0 else { return }
+ 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).
+ func signOut() async {
+ guard let userID = account.userID else { return }
+ // Sent first so it still counts toward the account.
+ Analytics.shared.capture(.signedOut)
+ // The cloud call goes out after Clerk signed out, on a token taken now (it outlives the session).
+ let cloud = await cloud?.pinningToken()
+ leaving = true
+ await account.signOut()
+ if hasLeft(userID) { await handBack(cloud: cloud) }
+ forget(userID)
+ }
+
+ /// 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,
+ /// grants and computers itself, on Clerk's `user.deleted`.
+ func deleteAccount() async {
+ guard let userID = account.userID else { return }
+ leaving = true
+ do {
+ try await account.deleteUser()
+ await handBack(cloud: nil)
+ } catch {
+ account.errorMessage = "Couldn't delete your account. Check your connection and try again."
+ }
+ 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.
+ private func forget(_ userID: String) {
+ 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 }
+ }
+
+ private func hasLeft(_ userID: String) -> Bool {
+ 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.
+ func handBack(cloud: CloudClient?) 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() } } }
+ }
+ }
+
+ private nonisolated static func bestEffort(_ limit: Duration, _ work: @escaping @Sendable () async throws -> Void) async {
+ await withTaskGroup(of: Void.self) { group in
+ group.addTask { try? await work() }
+ group.addTask { try? await Task.sleep(for: limit) }
+ await group.next()
+ group.cancelAll()
+ }
+ }
+}
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index 39818269..3130b7f2 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -15,8 +15,10 @@ struct CodyncApp: App {
@AppStorage(Appearance.storageKey) private var appearance = Appearance.system
@AppStorage("onboardingCompleted") private var onboardingCompleted = false
@AppStorage(AppLanguage.storageKey, store: AppLanguage.defaults) private var appLanguageRaw = AppLanguage.system.rawValue
- /// Cold launch with a computer to reach: the splash covers its connect and catch-up.
+ /// Cold launch with a computer to reach: the splash covers its connect and catch-up. Not over the sign-in
+ /// screen, where signed-out computers wait to move into the account.
@State private var launching = !AppStore.shared.accounts.computers.isEmpty
+ && (AppStore.shared.accounts.accountId != nil || !AppStore.shared.account.isConfigured)
init() {
// A tapped widget bot arrives as an intent, not a URL.
OpenBotIntent.open = { AppStore.shared.open($0) }
@@ -132,6 +134,8 @@ final class AppStore {
var showUsage = false
/// The computer whose marketplace is open.
var marketplace: ComputerID?
+ /// While an account is being left: its stores stay open until its computers have been told.
+ var leaving = false
private init() {
let session = AccountSession()
@@ -148,6 +152,7 @@ final class AppStore {
}
CrashReports.shared.start()
contextID = storage.id
+ Self.adoptSignedOutPairings(into: storage)
// Accounts Clerk hasn't restored by launch keep their computers' push on.
SharedStore.Context.splitPushSwitch(from: .standard,
into: Set([nil, storage.accountID] + session.accounts.map(\.id)).map { SharedStore.Context(accountID: $0) })
@@ -163,10 +168,11 @@ final class AppStore {
func switchAccount(to userID: String?) {
let storage = SharedStore.Context(accountID: userID)
- guard storage.id != contextID else { return }
+ guard storage.id != contextID, !leaving else { return }
accounts.retire()
PushRegistrar.shared.deactivate()
LiveActivities.shared.endAll()
+ Self.adoptSignedOutPairings(into: storage)
SharedStore.activeAccountID = userID
storage.bots = []
contextID = storage.id
@@ -178,22 +184,12 @@ final class AppStore {
WidgetCenter.shared.reloadAllTimelines()
}
- /// Signing out forgets this account on this iPhone: its device keys, computers and caches (spec §3.2).
- func signOut() async {
- guard let userID = account.userID else { return }
- // Sent first so it still counts toward the account.
- Analytics.shared.capture(.signedOut)
- await account.signOut()
- guard account.userID != userID, !account.accounts.contains(where: { $0.id == userID }) else { return }
- // Retire its stores first: a retiring store saves its cache one last time.
- switchAccount(to: account.userID)
- SharedStore.Context(accountID: userID).erase()
- }
-
/// 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.
+ await handBack(cloud: cloud)
await account.signOutAll()
accounts.retire()
PushRegistrar.shared.deactivate()
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
index 6d5f66f3..cabe9c2d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
@@ -12,6 +12,8 @@ public enum AnalyticsEvent: Equatable, Sendable {
case signInFailed(SignInProvider, reason: SignInFailure)
case signedIn(SignInProvider)
case signedOut
+ /// The signed-out computers moved into the account at sign-in: with this phone's keys, or to be scanned again.
+ case signedOutPairingsMoved(computers: Int, keys: MovedKeys)
case pairingFailed(PairingFailure)
case computerPaired(via: PairVia, computer: ComputerID)
case accessRequested
@@ -37,6 +39,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
public enum OnboardingVia: String, Sendable { case paired, account, skipped }
public enum SignInProvider: String, Sendable { case apple, google }
public enum SignInFailure: String, Sendable { case cancelled, verification, error }
+ public enum MovedKeys: String, Sendable { case moved, rescan }
public enum PairVia: String, Sendable { case qr, link, account }
public enum AccessFailure: String, Sendable { case denied, expired, cancelled }
public enum PromptSource: String, Sendable { case settings, widgets }
@@ -105,6 +108,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
case .signInFailed: "sign_in_failed"
case .signedIn: "signed_in"
case .signedOut: "signed_out"
+ case .signedOutPairingsMoved: "signed_out_pairings_moved"
case .pairingFailed: "pairing_failed"
case .computerPaired: "computer_paired"
case .accessRequested: "access_requested"
@@ -135,6 +139,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
case let .signInStarted(provider), let .signedIn(provider): return ["provider": .string(provider.rawValue)]
case let .signInFailed(provider, reason): return ["provider": .string(provider.rawValue), "reason": .string(reason.rawValue)]
case .signedOut, .accessRequested: return [:]
+ case let .signedOutPairingsMoved(computers, keys): return ["computers": .int(computers), "keys": .string(keys.rawValue)]
case let .pairingFailed(reason): return ["reason": .string(reason.rawValue)]
case let .computerPaired(via, computer):
return ["via": .string(via.rawValue), "computer": .string(Analytics.computerTag(computer))]
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
index 07435672..b7c671cc 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swift
@@ -64,6 +64,25 @@ public struct CloudClient: Sendable {
return res.devices
}
+ /// Signing out: 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)")
+ }
+
+ /// This device in the account; nil without a device key or when it was never registered.
+ private func thisDevice() async throws -> CloudDevice? {
+ guard let identity else { return nil }
+ return try await devices().first(where: { $0.deviceKey == identity.publicKey })
+ }
+
+ /// This client on the session token it would send now, for a call that goes out after signing out: a
+ /// session token stays valid until it expires (about a minute). Nil when there's no token to take.
+ public func pinningToken() async -> CloudClient? {
+ guard let token = try? await token() else { return nil }
+ return CloudClient(baseURL: baseURL, identity: identity, session: session) { token }
+ }
+
// MARK: computers
/// With a device identity, each computer says whether this device has access.
@@ -85,8 +104,8 @@ public struct CloudClient: Sendable {
/// Revokes only this phone's grants, so it can request a fresh approval without removing the computer.
public func revokeDeviceAccess(_ id: ComputerID) async throws {
- guard let identity else { throw CloudError(status: 0, code: "noDeviceKey", message: "Sign in again on this device.") }
- guard let device = try await devices().first(where: { $0.deviceKey == identity.publicKey }) else {
+ guard identity != nil else { throw CloudError(status: 0, code: "noDeviceKey", message: "Sign in again on this device.") }
+ guard let device = try await thisDevice() else {
throw CloudError(status: 404, code: "notFound", message: "This phone isn't registered in your account. Sign in again.")
}
for grant in try await grants(id) where grant.deviceId == device.deviceId {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift b/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
index 0eb7288a..a9b99aa0 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swift
@@ -40,6 +40,20 @@ public struct DeviceIdentity: Sendable {
Keychain.delete(service: pushService, account: context.id)
}
+ /// 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
+ }
+
+ /// Hands `source`'s keys to `target`, which must have none: hosts keep seeing the same device.
+ static func move(from source: SharedStore.Context, to target: SharedStore.Context) throws {
+ for service in [deviceService, pushService] {
+ guard let raw = try Keychain.read(service: service, account: source.id) else { continue }
+ try Keychain.add(raw, service: service, account: target.id)
+ Keychain.delete(service: service, account: source.id)
+ }
+ }
+
var deviceKey: Data { signing.publicKey.rawRepresentation }
func sign(_ data: Data) throws -> Data { try signing.signature(for: data) }
@@ -109,7 +123,15 @@ enum Keychain {
return q
}
+ #if DEBUG
+ /// The Kit's test bundle has no Keychain entitlement (-34018), so tests keep keys here; nil uses the Keychain.
+ static let memory = OSAllocatedUnfairLock<[String: Data]?>(initialState: nil)
+ #endif
+
static func read(service: String, account: String) throws -> Data? {
+ #if DEBUG
+ if let stored = memory.withLock({ $0 }) { return stored["\(service)/\(account)"] }
+ #endif
var q = query(service: service, account: account)
q[kSecReturnData] = true
q[kSecMatchLimit] = kSecMatchLimitOne
@@ -124,19 +146,36 @@ enum Keychain {
/// Stores a new key; if another process won the race, returns the one it stored.
static func create<K: RawKey>(service: String, account: String, _ make: () -> K) throws -> K {
let key = make()
- var q = query(service: service, account: account)
- q[kSecValueData] = key.rawRepresentation
- q[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
- switch SecItemAdd(q as CFDictionary, nil) {
- case errSecSuccess: return key
- case errSecDuplicateItem:
+ do {
+ try add(key.rawRepresentation, service: service, account: account)
+ return key
+ } catch let error as Failure where error.status == errSecDuplicateItem {
guard let raw = try read(service: service, account: account) else { throw Failure(status: errSecItemNotFound) }
return try K(rawRepresentation: raw)
- case let status: throw Failure(status: status)
}
}
+ static func add(_ raw: Data, service: String, account: String) throws {
+ #if DEBUG
+ if memory.withLock({ $0 != nil }) {
+ try memory.withLock { stored in
+ guard stored?["\(service)/\(account)"] == nil else { throw Failure(status: errSecDuplicateItem) }
+ stored?["\(service)/\(account)"] = raw
+ }
+ return
+ }
+ #endif
+ var q = query(service: service, account: account)
+ q[kSecValueData] = raw
+ q[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ let status = SecItemAdd(q as CFDictionary, nil)
+ guard status == errSecSuccess else { throw Failure(status: status) }
+ }
+
static func delete(service: String, account: String) {
+ #if DEBUG
+ if memory.withLock({ $0 != nil }) { memory.withLock { $0?["\(service)/\(account)"] = nil }; return }
+ #endif
SecItemDelete(query(service: service, account: account) as CFDictionary)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 6bdca6ac..25b24b43 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -352,6 +352,16 @@ public extension HostClient {
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.
+ func forgetDevice() async throws {
+ do {
+ let _: Empty = try await call("forgetDevice")
+ } catch {
+ let _: Empty = try await call("unregisterDevice")
+ }
+ }
+
func registerActivity(botId: String, ticket: String) async throws {
let _: Empty = try await call("registerActivity", ["botId": botId, "ticket": ticket])
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
index 84c40194..3a3165cd 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
@@ -24,8 +24,8 @@ public enum SharedStore {
/// The raw Clerk user ID; nil = the local (signed-out) context.
public let accountID: String?
/// The UserDefaults suite (the App Group; tests use their own).
- private let suite: String
- private var defaults: UserDefaults { UserDefaults(suiteName: suite) ?? .standard }
+ fileprivate let suite: String
+ fileprivate var defaults: UserDefaults { UserDefaults(suiteName: suite) ?? .standard }
public var id: String { accountID.map { Self.digest($0) } ?? "local" }
public init(accountID: String?, suite: String = SharedStore.appGroup) {
@@ -33,8 +33,8 @@ public enum SharedStore {
self.suite = suite
}
- private static let names = ["computers", "bots", "usage", "lastComputerId", "composerDrafts", "computerOrder", "shortcutLeadComputer"]
- private func key(_ name: String) -> String { accountID == nil ? name : "account.\(id).\(name)" }
+ fileprivate static let names = ["computers", "bots", "usage", "lastComputerId", "composerDrafts", "computerOrder", "shortcutLeadComputer"]
+ fileprivate func key(_ name: String) -> String { accountID == nil ? name : "account.\(id).\(name)" }
public static func digest(_ value: String) -> String {
SHA256.hash(data: Data(value.utf8)).map { String(format: "%02x", $0) }.joined()
}
@@ -124,6 +124,44 @@ public enum SharedStore {
}
}
+// MARK: signed-out pairings move into the account
+
+public extension SharedStore.Context {
+ /// What `adopt(from:)` did with the signed-out context's pairings: how many computers came over, and whether
+ /// this iPhone's keys came with them (`moved`: this context was new, so they keep working) or they have to be
+ /// paired again (`rescan`: this context has its own key).
+ struct Adoption: Equatable, Sendable {
+ public let computers: Int
+ public let keys: AnalyticsEvent.MovedKeys
+ }
+
+ /// Sign-in is required: the signed-out context's computers move into this account context, which
+ /// then erases it. Runs before this context's stores and keys load. Nil when there was nothing to move.
+ func adopt(from local: Self) -> Adoption? {
+ guard accountID != nil, local.accountID == nil, local.suite == suite else { return nil }
+ let moving = local.computers
+ guard !moving.isEmpty || DeviceIdentity.exists(context: local) else { return nil }
+ defer { local.erase() }
+ if !DeviceIdentity.exists(context: self), computers.isEmpty {
+ do {
+ try DeviceIdentity.move(from: local, to: self)
+ } catch {
+ Logger(subsystem: "com.pokai.Codync", category: "Account").error("Cannot move the device key: \(error.localizedDescription)")
+ return merge(moving)
+ }
+ for name in Self.names { defaults.set(local.defaults.object(forKey: local.key(name)), forKey: key(name)) }
+ return Adoption(computers: moving.count, keys: .moved)
+ }
+ return merge(moving)
+ }
+
+ private func merge(_ moving: [Computer]) -> Adoption {
+ let known = Set(computers.map(\.id))
+ computers += moving.filter { !known.contains($0.id) }
+ return Adoption(computers: moving.count, keys: .rescan)
+ }
+}
+
public extension SharedStore.Context {
/// Every usage provider this account's computers have reported, plus Claude and Codex so
/// there's a choice before the first report. Sorted by name.
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 3e6e0486..318c2a42 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "Abmeldung fehlgeschlagen. Prüfe deine Verbindung und versuche es erneut.",
"Couldn't switch accounts. Check your connection or sign in again.": "Kontowechsel fehlgeschlagen. Prüfe deine Verbindung oder melde dich erneut an.",
"Couldn't finish signing in. Please try again.": "Anmeldung konnte nicht abgeschlossen werden. Versuche es erneut.",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "Die Anmeldung ist noch nicht fertig eingerichtet. Du kannst weiterhin lokale Kopplung verwenden.",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "Die Apple-Anmeldung benötigt eine zusätzliche Bestätigung. Dein Konto ist noch nicht angemeldet.",
"Google sign-in needs additional verification. Your account is not signed in yet.": "Die Google-Anmeldung benötigt eine zusätzliche Bestätigung. Dein Konto ist noch nicht angemeldet.",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "Die Apple-Registrierung benötigt zusätzliche Kontodaten. Dein Konto ist noch nicht angemeldet.",
@@ -1479,5 +1478,16 @@
"It's in another account.": "Er ist in einem anderen Konto.",
"New devices ask for access with a 6-digit code.": "Neue Geräte fragen mit einem 6-stelligen Code nach Zugriff.",
"Keep it there": "Dort lassen",
- "Move here": "Hierher verschieben"
+ "Move here": "Hierher verschieben",
+ "Delete account": "Konto löschen",
+ "Delete your Codync account?": "Dein Codync-Konto löschen?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "Dein Konto, seine Computerliste und der Zugriff jedes Geräts darüber werden gelöscht. Deine Computer behalten ihre Bots und Chats. Das lässt sich nicht rückgängig machen.",
+ "Couldn't delete your account. Check your connection and try again.": "Konto konnte nicht gelöscht werden. Prüfe deine Verbindung und versuche es erneut.",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "Melde dich an, um deinen Computer weiter zu nutzen. Er wandert in dein Konto, du musst nicht erneut scannen.",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "Melde dich an, um deine {count} Computer weiter zu nutzen. Sie wandern in dein Konto, du musst nicht erneut scannen.",
+ "This computer is in {name}'s account": "Dieser Computer ist im Konto von {name}",
+ "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"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 4ad8bfe2..fa627307 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "No se pudo cerrar sesión. Comprueba tu conexión y vuelve a intentarlo.",
"Couldn't switch accounts. Check your connection or sign in again.": "No se pudo cambiar de cuenta. Comprueba tu conexión o inicia sesión otra vez.",
"Couldn't finish signing in. Please try again.": "No se pudo completar el inicio de sesión. Vuelve a intentarlo.",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "La configuración del inicio de sesión no está terminada. Puedes seguir usando la vinculación local.",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "El inicio de sesión con Apple requiere verificación adicional. Tu cuenta aún no ha iniciado sesión.",
"Google sign-in needs additional verification. Your account is not signed in yet.": "El inicio de sesión con Google requiere verificación adicional. Tu cuenta aún no ha iniciado sesión.",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "El registro con Apple requiere información adicional de la cuenta. Tu cuenta aún no ha iniciado sesión.",
@@ -1479,5 +1478,16 @@
"It's in another account.": "Está en otra cuenta.",
"New devices ask for access with a 6-digit code.": "Los dispositivos nuevos piden acceso con un código de 6 dígitos.",
"Keep it there": "Dejarla ahí",
- "Move here": "Mover aquí"
+ "Move here": "Mover aquí",
+ "Delete account": "Eliminar cuenta",
+ "Delete your Codync account?": "¿Eliminar tu cuenta de Codync?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "Se eliminan tu cuenta, su lista de ordenadores y el acceso de cada dispositivo a través de ella. Tus ordenadores conservan sus bots y chats. No se puede deshacer.",
+ "Couldn't delete your account. Check your connection and try again.": "No se pudo eliminar tu cuenta. Comprueba tu conexión e inténtalo de nuevo.",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "Inicia sesión para seguir usando tu ordenador. Pasa a tu cuenta, así que no tendrás que volver a escanear.",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "Inicia sesión para seguir usando tus {count} ordenadores. Pasan a tu cuenta, así que no tendrás que volver a escanear.",
+ "This computer is in {name}'s account": "Este ordenador está en la cuenta de {name}",
+ "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"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 8d40baac..70e0277a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "Déconnexion impossible. Vérifiez votre connexion réseau et réessayez.",
"Couldn't switch accounts. Check your connection or sign in again.": "Impossible de changer de compte. Vérifiez la connexion ou reconnectez-vous.",
"Couldn't finish signing in. Please try again.": "Impossible de terminer la connexion. Réessayez.",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "La configuration de la connexion n’est pas terminée. Vous pouvez continuer avec l’association locale.",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "La connexion Apple nécessite une vérification supplémentaire. Votre compte n’est pas encore connecté.",
"Google sign-in needs additional verification. Your account is not signed in yet.": "La connexion Google nécessite une vérification supplémentaire. Votre compte n’est pas encore connecté.",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "L’inscription Apple nécessite des informations supplémentaires. Votre compte n’est pas encore connecté.",
@@ -1479,5 +1478,16 @@
"It's in another account.": "Il est dans un autre compte.",
"New devices ask for access with a 6-digit code.": "Les nouveaux appareils demandent l'accès avec un code à 6 chiffres.",
"Keep it there": "Le laisser là",
- "Move here": "Déplacer ici"
+ "Move here": "Déplacer ici",
+ "Delete account": "Supprimer le compte",
+ "Delete your Codync account?": "Supprimer votre compte Codync ?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "Votre compte, sa liste d'ordinateurs et l'accès de chaque appareil qui en dépend sont supprimés. Vos ordinateurs gardent leurs bots et leurs conversations. Action irréversible.",
+ "Couldn't delete your account. Check your connection and try again.": "Suppression du compte impossible. Vérifiez votre connexion réseau et réessayez.",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "Connectez-vous pour continuer à utiliser votre ordinateur. Il rejoint votre compte : inutile de scanner à nouveau.",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "Connectez-vous pour continuer à utiliser vos {count} ordinateurs. Ils rejoignent votre compte : inutile de scanner à nouveau.",
+ "This computer is in {name}'s account": "Cet ordinateur est dans le compte de {name}",
+ "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"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 5adef211..4edddba8 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "Couldn't sign out.接続を確認して、もう一度試してください。",
"Couldn't switch accounts. Check your connection or sign in again.": "アカウントを切り替えられませんでした。接続を確認するか、再度サインインしてください。",
"Couldn't finish signing in. Please try again.": "サインインを完了できませんでした。もう一度お試しください。",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "サインインの設定はまだ完了していません。ローカル ペアリングを引き続き使用できます。",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "Apple サインインには追加の検証が必要です。あなたのアカウントはまだサインインしていません。",
"Google sign-in needs additional verification. Your account is not signed in yet.": "Google サインインには追加の検証が必要です。あなたのアカウントはまだサインインしていません。",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "Apple のサインアップには追加のアカウント情報が必要です。あなたのアカウントはまだサインインしていません。",
@@ -1479,5 +1478,16 @@
"It's in another account.": "別のアカウントに入っています。",
"New devices ask for access with a 6-digit code.": "新しいデバイスは6桁のコードでアクセスをリクエストします。",
"Keep it there": "そのままにする",
- "Move here": "ここに移動"
+ "Move here": "ここに移動",
+ "Delete account": "アカウントを削除",
+ "Delete your Codync account?": "Codync アカウントを削除しますか?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "アカウント、そのコンピュータの一覧、アカウント経由の各デバイスのアクセス権が削除されます。コンピュータのボットとチャットは残ります。元に戻すことはできません。",
+ "Couldn't delete your account. Check your connection and try again.": "アカウントを削除できませんでした。接続を確認して、もう一度お試しください。",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "サインインすると、このコンピュータをそのまま使えます。アカウントに移されるので、もう一度スキャンする必要はありません。",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "サインインすると、{count} 台のコンピュータをそのまま使えます。アカウントに移されるので、もう一度スキャンする必要はありません。",
+ "This computer is in {name}'s account": "このコンピュータは {name} のアカウントにあります",
+ "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": "このコンピュータはあなたのアカウントにありません"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index d23f5b25..8efe98eb 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "로그아웃하지 못했습니다. 연결을 확인하고 다시 시도하세요.",
"Couldn't switch accounts. Check your connection or sign in again.": "계정을 전환하지 못했습니다. 연결을 확인하거나 다시 로그인하세요.",
"Couldn't finish signing in. Please try again.": "로그인을 완료하지 못했습니다. 다시 시도하세요.",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "로그인 설정이 아직 완료되지 않았습니다. 로컬 페어링은 계속 사용할 수 있습니다.",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "Apple 로그인에 추가 인증이 필요합니다. 아직 계정에 로그인되지 않았습니다.",
"Google sign-in needs additional verification. Your account is not signed in yet.": "Google 로그인에 추가 인증이 필요합니다. 아직 계정에 로그인되지 않았습니다.",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "Apple 가입에 추가 계정 정보가 필요합니다. 아직 계정에 로그인되지 않았습니다.",
@@ -1479,5 +1478,16 @@
"It's in another account.": "다른 계정에 있습니다.",
"New devices ask for access with a 6-digit code.": "새 기기는 6자리 코드로 접근을 요청합니다.",
"Keep it there": "그대로 두기",
- "Move here": "여기로 옮기기"
+ "Move here": "여기로 옮기기",
+ "Delete account": "계정 삭제",
+ "Delete your Codync account?": "Codync 계정을 삭제할까요?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "계정, 계정의 컴퓨터 목록, 계정을 통한 모든 기기의 접근 권한이 삭제됩니다. 컴퓨터의 봇과 대화는 그대로 남습니다. 되돌릴 수 없습니다.",
+ "Couldn't delete your account. Check your connection and try again.": "계정을 삭제하지 못했습니다. 연결을 확인하고 다시 시도하세요.",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "로그인하면 컴퓨터를 계속 사용할 수 있습니다. 계정으로 옮겨지므로 다시 스캔할 필요가 없습니다.",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "로그인하면 컴퓨터 {count}대를 계속 사용할 수 있습니다. 계정으로 옮겨지므로 다시 스캔할 필요가 없습니다.",
+ "This computer is in {name}'s account": "이 컴퓨터는 {name}의 계정에 있습니다",
+ "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": "이 컴퓨터는 내 계정에 없습니다"
}
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 4134a885..6cc5d606 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "退出失败。检查网络后再试一次。",
"Couldn't switch accounts. Check your connection or sign in again.": "切换账户失败。检查网络,或重新登录。",
"Couldn't finish signing in. Please try again.": "登录没有完成。请再试一次。",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "登录还没配置好。你可以继续用本机配对。",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "Apple 登录还需要额外验证。账户还没有登录。",
"Google sign-in needs additional verification. Your account is not signed in yet.": "Google 登录还需要额外验证。账户还没有登录。",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "Apple 注册还需要补充账户信息。账户还没有登录。",
@@ -1479,5 +1478,16 @@
"It's in another account.": "它在另一个账户里。",
"New devices ask for access with a 6-digit code.": "新设备要用 6 位验证码请求访问。",
"Keep it there": "留在原处",
- "Move here": "移到这里"
+ "Move here": "移到这里",
+ "Delete account": "删除账户",
+ "Delete your Codync account?": "要删除你的 Codync 账户吗?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "你的账户、账户里的电脑列表,以及每台设备通过账户获得的使用权都会删除。电脑上的 bot 和对话会保留。无法撤销。",
+ "Couldn't delete your account. Check your connection and try again.": "删除账户失败。检查网络后再试一次。",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "登录后就能继续使用你的电脑。它会移进你的账户,不用再扫一次。",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "登录后就能继续使用你的 {count} 台电脑。它们会移进你的账户,不用再扫一次。",
+ "This computer is in {name}'s account": "这台电脑在 {name} 的账户里",
+ "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": "这台电脑不在你的账户里"
}
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 6edae300..8cc914ab 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -778,7 +778,6 @@
"Couldn't sign out. Check your connection and try again.": "退出失敗。檢查網路後再試一次。",
"Couldn't switch accounts. Check your connection or sign in again.": "切換賬戶失敗。檢查網路,或重新登入。",
"Couldn't finish signing in. Please try again.": "登入沒有完成。請再試一次。",
- "Sign-in setup isn't finished yet. You can continue using local pairing.": "登入還沒配置好。你可以繼續用本機配對。",
"Apple sign-in needs additional verification. Your account is not signed in yet.": "Apple 登入還需要額外驗證。賬戶還沒有登入。",
"Google sign-in needs additional verification. Your account is not signed in yet.": "Google 登入還需要額外驗證。賬戶還沒有登入。",
"Apple sign-up needs additional account information. Your account is not signed in yet.": "Apple 註冊還需要補充賬戶資訊。賬戶還沒有登入。",
@@ -1479,5 +1478,16 @@
"It's in another account.": "它在另一個賬戶裡。",
"New devices ask for access with a 6-digit code.": "新裝置要用 6 位驗證碼請求訪問。",
"Keep it there": "留在原處",
- "Move here": "移到這裡"
+ "Move here": "移到這裡",
+ "Delete account": "刪除賬戶",
+ "Delete your Codync account?": "要刪除你的 Codync 賬戶嗎?",
+ "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.": "你的賬戶、賬戶裡的電腦清單,以及每台裝置透過賬戶取得的使用權都會刪除。電腦上的 bot 和對話會保留。無法撤銷。",
+ "Couldn't delete your account. Check your connection and try again.": "刪除賬戶失敗。檢查網路後再試一次。",
+ "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "登入後就能繼續使用你的電腦。它會移進你的賬戶,不用再掃一次。",
+ "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "登入後就能繼續使用你的 {count} 台電腦。它們會移進你的賬戶,不用再掃一次。",
+ "This computer is in {name}'s account": "這臺電腦在 {name} 的賬戶裡",
+ "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": "這臺電腦不在你的賬戶裡"
}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
index 5eec738a..95b2a5b6 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
@@ -68,6 +68,7 @@ import Testing
#expect(try json(.voiceCallQuality(.onDevice, readyMs: nil, reconnects: 0, stuck: .connecting, failure: .none))
== #"{"engine":"on_device","failure":"none","reconnects":0,"stuck":"connecting"}"#)
#expect(try json(.linkOpened(.installCommand)) == #"{"link":"install_command"}"#)
+ #expect(try json(.signedOutPairingsMoved(computers: 2, keys: .rescan)) == #"{"computers":2,"keys":"rescan"}"#)
#expect(AnalyticsEvent.notificationOpened(.needsInput).name == "notification_opened")
#expect(AnalyticsEvent.NotificationKind(category: "needsInput") == .needsInput)
#expect(AnalyticsEvent.NotificationKind(category: "other") == nil)
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift
new file mode 100644
index 00000000..793ae355
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/RevokeThisDeviceTests.swift
@@ -0,0 +1,47 @@
+import Foundation
+import os
+import Testing
+@testable import CodyncKit
+
+/// Answers `GET /v1/devices` with this phone and another one, and records every call with its token.
+private final class DevicesStub: URLProtocol {
+ static let state = OSAllocatedUnfairLock(initialState: (deviceKey: "", calls: [String]()))
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ let call = "\(request.httpMethod!) \(request.url!.path) \(request.value(forHTTPHeaderField: "Authorization") ?? "")"
+ let key = Self.state.withLock { state in
+ state.calls.append(call)
+ return state.deviceKey
+ }
+ let json = request.url!.path == "/v1/devices"
+ ? #"{"devices":[{"deviceId":"other-phone","deviceKey":"other","name":"Other"},{"deviceId":"this-phone","deviceKey":"\#(key)","name":"Phone"}]}"#
+ : "{}"
+ client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Data(json.utf8))
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
+@Suite(.serialized) struct RevokeThisDeviceTests {
+ @Test func signingOutDeletesOnlyThisDeviceOnTheTokenTakenBefore() 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.revokeThisDevice()
+
+ #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")
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
new file mode 100644
index 00000000..adb010ef
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
@@ -0,0 +1,59 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+/// The signed-out context's Keychain items are shared by every test here, so they run one at a time.
+@Suite(.serialized) struct SignedOutAdoptionTests {
+ private let v = Vectors.shared
+
+ private func contexts() -> (local: SharedStore.Context, account: SharedStore.Context, suite: String) {
+ Keychain.memory.withLock { $0 = $0 ?? [:] }
+ let suite = "CodyncTests.\(UUID().uuidString)"
+ let local = SharedStore.Context(accountID: nil, suite: suite)
+ local.erase()
+ return (local, SharedStore.Context(accountID: "user_\(UUID().uuidString)", suite: suite), suite)
+ }
+
+ @Test func aNewAccountContextTakesTheKeysAndComputers() throws {
+ let (local, account, suite) = contexts()
+ defer { account.erase(); UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let key = try DeviceIdentity.load(context: local)
+ local.computers = [v.computer]
+ local.composerDrafts = [v.computer.id: ["b1": "draft"]]
+
+ #expect(account.adopt(from: local) == .init(computers: 1, keys: .moved))
+ #expect(account.computers == [v.computer])
+ #expect(account.composerDrafts[v.computer.id]?["b1"] == "draft")
+ let moved = try DeviceIdentity.load(context: account)
+ #expect(moved.publicKey == key.publicKey, "hosts see the same device")
+ #expect(moved.pushKey == key.pushKey, "push keeps opening")
+ #expect(local.computers.isEmpty && !DeviceIdentity.exists(context: local))
+ #expect(account.adopt(from: local) == nil, "nothing left to move")
+ }
+
+ @Test func aUsedAccountContextKeepsItsKeyAndListsTheComputers() throws {
+ let (local, account, suite) = contexts()
+ defer { account.erase(); UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let own = try DeviceIdentity.load(context: account)
+ var mine = v.computer
+ mine.name = "Account copy"
+ account.computers = [mine]
+ _ = try DeviceIdentity.load(context: local)
+ var other = v.computer
+ other.id = "other"
+ local.computers = [v.computer, other]
+
+ #expect(account.adopt(from: local) == .init(computers: 2, keys: .rescan))
+ #expect(account.computers.map(\.id) == [v.computer.id, "other"])
+ #expect(account.computers.first?.name == "Account copy", "the account's entry wins")
+ #expect(try DeviceIdentity.load(context: account).publicKey == own.publicKey)
+ #expect(local.computers.isEmpty && !DeviceIdentity.exists(context: local))
+ }
+
+ @Test func nothingToMove() {
+ let (local, account, suite) = contexts()
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ #expect(account.adopt(from: local) == nil)
+ #expect(local.adopt(from: account) == nil, "only into an account context")
+ }
+}
diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swift
index 111d484a..20e952dd 100644
--- a/apps/ios/Views/AccountSwitcherView.swift
+++ b/apps/ios/Views/AccountSwitcherView.swift
@@ -28,6 +28,7 @@ struct AccountSwitcherView: View {
@Environment(AppStore.self) private var app
@Environment(AccountSession.self) private var account
@State private var confirmSignOut = false
+ @State private var confirmDelete = false
@State private var pairing = false
@State private var addingAccount = false
@@ -63,6 +64,11 @@ struct AccountSwitcherView: View {
}
.buttonStyle(.plain)
.disabled(account.isBusy)
+ Button { confirmDelete = true } label: {
+ RowLabel("Delete account", systemImage: "trash", tint: Palette.danger)
+ }
+ .buttonStyle(.plain)
+ .disabled(account.isBusy)
}
}
@@ -93,6 +99,10 @@ struct AccountSwitcherView: View {
message: "This iPhone forgets the account's computers. Your bots stay on them.") {
[DialogAction("Sign out", destructive: true) { Task { await app.signOut() } }]
}
+ .codyncDialog("Delete your Codync account?", isPresented: $confirmDelete,
+ message: "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone.") {
+ [DialogAction("Delete account", destructive: true) { Task { await app.deleteAccount() } }]
+ }
}
/// The big picture: your face and address when signed in, both login options when not.
diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swift
index 57562635..b645ac1a 100644
--- a/apps/ios/Views/RootView.swift
+++ b/apps/ios/Views/RootView.swift
@@ -19,7 +19,11 @@ struct RootView: View {
var body: some View {
Group {
- if !onboardingCompleted && accounts.computers.isEmpty && accounts.cloudComputers.isEmpty {
+ if mustSignIn {
+ // Computers paired before sign-in was required wait in the signed-out context.
+ WelcomeView(signedOutComputers: accounts.computers.count) {}
+ .transition(.opacity)
+ } else if !onboardingCompleted && accounts.computers.isEmpty && accounts.cloudComputers.isEmpty {
if !welcomed && !account.isSignedIn {
WelcomeView { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { welcomed = true } }
.transition(.move(edge: .leading).combined(with: .opacity))
@@ -104,6 +108,12 @@ struct RootView: View {
}
}
+ /// Every build with accounts requires sign-in. While Clerk restores, the last signed-in account's context
+ /// stays on screen, so an offline launch still reaches its computers.
+ private var mustSignIn: Bool {
+ account.isConfigured && !account.isSignedIn && (account.isReady || accounts.accountId == nil)
+ }
+
/// Once per setup (Start over begins a new one): the first computer reached, or Skip.
private func completeOnboarding(via: AnalyticsEvent.OnboardingVia) {
guard !onboardingCompleted else { return }
diff --git a/apps/ios/Views/WelcomeView.swift b/apps/ios/Views/WelcomeView.swift
index 22624533..e9b79812 100644
--- a/apps/ios/Views/WelcomeView.swift
+++ b/apps/ios/Views/WelcomeView.swift
@@ -2,8 +2,11 @@ import CodyncKit
import CodyncUI
import SwiftUI
-/// First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward.
+/// Before any setup, and whenever signed out: who the bots are, a glimpse of talking to one, one way forward.
+/// With accounts that way is signing in; builds without them go straight on to pairing.
struct WelcomeView: View {
+ /// Computers paired before sign-in was required; they move into the account at sign-in.
+ var signedOutComputers = 0
let start: () -> Void
@Environment(AccountSession.self) private var account
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@@ -57,12 +60,25 @@ struct WelcomeView: View {
Spacer(minLength: 32)
VStack(spacing: 10) {
- Button(action: start) {
- Text(L10n.tr("Get started")).font(.headline).frame(maxWidth: .infinity, minHeight: 50)
+ if signedOutComputers > 0 {
+ Text(signedOutComputers == 1
+ ? L10n.tr("Sign in to keep using your computer. It moves into your account, so you won't need to scan again.")
+ : L10n.tr("Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.")
+ .replacingOccurrences(of: "{count}", with: String(signedOutComputers)))
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.bottom, 4)
+ }
+ if account.isConfigured {
+ SignInButtons().disabled(!account.isReady)
+ } else {
+ Button(action: start) {
+ Text(L10n.tr("Get started")).font(.headline).frame(maxWidth: .infinity, minHeight: 50)
+ }
+ .buttonStyle(.primary)
}
- .buttonStyle(.primary)
- // Signed in, the computers on the account show up without scanning a code.
- if account.isConfigured { SignInButtons() }
if let message = account.errorMessage {
Text(message).font(.footnote).foregroundStyle(Palette.danger)
.transition(.opacity)
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 1d3a3758..abf4c30b 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -5,3 +5,14 @@ listing what iPhone users notice, without emoji (the App Store rejects them; asc
any left). tools/asc-submit.py reads the released version's section;
a version without one gets a generic "Bug fixes and improvements" line. Delete old sections.
-->
+
+## 2.35.0
+### zh-Hant
+- Codync 現在需要用 Apple 或 Google 登入。以前沒登入就配對的電腦,第一次登入時會一起移進你的賬戶,不用再掃一次。
+- 登出時,這支手機會從它連得到的電腦和你的賬戶中移除。
+- 可以在 App 裡刪除賬戶:點 Bots 分頁左上角的賬戶按鈕,再點「刪除賬戶」。
+
+### en-US
+- Codync now asks you to sign in with Apple or Google. 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.
+- You can delete your account in the app: tap the account button at the top left of the Bots tab, then Delete account.
diff --git a/apps/project.yml b/apps/project.yml
index 32fe635c..562c3d35 100644
--- a/apps/project.yml
+++ b/apps/project.yml
@@ -25,7 +25,7 @@ configs:
DevRelease: release
settings:
base:
- MARKETING_VERSION: 2.34.2
+ MARKETING_VERSION: 2.35.0
CURRENT_PROJECT_VERSION: 24
SWIFT_VERSION: "6.0"
SWIFT_STRICT_CONCURRENCY: complete
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index 89ea17f7..ad06eb22 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -62,8 +62,8 @@ The desktop app runs on a computer with its own host, so its account and the com
| Computer | Its own app | Shown |
| --- | --- | --- |
| In A | Signed in to A | Nothing |
-| In A | Signed in to B | Asked once, **Move this computer to your account?** (*Keep it there* is remembered). After that, one small line in the main window: "This computer is in a•••@gmail.com's account", which opens the same choice |
-| In no account | Signed in | Joins on its own (`mayAutoClaim`), unless the cloud is off, it uses a private relay, or the user took it out; then the same small line says why |
+| In A | Signed in to B | Asked once, **Move this computer to your account?** (*Keep it there* is remembered). After that, an amber notice above the sidebar's account button, its text in full: "This computer is in a•••@gmail.com's account", which opens the same choice |
+| In no account | Signed in | Joins on its own (`mayAutoClaim`), unless the cloud is off, it uses a private relay, or the user took it out; then the same notice says which, and opens Settings → Computers |
The app manages its computer through loopback either way. Only same-account phones can pair with it (rule 3), so a B phone that tries is told which account the computer is in and how to move it.
@@ -135,12 +135,12 @@ 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` | Not built: no client has it |
-| 2 | Sign-out hands the key back (iPhone, Android) | Not built: iPhone erases locally only; Android tells only the computer it is connected to |
-| 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 | Not built |
+| 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) |
+| 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 | Not built: QR pairs any phone holding the code |
| 5 | Changing accounts drops every old-account device; the move dialog's text says so | Not built: QR devices are kept today |
-| 6 | The main-window line for an app and computer in different accounts; the phone's refusal text | Not built: Settings and the one-time dialog only |
+| 6 | The main-window line for an app and computer in different accounts; the phone's refusal text | Desktop line built (2.35.0); the refusal text comes with item 4 |
| 7 | One-click host install over SSH, then **Add to account** on its own | Not built: shows a `brew` command to copy |
| 8 | Honor the 15-minute lease when the relay drops | Not built: account devices are refused until the cloud state syncs again |
| 9 | The renames above, in every client | Not built |
diff --git a/docs/design/mobile-widgets.md b/docs/design/mobile-widgets.md
index 8f6e1aa5..bddeebbb 100644
--- a/docs/design/mobile-widgets.md
+++ b/docs/design/mobile-widgets.md
@@ -13,7 +13,7 @@
## Onboarding 與帳號
-1. 首次開啟由 Welcome 提供 Get started 與 Google 登入,再進入配對/帳號電腦流程。
+1. 首次開啟由 Welcome 提供 Apple/Google 登入(必須登入;沒有 Clerk 的 build 才有 Get started),再進入配對/帳號電腦流程。
2. 儲存第一台配對電腦後,記錄此裝置的 `onboardingCompleted`。
3. 既有已配對安裝自動視為完成 onboarding。
4. 完成後才顯示帳號入口;切換到沒有電腦的帳號,或解除配對後,入口仍保留,避免無法切回原帳號。
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index 65d7a135..f5c7ccd7 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -103,9 +103,11 @@ returning-user login, cancellation, restoration, account switching and sign-out
on a real device before release. Build success and enabled dashboard settings do
not prove that an Apple authorization completed successfully.
-QR pairing does not require matching email addresses or even a signed-in computer.
-The iPhone's scan step always offers **Skip**, including when signed out or when
-the account has no computers. Skipping finishes onboarding and opens the main
+Every build with Clerk requires sign-in on the phone and the desktop app
+([require sign-in](../plans/require-sign-in.md)); builds without Clerk keep the
+signed-out context. QR pairing does not yet require the phone and the computer to
+be in the same account (phase 2). The iPhone's scan step always offers **Skip**,
+including when the account has no computers. Skipping finishes onboarding and opens the main
tabs; this choice survives relaunches and account changes. The empty Bots screen
offers **Computers** to pair later. Skipping while adding a computer from settings
only closes that pairing sheet. It does not grant access to a computer or change
@@ -190,10 +192,14 @@ single-session enabled, it asks the user to sign out before using another accoun
Signing out passes the current session ID, rather than signing out all accounts.
Computers, device keys and caches are partitioned by the Clerk user ID on this
-iPhone (`SharedStore.Context`). Computers paired with a code while signed out stay
-in the local context and are not claimed by a newly signed-in user. Each account
-context gets its own `AccountStore`, retired when changing accounts; signing out
-erases that account's computers, device and push keys and caches from the iPhone.
+iPhone (`SharedStore.Context`). Computers paired with a code while signed out
+(before sign-in was required) move into the first account used on the phone:
+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.
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/plans/android-app.md b/docs/plans/android-app.md
index 6b5c7d60..640ddac1 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -102,12 +102,13 @@ the Dynamic Island) with its feature graphic, per language.
Play Console. Set the repository variable `PLAY_TRACK=alpha` once it runs, then run
`Submit Android` by hand with the current version and `alpha` (it moves the version Play
already has there) or promote it in Play Console.
-- [ ] Account deletion inside the app: Play requires it for apps that create accounts. Today an
- account is deleted on request (`codync.dev/privacy#delete-account`, by email); add a *Delete
- account* action (cloud method that deletes the Clerk user, whose webhook already removes the
- rest) to every client.
-- [ ] Reviewer access: pairing needs a computer, so review needs a way in (a demo video of
- pairing and a chat, or a reusable demo host), linked from App content → Login details.
+- [x] Account deletion inside the app: *Delete account* in the account sheet (2.35.0) deletes the
+ Clerk user, whose webhook removes the rest. The web address Play asks for is
+ `codync.dev/delete-account`.
+- [ ] Reviewer access: the app requires sign-in (2.35.0), and pairing needs a computer. In App
+ content → App access, say that the reviewer signs in with any Google account (no credentials
+ needed), and link a way to a computer (a demo video of pairing and a chat, or a reusable demo
+ host).
- [ ] The foreground service video Play asks for the microphone and media playback services
(voice calls), if it asks when the release goes to review.
- [ ] Physical upgrade keeps the saved account, pinned keys, bots and history.
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index 443dfc0a..6492a99d 100644
--- a/docs/plans/require-sign-in.md
+++ b/docs/plans/require-sign-in.md
@@ -1,6 +1,6 @@
# Require sign-in
-Plan agreed 2026-11-02 for [connections and accounts](../architecture/connections.md): every app is signed in, every phone-to-computer link lives in one account, and QR stays as the in-person way to pair. Nothing here is built yet.
+Plan agreed 2026-11-02 for [connections and accounts](../architecture/connections.md): every app is signed in, every phone-to-computer link lives in one account, and QR stays as the in-person way to pair. Phase 1 is built (2.35.0); phases 2 and 3 are not.
## Decisions
@@ -33,11 +33,11 @@ App Store 5.1.1(v) and Google Play require in-app deletion for any app that crea
- **Where:** the account sheet on iPhone (`AccountSwitcherView.swift`) and Android (`AccountSwitcherView.kt`), under **Sign out**; the desktop account menu (`PanelMenus.tsx`).
- **Confirmation dialog**, title "Delete your Codync account?", message: "Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone." Actions: **Delete account** (destructive), **Cancel**.
- **Steps:**
- 1. Hand back the key, the same way as signing out (section 2).
- 2. Delete the user in Clerk:
+ 1. Delete the user in Clerk first. When that fails ("Couldn't delete your account. Check your connection and try again."), nothing else changes:
- 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.
- **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.
@@ -47,15 +47,16 @@ App Store 5.1.1(v) and Google Play require in-app deletion for any app that crea
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):
-1. **Computers this phone can reach:** call the new host method `forgetDevice`. It removes the caller's own device row and push tickets.
+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.
-2. **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.
-3. **Clerk:** sign out, switch context, erase (as today).
+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).
-The two calls are best effort, with a short timeout each. Signing out never fails because a computer or the cloud is unreachable.
+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.
-**Host (`host/src/api/remote.rs`):** `forgetDevice` is for a device caller only. It removes `caller.device_key()` from devices and push tickets and emits `devices` so the desktop list updates. It is additive, so `minApp` doesn't change.
+**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.
### 3. Sign-in gate
@@ -82,6 +83,8 @@ The two calls are best effort, with a short timeout each. Signing out never fail
- With Clerk configured, **Continue on this Mac** (the button and the skip link) goes, and the welcome shows only **Continue with Apple** / **Continue with Google**.
- `onboarded` alone no longer opens the chat window. The welcome shows whenever the app is configured, ready and signed out, so signing out from the account menu returns to it.
- The host keeps running while signed out, and so do the tray and menu bar.
+- Signing out also revokes the desktop app's own cloud device (`DELETE /v1/devices/{id}`, best effort, on a token taken before Clerk signs out) once Clerk has signed out, then its key file goes: the cloud refuses a revoked key, so the next sign-in makes a new one.
+- A saved session stays "restoring" (retried every 30 seconds) until Clerk turns it down (401, 403 or 404) or answers, so a launch offline, behind a captive portal or during a Clerk outage isn't stopped at the welcome.
- Builds without Clerk keep **Continue on this Mac**.
### 4. Move signed-out pairings into the account
@@ -93,14 +96,14 @@ Runs on iPhone and Android when an account becomes active and the signed-out con
| **New** (no device key, no computers) | Everything moves: the device and push keys, the computers, order, drafts, shortcut lead, widget snapshot. Hosts see the same key, so nothing is paired again and push keeps working |
| **Already used** (has its own key) | The computer lists merge (the account's entry wins for the same id). Computers paired only with the signed-out key are refused by their hosts; they show the existing "pair again" state (`isStale`) |
-After either case the signed-out context is erased, and an analytics event `signed_out_pairings_moved {computers, keys: moved|rescan}` is sent (added to [analytics](../features/analytics.md) and both apps).
+After either case the signed-out context is erased, and when computers moved an analytics event `signed_out_pairings_moved {computers, keys: moved|rescan}` is sent (in [analytics events](../reference/analytics-events.md) and both apps).
**iOS**
- `SharedStore.Context.adopt(from:)` in the Kit:
- Moves the Keychain items `com.pokai.Codync.device-key` / `push-key` from account `local` to the context id.
- Moves the `UserDefaults` names in `Context.names` to their `account.<id>.` keys.
- - Moves `ActivityIconCache`.
- - Drops `codync-mirror-local-*` caches, which rebuild.
+ - Drops `ActivityIconCache` and the `codync-mirror-local-*` caches, which rebuild.
+ - The Kit's test bundle has no Keychain entitlement, so its tests keep keys in memory (`Keychain.memory`, debug builds only).
- Unit tests in `CodyncKitTests` cover both cases.
**Android**
@@ -112,13 +115,14 @@ After either case the signed-out context is erased, and an analytics event `sign
### 5. Desktop: computer in another account
-- **Logic:** a pure function next to `mayOfferMove` in `lib/auto-claim.ts`, `accountMismatch(host, userId)`. It returns one of three values:
+- **Logic:** a pure function next to `mayOfferMove` in `lib/auto-claim.ts`, `accountMismatch(host, userId, keptOut, seen)`. It returns one of three values:
- `other {email}`;
- `none {reason: cloudOff | privateRelay | keptOut}`;
- `null` when the accounts match.
Tested in `auto-claim.test.ts`.
-- **One line** in the sidebar footer (`SidebarFooter.tsx`), caption size and secondary color, for example "This computer is in a•••@gmail.com's account". It takes no space when there's no mismatch.
- - Clicking it reopens the move choice (`MoveComputerPrompt`), even after *Keep it there*. For `none`, it opens Settings → Computers.
+- **A notice** above the sidebar footer's buttons (`SidebarFooter.tsx`): an amber card with an icon that shows its text in full, wrapping as needed, and takes no space when there's no mismatch. The narrow rail shows it as an amber icon with the text as its tooltip.
+ - `other`: "This computer is in {email}'s account", with the full address as Settings and the move dialog show it. Clicking it reopens the move choice (`MoveComputerPrompt`), even after *Keep it there*.
+ - `none`: "This computer isn't in an account: its cloud is off" / "…: it uses a private relay", or "This computer isn't in your account" (taken out). Clicking it opens Settings → Computers.
- **The move dialog** stays as it is in this phase. Its "QR-paired devices keep access" text changes in phase 2.
### 6. Docs and release
@@ -146,10 +150,10 @@ After either case the signed-out context is erased, and an analytics event `sign
| --- | --- |
| 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 | Sign in, sign out, pair signed out, sign in again: the signed-out computer shows "pair again" |
+| 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 |
| 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 line shows and reopens the move choice |
+| 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 |
### Risks
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index b91f7ba7..312afd06 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -37,13 +37,14 @@ host answers and sends it once the host is up.
| `window_opened` | host `track` (desktop) | The chat window is shown after being hidden (tray, dock, shortcut, second launch). A long-running menu bar app opens it many times per launch. | — |
| `host_started` | host | Each start of the host process | `first_run` (the first start of a new install; `open_store` marks a new host id with an empty `analytics_version`), `updated_from` (the previous version, when it changed), `service` (started by launchd, systemd or the Windows runner: `XPC_SERVICE_NAME`, `SYSTEMD_EXEC_PID`, `CODYNC_SERVICE`) |
| `host_setup_failed` | desktop main | The desktop app couldn't get a working host | `stage` (`missing_binary`/`install`/`verify`/`not_responding`/`environment`) |
-| `onboarding_step_viewed` | iOS, Android | A first-run screen appears | `step` (`welcome`/`install`/`scan`) |
-| `onboarding_completed` | host `track` (desktop), iOS, Android | Desktop: the welcome screen is finished. Phones: the first-run screens are finished and the tabs appear (a computer paired, signed in to an account, or skipped). | desktop `signed_in`; phones `via` (`paired`/`account`/`skipped`) |
+| `onboarding_step_viewed` | iOS, Android | An onboarding screen appears. `welcome` is also the sign-in screen, so it's sent again after each sign-out (builds with accounts require sign-in): count persons, or the first one per person, for first runs | `step` (`welcome`/`install`/`scan`) |
+| `onboarding_completed` | host `track` (desktop), iOS, Android | Once per setup. Desktop: the first run's welcome is finished (by signing in, in a build with accounts). Phones: the first-run screens are finished and the tabs appear (a computer paired, signed in to an account with computers, or skipped). | desktop `signed_in`; phones `via` (`paired`/`account`/`skipped`) |
| `computer_access_finished` | host `track` (desktop) | The *Computer access* step is left | `ready` (screen recording and control granted), `onboarding` |
| `sign_in_started` | host `track` (desktop), iOS, Android | A sign-in button is pressed | `provider` (`apple`/`google`/`hosted`) |
| `sign_in_failed` | host `track` (desktop), iOS, Android | Sign-in ended without an account | `provider`, `reason` (`cancelled`/`timeout`/`verification`/`error`) |
| `signed_in` | host `track` (desktop), iOS, Android | Signed in to a Codync account | `provider` |
| `signed_out` | host `track` (desktop), iOS, Android | Signed out | — |
+| `signed_out_pairings_moved` | iOS, Android | At sign-in, computers paired while signed out (before sign-in was required) moved into the account | `computers` (count), `keys` (`moved`: this phone's keys went along, nothing to scan; `rescan`: the account already had its own key on this phone, so they need a new scan) |
| `pairing_code_created` | host (`pairing`) | A pairing QR code is made (desktop, terminal UI, `codync-host pair`), including each new one an open pairing screen makes when its code expires: count persons, not events | `client` |
| `pairing_failed` | iOS, Android | A pairing attempt fails | `reason` (`not_pairing_link`/`outdated_host`/`invalid`/`expired`/`unauthorized`/`unreachable`/`timeout`/`upgrade_required`/`other`) |
| `computer_paired` | iOS, Android | The phone reached a computer | `via` (`qr`: scanned or pasted on the scan screen; `link`: a pairing link opened from outside; `account`), `computer` |
@@ -135,11 +136,12 @@ host answers and sends it once the host is up.
The *Onboarding & conversion* dashboard in PostHog reads these steps, each per `$os`:
-- **Desktop**: first `app_opened` (or `host_setup_failed`) → `onboarding_completed` →
- `computer_access_finished` → `pairing_code_created` → `device_paired` → `message_sent` with
- `client = remote` (Activated).
-- **iPhone / Android**: `onboarding_step_viewed` `welcome` → `install` → `scan` →
- `computer_paired` → `message_sent` with `client = remote` on that `computer`.
+- **Desktop**: first `app_opened` (or `host_setup_failed`) → `sign_in_started` → `signed_in` →
+ `onboarding_completed` → `computer_access_finished` → `pairing_code_created` → `device_paired` →
+ `message_sent` with `client = remote` (Activated).
+- **iPhone / Android**: first `onboarding_step_viewed` `welcome` → `sign_in_started` → `signed_in`
+ → `install` → `scan` → `computer_paired` → `message_sent` with `client = remote` on that
+ `computer`. The sign-in steps are the gate's sign-in rate (sign-in is required since 2.35.0).
- **Star**: `star_prompt_answered` with `starred` ÷ all `star_prompt_answered`, per `ask`.
- **Website**: `$pageview` → `download_clicked` (per `platform`) → the first `app_opened` that day
(counts only, no link between a visitor and an install).
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 9aa1c928..3dd59073 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -88,7 +88,8 @@ 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;雲端只存公鑰。
-- 帳號登出/移除帳號:刪除該 context 的 device key、computers 快取、mailbox 草稿、widget snapshot。
+- 帳號登出/移除帳號:先在 Clerk 登出(失敗就保留金鑰、維持登入),成功後才交還金鑰(連得到的電腦呼叫 `forgetDevice`,舊版 host 改呼叫 `unregisterDevice`;雲端 `DELETE /v1/devices/{id}`,用登出前先取的 session token),各自最多數秒、失敗不擋登出,再刪除該 context 的 device key、computers 快取、mailbox 草稿、widget snapshot。刪除帳號則先在 Clerk 刪除使用者,成功後才交還給電腦,雲端那側由 `user.deleted` webhook 處理。
+- 有 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 金鑰
@@ -105,6 +106,7 @@ See [architecture](../architecture/overview.md) and [file structure](../architec
| 動作 | 效果 |
|---|---|
+| 裝置自己登出(`forgetDevice`,只能移除呼叫者自己) | 與在電腦上撤銷相同;帳號來源的 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)來源裝置不受影響 |
@@ -316,7 +318,7 @@ blob = epk(32) ‖ sig(64) ‖ ct
| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token) |
| 配對中 | `pair` | 只在 pairing 狀態的 channel;配對完成後不可再呼叫 |
| screen scope | `screenPrepare`, `screenOffer`, `screenCandidate`, `screenClose`, `screenTakeover` | Local,或 scopes 含 `screen` 的裝置 |
-| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |
+| control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `renameSection`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `forgetDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |
The `screenCandidates` subscription also requires `screen` scope and belongs to its device’s screen session. It carries ordered candidates and completion separately from chat events; see [remote screen](../features/remote-screen.md).
@@ -536,7 +538,7 @@ The route table below summarizes the contract. Executable schema and validation
## 11. Apps and SSH
-The iOS app (ClerkKit) and the desktop app (Clerk Frontend API) sign in to the same Clerk instance. QR pairing remains usable without an account; account sign-in requires host-approved device access. The desktop app uses OpenSSH forwarding for SSH computers, not a mobile SSH gateway. See [accounts and SSH](../guides/accounts-and-ssh.md).
+The iOS app (ClerkKit) and the desktop app (Clerk Frontend API) sign in to the same Clerk instance. Every app with Clerk requires sign-in ([require sign-in](../plans/require-sign-in.md)); QR pairing still works without the cloud, and account access requires host-approved device access. The desktop app uses OpenSSH forwarding for SSH computers, not a mobile SSH gateway. See [accounts and SSH](../guides/accounts-and-ssh.md).
## 12. Verification
diff --git a/host/Cargo.lock b/host/Cargo.lock
index f602f18f..40251acb 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -727,7 +727,7 @@ dependencies = [
[[package]]
name = "codync-host"
-version = "2.34.2"
+version = "2.35.0"
dependencies = [
"anyhow",
"axum",
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 3832e80d..fac5a798 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "codync-host"
-version = "2.34.2"
+version = "2.35.0"
edition = "2024"
# iroh (codync-network) needs 1.91.
rust-version = "1.91"
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index 77dcdf88..ecc4f787 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -79,15 +79,9 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
.collect();
json!({"devices": devices})
}
- "revokeDevice" => {
- let key = str_arg(&b, "key")?;
- let device = hub.store.device(key).ok_or_else(|| anyhow!("unknown device"))?;
- hub.revoke_device(key)?;
- if let Some(grant) = device.grant_id.filter(|_| device.source == DeviceSource::Account) {
- tokio::spawn(crate::remote::cloud::revoke_grant(hub.clone(), grant));
- }
- json!({})
- }
+ "revokeDevice" => revoke(hub, str_arg(&b, "key")?)?,
+ // A device leaving on its own (signing out): the same as revoking it at the computer.
+ "forgetDevice" => revoke(hub, caller.device_key())?,
"accessRequests" => json!({"requests": hub.cloud.requests_json()}),
"decideAccessRequest" => {
let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;
@@ -126,6 +120,16 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
}))
}
+/// Removes a device, and its cloud grant when it was approved through the account.
+fn revoke(hub: &Arc<Hub>, key: &str) -> Result<Value> {
+ let device = hub.store.device(key).ok_or_else(|| anyhow!("unknown device"))?;
+ hub.revoke_device(key)?;
+ if let Some(grant) = device.grant_id.filter(|_| device.source == DeviceSource::Account) {
+ tokio::spawn(crate::remote::cloud::revoke_grant(hub.clone(), grant));
+ }
+ Ok(json!({}))
+}
+
/// A new one-time pairing code and the QR that carries it (§4.1).
async fn pairing(hub: &Arc<Hub>) -> Result<Value> {
let port = hub.port;
@@ -175,3 +179,41 @@ async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {
"sig": crypto::b64(&hub.identity.sign(input.as_bytes())),
}))
}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+ use super::*;
+ use crate::remote::identity::Identity;
+ use crate::store::{Device, Scope, Store};
+
+ #[tokio::test]
+ async fn a_device_forgets_only_itself() {
+ let dir = std::env::temp_dir().join(format!("codync-forget-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ let hub = Hub::new(store, "test".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0);
+ let phone = Device {
+ key: "me".into(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: None,
+ created_at: 1,
+ last_seen_at: None,
+ };
+ hub.store.put_device(&phone).unwrap();
+ hub.store.put_device(&Device { key: "other".into(), ..phone.clone() }).unwrap();
+ hub.store.add_push_ticket("t1", "me", None, None, "Phone").unwrap();
+ let me = Caller::Device { key: "me".into(), scopes: phone.scopes.clone() };
+
+ assert!(call(&hub, &me, "forgetDevice", json!({"key": "other"})).await.unwrap().is_break());
+ assert!(hub.store.device("me").is_none());
+ assert!(hub.store.device("other").is_some(), "only the caller's own device goes");
+ assert!(hub.store.push_tickets().is_empty());
+ assert!(call(&hub, &me, "forgetDevice", json!({})).await.is_err(), "already gone");
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}
diff --git a/web/app/compare/rivals.ts b/web/app/compare/rivals.ts
index e9102f13..7f24ba0e 100644
--- a/web/app/compare/rivals.ts
+++ b/web/app/compare/rivals.ts
@@ -24,7 +24,7 @@ const us = {
apps: "iPhone, Mac, Windows and Linux apps, plus a terminal UI over SSH.",
data: "Stays on your computer. The phone connects directly, or through an end-to-end encrypted relay.",
source: "Open source, Apache 2.0.",
- account: "Not required: pair by scanning a code. Signing in is optional.",
+ account: "Sign in with Apple or Google, free. An account never unlocks a computer: each one approves each device itself.",
approvals: "Edits and commands come to your phone: allow once, always allow or deny.",
rooms: "Group chats where every bot answers in its own session, and replies that quote any message.",
memory: "Memory per bot, and routines that run on a schedule or from a webhook.",
diff --git a/web/app/components/compare.tsx b/web/app/components/compare.tsx
index e44396cd..d8a63594 100644
--- a/web/app/components/compare.tsx
+++ b/web/app/components/compare.tsx
@@ -17,7 +17,7 @@ const same = [
];
const different = [
- ["100% free, no hidden fees", "Apache 2.0 licensed. No subscription, no paid tier, no in-app purchases, no account required."],
+ ["100% free, no hidden fees", "Apache 2.0 licensed. No subscription, no paid tier, no in-app purchases."],
["Any coding agent, over ACP", "Speaks the Agent Client Protocol, so Claude Code, Codex, Cursor, Gemini, Copilot and 40+ more just work, with the logins you already have. Mix them in one room."],
["Built in Rust", "One small, fast binary hosts every bot. Bots, transcripts and memory stay on your computer; the phone reaches it end-to-end encrypted."],
["Mac, Windows and Linux", "The same host runs on macOS, Windows and Linux (a static binary on any distro, desktop or headless server). All three get the same desktop app, with a menu bar or tray icon and a chat window."],
diff --git a/web/app/components/privacy.tsx b/web/app/components/privacy.tsx
index 099e0142..5b9bb83a 100644
--- a/web/app/components/privacy.tsx
+++ b/web/app/components/privacy.tsx
@@ -6,7 +6,7 @@ const points = [
{
icon: HardDrives,
title: "Your data stays home",
- body: "Bots, transcripts and memory live on your Mac, Windows PC or Linux machine. Agents run there with your own logins. No account needed, no cloud copy of your files or conversations.",
+ body: "Bots, transcripts and memory live on your Mac, Windows PC or Linux machine. Agents run there with your own logins. No cloud copy of your files or conversations.",
},
{
icon: WifiHigh,
diff --git a/web/app/components/questions.tsx b/web/app/components/questions.tsx
index b5facc9b..44527280 100644
--- a/web/app/components/questions.tsx
+++ b/web/app/components/questions.tsx
@@ -18,7 +18,7 @@ const questions: [string, string][] = [
],
[
"How do I start?",
- "Install Codync on the computer your agents run on and create a bot. Then pair your iPhone by scanning the code from the Mac menu bar, the Windows or Linux app, or codync-host pair.",
+ "Install Codync on the computer your agents run on and create a bot. Then sign in on your iPhone with Apple or Google and pair it by scanning the code from the Mac menu bar, the Windows or Linux app, or codync-host pair.",
],
[
"Where does my data go?",
@@ -26,7 +26,7 @@ const questions: [string, string][] = [
],
[
"Do I need an account?",
- "No. Pair your phone by scanning a code. Signing in with Apple or Google is optional: it lists every computer on your account on your phone, and each computer still approves each device itself.",
+ "Yes, a free one: the apps ask you to sign in with Apple or Google. It lists every computer on your account on your phone. An account alone never unlocks a computer: you still pair in person by scanning a code, or approve a 6-digit code on the computer.",
],
[
"Which computers can run it?",
diff --git a/web/app/delete-account/page.tsx b/web/app/delete-account/page.tsx
new file mode 100644
index 00000000..34d446ab
--- /dev/null
+++ b/web/app/delete-account/page.tsx
@@ -0,0 +1,48 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+import { EMAIL } from "../links";
+
+export const metadata: Metadata = { title: "Delete your account", alternates: { canonical: "/delete-account" } };
+
+export default function DeleteAccount() {
+ return (
+ <main className="flex-1 flex flex-col items-center px-6 py-16">
+ <article className="max-w-2xl w-full space-y-6">
+ <h1 className="text-3xl font-bold text-white">Delete your Codync account</h1>
+
+ <Section title="In the app">
+ <ul className="list-disc pl-5 space-y-2">
+ <li><strong>iPhone and Android:</strong> on the Bots tab, tap the account button at the top left, then <strong>Delete account</strong>.</li>
+ <li><strong>Desktop app:</strong> open the account menu and choose <strong>Delete account</strong>.</li>
+ </ul>
+ </Section>
+
+ <Section title="Without the app">
+ Email{" "}
+ <a href={`mailto:${EMAIL}?subject=Delete%20my%20Codync%20account`} className="text-white underline">{EMAIL}</a>{" "}
+ from the address you sign in with, and ask us to delete your account. We delete it, and the usage analytics linked to it, within 30 days and reply when it&apos;s done.
+ </Section>
+
+ <Section title="What is deleted">
+ Your sign-in and email address, your account&apos;s list of computers, and every device&apos;s access through the account. Your computers keep their bots and chats, which never leave them. We keep a record that the account was deleted, with the revoked devices&apos; names and keys, so those devices can&apos;t be used with it again. Deleting in the app leaves the usage analytics linked to the account; email us to have them deleted too. See the{" "}
+ <Link href="/privacy" className="text-white underline">Privacy Policy</Link>.
+ </Section>
+
+ <div className="pt-4">
+ <Link href="/" className="text-sm text-neutral-500 hover:text-neutral-300 transition-colors">
+ &larr; Back to home
+ </Link>
+ </div>
+ </article>
+ </main>
+ );
+}
+
+function Section({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+ <section>
+ <h2 className="text-xl font-semibold text-white mb-2">{title}</h2>
+ <div className="text-neutral-400 leading-relaxed">{children}</div>
+ </section>
+ );
+}
diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsx
index 908882fb..86029e9f 100644
--- a/web/app/privacy/page.tsx
+++ b/web/app/privacy/page.tsx
@@ -9,7 +9,7 @@ export default function Privacy() {
<main className="flex-1 flex flex-col items-center px-6 py-16">
<article className="max-w-2xl w-full space-y-6">
<h1 className="text-3xl font-bold text-white">Privacy Policy</h1>
- <p className="text-neutral-400 text-sm">Last updated: October 31, 2026</p>
+ <p className="text-neutral-400 text-sm">Last updated: November 2, 2026</p>
<Section title="Overview">
Codync is made by Leeporic LLC (&quot;we&quot;, &quot;us&quot;). It lets you message the AI agents that run on your own computer. It is built so that your files, conversations and credentials stay on your devices.
@@ -36,13 +36,13 @@ export default function Privacy() {
If you turn cloud assistants on at a computer and add the Codync connector to ChatGPT, Claude or another assistant, that assistant&apos;s requests to your bots and the bots&apos; replies are not end-to-end encrypted: they pass through our relay over HTTPS, which can read them but doesn&apos;t store them, and the assistant&apos;s provider sees them as part of your conversation there, under its own privacy policy. Cloud assistants are off on every computer until you turn them on at that computer, and the relay passes on only requests from your own Codync account.
</Section>
- <Section title="Codync account (optional)">
- You can sign in with Apple or Google to find your computers from any phone. Your account keeps your email address, an account ID, and the names of the phones and computers you connect with it. Codync works without an account.
+ <Section title="Codync account">
+ The Codync apps ask you to sign in with Apple or Google, so your phones can find your computers. Your account keeps your email address, an account ID, and the names of the phones and computers you connect with it. You can delete it at any time: see <a href="#delete-account" className="underline">Delete your Codync account</a> below.
</Section>
<Section title="Data we collect">
<p className="mb-2">
- Usage analytics; the registration of each computer that uses our relay (its name, platform, device type, Codync version, public keys and when it was last online), with the public keys of the devices allowed to use it; and, if you sign in, the account data described under Codync account. Analytics are on by default; turn them off on each phone and each computer in Settings (Share usage analytics), and that device stops sending right away.
+ Usage analytics; the registration of each computer that uses our relay (its name, platform, device type, Codync version, public keys and when it was last online), with the public keys of the devices allowed to use it; and the account data described under Codync account. Analytics are on by default; turn them off on each phone and each computer in Settings (Share usage analytics), and that device stops sending right away.
</p>
<ul className="list-disc pl-5 space-y-2">
<li><strong>What we record:</strong> which features you use, such as opening the app and its screens, setting up and pairing a device (and whether you allow notifications), creating or deleting a bot, sending a message (with the number of attachments, not the files), starting a routine or a voice call, and installing a connector from the catalog. Each event carries the app version, the platform and the agent and model a bot uses.</li>
@@ -60,7 +60,7 @@ export default function Privacy() {
<li><strong>Apple Push Notification service</strong>: delivers notifications and Live Activity updates on iPhone.</li>
<li><strong>Google Firebase Cloud Messaging</strong>: delivers notifications and live updates on Android.</li>
<li><strong>Cloudflare Workers</strong>: runs the push relay (nothing stored), the relay between your phone and your computer (computer registrations, messages waiting for an offline computer, webhook deliveries) and the Codync account service; its TURN service forwards a remote screen session&apos;s encrypted video when there&apos;s no direct path.</li>
- <li><strong>Clerk</strong>: runs sign-in for the optional Codync account, including the sign-in an assistant you connect to Codync uses.</li>
+ <li><strong>Clerk</strong>: runs sign-in for the Codync account, including the sign-in an assistant you connect to Codync uses.</li>
<li><strong>n0 (iroh public relays)</strong>: only if you connect your computers with codync-network using the default connector. When two of your computers can&apos;t connect directly, their encrypted traffic goes through iroh&apos;s public relays, and they find each other through n0&apos;s address lookup; these see the computers&apos; IP addresses and connection metadata, not what they say. With your own relay or the private connector, none of it reaches n0.</li>
<li><strong>PostHog (US)</strong>: stores the usage analytics described above, unless you turned them off.</li>
<li><strong>The AI agents you choose</strong>: they run on your computer under their own terms and privacy policies.</li>
@@ -70,18 +70,18 @@ export default function Privacy() {
</Section>
<Section title="Data retention">
- Your bots and conversations live on your devices. Our services keep only these: your account, if you sign in; each computer&apos;s registration, the devices allowed to use it and its routines&apos; webhook keys, while the computer is registered; a log of account and access changes (30 days); messages waiting for an offline computer (up to 24 hours); and webhook deliveries waiting for it (up to 72 hours). Delete a bot to remove its conversation; uninstall the host and delete <code>~/.codync</code> to remove all of it. Deleting the phone app removes its cache. Turning analytics off stops new events from being sent.
+ Your bots and conversations live on your devices. Our services keep only these: your account; each computer&apos;s registration, the devices allowed to use it and its routines&apos; webhook keys, while the computer is registered; a log of account and access changes (30 days); messages waiting for an offline computer (up to 24 hours); and webhook deliveries waiting for it (up to 72 hours). Delete a bot to remove its conversation; uninstall the host and delete <code>~/.codync</code> to remove all of it. Deleting the phone app removes its cache. Turning analytics off stops new events from being sent.
</Section>
<Section id="delete-account" title="Delete your Codync account">
<p className="mb-2">
- To delete your Codync account, email{" "}
+ Delete it in the app: on iPhone and Android, tap the account button on the Bots tab, then <strong>Delete account</strong>; in the desktop app, open the account menu and choose <strong>Delete account</strong>. Without the app, email{" "}
<a href={`mailto:${EMAIL}?subject=Delete%20my%20Codync%20account`} className="text-white underline">{EMAIL}</a>{" "}
- from the address you sign in with, with the subject &ldquo;Delete my Codync account&rdquo;. We delete it within 30 days and reply when it&apos;s done.
+ from the address you sign in with, with the subject &ldquo;Delete my Codync account&rdquo;: we delete it, and the usage analytics linked to it, within 30 days and reply when it&apos;s done. The steps are also on <Link href="/delete-account" className="text-white underline">Delete your account</Link>.
</p>
<ul className="list-disc pl-5 space-y-2">
- <li><strong>Deleted:</strong> your account (email address and account ID), the phones and computers connected to it and their access, and the usage analytics linked to it.</li>
- <li><strong>Kept:</strong> nothing on our side. Bots and conversations stay on your computer until you delete them there (see Data retention).</li>
+ <li><strong>Deleted:</strong> your sign-in and email address, your account&apos;s list of computers, and every device&apos;s access through the account.</li>
+ <li><strong>Kept:</strong> a record that the account was deleted, with the revoked devices&apos; names and keys, so those devices can&apos;t be used with it again; the log of account and access changes (30 days); and, when you delete it in the app, the usage analytics linked to it, until you email us to delete them too. Bots and conversations stay on your computer until you delete them there (see Data retention).</li>
</ul>
</Section>
diff --git a/web/app/sitemap.ts b/web/app/sitemap.ts
index 57ad8290..e348b040 100644
--- a/web/app/sitemap.ts
+++ b/web/app/sitemap.ts
@@ -19,6 +19,7 @@ export default function sitemap(): MetadataRoute.Sitemap {
...docPages.map((p): [string, number] => [`/docs/${p.slug}`, 0.6]),
["/privacy", 0.2],
["/terms", 0.2],
+ ["/delete-account", 0.1],
];
return pages.map(([path, priority]) => ({ url: `${SITE}${path}`, lastModified: new Date(), priority }));
}
diff --git a/web/content/docs/getting-started.mdx b/web/content/docs/getting-started.mdx
index 3c6608ee..7d6be94a 100644
--- a/web/content/docs/getting-started.mdx
+++ b/web/content/docs/getting-started.mdx
@@ -41,7 +41,7 @@ You can also install the host with Homebrew (`brew install leepokai/codync/codyn
### The first launch of the desktop app
-The app first asks about an account. Signing in with Apple or Google is optional. Choose **Continue on this Mac** (or **Continue on this computer**) to go on without one. It then offers **Computer access**, which bots need only to use the screen; choose **Set up later** to skip it. See [Computer use](/docs/computer-use).
+The app first asks you to sign in with Apple or Google. The computer joins your account, so your phone can find it there. It then offers **Computer access**, which bots need only to use the screen; choose **Set up later** to skip it. See [Computer use](/docs/computer-use).
Setup also offers an optional GitHub star. If you skip it, the desktop app can remind you once after seven days. That reminder has two actions: **Star on GitHub** opens the repository, and **Not now** dismisses it. You can also dismiss it by clicking outside the card or pressing Escape. Opening the repository or dismissing this reminder ends further reminders on that computer.
@@ -70,7 +70,7 @@ Every iPhone release goes through Apple's App Review first, so the App Store ver
## 3. Pair your iPhone
-Pairing connects your phone to your computer with a QR code. No account is needed.
+Pairing connects your phone to your computer with a QR code. The phone needs to be signed in first, with Apple or Google.
On the computer, show the pairing code:
@@ -79,7 +79,7 @@ On the computer, show the pairing code:
- **Any desktop app:** Settings → Computers, then the **Pair iPhone** button on the computer.
- **Terminal:** run `codync-host pair`, or press `P` in the terminal UI.
-On the iPhone, open Codync and tap **Get started**, then **Continue**, then scan the code. The iPhone Camera app can scan it too. If you can't scan, copy the pairing link on the computer and paste it into the field under the viewfinder. To pair later, tap the account button at the top left of the Bots tab, then **Scan a computer's code**.
+On the iPhone, open Codync, sign in with Apple or Google, tap **Continue**, then scan the code. The iPhone Camera app can scan it too. If you can't scan, copy the pairing link on the computer and paste it into the field under the viewfinder. To pair later, tap the account button at the top left of the Bots tab, then **Scan a computer's code**.
The iPhone app has three tabs: **Bots** (your bots and chats), **State** (widgets, Live Activities and usage limits) and **Settings** (this iPhone's own settings). Each computer's settings, such as Extensions, voice chat and push notifications, are in **Manage computers**: tap the connection status at the top of the Bots tab (such as **1 connected**).
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index 7f663da7..4a81c8e0 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 in your terminal. On the iPhone, scan it 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**). If scanning a terminal QR code is awkward, run `codync-host pair --json` and paste the `codync://pair` link into the field under the scanner.
+With the host running, run `codync-host pair` over SSH. It prints a QR code in your terminal. On the iPhone, signed in, scan it 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**). If scanning a terminal QR code is awkward, run `codync-host pair --json` and paste the `codync://pair` link into the field under the scanner.
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/privacy.mdx b/web/content/docs/privacy.mdx
index 1c52b365..f355cd50 100644
--- a/web/content/docs/privacy.mdx
+++ b/web/content/docs/privacy.mdx
@@ -20,7 +20,7 @@ If you point a computer at [a relay you run yourself](/docs/remote-access#your-o
- that your computer is registered, with its name, platform, device type, Codync version and public keys;
- when your computer and your devices connect, how often, and how much data passes;
- messages you send from the iPhone while the computer is offline, which wait there, encrypted, for up to 24 hours until the computer picks them up;
-- if you sign in: your account's email address, the names and platforms of your signed-in devices, and which of them may use which computer. Sign-in itself is handled by Clerk, the sign-in service Codync uses.
+- your account's email address, the names and platforms of your signed-in devices, and which of them may use which computer. Sign-in itself is handled by Clerk, the sign-in service Codync uses. You can delete your account in the apps; see [Deleting your account](/docs/remote-access#deleting-your-account).
The relay can't add a device to your computer. A new device needs either a pairing code shown on the computer or your approval there. The one exception is the setting **Skip the 6-digit check**, which lets any device signed in to your account in without that check.
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index b1ed1e1e..cde89f99 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -28,11 +28,11 @@ Show the code on the computer:
Then, on the iPhone, scan it 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**). You can also paste the `codync://pair` link instead of scanning.
-A code works once and expires after 10 minutes. If it has expired, show a new one on the computer. Pairing needs no account and works over any route, including the relay.
+A code works once and expires after 10 minutes. If it has expired, show a new one on the computer. Pairing works over any route, including the relay.
-## Signing in (optional)
+## Signing in
-You can sign in with Apple or Google on the iPhone and in the desktop app. Signing in doesn't give any device access by itself. It lets your phone find the computers in your account without scanning a code:
+The iPhone, Android and desktop apps ask you to sign in with Apple or Google before you use them. Signing in doesn't give any device access by itself. It lets your phone find the computers in your account without scanning a code:
1. On the computer, sign in to the desktop app. The computer joins your account. For an SSH computer, choose **Add to account** on its card in **Settings → Computers**.
2. On the iPhone, sign in with the same account and open **Manage computers**. Your account's computers are listed there. Tap **Ask for access**. The phone shows a 6-digit code.
@@ -42,6 +42,17 @@ On a computer without the desktop app, use `codync-host access` to list requests
Signing out of the desktop app keeps the computer in your account. If you then sign in with a different account, the app asks whether to move the computer there. Choose **Move here** and your phone, signed in to the new account, finds it under **Manage computers**. Devices approved through the old account lose access. Moving it turns **Skip the 6-digit check** off, so new devices ask with the 6-digit code; turn it back on in **Settings → Computers** if you want. Choose **Keep it there** to leave it where it is; you can still move it later with **Remove from account** and then **Add to account**.
+When the computer and the desktop app's account differ, an amber notice at the bottom of the sidebar says how (in the narrow sidebar, an amber icon; point at it to read it):
+
+- **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.
+
+## Deleting your account
+
+On the iPhone or Android, tap the account button at the top left of the Bots tab, then **Delete account**. In the desktop app, open the account menu and choose **Delete account**. Your account, its list of computers and every device's access through it are deleted. Your computers keep their bots and chats. This can't be undone. Without the app, see [Delete your account](/delete-account).
+
Comparing the code is what stops anyone who controls the Codync cloud from slipping in their own device. In **Settings → Computers**, **Skip the 6-digit check** lets devices signed in to your account in without it. Leave it off unless you accept the risk the app warns about: anyone who gets into your account, or anyone who compromises Codync's cloud, could then add a device with full control of the computer. It turns off whenever the computer leaves your account. Devices paired with a QR code aren't affected by this setting.
Devices approved through your account only work while the computer stays in touch with the Codync cloud. Devices paired with a QR code don't depend on it.