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: use Codync without an account

leepokai6e53b0e69e93
diff --git a/README.md b/README.md
index bab54d11..d33ceadc 100644
--- a/README.md
+++ b/README.md
@@ -141,7 +141,7 @@ Building the desktop app yourself: `cd apps/desktop && npm ci && npm run dev`.
**Linux server / cloud VM** — the host runs headless on any distro (static binary, x86_64 + arm64). Setup, remote access and limitations: [Linux servers](https://www.codync.dev/docs/linux-servers) ([contributor notes](docs/guides/linux-servers.md)).
-**Remote access** works out of the box through the free Cloudflare relay, end-to-end encrypted; the phone switches to a direct connection on the same network or over Tailscale. Details: [Remote access](https://www.codync.dev/docs/remote-access) ([protocol](docs/reference/remote-relay.md)).
+**Remote access** is direct on the same network or over Tailscale, with no account. From anywhere else, a free Cloudflare relay, end-to-end encrypted, needs the computer and the phone in the same account. Details: [Remote access](https://www.codync.dev/docs/remote-access) ([protocol](docs/reference/remote-relay.md)).
**Agents** — install and sign in to whichever you use; Codync finds them. Claude Code, Codex and Pi run through their ACP adapters (fetched by `npx`, so Node.js is needed for those).
@@ -199,9 +199,9 @@ Data lives in `~/.codync`. The local bearer token authorizes loopback helpers an
**How is it different from Grok Bot, Muse or Dots?** The same bot-based way of working (named bots, group chats, replies, approvals, memory), but open source, free, running on your own computer and with any coding agent. Side-by-side pages: [codync.dev/compare](https://www.codync.dev/compare).
-**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.
+**Where does my data go?** Bots, chats and memory stay on your computer. The phone reaches it directly on the same network or over Tailscale. With an account, it can also go through an end-to-end encrypted relay that can't read your messages.
-**Do I need an account?** Yes, a free one: the apps ask you to sign in with Apple, Google or GitHub. An account alone never unlocks a computer: you still pair by scanning a QR code, or approve a 6-digit code on the computer.
+**Do I need an account?** No. Without one, your phone pairs by scanning a QR code and connects over Wi-Fi or Tailscale. A free account (Apple, Google or GitHub) adds the relay, which needs the computer and the phone in the same account. 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 d18f5d52..f8721679 100644
--- a/apps/Codync.xcodeproj/project.pbxproj
+++ b/apps/Codync.xcodeproj/project.pbxproj
@@ -75,6 +75,7 @@
B6ECB0743C67903DA1956B29 /* CallControlIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1162D95B42A1BF2EB5EC0E9 /* CallControlIntents.swift */; };
BA978F06CB1E58511FFB541B /* WidgetSetupDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D8961FADA8810B6CC479705 /* WidgetSetupDemo.swift */; };
BCB60463C96AF5725EC4A2C7 /* CodyncBot-hex-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = D827E43025A592B41CB68EFD /* CodyncBot-hex-Tint.ttf */; };
+ BEBC4600CDC7F17E6C8CF436 /* ComputerConnectionRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9BD05E0DC8A3F0F9EF3CF19 /* ComputerConnectionRows.swift */; };
BF77DD7946621D8818EDAB9B /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A87B0091DAF0E4807D62017 /* SettingsView.swift */; };
C7ED489193AC0934515D2E85 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D0DE72EEAEC947C1D3CA237F /* PrivacyInfo.xcprivacy */; };
CF8160C37D98BD7C1472CF49 /* ReviewInvitationModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB1B021A5F4CCAA3D180C2CB /* ReviewInvitationModifier.swift */; };
@@ -189,6 +190,7 @@
C518FF3FFD22C3A114B6D1B8 /* AppStore+Shortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppStore+Shortcuts.swift"; sourceTree = "<group>"; };
C6B96EE690FC5355C9E3D1B5 /* CodyncBot-wedge-Ink.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-wedge-Ink.ttf"; sourceTree = "<group>"; };
C8F46BD8301E7E2C83C35111 /* CodyncBot-teardrop-Tint.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-teardrop-Tint.ttf"; sourceTree = "<group>"; };
+ C9BD05E0DC8A3F0F9EF3CF19 /* ComputerConnectionRows.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerConnectionRows.swift; sourceTree = "<group>"; };
CE63C84233B14A2D63640EAA /* Capture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Capture.swift; sourceTree = "<group>"; };
CEF1A5792B9675FDA7E07740 /* CodyncBot-squircle-Ink.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "CodyncBot-squircle-Ink.ttf"; sourceTree = "<group>"; };
CFEBE2E6A9D0AF0A0D89FFE7 /* UsageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageView.swift; sourceTree = "<group>"; };
@@ -334,6 +336,7 @@
0582B6169BFC36E4BCD51C0D /* BotListView.swift */,
70093609851E57B883D23DB9 /* BotRosterLine.swift */,
A185663BBFC511BF4B4863D3 /* ChooseComputerView.swift */,
+ C9BD05E0DC8A3F0F9EF3CF19 /* ComputerConnectionRows.swift */,
1FB8080D4CB79347C36A7E75 /* ComputerSection.swift */,
6BC00039A6C2C0D3F39A5F67 /* ComputerStatus.swift */,
E3E35BCE6E7037B78D22F927 /* ComputersView.swift */,
@@ -738,6 +741,7 @@
AF04355DFF3452C3ED0CA641 /* CallControlIntents.swift in Sources */,
B526FFD824131DC9A8BF1499 /* ChooseComputerView.swift in Sources */,
7C20764DC05D499075BC5E8C /* CodyncApp.swift in Sources */,
+ BEBC4600CDC7F17E6C8CF436 /* ComputerConnectionRows.swift in Sources */,
9E1D40B1216F6D46A615277E /* ComputerSection.swift in Sources */,
2002C16E427B4E4E7279E1C4 /* ComputerStatus.swift in Sources */,
AC044B31C0B4A68463B9024E /* ComputersView.swift in Sources */,
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 9164dbd9..896fe602 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -7,6 +7,17 @@ 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.41.0
+### zh-Hant
+- 不登入也能用了:在歡迎畫面選擇「不登入繼續」,手機掃電腦的 QR 碼就能配對,透過 Wi-Fi 或 Tailscale 連線。之後登入,配對會留在手機上;到「管理電腦」按「加入帳號」,電腦確認後就能從任何地方連線。
+- 電腦可以不加入帳號。配對時電腦會詢問;不加入的話,手機只能用 Wi-Fi 或 Tailscale 連線,之後也能在「管理電腦」加入帳號。
+- 遠端畫面會照連線設定換路:自動是先直連再走 Cloudflare,Cloudflare 優先則相反。
+
+### en-US
+- Use Codync without an account: choose Continue without an account on the welcome screen, then scan your computer's QR code. It connects over Wi-Fi or Tailscale. Sign in later and your computers stay paired; Add to account in Manage computers brings each into your account once the computer confirms.
+- A computer can stay out of your account. It asks when you pair; without it, your phone connects only over Wi-Fi or Tailscale, and you can add it later in Manage computers.
+- Remote screen now follows the Connection setting: Auto tries direct first, then Cloudflare, and Cloudflare first does the reverse.
+
## 2.40.2
### zh-Hant
- bot 現在可以讓 dev server 持續在電腦上執行,不會因為 bot 閒置或重新啟動而中斷。port 會顯示在聊天標題下方;點 bot 的名稱,就能看記錄、重新啟動或停止;手機連得到電腦時,也能直接開啟。
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 af9aaaa0..5266842c 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
@@ -1,6 +1,7 @@
package com.codync.android
import android.app.Application
+import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.codync.android.core.*
@@ -80,7 +81,10 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
try {
WidgetRefreshWorker.stop(getApplication())
local = LocalStore(getApplication(), userId ?: "local")
- if (userId != null) adoptSignedOut()
+ val rescan = if (userId != null) {
+ withoutAccountChosen = false
+ adoptSignedOut()
+ } else false
widgetOwner = withContext(Dispatchers.IO) { WidgetStore.activate(getApplication(), local.contextId) }
PushDelivery.activate(getApplication(), userId)
val computers = withContext(Dispatchers.IO) { local.computers() }
@@ -89,7 +93,9 @@ 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() || Analytics.onboarded) }
+ setupComplete = complete || computers.isNotEmpty() || Analytics.onboarded,
+ withoutAccount = userId == null && withoutAccountChosen,
+ error = if (rescan) SCAN_AGAIN else null) }
// 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 }
@@ -109,19 +115,42 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
}
}
+ /** Go on without signing in (iOS `withoutAccount`): only over Wi-Fi or Tailscale. */
+ fun continueWithoutAccount() {
+ Analytics.capture(AnalyticsEvent.ContinuedWithoutAccount)
+ withoutAccountChosen = true
+ mutableState.update { it.copy(withoutAccount = true) }
+ }
+
+ /** Back on the welcome screen, signing in is on offer again. */
+ fun backToWelcome() {
+ withoutAccountChosen = false
+ mutableState.update { it.copy(withoutAccount = false) }
+ }
+
+ internal var withoutAccountChosen: Boolean
+ get() = getApplication<Application>().getSharedPreferences(ACCOUNT_PREFS, Context.MODE_PRIVATE).getBoolean(WITHOUT_ACCOUNT, false)
+ set(value) { getApplication<Application>().getSharedPreferences(ACCOUNT_PREFS, Context.MODE_PRIVATE).edit().putBoolean(WITHOUT_ACCOUNT, value).apply() }
+
/**
- * Sign-in is required: the signed-out context's pairings move into this account (`LocalStore.adopt`), with their
+ * Signing in: 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.
+ * True when they have to be paired again: this account has its own key on this phone.
*/
- private suspend fun adoptSignedOut() {
+ private suspend fun adoptSignedOut(): Boolean {
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))
+ } ?: return false
+ if (adopted.computers == 0) return false
+ Analytics.capture(AnalyticsEvent.SignedOutPairingsMoved(adopted.computers, adopted.keys))
+ return adopted.keys == MovedKeys.Rescan
} catch (error: CancellationException) { throw error }
- catch (error: Exception) { android.util.Log.w("Codync", "Couldn't move the signed-out pairings", error) }
+ catch (error: Exception) {
+ android.util.Log.w("Codync", "Couldn't move the signed-out pairings", error)
+ return false
+ }
}
private suspend fun configureCloud(userId: String) {
@@ -158,9 +187,7 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
for (other in stores.value) if (other !== opened) other.openBot(null)
mutableState.update { it.copy(removedChat = false) }
noteActive(opened.id)
- }, usageRead = ::publishUsage, joinAccount = { sign ->
- joinAccount(computer.id) { client -> client.createClaim().let { claim -> claim to sign(claim) } }
- })
+ }, usageRead = ::publishUsage)
store.open()
mutableStores.update { list -> list.filter { it.id != computer.id } + store }
sortStores()
@@ -323,3 +350,7 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
super.onCleared()
}
}
+
+private const val SCAN_AGAIN = "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept."
+private const val ACCOUNT_PREFS = "codync-account"
+private const val WITHOUT_ACCOUNT = "without_account"
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 beae2e36..0239329f 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
@@ -104,6 +104,7 @@ fun AccountStore.refreshCloud() = action("cloud") {
client.registerDevice(Build.MODEL.take(100))
val computers = client.computers()
mutableState.update { it.copy(cloudComputers = computers) }
+ learnRelay(computers)
} catch (error: IOException) {
if (error is CloudError && !error.isTransient) throw error
// Runs on every launch and foreground: a dropped connection, a busy cloud or a token not ready
@@ -112,6 +113,20 @@ fun AccountStore.refreshCloud() = action("cloud") {
} finally { mutableState.update { it.copy(cloudLoaded = true) } }
}
+/**
+ * A computer that joined this account while this phone couldn't hear its `hello` still has the relay, or a phone away
+ * from its network could never reach it to find out (iOS `learnRelay`). Listed online, it's on the relay; a phone
+ * connected to it goes by its `hello`.
+ */
+private suspend fun AccountStore.learnRelay(listed: List<CloudComputer>) {
+ for (store in stores.value) {
+ val state = store.state.value
+ if (state.computer.cloud != null || state.connection is LinkState.Ready || listed.none { it.computerId == store.id && it.online == true }) continue
+ store.changeComputer { it.copy(cloud = BuildConfig.CLOUD_URL) }
+ store.reconnect()
+ }
+}
+
/** A pull to refresh: the account's computers, joining a refresh already under way. */
suspend fun AccountStore.refreshComputers() { refreshCloud(); actions["cloud"]?.join() }
@@ -271,7 +286,8 @@ fun AccountStore.startOver() = sessionAction {
cache.listFiles()?.filter { it.name.startsWith("codync-images") }?.forEach { it.deleteRecursively() }
}
Analytics.forgetOnboarding()
- mutableState.update { it.copy(account = AccountState(ready = true), error = null) }
+ withoutAccountChosen = false
+ mutableState.update { it.copy(account = AccountState(ready = true), error = null, withoutAccount = false) }
loadContext(null)
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
index 514b0942..58ec57cd 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt
@@ -9,6 +9,9 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
// Pairing and the links notifications, widgets and other apps open.
@@ -22,15 +25,17 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {
state.first { !it.loading }
mutableState.update { it.copy(pairing = true, error = null) }
try {
- val link = Pairing.shortCode(text)?.let { code -> (cloud ?: throw IOException(NO_PROOF)).pairingLink(code) } ?: text
- val pairing = Pairing.parse(link, BuildConfig.URL_SCHEME)
+ val link = Pairing.shortCode(text)?.let { code -> (cloud ?: throw IOException(SIGN_IN_FOR_SHORT_CODE)).pairingLink(code) } ?: text
+ val client = cloud
+ // Signed out: not over the Codync relay, and only a computer in no account lets it in (iOS `AccountStore.pair`).
+ val pairing = Pairing.parse(link, BuildConfig.URL_SCHEME).let { if (client == null && relayHost(it.computer.cloud) == null) it.withoutRelay else it }
+ if (pairing.computer.urls.isEmpty() && pairing.computer.cloud == null) throw IOException(NO_DIRECT_ADDRESS)
val old = state.value.computers.firstOrNull { it.id == pairing.computer.id }
require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }
val identity = withContext(Dispatchers.IO) { local.identity() }
mutableState.update { it.copy(pairingCheck = pairing.checkCode(identity)) }
- val certificate = accountProof()
- val client = cloud
- // Without a claim a computer in no account still lets the phone in; it joins the account on a later connection.
+ val certificate = client?.let { accountProof() }
+ // Without a claim a computer in no account still lets the phone in and stays out of the account.
val claim = client?.let { bestEffort("start a claim") { it.createClaim() } }
val paired = HostConnector.pair(pairing, identity, Build.MODEL.take(100), certificate, claim)
// Picked on this phone: pairing again keeps them (iOS `AccountStore.pair`).
@@ -42,7 +47,9 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {
Analytics.completeOnboarding(OnboardingVia.Paired)
// The computer signed this account's claim: the account takes it in.
val signed = paired.claim
- if (claim != null && signed != null) joinAccount(computer.id) { claim to signed }
+ if (claim != null && signed != null) contextScope.launch {
+ bestEffort("join the account") { joinAccount(computer.id) { claim to signed } }
+ }
} catch (error: CancellationException) { throw error }
catch (error: Exception) {
val reason = PairingFailure.of(error)
@@ -74,27 +81,55 @@ private suspend fun AccountStore.accountProof(): DeviceCertificate {
}
private const val NO_PROOF = "Connect to the internet to pair, so Codync can confirm your account."
+private const val NO_DIRECT_ADDRESS = "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare."
+private const val SIGN_IN_FOR_SHORT_CODE = "Short codes need an account. Scan the computer's QR code instead, or sign in."
/**
- * The computer signs this account's claim ([sign]: while letting this phone in, or later through `joinAccount` when its
- * hello asks), and the phone, which holds the account's session, completes it in the background (iOS
- * `AccountStore.joinAccount`). One at a time per computer; the computer decides whether a join that failed here is asked
- * for again.
+ * Add to account: the computer asks its user, then signs the claim (iOS `AccountStore.addToAccount`). Without it, the
+ * computer stays reachable only over Wi-Fi or Tailscale.
*/
-internal fun AccountStore.joinAccount(id: String, sign: suspend (CloudClient) -> Pair<PairingClaim, JsonObject>) {
- val client = cloud ?: return
- if (!joining.add(id)) return
+internal fun AccountStore.addToAccount(store: AppStore) {
+ val active = store.channel ?: return
+ val id = store.id
+ if (id in state.value.addingToAccount || id in joining || cloud == null) return
+ Analytics.capture(AnalyticsEvent.AddToAccountAsked)
contextScope.launch {
try {
- val joined = bestEffort("join the account") {
- val (claim, signed) = sign(client)
- client.completeClaim(claim.claimId, signed)
+ val code = withContext(Dispatchers.IO) { store.state.value.computer.checkCode(local.identity()) }
+ mutableState.update { it.copy(addingToAccount = it.addingToAccount + (id to code)) }
+ joinAccount(id) { client ->
+ val certificate = accountProof()
+ val claim = client.createClaim()
+ val body = buildJsonObject {
+ put("claimId", claim.claimId); put("nonce", claim.nonce); put("certificate", certificate.json)
+ }
+ // The computer may be waiting for its user to answer (up to 90 seconds).
+ claim to active.call("joinAccount", body, timeoutMillis = 120_000).jsonObject
}
- if (joined != null) refreshCloud()
- } finally { joining.remove(id) }
+ Analytics.capture(AnalyticsEvent.AddToAccountCompleted)
+ } catch (error: CancellationException) { throw error }
+ catch (error: Exception) {
+ android.util.Log.i("Codync", "Couldn't join the account: ${error.message}")
+ Analytics.capture(AnalyticsEvent.AddToAccountFailed(AddToAccountFailure.of(error)))
+ showError(error)
+ } finally { mutableState.update { it.copy(addingToAccount = it.addingToAccount - id) } }
}
}
+/**
+ * The computer signs this account's claim ([sign]: while letting this phone in, or later when asked to from here), and
+ * the phone, which holds the account's session, completes it (iOS `AccountStore.joinAccount`). One at a time per computer.
+ */
+private suspend fun AccountStore.joinAccount(id: String, sign: suspend (CloudClient) -> Pair<PairingClaim, JsonObject>) {
+ val client = cloud
+ if (client == null || !joining.add(id)) return
+ try {
+ val (claim, signed) = sign(client)
+ client.completeClaim(claim.claimId, signed)
+ refreshCloud()
+ } finally { joining.remove(id) }
+}
+
/** [step] of joining the account, which pairing goes on without: a failure is only logged. */
private suspend fun <T> bestEffort(what: String, step: suspend () -> T): T? = try { step() }
catch (error: CancellationException) { throw error }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
index 56df5399..63d90f23 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
@@ -43,6 +43,13 @@ internal sealed class AnalyticsEvent(val name: String) {
override val properties get() = mapOf("provider" to provider.json)
}
data object SignedOut : AnalyticsEvent("signed_out")
+ data object ContinuedWithoutAccount : AnalyticsEvent("continued_without_account")
+ data object ComputerFoundOnNetwork : AnalyticsEvent("computer_found_on_network")
+ data object AddToAccountAsked : AnalyticsEvent("add_to_account_asked")
+ data object AddToAccountCompleted : AnalyticsEvent("add_to_account_completed")
+ data class AddToAccountFailed(val reason: AddToAccountFailure) : AnalyticsEvent("add_to_account_failed") {
+ override val properties get() = mapOf("reason" to reason.json)
+ }
/** 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)
@@ -123,6 +130,22 @@ internal enum class SignInFailure(override val wire: String) : CatalogValue {
Cancelled("cancelled"), Timeout("timeout"), Verification("verification"), Error("error")
}
+internal enum class AddToAccountFailure(override val wire: String) : CatalogValue {
+ Declined("declined"), Certificate("certificate"), Unreachable("unreachable"), Other("other");
+
+ companion object {
+ fun of(error: Throwable): AddToAccountFailure = when {
+ error is HostError && error.message == "The computer stayed out of this account." -> Declined
+ error is HostError && error.message.startsWith("Couldn't confirm your Codync account") -> Certificate
+ error is HostError -> Other
+ error is CloudError -> if (error.isTransient) Unreachable else Other
+ error is IOException && error.message == "Connect to the internet to pair, so Codync can confirm your account." -> Certificate
+ error is IOException -> Unreachable
+ else -> Other
+ }
+ }
+}
+
internal enum class PairingFailure(override val wire: String) : CatalogValue {
NotPairingLink("not_pairing_link"), OutdatedHost("outdated_host"), Invalid("invalid"), Expired("expired"), Unauthorized("unauthorized"),
Unreachable("unreachable"), Timeout("timeout"), UpgradeRequired("upgrade_required"), Other("other");
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
index d1a44a8a..431887cf 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
@@ -33,6 +33,10 @@ data class AccountContext(
val pairingCheck: String? = null,
/** The last pairing failed because the phone couldn't reach the computer (not a refusal): the network hint helps. */
val pairingUnreachable: Boolean = false,
+ /** Chose to go on without signing in; signing in or starting over ends it (iOS `withoutAccount`). */
+ val withoutAccount: Boolean = false,
+ /** Computers asked from here to join this account, with the code they show meanwhile. */
+ val addingToAccount: Map<String, String> = emptyMap(),
/** This phone's computers, in the order it shows them. */
val computers: List<Computer> = emptyList(),
/** The computer whose lead "Talk to Codync" calls; null is Automatic (iOS `shortcutLeadComputer`). */
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 1e1577f5..e07a3d72 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
@@ -29,8 +29,6 @@ class AppStore internal constructor(
internal val opened: (AppStore) -> Unit,
/** A usage read finished (the account refreshes the Usage widget). */
internal val usageRead: suspend (AppStore) -> Unit = {},
- /** Its hello says this phone paired without the computer joining the account: finish the join with this signer. */
- internal val joinAccount: (sign: suspend (PairingClaim) -> JsonObject) -> Unit = {},
) {
val id: String = computer.id
private val job = SupervisorJob(parent)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
index 9d2de40e..342e1c53 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
@@ -96,6 +96,12 @@ fun AppStore.discard(send: PendingSend) = action("discard:" + send.nonce) {
refresh()
}
fun AppStore.cancelQueued(send: PendingSend) = action("cancel:" + send.nonce) {
+ if (state.value.computer.cloud == null) {
+ // No relay holds it: it only waits on this phone.
+ withContext(Dispatchers.IO) { requireNotNull(database).discard(send.nonce) }
+ refresh()
+ return@action
+ }
val active = requireNotNull(channel) { "Reconnect to the relay to cancel this message." }
when (active.cancelQueued(send.nonce)) {
"cancelled" -> { withContext(Dispatchers.IO) { requireNotNull(database).discard(send.nonce) }; refresh() }
@@ -146,13 +152,25 @@ internal suspend fun AppStore.deliver(send: PendingSend) {
withContext(NonCancellable) { savePending(send.copy(status = SendStatus.Failed, error = "Sending was interrupted. Retry uses the same message ID.")) }
throw error
} catch (error: Exception) {
- savePending(send.copy(status = SendStatus.Failed, error = error.message ?: "Couldn't send."))
+ savePending(afterFailure(send, state.value.computer.cloud, error))
} finally {
sends.remove(send.nonce)
mutableState.update { it.copy(uploadProgress = it.uploadProgress - send.nonce) }
}
}
+/** A send that failed. With no relay holding it, a message waits here until the computer can be reached (`reconcileMailbox`). */
+internal fun afterFailure(send: PendingSend, cloud: String?, error: Exception): PendingSend =
+ if (cloud == null && error is IOException && error !is HostError) send.copy(status = SendStatus.Waiting)
+ else send.copy(status = SendStatus.Failed, error = error.message ?: "Couldn't send.")
+
+/** Can't reach a computer with no relay: text waits on this phone until it can (iOS `BotStore.holdsOnPhone`). */
+internal fun holdsOnPhone(cloud: String?, link: LinkState): Boolean = cloud == null && when (link) {
+ LinkState.Connecting -> true
+ is LinkState.Failed -> link.status !in listOf(403, 426)
+ else -> false
+}
+
internal suspend fun AppStore.savePending(send: PendingSend) {
withContext(Dispatchers.IO) { requireNotNull(database).save(send) }
refresh()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
index aa181882..cdd320cb 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -74,7 +74,10 @@ fun AppStore.connect() {
showConnection(LinkState.Connecting)
val identity = withContext(Dispatchers.IO) { local.identity() }
val target = state.value.computer
- val active = HostConnector.connect(target, identity)
+ // With no relay, a changed address can only be found on the network.
+ val found = if (target.cloud == null) LocalDiscovery.urls(application, target.id).filter { it !in target.urls } else emptyList()
+ val active = HostConnector.connect(target, identity, found)
+ if (found.isNotEmpty()) Analytics.capture(AnalyticsEvent.ComputerFoundOnNetwork)
connected = active
channel = active
coroutineScope {
@@ -111,9 +114,6 @@ fun AppStore.connect() {
// Dropped chats page their earlier messages again.
mutableState.update { it.copy(historyComplete = if (dropped) emptySet() else it.historyComplete) }
noteHello(hello)
- if (asksToJoinAccount(hello)) joinAccount { claim ->
- active.call("joinAccount", claim.json).jsonObject
- }
// The event catch-up is ordered by revision; bot revisions can
// follow hundreds of historical entries. Load the current roster
// without moving the event cursor before consuming that stream.
@@ -229,8 +229,12 @@ private fun AppStore.noteHello(hello: JsonObject) = mutableState.update {
it.copy(hello = hello, unreadable = it.unreadable && same, hostUpdate = it.hostUpdate.takeIf { same })
}
-/** The computer's [hello] asks this phone to finish bringing it into the account (iOS `BotStore.refreshHello`). */
-internal fun asksToJoinAccount(hello: JsonObject): Boolean = hello["joinAccount"]?.jsonPrimitive?.booleanOrNull == true
+/** The computer could join an account, so a signed-in phone may offer to add it (iOS `Hello.canJoinAccount`). */
+internal fun canJoinAccount(hello: JsonObject?): Boolean = hello?.get("canJoinAccount")?.jsonPrimitive?.booleanOrNull == true
+
+/** Whether this phone can offer to add a computer it reaches to its account (iOS `AccountStore.canAddToAccount`). */
+internal fun canAddToAccount(signedIn: Boolean, state: AppState): Boolean =
+ signedIn && state.connection is LinkState.Ready && canJoinAccount(state.hello)
private fun AppStore.showConnection(link: LinkState) {
mutableState.update { it.copy(actualConnection = link) }
@@ -247,7 +251,16 @@ private fun AppStore.showConnection(link: LinkState) {
}
}
+/** What waited on this phone, ready to go with the same nonces, oldest first. */
+internal fun heldOnPhone(pending: List<PendingSend>): List<PendingSend> =
+ pending.filter { it.status == SendStatus.Waiting }.sortedBy { it.createdAt }.map { it.copy(status = SendStatus.Sending) }
+
private suspend fun AppStore.reconcileMailbox(active: EncryptedChannel) {
+ // No relay holds them: what waited on this phone goes now, with the same nonces.
+ if (state.value.computer.cloud == null) {
+ for (send in heldOnPhone(state.value.pending)) deliver(send)
+ return
+ }
if (active.route != HostRoute.Relay || state.value.pending.none { it.status in listOf(SendStatus.Waiting, SendStatus.Delivering) }) return
try {
val response = active.queued()
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 0e80e6a9..1851cbd8 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
@@ -83,22 +83,22 @@ private data class Editing<T>(val computerId: String, val draft: T)
}
}
val signedIn = app.account.userId != null
- // Every build with accounts requires sign-in (iOS `mustSignIn`); only builds without them pair signed out.
- val required = app.account.configured
+ // Signed out, a build with accounts offers signing in or going on without one (iOS `mustSignIn`).
+ val required = app.account.configured && !app.withoutAccount
val onboarding = !app.setupComplete && app.computers.isEmpty()
// What the choice page offers: an older copy of a computer doesn't count as one more.
val askable = app.cloudComputers.filterNot(app::isOlderCopy)
val root = when {
app.loading || app.account.restoring -> Root.Loading
required && !signedIn -> Root.Welcome
- onboarding && !welcomed && !signedIn -> Root.Welcome
+ onboarding && !welcomed && !signedIn && !app.withoutAccount -> Root.Welcome
// Whether the account has computers decides the first page: none flashes by before that's known.
onboarding && signedIn && !app.cloudLoaded -> Root.AwaitingAccount
onboarding && !pairingNew && askable.isNotEmpty() -> Root.Choose
onboarding -> Root.Pairing
else -> Root.Tabs
}
- BackHandler(root == Root.Pairing && !signedIn) { welcomed = false }
+ BackHandler(root == Root.Pairing && !signedIn) { welcomed = false; accounts.backToWelcome() }
BackHandler(root == Root.Pairing && askable.isNotEmpty()) { pairingNew = false }
val states = app.computers.mapNotNull { computers[it.id] }
val edit = { computerId: String, bot: Bot ->
@@ -118,8 +118,10 @@ private data class Editing<T>(val computerId: String, val draft: T)
when (shown) {
Root.Loading -> Box(Modifier.fillMaxSize())
Root.AwaitingAccount -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Spinner(28.dp) }
- // 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 }
+ // Computers paired signed out wait in the signed-out context; signing in moves them.
+ Root.Welcome -> WelcomeView(app, accounts, signedOutComputers = if (required) app.computers.size else 0) {
+ if (app.account.configured) accounts.continueWithoutAccount() else welcomed = true
+ }
Root.Choose -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {
ChooseComputerView(app, askable, { access = it }, { pairingNew = true }, accounts::skipSetup) {
AccountSwitcherButton(app) { showAccount = true }
@@ -130,7 +132,7 @@ private data class Editing<T>(val computerId: String, val draft: T)
when {
askable.isNotEmpty() -> BackButton { pairingNew = false }
signedIn -> AccountSwitcherButton(app) { showAccount = true }
- else -> BackButton { welcomed = false }
+ else -> BackButton { welcomed = false; accounts.backToWelcome() }
}
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
index c2ec4760..41ad4228 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
@@ -20,6 +20,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -70,7 +71,7 @@ import kotlinx.serialization.json.put
val store = accounts.store(id) ?: continue
val inAccount = app.cloudComputers.firstOrNull { it.computerId == id }
CardSection {
- computerRows(state, store, inAccount != null, app.isStale(state, states), app.access[id]?.code,
+ computerRows(state, store, inAccount != null, app.isStale(state, states), app.access[id]?.code, app.account.userId != null,
ComputerActions({ extensions(id) }, store::openScreen, voice = { voice = id }, network = { network = id }, color = { coloring = id },
ask = inAccount?.let { c -> { ask(c) } }, revoke = inAccount?.takeIf { it.isGranted }?.let { c -> { confirmRevoke = c } }) {
confirmForget = state
@@ -131,7 +132,7 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit
* (saved with the computer, so another account's computer keeps its own), how it's reached, the Codync it runs
* (and its update) and, for a stale pairing, Remove (iOS `ComputerRows`).
*/
-private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Boolean, stale: Boolean, code: String?, actions: ComputerActions) {
+private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Boolean, stale: Boolean, code: String?, signedIn: Boolean, actions: ComputerActions) {
row { ComputerSummary(state, inAccount, stale, code, actions) }
if (state.connection is LinkState.Ready) {
row { RowLabel("Extensions", "square.grid.2x2", chevron = true, modifier = Modifier.plainButton(action = actions.extensions)) }
@@ -143,6 +144,7 @@ private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: B
ComputerNotificationsRow(state.computer.notifications, store::notifications)
}
row { ConnectionRow(state.computer, store) }
+ if (canAddToAccount(signedIn, state)) row { AddToAccount(store) }
// Kept while an update asked from here restarts the computer: its spinner says it's updating.
if ((state.connection is LinkState.Ready || state.isUpdating) && state.hello != null) row { CodyncVersionRow(state, store::requestHostUpdate) }
if (stale && !inAccount) row { RowLabel("Remove", "trash", Palette.danger, modifier = Modifier.plainButton(action = actions.remove)) }
@@ -204,16 +206,44 @@ private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: B
private const val NETWORK_ICON = "codync.network"
-/** How this phone reaches the computer: the short name on the row, the whole route in the menu. */
+/** A computer in no account: adding it lets this phone reach it from anywhere. The computer confirms. */
+@Composable private fun AddToAccount(store: AppStore) {
+ val accounts = LocalAccounts.current ?: return
+ val context by accounts.state.collectAsState()
+ val check = context.addingToAccount[store.id]
+ Row(Modifier.fillMaxWidth().plainButton(enabled = check == null) { accounts.addToAccount(store) },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.width(26.dp), contentAlignment = Alignment.Center) {
+ if (check != null) Spinner(18.dp) else Symbol("person.crop.circle.badge.plus", size = 20.dp, tint = Palette.text)
+ }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ if (check != null) Text(tr("Confirm on the computer. It shows {code}.").replace("{code}", check), style = Type.footnote, color = Palette.secondary)
+ else {
+ Text(tr("Add to account"), style = Type.body, color = Palette.text)
+ Text(tr("Reach this computer from anywhere, not only over Wi-Fi or Tailscale."), style = Type.footnote, color = Palette.secondary)
+ }
+ }
+ }
+}
+
+/**
+ * How this phone reaches the computer: the short name on the row, the whole route in the menu. With no relay (a
+ * computer in no account) there's nothing to choose.
+ */
@Composable private fun ConnectionRow(computer: Computer, store: AppStore) {
+ if (computer.cloud == null) return ConnectionRowContent(ConnectionRoute.DirectOnly, null, chevron = false)
DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(routeTitle(route, computer.cloud), icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },
Modifier.fillMaxWidth(), label = "Connection") {
- Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
- Box(Modifier.width(26.dp), contentAlignment = Alignment.Center) { Symbol(computer.route.icon, size = 20.dp, tint = Palette.text) }
- Text(tr("Connection"), Modifier.weight(1f), style = Type.body, color = Palette.text)
- Text(tr(routeShortTitle(computer.route, computer.cloud)), style = Type.body, color = Palette.secondary, maxLines = 1)
- Symbol("chevron.down", size = 13.dp, tint = Palette.tertiary)
- }
+ ConnectionRowContent(computer.route, computer.cloud, chevron = true)
+ }
+}
+
+@Composable private fun ConnectionRowContent(route: ConnectionRoute, cloud: String?, chevron: Boolean) {
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.width(26.dp), contentAlignment = Alignment.Center) { Symbol(route.icon, size = 20.dp, tint = Palette.text) }
+ Text(tr("Connection"), Modifier.weight(1f), style = Type.body, color = Palette.text)
+ Text(tr(routeShortTitle(route, cloud)), style = Type.body, color = Palette.secondary, maxLines = 1)
+ if (chevron) Symbol("chevron.down", size = 13.dp, tint = Palette.tertiary)
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
index 25d74ea6..f0420d12 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
@@ -91,8 +91,11 @@ internal fun pairingLine(cloud: String?): String {
}
/** The pairing page's line. Parsing stays here so a view only renders the sentence. */
-internal fun pairingLine(pasted: String, scheme: String): String =
- pairingLine(runCatching { Pairing.parse(pasted, scheme).computer.cloud }.getOrNull())
+internal fun pairingLine(pasted: String, scheme: String, signedIn: Boolean): String {
+ val cloud = runCatching { Pairing.parse(pasted, scheme).computer.cloud }.getOrNull()
+ // Signed out, only a private relay: the Codync relay is for signed-in phones.
+ return if (signedIn || relayHost(cloud) != null) pairingLine(cloud) else "Connects on Wi-Fi or over Tailscale. End-to-end encrypted."
+}
/** What the pairing page shows while it pairs: the code a computer in no account shows when it asks, as `123 456`. */
/** The code's halves keep together on one line (a no-break space). */
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LocalDiscovery.kt b/apps/android/app/src/main/kotlin/com/codync/android/LocalDiscovery.kt
new file mode 100644
index 00000000..6b702324
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LocalDiscovery.kt
@@ -0,0 +1,87 @@
+package com.codync.android
+
+import android.content.Context
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import com.codync.android.core.DiscoveredComputer
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * Finds computers in no account on the local network (docs/plans/optional-sign-in.md; iOS `LocalDiscovery`). They have
+ * no relay to tell a phone their new address, so they advertise it. Nothing found here is trusted: the phone dials the
+ * address and the handshake checks the computer's pinned key.
+ */
+internal object LocalDiscovery {
+ /** Also in the host's `remote/discovery.rs`. */
+ private const val SERVICE = "_codync._tcp."
+
+ private val services = ConcurrentHashMap<String, NsdServiceInfo>()
+ private val found = ConcurrentHashMap<String, DiscoveredComputer>()
+ private val waiting = ArrayDeque<NsdServiceInfo>()
+ private var manager: NsdManager? = null
+ private var resolving = false
+
+ /**
+ * The addresses [id] advertised when last asked. The first call starts browsing. Each call asks again for the next try:
+ * a computer with a new address keeps its name, and browsing doesn't report that.
+ */
+ fun urls(context: Context, id: String): List<String> {
+ synchronized(this) { if (manager == null) start(context) }
+ services.values.forEach(::resolve)
+ return found.values.firstOrNull { it.id == id }?.urls.orEmpty()
+ }
+
+ private fun start(context: Context) {
+ val nsd = context.applicationContext.getSystemService(NsdManager::class.java) ?: return
+ manager = nsd
+ nsd.discoverServices(SERVICE, NsdManager.PROTOCOL_DNS_SD, object : NsdManager.DiscoveryListener {
+ override fun onServiceFound(info: NsdServiceInfo) {
+ services[info.serviceName] = info
+ resolve(info)
+ }
+ override fun onServiceLost(info: NsdServiceInfo) {
+ services.remove(info.serviceName)
+ found.remove(info.serviceName)
+ }
+ override fun onDiscoveryStarted(type: String) = Unit
+ override fun onDiscoveryStopped(type: String) = Unit
+ override fun onStartDiscoveryFailed(type: String, code: Int) = stopped(code)
+ override fun onStopDiscoveryFailed(type: String, code: Int) = stopped(code)
+ })
+ }
+
+ private fun stopped(code: Int) {
+ android.util.Log.i("Codync", "Local discovery stopped: $code")
+ synchronized(this) { manager = null }
+ }
+
+ /** One resolve at a time: the platform refuses a second while one runs. */
+ private fun resolve(info: NsdServiceInfo) {
+ val next = synchronized(this) {
+ if (resolving) {
+ if (waiting.none { it.serviceName == info.serviceName }) waiting.addLast(info)
+ return
+ }
+ resolving = true
+ info
+ }
+ @Suppress("DEPRECATION") // Its replacement needs API 34; this one still works there.
+ manager?.resolveService(next, object : NsdManager.ResolveListener {
+ override fun onServiceResolved(resolved: NsdServiceInfo) {
+ val attributes = resolved.attributes
+ DiscoveredComputer.of(attributes["id"]?.decodeToString(), attributes["urls"]?.decodeToString())
+ ?.let { found[resolved.serviceName] = it }
+ resolveNext()
+ }
+ override fun onResolveFailed(failed: NsdServiceInfo, code: Int) = resolveNext()
+ })
+ }
+
+ private fun resolveNext() {
+ val next = synchronized(this) {
+ resolving = false
+ waiting.removeFirstOrNull()
+ }
+ next?.let(::resolve)
+ }
+}
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 a34f2c9d..aa81791c 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
@@ -57,11 +57,12 @@ class LocalStore(private val context: Context, val contextId: String = "local")
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
+ * Signing in: [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.
+ * fails, the computer list merges (this context's entry wins) with the chats and waiting messages of the computers it
+ * gains, 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? {
@@ -70,13 +71,27 @@ class LocalStore(private val context: Context, val contextId: String = "local")
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 })
+ val gained = moving.filter { it.id !in known }
+ takeChats(from, gained)
+ saveComputers(own + gained)
MovedKeys.Rescan
}
from.erase()
return Adoption(moving.size, keys)
}
+ /** [from]'s chats, drafts and outgoing files of [computers], for [adopt]: messages waiting to go live there. */
+ private fun takeChats(from: LocalStore, computers: List<Computer>) {
+ val prefixes = computers.flatMap { listOf("mirror-${it.id}.db", "drafts-${it.id}.json") }
+ for (file in from.directory.listFiles().orEmpty()) {
+ if (file.name == "outgoing" || prefixes.any(file.name::startsWith)) file.copyRecursively(File(directory, file.name), overwrite = true)
+ }
+ for (computer in computers) {
+ DraftBook(directory, computer.id).relocate(from.directory)
+ MirrorDatabase.relocate(context, directory, computer.id, from.directory)
+ }
+ }
+
/** [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) } }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
index 790db434..cde760d0 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
@@ -131,8 +131,9 @@ private enum class Trailing { Interrupt, Stop, Call, Send }
} }
val online = state.actualConnection is LinkState.Ready
val empty = text.text.isBlank() && files.isEmpty()
- // Offline computers still take text when the relay can hold it; files need the computer.
- val canSend = !empty && !importing && !queuing && (online || state.actualConnection is LinkState.ComputerOffline && files.isEmpty())
+ // Offline computers still take text: the relay holds it for them, or with no relay this phone does. Files need the computer.
+ val canHold = state.actualConnection is LinkState.ComputerOffline || holdsOnPhone(state.computer.cloud, state.actualConnection)
+ val canSend = !empty && !importing && !queuing && (online || canHold && files.isEmpty())
val working = bot.isWorking(bot.id)
val bare = text.text.isEmpty() && files.isEmpty()
val trailing = when {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
index 77515fa2..a6eafc23 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
@@ -267,15 +267,18 @@ private enum class ComputerOS { Mac, Linux }
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(tr(error.orEmpty()), style = Type.footnote, color = Palette.danger)
// The usual cause: the phone has no road to the computer yet.
- if (state.pairingUnreachable) IconLabel("Check that this phone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer.",
+ if (state.pairingUnreachable) IconLabel(if (state.account.userId != null) "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer."
+ else "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.",
"wifi.exclamationmark", Palette.secondary)
+ if (state.pairingUnreachable) IconLabel("Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.",
+ "lock.shield", Palette.secondary)
}
}
// Signed in, account computers show up in Computers, where a tap asks one for access.
if (state.account.configured && state.account.userId == null) SignInButtons(state, store)
// How it connects is never a choice here: every paired computer gets every route.
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- IconLabel(pairingLine(pasted, BuildConfig.URL_SCHEME), "lock.fill")
+ IconLabel(pairingLine(pasted, BuildConfig.URL_SCHEME, state.account.userId != null), "lock.fill")
if (tailscale) IconLabel("Tailscale is on: Codync connects over it directly.", "checkmark.circle.fill")
else IconLabel("Use Tailscale? Direct and faster away from home.", "arrow.up.right",
modifier = Modifier.plainButton { uri.open("https://tailscale.com/download", OutboundLink.Tailscale) })
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesView.kt b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesView.kt
index 102da1b3..4153b58e 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesView.kt
@@ -317,7 +317,8 @@ private val WEEKDAYS = listOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4
IconButton(if (copied == "key") "Copied" else "Copy", if (copied == "key") "checkmark" else "doc.on.doc") { copy("key", value) }
}
}
- Note(if (value.url == null) "The Codync cloud is off, so only this computer can send to it."
+ Note(if (value.url == null && value.needsAccount) "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one."
+ else if (value.url == null) "The Codync cloud is off, so only this computer can send to it."
else "POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. " +
"Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them.")
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt b/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
index 7ea76e98..9bd09595 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
@@ -108,6 +108,13 @@ class ScreenSession(private val store: AppStore, display: ScreenDisplay?) {
catch (_: Superseded) { /* Its replacement reports for itself. */ }
catch (error: Exception) {
if (phase != Phase.Connecting) return@launch
+ if (store.state.value.computer.route == ConnectionRoute.CloudflareFirst) {
+ // TURN may be what failed: the other way gets a try before this gives up.
+ lastError = error.message
+ phase = Phase.Reconnecting
+ scheduleRecovery(0)
+ return@launch
+ }
close()
phase = Phase.Failed(error.message ?: "Couldn't connect to the remote screen.")
}
@@ -117,7 +124,14 @@ class ScreenSession(private val store: AppStore, display: ScreenDisplay?) {
private suspend fun connect() {
val preparing = generation
val active = store.ready()
- val relay = (active.state.value as? LinkState.Ready)?.route == HostRoute.Relay
+ val computer = store.state.value.computer
+ val relay = screenAsksForTurn(
+ channelOnRelay = (active.state.value as? LinkState.Ready)?.route == HostRoute.Relay,
+ route = computer.route,
+ // A private relay has no TURN (`relayHost`), and a computer in no account gets no address.
+ hasTurn = computer.cloud != null && relayHost(computer.cloud) == null,
+ failedAttempts = recoveryAttempts,
+ )
val connection = WireJson.decodeFromJsonElement<ScreenConnection>(active.call("screenPrepare", buildJsonObject { put("relay", relay); put("trickle", true) }))
if (BuildConfig.DEBUG) Log.d("CodyncScreen", "screen prepared: trickle=${connection.trickle}")
if (generation != preparing || phase == Phase.Closed) {
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 54c6895c..7cf5b966 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
@@ -55,8 +55,8 @@ import kotlin.math.sin
/**
* 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.
+ * With accounts that's signing in, or going on without one; builds without them go on to pairing. [signedOutComputers]
+ * were paired signed out; this phone keeps them when it signs in.
*/
@Composable internal fun WelcomeView(state: AccountContext, store: AccountStore, signedOutComputers: Int = 0, start: () -> Unit) {
AnalyticsOnAppear(AnalyticsEvent.OnboardingStepViewed(OnboardingStep.Welcome))
@@ -85,11 +85,18 @@ import kotlin.math.sin
}
Column(Modifier.padding(top = 32.dp).rise(beat >= 4), verticalArrangement = Arrangement.spacedBy(10.dp)) {
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.")
+ tr("Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.")
+ else tr("Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.")
.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)
+ if (state.account.configured) {
+ SignInButtons(state, store)
+ Column(Modifier.fillMaxWidth().plainButton(action = start).padding(vertical = 8.dp),
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(tr("Continue without an account"), style = Type.subheadline, color = Palette.text)
+ Text(tr("Only on the same Wi-Fi or Tailscale as your computer"), style = Type.caption, color = Palette.secondary)
+ }
+ } else WideButton("Get started", action = start)
// Restoring sign-in failed (the only account error): Clerk retries on its own with a backoff of up to a minute; Try again asks now.
state.account.error?.let {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
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 d38bf642..38247af9 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,7 @@ 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("""{"reason":"declined"}""", json(AnalyticsEvent.AddToAccountFailed(AddToAccountFailure.Declined)))
assertEquals("dev_server_action", AnalyticsEvent.DevServerAction(DevServerUse.Copy).name)
assertEquals("""{"action":"copy"}""", json(AnalyticsEvent.DevServerAction(DevServerUse.Copy)))
assertEquals("""{"link":"install_link"}""", json(AnalyticsEvent.LinkOpened(OutboundLink.InstallLink)))
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt
index 5b72b952..a1b2f4c7 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/JoinAccountTest.kt
@@ -1,15 +1,39 @@
package com.codync.android
+import com.codync.android.core.Computer
+import com.codync.android.core.HostError
+import com.codync.android.core.HostRoute
+import com.codync.android.core.LinkState
+import java.io.IOException
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.*
import org.junit.Test
-/** A computer whose hello says this phone paired without it joining the account asks to finish (iOS `JoinAccountTests`). */
+/** A computer whose hello says it could join an account gets the offer, and only that (iOS `JoinAccountTests`). */
class JoinAccountTest {
- @Test fun helloAsksToFinishJoiningTheAccount() {
- assertTrue(asksToJoinAccount(buildJsonObject { put("joinAccount", true) }))
- assertFalse(asksToJoinAccount(buildJsonObject { put("joinAccount", false) }))
- assertFalse("an older host doesn't say", asksToJoinAccount(buildJsonObject { }))
+ @Test fun helloSaysWhetherTheComputerCouldJoin() {
+ assertTrue(canJoinAccount(buildJsonObject { put("canJoinAccount", true) }))
+ assertFalse(canJoinAccount(buildJsonObject { put("canJoinAccount", false) }))
+ assertFalse("an older host doesn't say", canJoinAccount(buildJsonObject { }))
+ assertFalse("before the first hello", canJoinAccount(null))
+ }
+
+ @Test fun onlyASignedInPhoneReachingTheComputerGetsTheOffer() {
+ val computer = Computer("id", "Mac", "key")
+ val joinable = buildJsonObject { put("canJoinAccount", true) }
+ val ready = AppState(computer, connection = LinkState.Ready(HostRoute.Direct), hello = joinable)
+ assertTrue(canAddToAccount(true, ready))
+ assertFalse("with no account there's nothing to add it to", canAddToAccount(false, ready))
+ assertFalse(canAddToAccount(true, ready.copy(connection = LinkState.Connecting)))
+ assertFalse(canAddToAccount(true, ready.copy(hello = buildJsonObject { put("canJoinAccount", false) })))
+ }
+
+ @Test fun aFailedAddSaysWhy() {
+ assertEquals(AddToAccountFailure.Declined, AddToAccountFailure.of(HostError(500, "The computer stayed out of this account.")))
+ assertEquals(AddToAccountFailure.Certificate, AddToAccountFailure.of(HostError(500, "Couldn't confirm your Codync account. Sign in again.")))
+ assertEquals(AddToAccountFailure.Certificate, AddToAccountFailure.of(IOException("Connect to the internet to pair, so Codync can confirm your account.")))
+ assertEquals(AddToAccountFailure.Unreachable, AddToAccountFailure.of(IOException("Offline")))
+ assertEquals(AddToAccountFailure.Other, AddToAccountFailure.of(IllegalStateException("?")))
}
}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt
index dc516fe1..f5f6096e 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt
@@ -10,7 +10,7 @@ import org.junit.Test
class PairingCopyTest {
@Test fun `a pasted private relay is named and a bad link stays on Cloudflare`() {
val cloudflare = "Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted."
- assertEquals(cloudflare, pairingLine("not a link", "codync"))
+ assertEquals(cloudflare, pairingLine("not a link", "codync", signedIn = true))
val link = "codync://pair?" + mapOf(
"v" to "3",
"id" to "NHUPmL1Z_PyUbaRaqr6TOw",
@@ -19,7 +19,12 @@ class PairingCopyTest {
"code" to "CAgICAgICAgICAgICAgICA",
"cloud" to "https://relay.example.com",
).entries.joinToString("&") { "${it.key}=${URLEncoder.encode(it.value, "UTF-8")}" }
- assertTrue(pairingLine(link, "codync").contains("Private relay (relay.example.com)"))
+ assertTrue(pairingLine(link, "codync", signedIn = true).contains("Private relay (relay.example.com)"))
+ assertTrue("a private relay is the user's own", pairingLine(link, "codync", signedIn = false).contains("Private relay (relay.example.com)"))
+ }
+
+ @Test fun `signed out it only names Wi-Fi and Tailscale`() {
+ assertEquals("Connects on Wi-Fi or over Tailscale. End-to-end encrypted.", pairingLine("not a link", "codync", signedIn = false))
}
@Test fun `the pairing check reads as two groups of three and fills the shared phrase`() {
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
index cb58216d..a48fcc71 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/QueuedMessagesTest.kt
@@ -1,13 +1,44 @@
package com.codync.android
import com.codync.android.core.Entry
+import com.codync.android.core.HostError
+import com.codync.android.core.HostRoute
+import com.codync.android.core.LinkState
import com.codync.android.core.PendingSend
+import com.codync.android.core.SendStatus
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
import org.junit.Test
class QueuedMessagesTest {
+ private fun send(nonce: String, createdAt: Long = 1, status: SendStatus = SendStatus.Sending) =
+ PendingSend(nonce, "bot", "hello", createdAt, status)
+
+ @Test fun `with no relay a message that can't go waits on the phone and goes with the same nonce`() {
+ val held = afterFailure(send("n1"), null, java.io.IOException("Can't reach the computer."))
+ assertEquals(SendStatus.Waiting, held.status)
+ val pending = listOf(send("n2", 2, SendStatus.Waiting), held, send("n3", 3, SendStatus.Failed))
+ assertEquals(listOf("n1", "n2"), heldOnPhone(pending).map { it.nonce })
+ assertEquals(setOf(SendStatus.Sending), heldOnPhone(pending).map { it.status }.toSet())
+ }
+
+ @Test fun `with a relay or a refusal a message that can't go fails`() {
+ assertEquals(SendStatus.Failed, afterFailure(send("n1"), "https://api.codync.dev", java.io.IOException("Offline")).status)
+ assertEquals(SendStatus.Failed, afterFailure(send("n1"), null, HostError(403, "Turned away")).status)
+ assertEquals(SendStatus.Failed, afterFailure(send("n1"), null, IllegalStateException("Bad")).status)
+ }
+
+ @Test fun `only a computer with no relay holds text on the phone, unless it turned the phone away`() {
+ assertTrue(holdsOnPhone(null, LinkState.Failed("Unreachable")))
+ assertTrue(holdsOnPhone(null, LinkState.Connecting))
+ assertFalse(holdsOnPhone(null, LinkState.Failed("Revoked", 403)))
+ assertFalse(holdsOnPhone(null, LinkState.Ready(HostRoute.Direct)))
+ assertFalse(holdsOnPhone("https://api.codync.dev", LinkState.Failed("Unreachable")))
+ }
+
private fun user(id: String, seq: Long, status: String = "sent", nonce: String? = null) =
Entry(id, seq, "bot", seq, "user", 1, buildJsonObject {
put("text", id); put("status", status)
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 439fd409..592c8794 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
@@ -40,7 +40,7 @@ data class AccessStatus(val requestId: String, val status: String, val computerI
data class DeviceCertificate(val payload: String, val sig: String) {
/** When it stops being valid (ms), from the signed payload. */
val expiresAt: Long = Json.parseToJsonElement(payload).jsonObject.getValue("exp").jsonPrimitive.long
- internal val json: JsonObject get() = buildJsonObject { put("payload", payload); put("sig", sig) }
+ val json: JsonObject get() = buildJsonObject { put("payload", payload); put("sig", sig) }
}
/** What a computer that joins this phone's account by pairing signs, so the account takes it in. */
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
index 906a1622..ae9fedfc 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
@@ -38,6 +38,16 @@ enum class ConnectionRoute { Automatic, CloudflareFirst, DirectOnly }
/** Phones keep at most this many direct addresses; a computer with many networks sends more, best first. */
internal const val MAX_URLS = 16
+/** One computer advertised on the local network: its id and the valid ones among its comma-separated addresses. */
+data class DiscoveredComputer(val id: String, val urls: List<String>) {
+ companion object {
+ fun of(id: String?, urls: String?): DiscoveredComputer? {
+ if (id.isNullOrEmpty() || urls == null) return null
+ return directUrls(urls.split(",")).takeIf { it.isNotEmpty() }?.let { DiscoveredComputer(id, it) }
+ }
+ }
+}
+
/** The direct addresses kept from a computer's list: valid ones, once each, the best [MAX_URLS]. */
internal fun directUrls(urls: Iterable<String>): List<String> = urls.filter(::isDirectUrl).distinct().take(MAX_URLS)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
index 9e498a96..795ab829 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
@@ -17,12 +17,18 @@ import okhttp3.Request
/** A computer pairing let in, and the claim it signed when it joined this phone's account (null when it didn't). */
data class Paired(val computer: Computer, val claim: JsonObject?)
+private const val UNREACHABLE_DIRECTLY = "Can't reach your computer. Check you're on the same network or that Tailscale is on."
+
+/** Nothing answered at the address, as opposed to a host that turned this phone away. */
+private val Throwable?.isNoAnswer get() = this == null || this is java.net.SocketException ||
+ this is java.net.UnknownHostException || this is java.io.InterruptedIOException
+
object HostConnector {
/**
* Pairs with [certificate] as the account proof; a computer in no account first asks its user (up to 90 seconds),
* then signs [claim] to join the phone's account.
*/
- suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String, certificate: DeviceCertificate,
+ suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String, certificate: DeviceCertificate?,
claim: PairingClaim? = null): Paired {
require(deviceName.isNotBlank() && deviceName.codePointCount(0, deviceName.length) <= 100)
val channel = connect(pairing.computer, identity, pairing)
@@ -30,7 +36,7 @@ object HostConnector {
val response = try {
channel.call("pair", buildJsonObject {
put("code", pairing.code); put("name", deviceName); put("platform", "android")
- put("certificate", certificate.json)
+ certificate?.let { put("certificate", it.json) }
claim?.let { put("claim", it.json) }
}, timeoutMillis = 150_000)
} catch (error: HostError) {
@@ -47,9 +53,12 @@ object HostConnector {
}
}
- suspend fun connect(computer: Computer, identity: DeviceIdentity): EncryptedChannel = connect(computer, identity, null)
+ /** [discovered]: addresses found on the local network, for a computer with no relay to learn them from. */
+ suspend fun connect(computer: Computer, identity: DeviceIdentity, discovered: List<String> = emptyList()): EncryptedChannel =
+ connect(computer, identity, null, discovered)
- private suspend fun connect(computer: Computer, identity: DeviceIdentity, pairing: Pairing?): EncryptedChannel {
+ private suspend fun connect(computer: Computer, identity: DeviceIdentity, pairing: Pairing?,
+ discovered: List<String> = emptyList()): EncryptedChannel {
computer.validate()
if (computer.route == ConnectionRoute.CloudflareFirst && computer.cloud != null) {
try { return relay(computer, identity, pairing) }
@@ -57,12 +66,13 @@ object HostConnector {
catch (error: SecurityException) { throw error }
catch (_: IOException) { /* Try the direct candidates below. */ }
}
+ val candidates = (computer.urls + discovered).distinct()
var directError: Throwable? = null
var ownedWinner: EncryptedChannel? = null
val direct = try { coroutineScope {
val attempts = Channel<Result<EncryptedChannel>>(Channel.UNLIMITED,
onUndeliveredElement = { result -> result.getOrNull()?.close() })
- val jobs = computer.urls.map { base -> launch {
+ val jobs = candidates.map { base -> launch {
var channel: EncryptedChannel? = null
try {
val url = base.toHttpUrl().newBuilder().encodedPath("/channel").query("v=1").build()
@@ -81,7 +91,7 @@ object HostConnector {
val budget = if (computer.route == ConnectionRoute.DirectOnly || computer.cloud == null) 15_000L else 1_500L
withTimeoutOrNull(budget) {
var winner: EncryptedChannel? = null
- repeat(computer.urls.size) {
+ repeat(candidates.size) {
if (winner == null) {
val outcome = attempts.receive()
winner = outcome.getOrNull()
@@ -99,6 +109,10 @@ object HostConnector {
if (direct != null) return direct
if (directError is SecurityException) throw requireNotNull(directError)
if (computer.cloud != null && computer.route == ConnectionRoute.Automatic) return relay(computer, identity, pairing)
+ // With no relay, a computer that's off and a phone that's away look the same. An answer from the host says more.
+ if (directError.isNoAnswer && (computer.cloud == null || computer.route == ConnectionRoute.DirectOnly)) {
+ throw IOException(UNREACHABLE_DIRECTLY)
+ }
throw directError ?: IOException("Can't reach the computer. Check its connection and try again.")
}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
index bd5d283b..7bffe1a3 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
@@ -13,12 +13,18 @@ class PairingProblem(val kind: Kind, cause: Throwable? = null) : IllegalArgument
}
}
+/** The code this computer shows if it asks about [identity]'s phone. */
+fun Computer.checkCode(identity: DeviceIdentity): String = RelayCrypto.pairCheck(identity.deviceKey, signKey.decodeBase64Url(32))
+
/** A short-lived pairing URL. Only the resulting Computer may be persisted. */
data class Pairing(val computer: Computer, val code: String) {
+ /** With the Codync relay left out, as a phone with no account uses it. A private relay is the user's own: the caller keeps it. */
+ val withoutRelay: Pairing get() = copy(computer = computer.copy(cloud = null))
+
internal val offerId: String get() = RelayCrypto.offerId(code.decodeBase64Url(16))
/** The code the computer shows if it asks whether to let [identity]'s phone in. */
- fun checkCode(identity: DeviceIdentity): String = RelayCrypto.pairCheck(identity.deviceKey, computer.signKey.decodeBase64Url(32))
+ fun checkCode(identity: DeviceIdentity): String = computer.checkCode(identity)
companion object {
private val SHORT_CODE = Regex("([A-Za-z]{4})[- ]?([0-9]{4})")
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
index 33c539ed..6ebe7670 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
@@ -90,7 +90,7 @@ val routineRepeats = listOf("hourly" to "Hourly", "daily" to "Daily", "weekdays"
?.get("expression")?.jsonPrimitive?.content
}
-@Serializable data class RoutineWebhook(val url: String? = null, val localUrl: String, val key: String, val connected: Boolean)
+@Serializable data class RoutineWebhook(val url: String? = null, val needsAccount: Boolean = false, val localUrl: String, val key: String, val connected: Boolean)
data class RoutineDraft(val id: String? = null, val name: String = "", val instruction: String = "",
val schedule: RoutineScheduleDraft = RoutineScheduleDraft(), val timeoutSeconds: String = "3600") {
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/ScreenRoute.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/ScreenRoute.kt
index 07e068f4..94773396 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/ScreenRoute.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/ScreenRoute.kt
@@ -21,3 +21,18 @@ suspend fun waitForScreenRoute(current: () -> LinkState?) {
delay(100)
}
}
+
+/**
+ * Whether attempt number [failedAttempts] asks for TURN, the screen's way through Cloudflare, by the computer's
+ * Connection choice; the other way gets the next attempt when one fails (iOS `ScreenRoute`). [channelOnRelay]: chat
+ * itself reaches the computer through a relay. [hasTurn]: the computer is in an account on the Codync cloud; a computer
+ * in no account and a private relay have none.
+ */
+fun screenAsksForTurn(channelOnRelay: Boolean, route: ConnectionRoute, hasTurn: Boolean, failedAttempts: Int): Boolean {
+ val later = failedAttempts % 2 == 1
+ return when (route) {
+ ConnectionRoute.DirectOnly -> false
+ ConnectionRoute.CloudflareFirst -> if (hasTurn) !later else channelOnRelay
+ ConnectionRoute.Automatic -> channelOnRelay || (hasTurn && later)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
index 3f298728..333ce03d 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
@@ -129,6 +129,14 @@ class ChannelIntegrationTest {
}))
}
+ @Test fun `an address found on the network is dialed when none saved answers`() = runBlocking {
+ enqueueHost()
+ val saved = computer()
+ val channel = HostConnector.connect(saved.copy(urls = emptyList()), identity(), discovered = saved.urls)
+ try { assertEquals(cid, channel.call("probe").jsonObject.text("computerId")) }
+ finally { channel.close() }
+ }
+
@Test fun `screen overflow cannot block unrelated RPC responses`() = runBlocking {
enqueueHost(screenBurst = 300)
val channel = HostConnector.connect(computer(), identity())
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
index 7e0f9886..b5adcffa 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
@@ -32,6 +32,19 @@ class PairingTest {
assertEquals(fixture.getValue("pairing").let { it as kotlinx.serialization.json.JsonObject }.text("offerId"), pairing.offerId)
}
+ @Test fun `without the relay a pairing keeps its direct addresses`() {
+ val pairing = Pairing.parse(link(), "codync").withoutRelay
+ assertEquals(null, pairing.computer.cloud)
+ assertEquals(2, pairing.computer.urls.size)
+ }
+
+ @Test fun `an address found on the network is used only when it reads as one`() {
+ val found = DiscoveredComputer.of("id", "http://192.168.1.5:19222,not a url,http://10.0.0.2:19222")
+ assertEquals(DiscoveredComputer("id", listOf("http://192.168.1.5:19222", "http://10.0.0.2:19222")), found)
+ assertEquals(null, DiscoveredComputer.of("id", "not a url"))
+ assertEquals(null, DiscoveredComputer.of(null, "http://192.168.1.5:19222"))
+ }
+
@Test fun `pairing again keeps the color route and push switch picked on this phone`() {
val paired = Pairing.parse(link(), "codync").computer
val picked = paired.copy(name = "Old name", color = "mint", route = ConnectionRoute.DirectOnly, notifications = false)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ScreenTurnTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ScreenTurnTest.kt
new file mode 100644
index 00000000..3c44fcf2
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ScreenTurnTest.kt
@@ -0,0 +1,46 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+/** The same table as iOS `ScreenRouteTests`. */
+class ScreenTurnTest {
+ private fun turn(route: ConnectionRoute, onRelay: Boolean = false, hasTurn: Boolean = true, failed: Int = 0) =
+ screenAsksForTurn(onRelay, route, hasTurn, failed)
+
+ @Test fun autoGoesDirectThenThroughTurn() {
+ assertFalse(turn(ConnectionRoute.Automatic))
+ assertTrue(turn(ConnectionRoute.Automatic, failed = 1))
+ assertFalse(turn(ConnectionRoute.Automatic, failed = 2))
+ assertTrue("chat came through the relay", turn(ConnectionRoute.Automatic, onRelay = true))
+ assertTrue(turn(ConnectionRoute.Automatic, onRelay = true, failed = 1))
+ }
+
+ @Test fun cloudflareFirstGoesThroughTurnThenDirect() {
+ assertTrue(turn(ConnectionRoute.CloudflareFirst))
+ assertFalse(turn(ConnectionRoute.CloudflareFirst, failed = 1))
+ assertTrue(turn(ConnectionRoute.CloudflareFirst, onRelay = true))
+ }
+
+ @Test fun directOnlyNeverAsks() {
+ for (failed in 0..2) assertFalse(turn(ConnectionRoute.DirectOnly, failed = failed))
+ }
+
+ @Test fun aComputerInNoAccountHasNoTurn() {
+ for (route in ConnectionRoute.entries) for (failed in 0..2) assertFalse(turn(route, hasTurn = false, failed = failed))
+ }
+
+ @Test fun aPrivateRelayStillSaysItHasNoScreen() {
+ assertTrue(turn(ConnectionRoute.Automatic, onRelay = true, hasTurn = false))
+ }
+}
+
+class DiscoveredComputerTest {
+ @Test fun keepsOnlyValidAddresses() {
+ val found = DiscoveredComputer.of("c1", "http://192.168.1.5:19222,not a url,http://10.0.0.2:19222")
+ assertEquals(DiscoveredComputer("c1", listOf("http://192.168.1.5:19222", "http://10.0.0.2:19222")), found)
+ assertNull(DiscoveredComputer.of(null, "http://192.168.1.5:19222"))
+ assertNull(DiscoveredComputer.of("c1", null))
+ assertNull(DiscoveredComputer.of("c1", "nope"))
+ }
+}
diff --git a/apps/desktop/e2e/optional-sign-in.spec.ts b/apps/desktop/e2e/optional-sign-in.spec.ts
new file mode 100644
index 00000000..287a4f0c
--- /dev/null
+++ b/apps/desktop/e2e/optional-sign-in.spec.ts
@@ -0,0 +1,116 @@
+import { test, expect, type Page } from '@playwright/test'
+import type { CloudStatus } from '../src/shared/models.ts'
+import { pairAsSignedOutPhone } from './phone.ts'
+import { api, attach, openGeneralSettings, sandbox, setPref } from './sandbox.ts'
+
+// docs/plans/optional-sign-in.md.
+
+const status = (page: Page) => api<CloudStatus>(page, 'cloudStatus', {})
+const owner = async (page: Page) => (await status(page)).owner?.userId ?? null
+
+/** As on an identity this app never saw or kept out of an account. */
+const forgetChoices = (page: Page) =>
+ page.evaluate(() => {
+ for (const key of Object.keys(localStorage)) {
+ if (key.startsWith('claimedComputerIds.') || key.startsWith('keptOutOfAccount.')) localStorage.removeItem(key)
+ }
+ })
+
+// Two pairing attempts: a second run within a minute goes over the host's three a minute, as it should.
+test('a phone with no account is asked about, on a computer in no account', async () => {
+ const { browser, page } = await attach()
+ const dialog = page.getByRole('alertdialog')
+ const devices = async () => (await api<{ devices: { name: string; key: string }[] }>(page, 'devices', {})).devices
+ const pair = async (name: string) => {
+ const { pairingUrl } = await api<{ pairingUrl: string }>(page, 'pairing', {})
+ const { computerId } = await api<{ computerId: string }>(page, 'hello', {})
+ const code = new URL(pairingUrl).searchParams.get('code') as string
+ return pairAsSignedOutPhone(sandbox().port, computerId, code, name)
+ }
+ try {
+ test.skip((await owner(page)) !== null, 'Needs a computer in no account: `npm run dev -- --cdp`, without `--cloud`.')
+
+ const refused = pair('Stranger phone')
+ await expect(dialog.getByRole('heading', { name: 'Let Stranger phone in?' })).toBeVisible()
+ await expect(dialog.getByText(/It can connect only over Wi-Fi or Tailscale/)).toBeVisible()
+ await expect(dialog.getByRole('button', { name: 'Add to account' })).toHaveCount(0)
+ await dialog.getByRole('button', { name: "Don't allow" }).click()
+ expect((await refused).err?.status).toBe(403)
+
+ const allowed = pair('E2E phone')
+ await expect(dialog.getByRole('heading', { name: 'Let E2E phone in?' })).toBeVisible()
+ await dialog.getByRole('button', { name: 'Let in' }).click()
+ expect((await allowed).ok).toBeTruthy()
+ const phone = (await devices()).find((device) => device.name === 'E2E phone')
+ expect(phone).toBeTruthy()
+ await api(page, 'revokeDevice', { key: phone?.key })
+ } finally {
+ await browser.close()
+ }
+})
+
+test('the welcome lets you go on without an account, and it stays that way', async () => {
+ const { browser, page } = await attach()
+ const goOn = page.getByRole('button', { name: /^Continue on this/ })
+ const restore = async () => {
+ await setPref(page, 'macAccountOnboardingCompleted', true)
+ await setPref(page, 'withoutAccount', false)
+ await page.reload()
+ }
+ try {
+ await setPref(page, 'macAccountOnboardingCompleted', false)
+ await page.reload()
+ // Signed in, the welcome finishes on its own.
+ test.skip(!(await goOn.isVisible({ timeout: 5_000 }).catch(() => false)), 'Needs the app signed out in a build with accounts.')
+ await goOn.click()
+ await expect(goOn).toHaveCount(0)
+ await page.reload()
+ await expect(page.locator('#root')).not.toBeEmpty()
+ await expect(goOn).toHaveCount(0)
+ } finally {
+ await restore()
+ await browser.close()
+ }
+})
+
+test('signed in, a computer in no account is asked about once, and Add to account asks again', async () => {
+ // Leaving an account and joining one each wait on the dev cloud.
+ test.setTimeout(180_000)
+ const { browser, page } = await attach()
+ const prompt = page.getByRole('alertdialog')
+ const question = prompt.getByRole('heading', { name: 'Add this computer to your account?' })
+ const started = await status(page)
+ const on = await api<CloudStatus>(page, 'setCloud', { enabled: true })
+ if (!on.enabled) await browser.close()
+ test.skip(!on.enabled, 'Needs the dev cloud on and a signed-in sandbox: `npm run dev -- --cdp --cloud`.')
+ try {
+ if (on.owner) await api(page, 'unclaim', {})
+ await expect.poll(() => owner(page), { timeout: 30_000 }).toBeNull()
+ await forgetChoices(page)
+ await page.reload()
+
+ await expect(question).toBeVisible({ timeout: 20_000 })
+ await prompt.getByRole('button', { name: 'Not now' }).click()
+ await expect(prompt).toHaveCount(0)
+ expect(await owner(page)).toBeNull()
+ await page.reload()
+ await page.waitForTimeout(3_000)
+ await expect(prompt).toHaveCount(0)
+
+ await openGeneralSettings(page)
+ await page.getByRole('dialog').getByRole('button', { name: 'Computers', exact: true }).click()
+ await expect(page.getByText('Not in an account: only Wi-Fi and Tailscale reach it.')).toBeVisible()
+
+ await page.getByRole('button', { name: 'Add to account' }).click()
+ await expect(question).toBeVisible()
+ await prompt.getByRole('button', { name: 'Add to account' }).click()
+ await expect(prompt).toHaveCount(0)
+ await expect.poll(() => owner(page), { timeout: 60_000 }).not.toBeNull()
+ } finally {
+ if (!started.owner && (await owner(page).catch(() => null))) await api(page, 'unclaim', {}).catch(() => {})
+ await api(page, 'setCloud', { enabled: started.enabled }).catch(() => {})
+ await forgetChoices(page).catch(() => {})
+ await page.reload()
+ await browser.close()
+ }
+})
diff --git a/apps/desktop/e2e/phone.ts b/apps/desktop/e2e/phone.ts
new file mode 100644
index 00000000..c680de9a
--- /dev/null
+++ b/apps/desktop/e2e/phone.ts
@@ -0,0 +1,73 @@
+import { createCipheriv, createDecipheriv, createHash, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, sign, type KeyObject } from 'node:crypto'
+
+// A phone with no account on the encrypted channel (docs/reference/remote-relay.md §6), for what only a phone can make
+// the host do: asking to pair.
+
+const b64 = (bytes: Uint8Array) => Buffer.from(bytes).toString('base64url')
+const unb64 = (text: string) => Buffer.from(text, 'base64url')
+const rawKey = (key: KeyObject) => unb64(key.export({ format: 'jwk' }).x as string)
+const sha256 = (...parts: (string | Uint8Array)[]) => parts.reduce((hash, part) => hash.update(part), createHash('sha256')).digest()
+
+const FINAL = Buffer.from([0x00])
+const TAG_LENGTH = 16
+
+function frameParams(counter: number) {
+ const be = Buffer.alloc(8)
+ be.writeBigUInt64BE(BigInt(counter))
+ return { nonce: Buffer.concat([Buffer.alloc(4), be]), aad: Buffer.concat([Buffer.from('codync/frame/v1'), be]) }
+}
+
+function sealFrame(key: Uint8Array, counter: number, message: string) {
+ const { nonce, aad } = frameParams(counter)
+ const plain = Buffer.concat([FINAL, Buffer.from(message)])
+ const cipher = createCipheriv('chacha20-poly1305', key, nonce, { authTagLength: TAG_LENGTH })
+ cipher.setAAD(aad, { plaintextLength: plain.length })
+ return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])
+}
+
+function openFrame(key: Uint8Array, counter: number, sealed: Buffer) {
+ const { nonce, aad } = frameParams(counter)
+ const text = sealed.subarray(0, sealed.length - TAG_LENGTH)
+ const decipher = createDecipheriv('chacha20-poly1305', key, nonce, { authTagLength: TAG_LENGTH })
+ decipher.setAAD(aad, { plaintextLength: text.length })
+ decipher.setAuthTag(sealed.subarray(sealed.length - TAG_LENGTH))
+ return Buffer.concat([decipher.update(text), decipher.final()]).subarray(1).toString()
+}
+
+/** Sends `pair` for a pairing code and resolves with the host's reply: `ok`, or `err` with its status and message. */
+export async function pairAsSignedOutPhone(port: number, computerId: string, code: string, name: string) {
+ const device = generateKeyPairSync('ed25519')
+ const ephemeral = generateKeyPairSync('x25519')
+ const cid = unb64(computerId)
+ const [dk, ek, n] = [rawKey(device.publicKey), rawKey(ephemeral.publicKey), randomBytes(32)]
+ const socket = new WebSocket(`ws://127.0.0.1:${port}/channel?v=1`)
+ return new Promise<{ ok?: unknown; err?: { status: number; message: string } }>((resolve, reject) => {
+ let receiveKey: Buffer
+ socket.onerror = () => reject(new Error('The sandbox host refused the channel.'))
+ socket.onopen = () => socket.send(JSON.stringify({
+ t: 'hello', v: 1, dk: b64(dk), ek: b64(ek), n: b64(n), pair: true,
+ sig: b64(sign(null, Buffer.concat([Buffer.from('codync/hs1/v1'), cid, dk, ek, n]), device.privateKey)),
+ }))
+ socket.onmessage = ({ data }) => {
+ const message = JSON.parse(String(data)) as { t: string; ek?: string; c?: number; d?: string }
+ if (message.t === 'welcome') {
+ const hostEk = unb64(message.ek as string)
+ const th = sha256('codync/hs2/v1', cid, dk, ek, n, hostEk)
+ const shared = diffieHellman({ privateKey: ephemeral.privateKey, publicKey: x25519PublicKey(hostEk) })
+ const key = (info: string) => Buffer.from(hkdfSync('sha256', shared, th, info, 32))
+ receiveKey = key('codync/h2d/v1')
+ const body = { id: 1, m: 'pair', b: { code, name, platform: 'android' } }
+ socket.send(JSON.stringify({ t: 'f', c: 0, d: b64(sealFrame(key('codync/d2h/v1'), 0, JSON.stringify(body))) }))
+ } else if (message.t === 'f') {
+ resolve(JSON.parse(openFrame(receiveKey, message.c as number, unb64(message.d as string))))
+ socket.close()
+ } else if (message.t === 'reject') {
+ reject(new Error(`The sandbox host rejected the phone: ${String(data)}`))
+ }
+ }
+ })
+}
+
+function x25519PublicKey(raw: Uint8Array) {
+ return createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: b64(raw) }, format: 'jwk' })
+}
diff --git a/apps/desktop/e2e/reach-anywhere.spec.ts b/apps/desktop/e2e/reach-anywhere.spec.ts
index b39421d4..4286ccd6 100644
--- a/apps/desktop/e2e/reach-anywhere.spec.ts
+++ b/apps/desktop/e2e/reach-anywhere.spec.ts
@@ -5,7 +5,7 @@ import { api, attach, openGeneralSettings } from './sandbox.ts'
const status = (page: Page) => api<CloudStatus>(page, 'cloudStatus', {})
const owner = async (page: Page) => (await status(page)).owner?.userId ?? null
-/** As on an identity this app never saw in an account: only `keptOut` can stop `mayAutoClaim` then. */
+/** As on an identity this app never saw in an account: only `keptOut` can stop `mayOfferJoin` then. */
const forgetClaims = (page: Page) =>
page.evaluate(() => {
for (const key of Object.keys(localStorage)) {
diff --git a/apps/desktop/e2e/sandbox.ts b/apps/desktop/e2e/sandbox.ts
index bd7a5a13..896bdeda 100644
--- a/apps/desktop/e2e/sandbox.ts
+++ b/apps/desktop/e2e/sandbox.ts
@@ -35,6 +35,9 @@ export async function attach(): Promise<{ browser: Browser; page: Page }> {
.find((p) => !p.url().startsWith('devtools://'))
if (!page) throw new Error('The sandbox app has no window open.')
await setPref(page, 'githubStarAsk', { kind: 'done' }) // Its sheet would cover what a test clicks.
+ // So would the ask to add a computer in no account, on a signed-in `--cloud` sandbox.
+ const notNow = page.getByRole('alertdialog').getByRole('button', { name: 'Not now' })
+ if (await notNow.isVisible()) await notNow.click()
return { browser, page }
}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 1fe35da2..e5d83920 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -39,7 +39,12 @@ function computerName() {
}
// UI checks drive the renderer over the DevTools protocol (development builds only).
-if (!app.isPackaged && process.env.CODYNC_REMOTE_DEBUG) app.commandLine.appendSwitch('remote-debugging-port', process.env.CODYNC_REMOTE_DEBUG)
+if (!app.isPackaged && process.env.CODYNC_REMOTE_DEBUG) {
+ app.commandLine.appendSwitch('remote-debugging-port', process.env.CODYNC_REMOTE_DEBUG)
+ // As Playwright does for the Chromium it launches. Reloading the dev server's unbundled modules holds about 750 MB of
+ // shared memory until a garbage collection; past a Linux VM's /dev/shm (half its memory) requests fail and the window stays blank.
+ app.commandLine.appendSwitch('disable-dev-shm-usage')
+}
const host = new HostController()
registerErrorReports(host)
diff --git a/apps/desktop/src/renderer/lib/account-copy.test.ts b/apps/desktop/src/renderer/lib/account-copy.test.ts
index 40335c7d..264f6212 100644
--- a/apps/desktop/src/renderer/lib/account-copy.test.ts
+++ b/apps/desktop/src/renderer/lib/account-copy.test.ts
@@ -1,20 +1,58 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { devicesLoseAccess, pairingAskText, spacedCode } from './account-copy.ts'
+import { devicesLoseAccess, joinRemovesText, pairingAnswers, pairingAskText, spacedCode, withJoinRemoves } from './account-copy.ts'
const tr = (text: string) => text
-test('the pairing ask names the phone, its account and the spaced code', () => {
- assert.deepEqual(pairingAskText(tr, { deviceName: 'Pixel', email: '[email protected]', code: '123456' }), {
+test('a signed-in phone is asked about the account, and told what staying out means', () => {
+ const ask = { deviceName: 'Pixel', email: '[email protected]', code: '123456', canJoin: true, phoneOnly: true }
+ assert.deepEqual(pairingAskText(tr, ask), {
+ title: "Add this computer to [email protected]'s account?",
+ message: 'Without it, this phone can connect only over Wi-Fi or Tailscale. Check Pixel shows 123 456.',
+ })
+})
+
+test('a phone that has to join is only asked about joining', () => {
+ const ask = { deviceName: 'Pixel', email: '[email protected]', code: '123456', canJoin: true, phoneOnly: false }
+ assert.equal(pairingAskText(tr, ask).message, 'Pixel wants to add it. Check Pixel shows 123 456.')
+})
+
+test('a signed-out phone is let in or not, with no account in the question', () => {
+ const ask = { deviceName: 'Pixel', code: '123456', canJoin: false, phoneOnly: true }
+ assert.deepEqual(pairingAskText(tr, ask), {
title: 'Let Pixel in?',
- message: "[email protected] wants to use this computer, which then joins [email protected]'s account. Check Pixel shows 123\u00a0456.",
+ message: 'It can connect only over Wi-Fi or Tailscale. Check Pixel shows 123 456.',
})
})
+test('a join names the phones it removes', () => {
+ const ask = { deviceName: 'Pixel', email: '[email protected]', code: '123456', canJoin: true, phoneOnly: true, removes: ['Old', 'iPad'] }
+ assert.match(pairingAskText(tr, ask).message, /These phones lose access and must pair again: Old, iPad\./)
+ assert.equal(joinRemovesText(tr, []), "")
+ assert.equal(joinRemovesText(tr, null), "")
+})
+
+test('a host before these answers says plainly that letting the phone in joins its account', () => {
+ const ask = { deviceName: 'Pixel', email: '[email protected]', code: '123456' }
+ assert.equal(pairingAskText(tr, ask).message, "[email protected] wants to use this computer, which then joins [email protected]'s account. Check Pixel shows 123\u00a0456.")
+ assert.deepEqual(pairingAnswers({ canJoin: null }), [{ title: 'Let in' }])
+})
+
+test('the answers offered follow what the host says the phone may get', () => {
+ assert.deepEqual(pairingAnswers({ canJoin: true, phoneOnly: true }), [{ title: 'Wi-Fi or Tailscale only', join: false }, { title: 'Add to account', join: true }])
+ assert.deepEqual(pairingAnswers({ canJoin: true, phoneOnly: false }), [{ title: 'Add to account', join: true }])
+ assert.deepEqual(pairingAnswers({ canJoin: false, phoneOnly: true }), [{ title: 'Let in' }])
+})
+
+test('the phones a join removes follow what it says', () => {
+ assert.equal(withJoinRemoves(tr, 'Add it?', []), 'Add it?')
+ assert.equal(withJoinRemoves(tr, 'Add it?', ['Old']), 'Add it? These phones lose access and must pair again: Old.')
+})
+
test('a phone without an email is a Codync account, and names keep their braces', () => {
- const text = pairingAskText(tr, { deviceName: '{code}', email: null, code: '000042' })
- assert.equal(text.title, 'Let {code} in?')
- assert.equal(text.message, "A Codync account wants to use this computer, which then joins A Codync account's account. Check {code} shows 000\u00a0042.")
+ const text = pairingAskText(tr, { deviceName: '{code}', email: null, code: '000042', canJoin: true, phoneOnly: true })
+ assert.equal(text.title, "Add this computer to A Codync account's account?")
+ assert.equal(text.message, 'Without it, this phone can connect only over Wi-Fi or Tailscale. Check {code} shows 000 042.')
})
test('changing account drops every device of the old one', () => {
diff --git a/apps/desktop/src/renderer/lib/account-copy.ts b/apps/desktop/src/renderer/lib/account-copy.ts
index c1419a51..46482d2d 100644
--- a/apps/desktop/src/renderer/lib/account-copy.ts
+++ b/apps/desktop/src/renderer/lib/account-copy.ts
@@ -1,4 +1,5 @@
-/** What the interface says when a computer joins or leaves an account (docs/plans/require-sign-in.md, phase 2). */
+/** What the interface says when a computer joins or leaves an account (docs/plans/optional-sign-in.md). */
+import type { PairingRequest } from '@shared/models'
import { fill } from './fill.ts'
type Tr = (text: string) => string
@@ -6,16 +7,45 @@ type Tr = (text: string) => string
/** "123 456" for a 6-digit code. */
export const spacedCode = (code: string) => (code.length === 6 ? `${code.slice(0, 3)} ${code.slice(3)}` : code)
-/** A signed-in phone scanned a computer in no account: letting it in brings the computer into the phone's account. */
-export function pairingAskText(tr: Tr, request: { deviceName: string; email?: string | null; code: string }) {
+/** The phones a join removes (docs/plans/optional-sign-in.md), or nothing when it removes none. */
+export function joinRemovesText(tr: Tr, names: readonly string[] | null | undefined) {
+ return names?.length ? fill(tr('These phones lose access and must pair again: {names}.'), { names: names.join(', ') }) : ''
+}
+
+/** `text`, then the phones a join removes. */
+export const withJoinRemoves = (tr: Tr, text: string, names: readonly string[] | null | undefined) =>
+ [text, joinRemovesText(tr, names)].filter(Boolean).join(' ')
+
+/**
+ * A phone scanned a computer in no account, or a paired phone asks to add it to its account. A signed-in phone may
+ * bring the computer along; without that the phone connects only over Wi-Fi or Tailscale.
+ */
+export function pairingAskText(tr: Tr, request: Pick<PairingRequest, 'deviceName' | 'email' | 'code' | 'canJoin' | 'phoneOnly' | 'removes'>) {
// A no-break space: the code never wraps apart.
const values = { name: request.deviceName, email: request.email || tr('A Codync account'), code: spacedCode(request.code).replace(' ', '\u00a0') }
+ const check = fill(tr('Check {name} shows {code}.'), values)
+ const body = (text: string) => [withJoinRemoves(tr, fill(tr(text), values), request.removes), check].join(' ')
+ // A host before 2.41.0 doesn't say: letting the phone in joins its account, whatever the answer asks.
+ if (request.canJoin == null) {
+ return { title: fill(tr('Let {name} in?'), values), message: body("{email} wants to use this computer, which then joins {email}'s account.") }
+ }
+ if (!request.canJoin) {
+ return { title: fill(tr('Let {name} in?'), values), message: body('It can connect only over Wi-Fi or Tailscale.') }
+ }
+ const title = fill(tr("Add this computer to {email}'s account?"), values)
return {
- title: fill(tr('Let {name} in?'), values),
- message: fill(tr("{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}."), values),
+ title,
+ message: body(request.phoneOnly ? 'Without it, this phone can connect only over Wi-Fi or Tailscale.' : '{name} wants to add it.'),
}
}
+/** The answers that let the phone in: `join` says whether the computer joins its account. */
+export function pairingAnswers(request: Pick<PairingRequest, 'canJoin' | 'phoneOnly'>): { title: string; join?: boolean }[] {
+ if (!request.canJoin) return [{ title: 'Let in' }]
+ const stayOut = request.phoneOnly ? [{ title: 'Wi-Fi or Tailscale only', join: false }] : []
+ return [...stayOut, { title: 'Add to account', join: true }]
+}
+
/** A computer that changes its account drops every device of the old one, QR-paired ones included. */
export function devicesLoseAccess(tr: Tr, email: string | null | undefined) {
return email ? fill(tr("Every device of {email}'s account loses access."), { email }) : tr('Every device of that account loses access.')
diff --git a/apps/desktop/src/renderer/lib/auto-claim.test.ts b/apps/desktop/src/renderer/lib/auto-claim.test.ts
deleted file mode 100644
index 0b5e5969..00000000
--- a/apps/desktop/src/renderer/lib/auto-claim.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import assert from 'node:assert/strict'
-import { test } from 'node:test'
-import { accountMismatch, mayAutoClaim, mayJoinAfterInstall, mayOfferMove } from './auto-claim.ts'
-
-const host = { id: 'new', online: true, cloud: { enabled: true, owner: null } }
-
-test('a new identity with the cloud on joins the account on its own', () => {
- assert.equal(mayAutoClaim(host, [], ['old']), true)
-})
-
-test('an identity seen in the account and removed since stays out', () => {
- assert.equal(mayAutoClaim(host, [], ['old', 'new']), false)
-})
-
-test('no auto-claim when kept out, owned, offline, or the cloud is off or unknown', () => {
- assert.equal(mayAutoClaim(host, ['new'], []), false)
- assert.equal(mayAutoClaim({ ...host, cloud: { enabled: true, owner: { userId: 'u' } } }, [], []), false)
- assert.equal(mayAutoClaim({ ...host, online: false }, [], []), false)
- assert.equal(mayAutoClaim({ ...host, cloud: { enabled: false } }, [], []), false)
- assert.equal(mayAutoClaim({ ...host, cloud: null }, [], []), false)
-})
-
-test('a computer on a private relay never joins: it has no accounts', () => {
- assert.equal(mayAutoClaim({ ...host, cloud: { enabled: true, owner: null, relay: 'private' } }, [], []), false)
- assert.equal(mayAutoClaim({ ...host, cloud: { enabled: true, owner: null, relay: 'codync' } }, [], []), true)
-})
-
-test('a computer in another account offers to move into the signed-in one', () => {
- const owned = (userId: string) => ({ ...host, cloud: { enabled: true, owner: { userId } } })
- assert.equal(mayOfferMove(owned('a'), 'b', []), true)
- assert.equal(mayOfferMove(owned('b'), 'b', []), false, 'already in this account')
- assert.equal(mayOfferMove(host, 'b', []), false, 'in no account: auto-claim covers it')
- assert.equal(mayOfferMove(owned('a'), 'b', ['new']), false, 'the user said no')
- assert.equal(mayOfferMove({ ...owned('a'), online: false }, 'b', []), false)
- assert.equal(mayOfferMove({ ...host, cloud: { enabled: true, owner: { userId: 'a' }, relay: 'private' } }, 'b', []), false)
-})
-
-test('an SSH computer installed from here joins unless it is in an account or on a private relay', () => {
- // Its cloud may still be off: Add to account turns it on, as installing shows the intent.
- assert.equal(mayJoinAfterInstall({ owner: null }), true)
- assert.equal(mayJoinAfterInstall({ owner: null, relay: 'codync' }), true)
- assert.equal(mayJoinAfterInstall({ owner: { userId: 'a' } }), false)
- assert.equal(mayJoinAfterInstall({ owner: null, relay: 'private' }), 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
deleted file mode 100644
index e2a2ad04..00000000
--- a/apps/desktop/src/renderer/lib/auto-claim.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { CloudStatus } from '@shared/models'
-
-/** What the auto-claim rule reads of this computer's host. */
-export interface ClaimCandidate {
- id: string
- online: boolean
- cloud: Pick<CloudStatus, 'enabled' | 'owner' | 'relay'> | null
-}
-
-/**
- * Whether this computer can join the signed-in account here at all. Only with the Codync cloud on: joining
- * needs it (a private relay has no accounts), and turning it back on is never done silently. Never an
- * identity the user took out here (`keptOut`).
- */
-function joinable(host: ClaimCandidate, keptOut: readonly string[]) {
- return host.online && !!host.cloud?.enabled && host.cloud.relay !== 'private' && !keptOut.includes(host.id)
-}
-
-/**
- * Whether this computer joins the signed-in account on its own (`joinable`). Never an identity this app
- * has seen in the account (`seen`): without an owner now, it was removed, maybe from a phone, and stays
- * out until it's added by hand. A new identity (a host reset) joins.
- */
-export function mayAutoClaim(host: ClaimCandidate, keptOut: readonly string[], seen: readonly string[]) {
- return joinable(host, keptOut) && !host.cloud?.owner && !seen.includes(host.id)
-}
-
-/** Whether an SSH computer just installed from here joins the account: not one in an account already, nor on a private relay (no accounts). */
-export const mayJoinAfterInstall = (cloud: Pick<CloudStatus, 'owner' | 'relay'>) => !cloud.owner && cloud.relay !== 'private'
-
-/**
- * Whether to ask to move this computer into the signed-in account: it's in another one, and signing in
- * here with a different account means it goes with that one now. Saying no keeps it out (`keptOut`).
- */
-export function mayOfferMove(host: ClaimCandidate, userId: string, keptOut: readonly string[]) {
- 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/join-offer.test.ts b/apps/desktop/src/renderer/lib/join-offer.test.ts
new file mode 100644
index 00000000..4bbc2da5
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/join-offer.test.ts
@@ -0,0 +1,54 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { accountMismatch, mayOfferJoin, mayJoinAfterInstall, mayOfferMove } from './join-offer.ts'
+
+const host = { id: 'new', online: true, cloud: { enabled: true, owner: null } }
+
+test('a new identity with the cloud on is asked about', () => {
+ assert.equal(mayOfferJoin(host, [], ['old']), true)
+})
+
+test('an identity seen in the account and removed since stays out', () => {
+ assert.equal(mayOfferJoin(host, [], ['old', 'new']), false)
+})
+
+test('nothing is asked when kept out, owned, offline, or the cloud is off or unknown', () => {
+ assert.equal(mayOfferJoin(host, ['new'], []), false)
+ assert.equal(mayOfferJoin({ ...host, cloud: { enabled: true, owner: { userId: 'u' } } }, [], []), false)
+ assert.equal(mayOfferJoin({ ...host, online: false }, [], []), false)
+ assert.equal(mayOfferJoin({ ...host, cloud: { enabled: false } }, [], []), false)
+ assert.equal(mayOfferJoin({ ...host, cloud: null }, [], []), false)
+})
+
+test('a computer on a private relay is never asked about: it has no accounts', () => {
+ assert.equal(mayOfferJoin({ ...host, cloud: { enabled: true, owner: null, relay: 'private' } }, [], []), false)
+ assert.equal(mayOfferJoin({ ...host, cloud: { enabled: true, owner: null, relay: 'codync' } }, [], []), true)
+})
+
+test('a computer in another account offers to move into the signed-in one', () => {
+ const owned = (userId: string) => ({ ...host, cloud: { enabled: true, owner: { userId } } })
+ assert.equal(mayOfferMove(owned('a'), 'b', []), true)
+ assert.equal(mayOfferMove(owned('b'), 'b', []), false, 'already in this account')
+ assert.equal(mayOfferMove(host, 'b', []), false, 'in no account: the join offer covers it')
+ assert.equal(mayOfferMove(owned('a'), 'b', ['new']), false, 'the user said no')
+ assert.equal(mayOfferMove({ ...owned('a'), online: false }, 'b', []), false)
+ assert.equal(mayOfferMove({ ...host, cloud: { enabled: true, owner: { userId: 'a' }, relay: 'private' } }, 'b', []), false)
+})
+
+test('an SSH computer installed from here is asked about unless it is in an account or on a private relay', () => {
+ // Its cloud may still be off: Add to account turns it on, as installing shows the intent.
+ assert.equal(mayJoinAfterInstall({ owner: null }), true)
+ assert.equal(mayJoinAfterInstall({ owner: null, relay: 'codync' }), true)
+ assert.equal(mayJoinAfterInstall({ owner: { userId: 'a' } }), false)
+ assert.equal(mayJoinAfterInstall({ owner: null, relay: 'private' }), 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'), { email: '[email protected]' })
+ assert.equal(accountMismatch(owned, 'a'), null, 'the same account')
+ assert.equal(accountMismatch(host, 'b'), null, 'in no account is a choice')
+ assert.equal(accountMismatch({ ...host, cloud: { enabled: false } }, 'b'), null)
+ 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/join-offer.ts b/apps/desktop/src/renderer/lib/join-offer.ts
new file mode 100644
index 00000000..d2719fee
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/join-offer.ts
@@ -0,0 +1,50 @@
+import type { CloudStatus } from '@shared/models'
+
+/** What the account rules read of a computer's host. */
+export interface ClaimCandidate {
+ id: string
+ online: boolean
+ cloud: Pick<CloudStatus, 'enabled' | 'owner' | 'relay'> | null
+}
+
+/**
+ * Whether this computer can join the signed-in account here at all. Only with the Codync cloud on: joining
+ * needs it (a private relay has no accounts), and turning it back on is never done silently. Never an
+ * identity the user took out here (`keptOut`).
+ */
+function joinable(host: ClaimCandidate, keptOut: readonly string[]) {
+ return host.online && !!host.cloud?.enabled && host.cloud.relay !== 'private' && !keptOut.includes(host.id)
+}
+
+/**
+ * Whether to ask once to add this computer to the signed-in account (`joinable`). Never an identity this app has seen in
+ * the account (`seen`): without an owner now, it was removed, maybe from a phone, and stays out until it's added by
+ * hand. A new identity (a host reset) is asked about.
+ */
+export function mayOfferJoin(host: ClaimCandidate, keptOut: readonly string[], seen: readonly string[]) {
+ return joinable(host, keptOut) && !host.cloud?.owner && !seen.includes(host.id)
+}
+
+/** Whether to ask to add an SSH computer just installed from here: not one in an account already, nor on a private relay (no accounts). */
+export const mayJoinAfterInstall = (cloud: Pick<CloudStatus, 'owner' | 'relay'>) => !cloud.owner && cloud.relay !== 'private'
+
+/**
+ * Whether to ask to move this computer into the signed-in account: it's in another one, and signing in
+ * here with a different account means it goes with that one now. Saying no keeps it out (`keptOut`).
+ */
+export function mayOfferMove(host: ClaimCandidate, userId: string, keptOut: readonly string[]) {
+ const owner = host.cloud?.owner
+ return joinable(host, keptOut) && !!owner && owner.userId !== userId
+}
+
+/** The other account this computer is in, for the line in the sidebar (`accountMismatch`). */
+export type AccountMismatch = { email: string | null }
+
+/**
+ * Whether this computer is in another account than the one signed in here. Null when they match, when it's in none (a
+ * choice, not a problem: docs/plans/optional-sign-in.md), or when the host can't say (offline).
+ */
+export function accountMismatch(host: ClaimCandidate, userId: string): AccountMismatch | null {
+ const owner = host.online ? host.cloud?.owner : null
+ return owner && owner.userId !== userId ? { email: owner.email ?? null } : null
+}
diff --git a/apps/desktop/src/renderer/lib/prefs.ts b/apps/desktop/src/renderer/lib/prefs.ts
index 3364cff4..3d9e460c 100644
--- a/apps/desktop/src/renderer/lib/prefs.ts
+++ b/apps/desktop/src/renderer/lib/prefs.ts
@@ -76,6 +76,8 @@ export const prefs = {
/** The roster marks each bot with its agent's logo while the bots run more than one agent. */
agentLogos: pref('showAgentLogos', true),
onboardingDone: pref('macAccountOnboardingCompleted', false),
+ /** Chose to go on without signing in; signing in ends it. */
+ withoutAccount: pref('withoutAccount', false),
computerAccessSetup: pref<'ready' | 'later' | null>('computerAccessSetup', null),
starAsk: pref<StarAsk>('githubStarAsk', { kind: 'never' }),
/** Prompts this computer delivered, voice calls aside; they bring the second star ask. */
diff --git a/apps/desktop/src/renderer/lib/relay-copy.test.ts b/apps/desktop/src/renderer/lib/relay-copy.test.ts
index 7979a06d..a36d7395 100644
--- a/apps/desktop/src/renderer/lib/relay-copy.test.ts
+++ b/apps/desktop/src/renderer/lib/relay-copy.test.ts
@@ -16,6 +16,10 @@ test('official clouds stay Cloudflare and any other host is named', () => {
cloudStatusLine({ enabled: true, url: 'https://relay.example.com', connected: true }),
'Reachable from anywhere through Private relay (relay.example.com) (encrypted).',
)
+ assert.equal(
+ cloudStatusLine({ enabled: true, canJoinAccount: true }),
+ 'Not in an account: only Wi-Fi and Tailscale reach it.',
+ )
assert.equal(
cloudStatusLine({ enabled: false, url: 'https://relay.example.com' }),
'Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare.',
diff --git a/apps/desktop/src/renderer/lib/relay-copy.ts b/apps/desktop/src/renderer/lib/relay-copy.ts
index c543708d..9125ac58 100644
--- a/apps/desktop/src/renderer/lib/relay-copy.ts
+++ b/apps/desktop/src/renderer/lib/relay-copy.ts
@@ -23,8 +23,10 @@ export function connectedThrough(cloud: string | null | undefined): string {
}
/** The desktop "Reach from anywhere" caption while there is no error to show. */
-export function cloudStatusLine(cloud: { enabled: boolean; url?: string | null; connected?: boolean | null }): string {
+export function cloudStatusLine(cloud: { enabled: boolean; url?: string | null; connected?: boolean | null; canJoinAccount?: boolean | null }): string {
if (!cloud.enabled) return 'Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare.'
+ // In no account it holds no relay socket: phones go over Wi-Fi or Tailscale (docs/plans/optional-sign-in.md).
+ if (cloud.canJoinAccount) return 'Not in an account: only Wi-Fi and Tailscale reach it.'
const host = relayHost(cloud.url)
if (!host) return cloud.connected ? 'Reachable from anywhere through Cloudflare (encrypted).' : 'Connecting to Cloudflare…'
return cloud.connected
diff --git a/apps/desktop/src/renderer/lib/welcome-gate.test.ts b/apps/desktop/src/renderer/lib/welcome-gate.test.ts
index dc5a162a..f9d90202 100644
--- a/apps/desktop/src/renderer/lib/welcome-gate.test.ts
+++ b/apps/desktop/src/renderer/lib/welcome-gate.test.ts
@@ -3,15 +3,16 @@ 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 }
+ const signedOut = { onboarded: true, configured: true, ready: true, signedIn: false, withoutAccount: 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')
+ assert.equal(showsWelcome({ ...signedOut, withoutAccount: true }), false, 'going on without an account')
})
test('without accounts, the first choice is the only welcome', () => {
- const local = { onboarded: false, configured: false, ready: true, signedIn: false }
+ const local = { onboarded: false, configured: false, ready: true, signedIn: false, withoutAccount: 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
index dea7062a..dc6f7734 100644
--- a/apps/desktop/src/renderer/lib/welcome-gate.ts
+++ b/apps/desktop/src/renderer/lib/welcome-gate.ts
@@ -1,8 +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.
+ * one is signed in once the saved session has been checked (signing out comes back here), unless the user chose to go
+ * on without an account. 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)
+export function showsWelcome({ onboarded, configured, ready, signedIn, withoutAccount }: { onboarded: boolean; configured: boolean; ready: boolean; signedIn: boolean; withoutAccount: boolean }) {
+ return !onboarded || (configured && ready && !signedIn && !withoutAccount)
}
diff --git a/apps/desktop/src/renderer/store/app-model.ts b/apps/desktop/src/renderer/store/app-model.ts
index db91cd2c..f09e97f4 100644
--- a/apps/desktop/src/renderer/store/app-model.ts
+++ b/apps/desktop/src/renderer/store/app-model.ts
@@ -242,10 +242,10 @@ export class AppModel extends Observable {
.filter((ask) => !this.answeredPairings.has(ask.id))
}
- decidePairing(ask: PairingAsk, approve: boolean) {
+ decidePairing(ask: PairingAsk, approve: boolean, join?: boolean) {
this.answeredPairings.add(ask.id)
this.changed()
- const answer = ask.store.ready().then((client) => client.call('decidePairing', { requestId: ask.request.requestId, approve }, 30_000))
+ const answer = ask.store.ready().then((client) => client.call('decidePairing', { requestId: ask.request.requestId, approve, join }, 30_000))
// The host may not have the answer: the question comes back.
return undoOnFailure(answer, () => {
this.answeredPairings.delete(ask.id)
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 6d421e81..e64c0ab4 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -1,6 +1,6 @@
import type { ClaimFailure } from '@shared/analytics'
import type { CloudStatus, ClaimSignature } from '@shared/models'
-import { accountMismatch, mayAutoClaim, mayJoinAfterInstall, mayOfferMove, type AccountMismatch, type ClaimCandidate } from '../lib/auto-claim'
+import { accountMismatch, mayJoinAfterInstall, mayOfferJoin, mayOfferMove, type AccountMismatch, type ClaimCandidate } from '../lib/join-offer'
import { Observable } from '../lib/observable'
import { isOlderCopy } from '../lib/older-copy'
import { relayAddressToSave } from '../lib/relay-address'
@@ -99,9 +99,12 @@ export class CloudModel extends Observable {
/** The latest list request: an earlier one it overtook answers with it. */
private listing: Promise<boolean> = Promise.resolve(false)
private enablingCloud = false
- private autoClaiming = false
+ /** A computer the user asked to add (Settings, an SSH install), waiting for the join prompt's answer. */
+ private joinRequest: BotStore | null = null
/** This computer is on its way from another account into this one (`moveHere`). */
private moving = false
+ /** A computer the user said yes to is on its way into this account (`acceptJoin`). */
+ private joining = false
constructor(private app: AppModel) {
super()
@@ -151,7 +154,7 @@ export class CloudModel extends Observable {
void this.refresh(true)
}
this.applyCloudDefault()
- this.autoClaim()
+ this.noteClaimed()
}
/**
@@ -199,31 +202,64 @@ export class CloudModel extends Observable {
.finally(() => (this.enablingCloud = false))
}
- /** Signed in, this computer joins the account on its own (`mayAutoClaim`). */
- private autoClaim() {
+ /** Remembers this computer's identity once it's seen in the account (`mayOfferJoin`). */
+ private noteClaimed() {
const user = this.userId
const store = this.app.local
if (user && store && store.cloud?.owner?.userId === user) include(claimedIds(user), store.computer.id)
- const target = this.autoClaimTarget
- if (!target || this.autoClaiming) return
- this.autoClaiming = true
- void (async () => {
- // A failed join (network hiccup) is retried with backoff for as long as it's still wanted.
- let delay = 30_000
- while (!(await this.claim(target, true))) {
- await new Promise((r) => setTimeout(r, delay))
- delay = Math.min(delay * 2, 600_000)
- if (this.autoClaimTarget?.computer.id !== target.computer.id) break
- }
- this.autoClaiming = false
- })()
}
- private get autoClaimTarget(): BotStore | null {
+ /** What the join prompt asks about: a computer the user asked to add, or this one, once, while it's in no account. */
+ get joinOffer(): BotStore | null {
const user = this.userId
+ if (!user || this.moving || this.joining) return null
+ if (this.joinRequest) return this.joinRequest
const store = this.app.local
- if (!user || !store || this.moving) return null
- return mayAutoClaim(candidate(store), keptOut(user).get(), claimedIds(user).get()) ? store : null
+ return store && mayOfferJoin(candidate(store), keptOut(user).get(), claimedIds(user).get()) ? store : null
+ }
+
+ /** Add to account, through the prompt that says which phones it removes. */
+ requestJoin(store: BotStore) {
+ this.joinRequest = store
+ this.changed()
+ }
+
+ /**
+ * Yes to `joinOffer`. The host hears of its account a moment later, so a computer that joined isn't asked about
+ * again meanwhile; one that couldn't says why (`fail`), and Add to account tries again.
+ */
+ async acceptJoin(store: BotStore) {
+ const user = this.userId
+ if (this.joining || !user) return
+ this.joinRequest = null
+ this.joining = true
+ this.changed()
+ const joined = await this.claim(store)
+ include(joined ? claimedIds(user) : keptOut(user), store.computer.id)
+ this.joining = false
+ this.changed()
+ analytics.track({ event: 'join_offer_answered', outcome: joined ? 'added' : 'failed' })
+ }
+
+ /** The phones `store`'s computer would remove by joining the signed-in account. A host before this method removes the same phones and can't name them. */
+ async joinWouldRemove(store: BotStore): Promise<string[]> {
+ const userId = this.userId
+ if (!userId) return []
+ try {
+ return (await (await store.ready()).call<{ names: string[] }>('joinWouldRemove', { userId })).names
+ } catch (error) {
+ this.fail(error, true)
+ return []
+ }
+ }
+
+ /** No to `joinOffer`: phones reach it only over Wi-Fi or Tailscale, and it isn't offered again (Add to account still adds it). */
+ declineJoin(store: BotStore) {
+ const user = this.userId
+ if (user) include(keptOut(user), store.computer.id)
+ this.joinRequest = null
+ this.changed()
+ analytics.track({ event: 'join_offer_answered', outcome: 'kept_out' })
}
/** This computer, still in another account than the one signed in here: the user is asked to move it (`mayOfferMove`). */
@@ -239,7 +275,7 @@ export class CloudModel extends Observable {
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())
+ return accountMismatch(candidate(store), user)
}
/** The sidebar line: asks again whether to move this computer here, even after "Keep it there". */
@@ -278,11 +314,11 @@ export class CloudModel extends Observable {
}
}
- /** Add to account for an SSH computer just installed from here (installing shows the intent), once its host is up. */
+ /** Asks to add an SSH computer just installed from here, once its host is up. */
async joinAfterInstall(store: BotStore) {
if (!this.userId) return
try {
- if (mayJoinAfterInstall(await (await store.ready()).call<CloudStatus>('cloudStatus'))) await this.claim(store)
+ if (mayJoinAfterInstall(await (await store.ready()).call<CloudStatus>('cloudStatus'))) this.requestJoin(store)
} catch (error) {
this.fail(error)
}
@@ -326,7 +362,7 @@ export class CloudModel extends Observable {
/**
* Asked before Reach from anywhere turns on: Use your own relay. It's on the Codync relay until its address is saved,
- * so it's kept out of auto-claim meanwhile (`keptOut`; Add to account still adds it).
+ * so it isn't offered the account meanwhile (`keptOut`; Add to account still adds it).
*/
async useOwnRelay(store: BotStore) {
const user = this.userId
@@ -425,7 +461,7 @@ export class CloudModel extends Observable {
}
}
-/** What the account rules (`auto-claim`) read of a computer's host. */
+/** What the account rules (`join-offer`) read of a computer's host. */
function candidate(store: BotStore): ClaimCandidate {
return { id: store.computer.id, online: store.connection.kind === 'online', cloud: store.cloud }
}
diff --git a/apps/desktop/src/renderer/views/AccountWelcomeView.tsx b/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
index 7e5126b2..475737c4 100644
--- a/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
+++ b/apps/desktop/src/renderer/views/AccountWelcomeView.tsx
@@ -19,16 +19,25 @@ const deviceName = window.codync.platform === 'darwin' ? 'Mac' : 'computer'
/** 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 [withoutAccount, setWithoutAccount] = usePref(prefs.withoutAccount)
const { isConfigured, isReady, isSignedIn } = useAccount()
const finish = useCallback(() => {
+ if (!account.isSignedIn && account.isConfigured) {
+ setWithoutAccount(true)
+ analytics.track({ event: 'continued_without_account' })
+ }
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 }
+ }, [setOnboarded, setWithoutAccount])
+ // Signing in, however it happens, ends going on without an account.
+ useEffect(() => {
+ if (isSignedIn && withoutAccount) setWithoutAccount(false)
+ }, [isSignedIn, withoutAccount, setWithoutAccount])
+ return { shown: showsWelcome({ onboarded, configured: isConfigured, ready: isReady, signedIn: isSignedIn, withoutAccount }), 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. */
+/** The welcome: signing in, or going on without an account. A restored session skips it as soon as it is back. */
export function AccountWelcomeView({ onContinue }: { onContinue: () => void }) {
const account = useAccount()
const reduce = useReduceMotion()
@@ -82,14 +91,15 @@ export function AccountWelcomeView({ onContinue }: { onContinue: () => void }) {
</VStack>
<Spacer min={32} />
<VStack gap={10} style={rise(beat >= 4)}>
- {account.isConfigured ? null : (
- <Button onClick={onContinue} className="welcome-button">
- {onThis}
- </Button>
- )}
<ProviderButton provider="apple" mark={<Icon name="apple.logo" size={20} />} title="Continue with Apple" />
<ProviderButton provider="google" kind="secondary" mark={<img src={googleLogo} alt="" width={20} height={20} />} title="Continue with Google" />
<ProviderButton provider="github" kind="secondary" mark={<Icon name="github.logo" size={20} />} title="Continue with GitHub" />
+ <Button kind="secondary" onClick={onContinue} className="welcome-button">
+ {onThis}
+ </Button>
+ {account.isConfigured ? (
+ <Text as="div" size="footnote" tone="tertiary">{tr('Phones then connect only over Wi-Fi or Tailscale.')}</Text>
+ ) : null}
{!account.isConfigured ? (
<Text as="div" size="footnote" tone="tertiary">{tr(deviceName === 'Mac' ? "Sign-in isn't configured in this build. You can still use Codync on this Mac." : "Sign-in isn't configured in this build. You can still use Codync on this computer.")}</Text>
) : null}
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 152edb92..53c4367f 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -37,6 +37,7 @@ import { StartupRecovery } from './StartupRecovery'
export { EmptyState } from './HostStateView'
import { RefreshIndicator } from './RefreshIndicator'
import { StarPrompt } from './StarPrompt'
+import { JoinAccountPrompt } from './JoinAccountPrompt'
import { MoveComputerPrompt } from './MoveComputerPrompt'
import { PairingRequestPrompt } from './PairingRequestPrompt'
import { DeleteAccountPrompt } from './DeleteAccountPrompt'
@@ -138,7 +139,7 @@ export function ChatWindow() {
<AccountWelcomeView onContinue={welcome.finish} />
)}
{!welcome.shown && accessSetup !== null && showsChat ? null : <div className="window-drag drag" />}
- {!welcome.shown && accessSetup !== null ? <><StarPrompt /><MoveComputerPrompt /><DeleteAccountPrompt /></> : null}
+ {!welcome.shown && accessSetup !== null ? <><StarPrompt /><MoveComputerPrompt /><JoinAccountPrompt /><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) }} />
@@ -414,14 +415,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')} />
+ <RailAccountNotice />
<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} onComputers={() => setSettings('computers')} />
+ <SidebarFooter accountOpen={showAccount} onAccount={() => setShowAccount((s) => !s)} onExtensions={roster.grouped ? undefined : openMarketplace} />
)}
</aside>
<ResizeHandle label={tr('Resize sidebar')} width={width} min={76} max={sidebarMax} edge="trailing" onResize={resizeSidebar} onDragging={setResizing} />
diff --git a/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx b/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx
new file mode 100644
index 00000000..43a23585
--- /dev/null
+++ b/apps/desktop/src/renderer/views/JoinAccountPrompt.tsx
@@ -0,0 +1,37 @@
+import { Dialog } from '../components/Overlay'
+import { withJoinRemoves } from '../lib/account-copy'
+import { useModel } from '../lib/observable'
+import { useTr } from '../lib/use-language'
+import { useAccount } from '../store/account'
+import { useApp } from '../store/context'
+import { useJoinRemoves } from './use-join-removes'
+
+/**
+ * Signed in, with a computer in no account: add it, or keep it out (docs/plans/optional-sign-in.md). Asked once for this
+ * computer (`joinOffer`), and whenever the user asks to add one.
+ */
+export function JoinAccountPrompt() {
+ const tr = useTr()
+ const app = useApp()
+ useAccount()
+ useModel(app.cloud)
+ useModel(app.local)
+ const store = app.cloud.joinOffer
+ const names = useJoinRemoves(store, store !== null)
+ // An SSH computer: the Mac in front of the user isn't the one this adds.
+ const title = store && store !== app.local ? tr('Add {name} to your account?').replaceAll('{name}', () => store.hostName) : tr('Add this computer to your account?')
+ return (
+ <Dialog
+ open={store !== null}
+ title={title}
+ message={withJoinRemoves(tr, tr('Without it, phones can connect only over Wi-Fi or Tailscale.'), names)}
+ // A choice either way: "not now" is remembered, so it isn't a dismissal.
+ cancel={null}
+ actions={store ? [
+ { title: 'Not now', action: () => app.cloud.declineJoin(store) },
+ { title: 'Add to account', action: () => void app.cloud.acceptJoin(store) },
+ ] : []}
+ onClose={() => {}}
+ />
+ )
+}
diff --git a/apps/desktop/src/renderer/views/PairingCode.tsx b/apps/desktop/src/renderer/views/PairingCode.tsx
index ef72dced..6b44eef3 100644
--- a/apps/desktop/src/renderer/views/PairingCode.tsx
+++ b/apps/desktop/src/renderer/views/PairingCode.tsx
@@ -57,7 +57,7 @@ export function PairingCode({ name, cloud, requestCode, renew = 0 }: { name: str
</Text>
{cloud?.canJoinAccount ? (
<Text as="div" size="caption" tone="attention" className="pairing-note">
- {tr('Not in an account: a signed-in phone that scans this asks to bring the computer into its account.')}
+ {tr('Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.')}
</Text>
) : null}
{cloud?.enabled !== true ? (
diff --git a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
index 81fe3b91..9d3bd8ef 100644
--- a/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
+++ b/apps/desktop/src/renderer/views/PairingRequestPrompt.tsx
@@ -1,14 +1,14 @@
import { useEffect } from 'react'
import { Dialog } from '../components/Overlay'
-import { pairingAskText } from '../lib/account-copy'
+import { pairingAnswers, pairingAskText } from '../lib/account-copy'
import { useModel, useModels } from '../lib/observable'
import { useTr } from '../lib/use-language'
import { useApp } from '../store/context'
/**
- * A signed-in phone scanned a computer this app manages that is in no account: let it in, and the computer joins
- * the phone's account (docs/plans/require-sign-in.md, phase 2). The phone shows the same code. Unanswered, the
- * host turns the phone away after 90 seconds.
+ * A phone asks about a computer this app manages that is in no account: let it in, and join its account when it has one
+ * (docs/plans/optional-sign-in.md). The phone shows the same code. Unanswered, the host turns the phone away after 90
+ * seconds.
*/
export function PairingRequestPrompt() {
const tr = useTr()
@@ -20,9 +20,9 @@ export function PairingRequestPrompt() {
if (ask) window.codync.app.showWindow()
}, [ask?.id])
- const decide = (approve: boolean) => {
+ const decide = (approve: boolean, join?: boolean) => {
if (!ask) return
- void app.decidePairing(ask, approve)
+ void app.decidePairing(ask, approve, join)
}
const text = ask ? pairingAskText(tr, ask.request) : null
return (
@@ -34,7 +34,7 @@ export function PairingRequestPrompt() {
cancel={null}
actions={[
{ title: "Don't allow", action: () => decide(false) },
- { title: 'Let in', action: () => decide(true) },
+ ...(ask ? pairingAnswers(ask.request).map(({ title, join }) => ({ title, action: () => decide(true, join) })) : []),
]}
onClose={() => {}}
/>
diff --git a/apps/desktop/src/renderer/views/SidebarFooter.tsx b/apps/desktop/src/renderer/views/SidebarFooter.tsx
index fd00573d..86d9eae1 100644
--- a/apps/desktop/src/renderer/views/SidebarFooter.tsx
+++ b/apps/desktop/src/renderer/views/SidebarFooter.tsx
@@ -2,7 +2,6 @@ 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'
@@ -15,15 +14,13 @@ 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, onComputers }: {
+export function SidebarFooter({ accountOpen, onAccount, onExtensions }: {
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 notice = useAccountNotice()
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(() => {
@@ -71,16 +68,16 @@ export function SidebarFooter({ accountOpen, onAccount, onExtensions, onComputer
}
/** 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)
+export function RailAccountNotice() {
+ const notice = useAccountNotice()
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.
+ * This computer is in another account than the one signed in here (`CloudModel.mismatch`): what to say, and the move
+ * prompt again.
*/
-function useAccountNotice(onComputers: () => void) {
+function useAccountNotice() {
const tr = useTr()
const app = useApp()
useAccount()
@@ -88,16 +85,6 @@ function useAccountNotice(onComputers: () => void) {
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`)
- }
+ const text = mismatch.email ? tr(`This computer is in {name}'s account`).replaceAll('{name}', mismatch.email) : tr('This computer is in another account')
+ return { text, open: () => app.cloud.reconsiderMove() }
}
diff --git a/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx b/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
index 984010da..f54cd855 100644
--- a/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
+++ b/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
@@ -68,7 +68,9 @@ export function RoutineWebhookPanel({ botId, routineId }: { botId: string; routi
webhook.url
? 'POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. ' +
tr('Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them.')
- : 'The Codync cloud is off, so only this computer can send to it.'
+ : webhook.needsAccount
+ ? "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one."
+ : 'The Codync cloud is off, so only this computer can send to it.'
}
>
{row(webhook.url ? tr('URL') : tr('Local URL'), webhook.url ?? webhook.localUrl, 'url')}
diff --git a/apps/desktop/src/renderer/views/routines/routine.ts b/apps/desktop/src/renderer/views/routines/routine.ts
index 23871634..5a4872ba 100644
--- a/apps/desktop/src/renderer/views/routines/routine.ts
+++ b/apps/desktop/src/renderer/views/routines/routine.ts
@@ -78,6 +78,8 @@ export interface RoutineWebhook {
localUrl: string
key: string
connected: boolean
+ /** In no account, so public deliveries can't reach it. */
+ needsAccount?: boolean
}
/** Form values only. */
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 02c51396..40907063 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -16,7 +16,8 @@ import { ComputerBadge } from '../ComputerBadge'
import { PairingCode } from '../PairingCode'
import { AuthorizedDevicesSection } from './AuthorizedDevicesSection'
import { ComputersUsedSection } from './ComputersUsedSection'
-import { devicesLoseAccess } from '../../lib/account-copy'
+import { devicesLoseAccess, withJoinRemoves } from '../../lib/account-copy'
+import { useJoinRemoves } from '../use-join-removes'
import { cloudStatusLine } from '../../lib/relay-copy'
import { useTr } from '../../lib/use-language'
import { errorText, liveClient, relativeDay, SectionHeader, statusText, thisMac } from './parts'
@@ -138,9 +139,10 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B
}
})
- // Turning it on asks to add a computer that would be in no account (`joinsAccountOnEnable`). Signed out, the welcome
- // covers Settings and a build without accounts has none to join; a saved session still restoring makes the switch wait.
+ // Turning it on asks to add a computer that would be in no account (`joinsAccountOnEnable`). Signed out there's no
+ // account to add it to, and it stays in none; a saved session still restoring makes the switch wait.
const asksAccount = cloud?.joinsAccountOnEnable === true
+ const joinRemoves = useJoinRemoves(store, askAccount)
const setReach = (on: boolean) => {
if (on && asksAccount && account.isSignedIn) setAskAccount(true)
else void run(() => app.cloud.setCloud(store, on))
@@ -168,8 +170,8 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B
Remove from account
</Button>
) : account.isSignedIn ? (
- <Button kind="secondary" onClick={() => run(async () => void (await app.cloud.claim(store)))} disabled={busy || !manageable}>
- {busy ? 'Adding…' : 'Add to account'}
+ <Button kind="secondary" onClick={() => app.cloud.requestJoin(store)} disabled={busy || !manageable}>
+ Add to account
</Button>
) : null}
</HStack>
@@ -282,7 +284,7 @@ function ManagedComputerCard({ store, ssh: overSSH, nested = false }: { store: B
<Dialog
open={askAccount}
title={tr('Add {name} to your account first').replaceAll('{name}', () => name)}
- message={tr('Your phone reaches {name} from anywhere through your account. Adding it also turns this on.').replaceAll('{name}', () => name)}
+ message={withJoinRemoves(tr, tr('Your phone reaches {name} from anywhere through your account. Adding it also turns this on.').replaceAll('{name}', () => name), joinRemoves)}
actions={[
{ title: 'Add to account', action: () => void run(() => app.cloud.addFromReach(store)) },
{ title: 'Use your own relay', action: () => void run(() => app.cloud.useOwnRelay(store)) },
diff --git a/apps/desktop/src/renderer/views/use-join-removes.ts b/apps/desktop/src/renderer/views/use-join-removes.ts
new file mode 100644
index 00000000..35529443
--- /dev/null
+++ b/apps/desktop/src/renderer/views/use-join-removes.ts
@@ -0,0 +1,18 @@
+import { useEffect, useState } from 'react'
+import type { BotStore } from '../store/bot-store'
+import { useApp } from '../store/context'
+
+/** The names of the phones `store`'s computer would remove by joining the signed-in account, while `open`. */
+export function useJoinRemoves(store: BotStore | null, open: boolean) {
+ const app = useApp()
+ const [names, setNames] = useState<string[]>([])
+ useEffect(() => {
+ if (!open || !store) return setNames([])
+ let current = true
+ void app.cloud.joinWouldRemove(store).then((removed) => current && setNames(removed))
+ return () => {
+ current = false
+ }
+ }, [app, store, open])
+ return names
+}
diff --git a/apps/desktop/src/shared/analytics.ts b/apps/desktop/src/shared/analytics.ts
index c1b8884e..7d3a9081 100644
--- a/apps/desktop/src/shared/analytics.ts
+++ b/apps/desktop/src/shared/analytics.ts
@@ -59,6 +59,8 @@ export type AnalyticsEvent =
| { event: 'voice_call_quality'; engine: VoiceCallEngine; ready_ms?: number; reconnects: number; stuck: VoiceStuck; failure: VoiceFailure }
| { event: 'window_recovery'; outcome: WindowRecoveryOutcome }
| { event: 'reach_account_answered'; outcome: ReachOutcome; error?: ClaimFailure }
+ | { event: 'continued_without_account' }
+ | { event: 'join_offer_answered'; outcome: 'added' | 'kept_out' | 'failed' }
/** `track`'s body: the event with its properties, from the desktop app. */
export const trackBody = (event: AnalyticsEvent) => ({ ...event, app: 'desktop' as const })
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 7d7b0d7d..bea049ae 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -568,10 +568,16 @@ export interface PairingRequest {
requestId: string
deviceName: string
platform?: string | null
- /** The phone's account, which the computer joins. */
+ /** The phone's account, which the computer can join. */
email?: string | null
/** The 6 digits the phone shows too. */
code: string
+ /** The phone is signed in and the Codync cloud is on, so the computer can join its account. */
+ canJoin?: boolean | null
+ /** The computer can stay out of an account: the phone then connects only over Wi-Fi or Tailscale. */
+ phoneOnly?: boolean | null
+ /** The phones that lose access if the computer joins. */
+ removes?: string[] | null
expiresAt?: number | null
}
diff --git a/apps/ios/App/AppStore+Account.swift b/apps/ios/App/AppStore+Account.swift
index 1fda0187..d2f08550 100644
--- a/apps/ios/App/AppStore+Account.swift
+++ b/apps/ios/App/AppStore+Account.swift
@@ -3,13 +3,18 @@ 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 }
+ /// 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. True when they have to be paired again: this
+ /// account has its own key on this iPhone.
+ @discardableResult
+ static func adoptSignedOutPairings(into storage: SharedStore.Context) -> Bool {
+ guard let adoption = storage.adopt(from: SharedStore.Context(accountID: nil)), adoption.computers > 0 else { return false }
Analytics.shared.capture(.signedOutPairingsMoved(computers: adoption.computers, keys: adoption.keys))
+ return adoption.keys == .rescan
}
+ static let scanAgain = "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept."
+
/// Signing out: Clerk first, so a sign-out that fails changes nothing. This iPhone keeps the account's key,
/// computers and drafts, so signing back in needs no scan or check; only its alerts stop: the computers it reaches
/// drop them now, the others when the account tells them (connections.md, accounts on a phone).
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index 8d597b71..c9d9f724 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -150,11 +150,12 @@ final class AppStore {
}
CrashReports.shared.start()
contextID = storage.id
- Self.adoptSignedOutPairings(into: storage)
+ let rescan = 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) })
(accounts, cloud) = Self.makeAccounts(storage, session: session)
+ if rescan { accounts.lastError = Self.scanAgain }
}
var storage: SharedStore.Context { accounts.storage }
@@ -170,7 +171,7 @@ final class AppStore {
accounts.retire()
PushRegistrar.shared.deactivate()
LiveActivities.shared.endAll()
- Self.adoptSignedOutPairings(into: storage)
+ let rescan = Self.adoptSignedOutPairings(into: storage)
SharedStore.activeAccountID = userID
storage.bots = []
contextID = storage.id
@@ -178,6 +179,7 @@ final class AppStore {
showComputers = false
marketplace = nil
(accounts, cloud) = Self.makeAccounts(storage, session: account)
+ if rescan { accounts.lastError = Self.scanAgain }
BotsWidgetFeed.reset()
WidgetCenter.shared.reloadAllTimelines()
}
@@ -197,6 +199,7 @@ final class AppStore {
storage.bots = []
SharedStore.activeAccountID = nil
UserDefaults.standard.set(false, forKey: "onboardingCompleted")
+ UserDefaults.standard.set(false, forKey: "withoutAccount")
showComputers = false
account.showSwitcher = false
marketplace = nil
@@ -213,7 +216,7 @@ final class AppStore {
func pairing(from text: String) async throws -> Pairing {
do {
guard let code = Pairing.shortCode(text) else { return try Pairing.parse(text) }
- guard let cloud else { throw AccountStore.noCertificate }
+ guard let cloud else { throw AccountStore.signInForShortCode }
return try Pairing.parse(try await cloud.pairingLink(code: code))
} catch {
throw pairingFailed(error)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
index 6b176044..bf2b4367 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
@@ -14,6 +14,11 @@ public enum AnalyticsEvent: Equatable, Sendable {
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 continuedWithoutAccount
+ case computerFoundOnNetwork
+ case addToAccountAsked
+ case addToAccountCompleted
+ case addToAccountFailed(AddToAccountFailure)
case pairingFailed(PairingFailure)
case computerPaired(via: PairVia, computer: ComputerID)
case accessRequested
@@ -69,6 +74,22 @@ public enum AnalyticsEvent: Equatable, Sendable {
}
}
+ public enum AddToAccountFailure: String, Sendable {
+ case declined, certificate, unreachable, other
+
+ public init(_ error: any Error) {
+ switch error {
+ case let host as HostError where host.isTransient: self = .unreachable
+ case let HostError.http(_, message) where message == "The computer stayed out of this account.": self = .declined
+ case let HostError.http(_, message) where message.hasPrefix("Couldn't confirm your Codync account"): self = .certificate
+ case let cloud as CloudError where cloud.code == "noCertificate": self = .certificate
+ case let cloud as CloudError where cloud.isTransient: self = .unreachable
+ case is URLError: self = .unreachable
+ default: self = .other
+ }
+ }
+ }
+
public enum PairingFailure: String, Sendable {
case notPairingLink = "not_pairing_link", outdatedHost = "outdated_host", invalid
case expired, unauthorized, unreachable, timeout, upgradeRequired = "upgrade_required", other
@@ -85,6 +106,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
case let host as HostError:
self = switch host {
case .upgradeRequired: .upgradeRequired
+ case .unreachableDirectly: .unreachable
// The host turns down a pairing code that expired or was already used, and a phone it doesn't
// let in: another account's, one it can't confirm, or one its user declined.
case let .http(403, message): message.hasPrefix("This pairing code expired") ? .expired : .unauthorized
@@ -109,6 +131,11 @@ public enum AnalyticsEvent: Equatable, Sendable {
case .signedIn: "signed_in"
case .signedOut: "signed_out"
case .signedOutPairingsMoved: "signed_out_pairings_moved"
+ case .continuedWithoutAccount: "continued_without_account"
+ case .computerFoundOnNetwork: "computer_found_on_network"
+ case .addToAccountAsked: "add_to_account_asked"
+ case .addToAccountCompleted: "add_to_account_completed"
+ case .addToAccountFailed: "add_to_account_failed"
case .pairingFailed: "pairing_failed"
case .computerPaired: "computer_paired"
case .accessRequested: "access_requested"
@@ -137,7 +164,9 @@ public enum AnalyticsEvent: Equatable, Sendable {
case let .onboardingCompleted(via): return ["via": .string(via.rawValue)]
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 .signedOut, .accessRequested, .continuedWithoutAccount, .computerFoundOnNetwork, .addToAccountAsked,
+ .addToAccountCompleted: return [:]
+ case let .addToAccountFailed(reason): return ["reason": .string(reason.rawValue)]
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):
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Calls.swift b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Calls.swift
index 35a29ca1..a10918b7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Calls.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Calls.swift
@@ -20,7 +20,7 @@ extension ChannelTransport {
switch state {
case .ready where link?.sealer != nil: return
case .ready, .connecting:
- guard ContinuousClock.now < deadline else { throw HostError.unreachable }
+ guard ContinuousClock.now < deadline else { throw linkError(.connecting) }
await stateChange(until: deadline)
case .hostOffline, .unauthorized, .failed: throw linkError(state)
}
@@ -48,7 +48,7 @@ extension ChannelTransport {
case let .hostOffline(lastSeen): .computerOffline(lastSeen: lastSeen)
case let .unauthorized(message): .unauthorized(message)
case .failed where needsUpgrade: .upgradeRequired
- case .connecting, .ready, .failed: .unreachable
+ case .connecting, .ready, .failed: computer.cloud == nil ? .unreachableDirectly : .unreachable
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
index 5052fada..852cf5e4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport+Connection.swift
@@ -51,10 +51,18 @@ extension ChannelTransport {
let socket = try? await dial(.relay(relayRequest(cloud))) {
return await serve(socket, route: .relay, keys: nil)
}
- let directURLs = computer.urls.compactMap(Self.channelURL)
+ // With no relay, a changed address can only be found on the network.
+ var found: [String] = []
+ if computer.cloud == nil {
+ let saved = computer.urls
+ found = await discovered(computer.id).filter { !saved.contains($0) }
+ }
+ let directURLs = (computer.urls + found).compactMap(Self.channelURL)
if !directURLs.isEmpty {
switch await raceDirect(directURLs) {
- case let .connected(socket, keys): return await serve(socket, route: .direct, keys: keys)
+ case let .connected(socket, keys):
+ if !found.isEmpty { await Analytics.shared.capture(.computerFoundOnNetwork) }
+ return await serve(socket, route: .direct, keys: keys)
case let .outcome(end): return end
case let .rejected(end):
// A plaintext `reject` isn't signed: whatever answers at a saved LAN address can
@@ -71,7 +79,11 @@ extension ChannelTransport {
}
}
// Already tried first, or ruled out by the user (privacy): no second relay attempt.
- guard let cloud = computer.cloud, route == .automatic else { return .retry(HostError.unreachable.localizedDescription) }
+ guard let cloud = computer.cloud else { return .retry(HostError.unreachableDirectly.localizedDescription) }
+ guard route == .automatic else {
+ let failure = route == .directOnly ? HostError.unreachableDirectly : HostError.unreachable
+ return .retry(failure.localizedDescription)
+ }
let socket: any ChannelSocket
do {
socket = try await dial(.relay(relayRequest(cloud)))
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swift b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swift
index 3fe4ac50..cac64d18 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swift
@@ -22,11 +22,16 @@ public actor ChannelTransport: RemoteTransport {
private let watchesNetwork: Bool
/// The screen follows the active signaling route; direct-only connections never request TURN.
- public func screenRelayRequired() async throws -> Bool {
+ public func screenRelayRequired(failedAttempts: Int = 0) async throws -> Bool {
try await ready(within: 20)
- return link?.route == .relay
+ // A private relay has no TURN (`RelayCopy.host`), and a computer in no account gets no address.
+ return ScreenRoute.asksForTurn(channelOnRelay: link?.route == .relay, route: computer.route ?? .automatic,
+ hasTurn: computer.cloud != nil && RelayCopy.host(of: computer.cloud) == nil,
+ failedAttempts: failedAttempts)
}
+ var prefersCloudflare: Bool { computer.route == .cloudflareFirst }
+
var state: LinkState = .connecting
var lastSeen: Date?
var link: Link?
@@ -53,6 +58,10 @@ public actor ChannelTransport: RemoteTransport {
var computerObservers: [UUID: AsyncStream<Computer>.Continuation] = [:]
var mailboxObservers: [UUID: AsyncStream<MailboxEvent>.Continuation] = [:]
+ /// What the local network says about a computer's addresses, for one with no relay to learn them from.
+ typealias Discovered = @Sendable (ComputerID) async -> [String]
+ let discovered: Discovered
+
/// One open socket and, once the handshake is done, its channel keys.
struct Link {
let socket: any ChannelSocket
@@ -77,11 +86,13 @@ public actor ChannelTransport: RemoteTransport {
}
public init(computer: Computer, identity: DeviceIdentity) {
- self.init(computer: computer, identity: identity, pairingCode: nil)
+ self.init(computer: computer, identity: identity, pairingCode: nil, discovered: { await LocalDiscovery.shared.urls(for: $0) })
}
init(computer: Computer, identity: DeviceIdentity, pairingCode: String?, dial: @escaping Dialer = URLSessionSocket.dial,
- directBudget: Duration = .milliseconds(1500), watchesNetwork: Bool = true) {
+ directBudget: Duration = .milliseconds(1500), watchesNetwork: Bool = true,
+ discovered: @escaping Discovered = { _ in [] }) {
+ self.discovered = discovered
self.computer = computer
self.identity = identity
self.pairingCode = pairingCode
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Screen.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Screen.swift
new file mode 100644
index 00000000..e8208653
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Screen.swift
@@ -0,0 +1,43 @@
+import Foundation
+
+// MARK: - Remote screen
+
+public extension HostClient {
+ func screenStatus() async throws -> ScreenState { try await call("screenStatus") }
+
+ /// `failedAttempts`: tries that ended without a picture, so the next one can go the other way (`ScreenRoute`).
+ func screenPrepare(failedAttempts: Int = 0) async throws -> ScreenConnection {
+ let relay = if let channel = transport as? ChannelTransport {
+ try await channel.screenRelayRequired(failedAttempts: failedAttempts)
+ } else {
+ false
+ }
+ return try await call("screenPrepare", ["relay": relay, "trickle": true])
+ }
+
+ /// Whether a screen attempt that couldn't even start should try the other way: Cloudflare first has one to try.
+ func screenFallsBack() async -> Bool {
+ await (transport as? ChannelTransport)?.prefersCloudflare ?? false
+ }
+
+ /// Sends the offer using the prepared session’s negotiated ICE mode.
+ /// Trickle negotiations use a fresh session for every connection attempt.
+ func screenOffer(sdp: String, session: String?, display: UInt32?) async throws -> ScreenAnswer {
+ struct Body: Encodable { var sdp: String; var session: String?; var display: UInt32? }
+ return try await call("screenOffer", Body(sdp: sdp, session: session, display: display), timeout: 30)
+ }
+
+ func screenClose(session: String) async throws {
+ let _: Empty = try await call("screenClose", ["session": session])
+ }
+
+ /// Takes control from bots (they can still look) or hands it back.
+ func screenTakeover(_ on: Bool) async throws -> ScreenState {
+ try await call("screenTakeover", ["on": on])
+ }
+}
+
+public struct ScreenAnswer: Codable, Sendable {
+ public var session: String
+ public var sdp: String
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 096db499..83d2a709 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -156,10 +156,12 @@ public extension HostClient {
let _: Empty = try await call("installHostUpdate")
}
- /// The computer signs `claim` for the account this phone paired from (`Hello.joinAccount`), as JSON to
- /// pass on to `CloudClient.completeClaim` as it came.
- func joinAccount(_ claim: CloudClaim) async throws -> Data {
- try await transport.call("joinAccount", body: try Self.encoder.encode(claim), timeout: 20)
+ /// The computer asks its user (up to 90 seconds), then signs `claim` for this phone's account
+ /// (`Hello.canJoinAccount`), as JSON to pass on to `CloudClient.completeClaim` as it came.
+ func joinAccount(_ claim: CloudClaim, certificate: DeviceCertificate) async throws -> Data {
+ struct Body: Encodable { var claimId: String; var nonce: String; var certificate: DeviceCertificate }
+ let body = Body(claimId: claim.claimId, nonce: claim.nonce, certificate: certificate)
+ return try await transport.call("joinAccount", body: try Self.encoder.encode(body), timeout: 120)
}
func history(botId: String, beforeSeq: Int64, limit: Int = 100) async throws -> [Entry] {
@@ -403,32 +405,6 @@ public extension HostClient {
struct Body: Encodable { var path: String? }
return try await call("listDirs", Body(path: path))
}
-
- // MARK: remote screen
-
- func screenStatus() async throws -> ScreenState { try await call("screenStatus") }
-
- func screenPrepare() async throws -> ScreenConnection {
- let relay = if let channel = transport as? ChannelTransport { try await channel.screenRelayRequired() } else { false }
- return try await call("screenPrepare", ["relay": relay, "trickle": true])
- }
-
- /// Sends the offer using the prepared session’s negotiated ICE mode.
- /// Trickle negotiations use a fresh session for every connection attempt.
- func screenOffer(sdp: String, session: String?, display: UInt32?) async throws -> ScreenAnswer {
- struct Body: Encodable { var sdp: String; var session: String?; var display: UInt32? }
- return try await call("screenOffer", Body(sdp: sdp, session: session, display: display), timeout: 30)
- }
-
- func screenClose(session: String) async throws {
- let _: Empty = try await call("screenClose", ["session": session])
- }
-
- /// Takes control from bots (they can still look) or hands it back.
- func screenTakeover(_ on: Bool) async throws -> ScreenState {
- try await call("screenTakeover", ["on": on])
- }
-
}
// MARK: - Agent setup
@@ -483,8 +459,3 @@ public extension HostClient {
let _: Empty = try await call("termClose", ["term": term])
}
}
-
-public struct ScreenAnswer: Codable, Sendable {
- public var session: String
- public var sdp: String
-}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
index 6a6cd0dc..a0243759 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swift
@@ -16,17 +16,18 @@ public enum HostConnector {
throw HostError.unreachable
}
- /// Proves the QR's one-time code inside a channel to the QR's host key, with the account's `certificate`;
- /// the host then authorizes this device and closes with `4100 paired`. A computer in no account asks its
- /// user first, then signs `claim` and returns it (as JSON) for the phone to complete with the cloud.
+ /// Proves the QR's one-time code inside a channel to the QR's host key, with the account's `certificate`, if this
+ /// phone is signed in; the host then authorizes this device and closes with `4100 paired`. A computer in no
+ /// account asks its user first, and when told to join signs `claim` and returns it (as JSON) for the phone to
+ /// complete with the cloud.
public static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String,
- certificate: DeviceCertificate, claim: CloudClaim?) async throws -> (computer: Computer, claim: Data?) {
+ certificate: DeviceCertificate?, claim: CloudClaim?) async throws -> (computer: Computer, claim: Data?) {
try await pair(pairing, identity: identity, deviceName: deviceName, platform: platform,
certificate: certificate, claim: claim, dial: URLSessionSocket.dial)
}
static func pair(_ pairing: Pairing, identity: DeviceIdentity, deviceName: String, platform: String,
- certificate: DeviceCertificate, claim: CloudClaim?, dial: @escaping Dialer) async throws -> (computer: Computer, claim: Data?) {
+ certificate: DeviceCertificate?, claim: CloudClaim?, dial: @escaping Dialer) async throws -> (computer: Computer, claim: Data?) {
let transport = ChannelTransport(computer: pairing.computer, identity: identity, pairingCode: pairing.code, dial: dial)
await transport.start()
do {
@@ -34,12 +35,13 @@ public enum HostConnector {
var code: String
var name: String
var platform: String
- var certificate: DeviceCertificate
+ var certificate: DeviceCertificate?
var claim: CloudClaim?
}
struct Res: Decodable { var computerId: ComputerID; var name: String? }
let body = try JSONEncoder().encode(Body(code: pairing.code, name: deviceName, platform: platform, certificate: certificate, claim: claim))
- try await transport.ready(within: 30)
+ // Without a relay there's only the direct race to wait for, and waiting longer changes nothing.
+ try await transport.ready(within: pairing.computer.cloud == nil ? 12 : 30)
// The computer may be waiting for its user to let this phone in (up to 90 seconds).
let data = try await transport.call("pair", body: body, timeout: 150)
await transport.shutdown()
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
index 4a852880..ad5ad502 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swift
@@ -68,6 +68,8 @@ public protocol RemoteTransport: HostTransport {
public enum HostError: LocalizedError, Sendable, Equatable {
case http(Int, String)
case unreachable
+ /// With no relay, a computer that's off and a phone that's away look the same.
+ case unreachableDirectly
case computerOffline(lastSeen: Date?)
case unauthorized(String)
case upgradeRequired
@@ -77,6 +79,7 @@ public enum HostError: LocalizedError, Sendable, Equatable {
case .http(401, _): "This device isn't allowed on that computer anymore."
case let .http(_, message): message
case .unreachable: "Can't reach your computer. Is it on and connected to the internet?"
+ case .unreachableDirectly: "Can't reach your computer. Check you're on the same network or that Tailscale is on."
case .computerOffline: "Your computer is offline."
case let .unauthorized(message): message
case .upgradeRequired: "Update Codync to connect to this computer."
@@ -86,7 +89,7 @@ public enum HostError: LocalizedError, Sendable, Equatable {
/// The link failed, not the request: the same call can work once the computer is reachable again.
public var isTransient: Bool {
switch self {
- case .unreachable, .computerOffline: true
+ case .unreachable, .unreachableDirectly, .computerOffline: true
default: false
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/LocalDiscovery.swift b/apps/ios/Kit/Sources/CodyncKit/Client/LocalDiscovery.swift
new file mode 100644
index 00000000..e650eaf2
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/LocalDiscovery.swift
@@ -0,0 +1,54 @@
+import Foundation
+import Network
+
+/// Finds computers in no account on the local network (docs/plans/optional-sign-in.md). They have no relay to tell a
+/// phone their new address, so they advertise it over Bonjour. Nothing found here is trusted: the phone dials the
+/// address and the handshake checks the computer's pinned key.
+public actor LocalDiscovery {
+ public static let shared = LocalDiscovery()
+
+ /// Also in `NSBonjourServices`, and in the host's `remote/discovery.rs`.
+ static let service = "_codync._tcp"
+
+ private var browser: NWBrowser?
+ private var found: [ComputerID: [String]] = [:]
+
+ /// The addresses `id` advertises right now. The first call starts browsing, which asks for the Local Network
+ /// permission a direct connection needs anyway.
+ public func urls(for id: ComputerID) -> [String] {
+ if browser == nil { start() }
+ return found[id] ?? []
+ }
+
+ private func start() {
+ let browser = NWBrowser(for: .bonjourWithTXTRecord(type: Self.service, domain: nil), using: .tcp)
+ browser.browseResultsChangedHandler = { results, _ in
+ let entries = results.compactMap { result -> (id: ComputerID, urls: [String])? in
+ guard case let .bonjour(txt) = result.metadata else { return nil }
+ return Self.entry(id: txt["id"], urls: txt["urls"])
+ }
+ Task { await self.update(entries) }
+ }
+ browser.stateUpdateHandler = { state in
+ if case .failed = state { Task { await self.stop() } }
+ }
+ browser.start(queue: .global(qos: .utility))
+ self.browser = browser
+ }
+
+ private func stop() {
+ browser?.cancel()
+ browser = nil
+ }
+
+ private func update(_ entries: [(id: ComputerID, urls: [String])]) {
+ found = Dictionary(entries.map { ($0.id, $0.urls) }, uniquingKeysWith: { a, _ in a })
+ }
+
+ /// One advertised record: the computer's ID and its comma-separated addresses, kept only if they're valid.
+ nonisolated static func entry(id: String?, urls: String?) -> (id: ComputerID, urls: [String])? {
+ guard let id, !id.isEmpty, let urls else { return nil }
+ let valid = Pairing.directURLs(urls.split(separator: ",").map(String.init))
+ return valid.isEmpty ? nil : (id, valid)
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
index 78714410..e8c58eb9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swift
@@ -69,11 +69,16 @@ public struct Pairing: Hashable, Sendable {
self.code = code
}
- /// The 6 digits the computer shows if it asks whether to let `identity` in.
- public func checkCode(for identity: DeviceIdentity) -> String {
- RelayCrypto.pairCheck(deviceKey: identity.deviceKey, hostSignKey: Data(base64URL: computer.signKey) ?? Data())
+ /// As a phone with no account uses it: the Codync relay is for signed-in phones. A private relay is the user's own.
+ public var withoutRelay: Pairing {
+ var computer = computer
+ if RelayCopy.host(of: computer.cloud) == nil { computer.cloud = nil }
+ return Pairing(computer: computer, code: code)
}
+ /// The 6 digits the computer shows if it asks whether to let `identity` in.
+ public func checkCode(for identity: DeviceIdentity) -> String { computer.checkCode(for: identity) }
+
/// The relay's pairing socket parameter.
var offerId: String? { Data(base64URL: code).map(RelayCrypto.offerId(code:)) }
@@ -102,3 +107,10 @@ public struct Pairing: Hashable, Sendable {
#endif
}
}
+
+extension Computer {
+ /// The 6 digits this computer shows if it asks about `identity`.
+ public func checkCode(for identity: DeviceIdentity) -> String {
+ RelayCrypto.pairCheck(deviceKey: identity.deviceKey, hostSignKey: Data(base64URL: signKey) ?? Data())
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
index bb4c4cf9..ce867c09 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift
@@ -156,8 +156,8 @@ public extension SharedStore.Context {
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.
+ /// Signing in: 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
@@ -169,24 +169,25 @@ public extension SharedStore.Context {
try DeviceIdentity.move(from: local, to: self)
} catch {
log.error("Cannot move the device key: \(error.localizedDescription)")
- return merge(moving)
+ return merge(moving, from: local, unmoved: &unmoved)
}
for name in Self.names { defaults.set(local.defaults.object(forKey: local.key(name)), forKey: key(name)) }
unmoved = moveMirrorCaches(from: local)
return Adoption(computers: moving.count, keys: .moved)
}
- return merge(moving)
+ return merge(moving, from: local, unmoved: &unmoved)
}
/// Unsent and failed messages live only in the mirror caches: they come along rather than go with `erase()`.
/// A rename in one folder: only a cache left at the account's name (it has no computers yet) is in the way.
/// Returns the caches that couldn't move: `erase` leaves them on disk rather than delete the only copy, though
/// nothing loads them again (Start over removes them).
- private func moveMirrorCaches(from local: Self) -> [URL] {
+ private func moveMirrorCaches(from local: Self, keeping own: Set<ComputerID> = []) -> [URL] {
var unmoved: [URL] = []
for file in Self.mirrorCaches(id: local.id) {
let name = file.lastPathComponent
- guard let marker = name.range(of: "-\(local.id)-") else { continue }
+ // A computer this account already has keeps this account's chat.
+ guard let marker = name.range(of: "-\(local.id)-"), !own.contains(where: { name.hasSuffix("-\($0).json") }) else { continue }
let moved = file.deletingLastPathComponent().appending(path: name.replacingCharacters(in: marker, with: "-\(id)-"))
do {
if FileManager.default.fileExists(atPath: moved.path()) { try FileManager.default.removeItem(at: moved) }
@@ -199,9 +200,11 @@ public extension SharedStore.Context {
return unmoved
}
- private func merge(_ moving: [Computer]) -> Adoption {
+ /// This context has its own key, so the computers ask to be paired again; their chats and waiting messages come along.
+ private func merge(_ moving: [Computer], from local: Self, unmoved: inout [URL]) -> Adoption {
let known = Set(computers.map(\.id))
computers += moving.filter { !known.contains($0.id) }
+ unmoved = moveMirrorCaches(from: local, keeping: known)
return Adoption(computers: moving.count, keys: .rescan)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
index 3d34e8b2..560f7a93 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift
@@ -63,6 +63,8 @@ public struct EntryData: Codable, Hashable, Sendable {
/// The voice call it was said in (user), answered during (agent), or that it ends (notice); the chat shows those
/// messages only in the call's conversation.
public var call: String?
+ /// What the user pasted rather than typed, which memory never takes as their own words: kept for a resend.
+ public var pasted: [String]?
/// user: `voice` when a call's voice model wrote it for the user (`send_to_bot`).
public var from: String?
/// notice: what was said on a realtime call, oldest first.
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
index 196d1b40..a44c74ab 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
@@ -262,8 +262,8 @@ public struct Hello: Codable, Sendable {
public var canUpdate: Bool?
/// The latest release the computer found; nil while unknown (development builds, older hosts).
public var latestVersion: String?
- /// This phone paired without the computer joining its account: it calls `joinAccount` to finish (older hosts: nil).
- public var joinAccount: Bool?
+ /// The computer could join an account: a signed-in phone may offer to add it (`HostClient.joinAccount`).
+ public var canJoinAccount: Bool?
}
public struct RecentWorkspace: Codable, Sendable, Identifiable {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift b/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift
index 95d80e3b..61e1c11f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift
@@ -64,7 +64,10 @@ public enum RelayCopy {
}
/// The pairing page's line. Parsing stays here so a view only renders the sentence.
- public static func pairing(pasted: String) -> String {
- pairing(cloud: Pairing(string: pasted)?.computer.cloud)
+ public static func pairing(pasted: String, signedIn: Bool) -> String {
+ let cloud = Pairing(string: pasted)?.computer.cloud
+ // Signed out, only a private relay: the Codync relay is for signed-in phones.
+ guard signedIn || host(of: cloud) != nil else { return "Connects on Wi-Fi or over Tailscale. End-to-end encrypted." }
+ return pairing(cloud: cloud)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
index b617cef1..5791b30f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
@@ -73,6 +73,8 @@ public struct RoutineWebhook: Codable, Sendable, Equatable {
public var localUrl: String
public var key: String
public var connected: Bool
+ /// In no account, so public deliveries can't reach it (older hosts: nil).
+ public var needsAccount: Bool?
}
extension HostClient {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/ScreenRoute.swift b/apps/ios/Kit/Sources/CodyncKit/Models/ScreenRoute.swift
new file mode 100644
index 00000000..23e398e3
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/ScreenRoute.swift
@@ -0,0 +1,15 @@
+/// Which way a remote screen attempt goes, by the computer's Connection choice: TURN is the screen's way through
+/// Cloudflare (docs/features/remote-screen.md). The other way gets the next attempt when one fails.
+public enum ScreenRoute {
+ /// Whether attempt number `failedAttempts` asks for TURN. `channelOnRelay`: chat itself reaches the computer
+ /// through a relay. `hasTurn`: the computer is in an account on the Codync cloud; a computer in no account and a
+ /// private relay have none.
+ public static func asksForTurn(channelOnRelay: Bool, route: ConnectionRoute, hasTurn: Bool, failedAttempts: Int) -> Bool {
+ let later = failedAttempts % 2 == 1
+ switch route {
+ case .directOnly: return false
+ case .cloudflareFirst: return hasTurn ? !later : channelOnRelay
+ case .automatic: return channelOnRelay || (hasTurn && later)
+ }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index cefe63ea..a2cfa80b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "Wenn der Computer fragt, prüfe, dass er {code} anzeigt.",
"Connect to the internet to pair, so Codync can confirm your account.": "Verbinde dich mit dem Internet, damit Codync beim Koppeln dein Konto bestätigen kann.",
"Let {name} in?": "{name} hereinlassen?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} möchte diesen Computer nutzen, der dann dem Konto von {email} beitritt. Prüfe, dass {name} {code} anzeigt.",
"Let in": "Hereinlassen",
"Don't allow": "Nicht erlauben",
"A Codync account": "Ein Codync-Konto",
"Every device of {email}'s account loses access.": "Alle Geräte des Kontos von {email} verlieren den Zugriff.",
"Every device of that account loses access.": "Alle Geräte dieses Kontos verlieren den Zugriff.",
"Access comes back only when you add {name} to the account again on {name} itself.": "Der Zugriff kommt erst zurück, wenn du {name} auf {name} selbst wieder zum Konto hinzufügst.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} möchte diesen Computer nutzen. Er tritt dem Konto von {email} bei. Prüfe, dass das Telefon {code} anzeigt.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "In keinem Konto: Ein angemeldetes Telefon, das dies scannt, bittet darum, den Computer in sein Konto aufzunehmen.",
"Pairing link or code": "Kopplungslink oder Code",
"Or type this code in the app's pairing screen: {code}": "Oder gib diesen Code auf dem Kopplungsbildschirm der App ein: {code}",
"That code isn't valid. Check it on the computer.": "Dieser Code ist ungültig. Prüfe ihn auf dem Computer.",
@@ -1507,13 +1504,8 @@
"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",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses iPhone bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses Telefon bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen.",
"Paste this code on the sign-in page that opens next.": "Füge diesen Code auf der Anmeldeseite ein, die sich als Nächstes öffnet.",
@@ -1844,5 +1836,48 @@
"Completions": "Vervollständigungen",
"Choose and arrange": "Auswählen und anordnen",
"Move {name}": "{name} verschieben",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ wählen · J K ordnen · space schalten · esc schließen"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ wählen · J K ordnen · space schalten · esc schließen",
+ "Continue without an account": "Ohne Konto fortfahren",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Nur im selben WLAN oder Tailscale wie dein Computer",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Verbindet sich über WLAN oder Tailscale. Ende-zu-Ende-verschlüsselt.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Prüfe auch, dass „Lokales Netzwerk“ für Codync in den iOS-Einstellungen aktiv ist und das WLAN kein Gastnetz ist.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Prüfe auch, dass das WLAN kein Gastnetz ist und keine Firewall auf dem Computer Codync blockiert.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "Dein Computer ist nicht erreichbar. Prüfe, ob du im selben Netzwerk bist oder Tailscale aktiv ist.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "Dieser Computer hat keine WLAN- oder Tailscale-Adresse. Verbinde ihn mit einem Netzwerk oder melde dich an, um über Cloudflare zu koppeln.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "Kurzcodes brauchen ein Konto. Scanne stattdessen den QR-Code des Computers oder melde dich an.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Erreiche diesen Computer von überall, nicht nur über WLAN oder Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Bestätige es auf dem Computer. Er zeigt {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Dieser Computer ist in keinem Konto, daher kann nur er an diese Adresse senden. Füge ihn deinem Konto hinzu, um eine öffentliche zu erhalten.",
+ "These phones lose access and must pair again: {names}.": "Diese Telefone verlieren den Zugriff und müssen neu gekoppelt werden: {names}.",
+ "Check {name} shows {code}.": "Prüfe, ob {name} {code} anzeigt.",
+ "It can connect only over Wi-Fi or Tailscale.": "Es kann sich nur über WLAN oder Tailscale verbinden.",
+ "Add this computer to {email}'s account?": "Diesen Computer zum Konto von {email} hinzufügen?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Ohne das kann sich dieses Telefon nur über WLAN oder Tailscale verbinden.",
+ "{name} wants to add it.": "{name} möchte ihn hinzufügen.",
+ "Wi-Fi or Tailscale only": "Nur WLAN oder Tailscale",
+ "Add this computer to your account?": "Diesen Computer zu deinem Konto hinzufügen?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Ohne das können sich Telefone nur über WLAN oder Tailscale verbinden.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "Telefone verbinden sich dann nur über WLAN oder Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "In keinem Konto: nur über WLAN und Tailscale erreichbar.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "In keinem Konto: Telefone verbinden sich nur über WLAN oder Tailscale, bis ein angemeldetes Telefon ihn seinem Konto hinzufügt.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} möchte diesen Computer nutzen. Zum Konto von {email} hinzufügen? Ohne das kann sich dieses Telefon nur über WLAN oder Tailscale verbinden. Prüfe, ob das Telefon {code} anzeigt.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} möchte diesen Computer zum Konto von {email} hinzufügen. Prüfe, ob das Telefon {code} anzeigt.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} möchte diesen Computer nutzen. Es kann sich nur über WLAN oder Tailscale verbinden. Prüfe, ob das Telefon {code} anzeigt.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Dieser Computer ist in einem Codync-Konto. Melde dich bei diesem Konto an, um dich zu verbinden.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Melde dich an, um über das Internet zu koppeln, oder verbinde dich mit demselben WLAN oder Tailscale wie der Computer.",
+ "The computer stayed out of this account.": "Der Computer ist diesem Konto nicht beigetreten.",
+ "This computer can't join an account now.": "Dieser Computer kann gerade keinem Konto beitreten.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Dein Computer bleibt gekoppelt. Meldest du dich mit einem Konto an, das schon auf diesem Telefon verwendet wurde, scanne seinen Code erneut. „Zum Konto hinzufügen“ bringt ihn in dein Konto.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "Deine {count} Computer bleiben gekoppelt. Meldest du dich mit einem Konto an, das schon auf diesem Telefon verwendet wurde, scanne ihre Codes erneut. „Zum Konto hinzufügen“ bringt jeden in dein Konto.",
+ "Couldn't confirm your Codync account. Sign in again.": "Dein Codync-Konto konnte nicht bestätigt werden. Melde dich erneut an.",
+ "This computer can't join that phone's account.": "Dieser Computer kann dem Konto dieses Telefons nicht beitreten.",
+ "This phone can only connect if the computer joins its account.": "Dieses Telefon kann sich nur verbinden, wenn der Computer seinem Konto beitritt.",
+ "Couldn't add this computer to your account. Scan the code again.": "Dieser Computer konnte nicht zu deinem Konto hinzugefügt werden. Scanne den Code erneut.",
+ "Copied a curl command (not in an account: this computer only)": "curl-Befehl kopiert (nicht in einem Konto: nur dieser Computer)",
+ "Add {name} to your account?": "{name} zu deinem Konto hinzufügen?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Prüfe, ob dieses iPhone und der Computer im selben WLAN oder beide mit Tailscale verbunden sind.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Prüfe, ob dieses Telefon und der Computer im selben WLAN oder beide mit Tailscale verbunden sind.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "Dieses Konto hat auf diesem iPhone bereits einen eigenen Schlüssel. Scanne den Code jedes Computers erneut, den du ohne Konto gekoppelt hast. Deine Nachrichten bleiben erhalten.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Dieses Konto hat auf diesem Telefon bereits einen eigenen Schlüssel. Scanne den Code jedes Computers erneut, den du ohne Konto gekoppelt hast. Deine Nachrichten bleiben erhalten.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} möchte diesen Computer verwenden, der dann dem Konto von {email} beitritt."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index b3161c55..1e8b50ed 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "Si el ordenador lo pregunta, comprueba que muestra {code}.",
"Connect to the internet to pair, so Codync can confirm your account.": "Conéctate a internet para vincular, así Codync puede confirmar tu cuenta.",
"Let {name} in?": "¿Dejar entrar a {name}?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} quiere usar esta computadora, que luego se une a la cuenta de {email}. Comprueba que {name} muestra {code}.",
"Let in": "Dejar entrar",
"Don't allow": "No permitir",
"A Codync account": "Una cuenta de Codync",
"Every device of {email}'s account loses access.": "Todos los dispositivos de la cuenta de {email} pierden el acceso.",
"Every device of that account loses access.": "Todos los dispositivos de esa cuenta pierden el acceso.",
"Access comes back only when you add {name} to the account again on {name} itself.": "El acceso solo vuelve cuando añades {name} a la cuenta de nuevo desde {name}.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} quiere usar esta computadora. Se une a la cuenta de {email}. Comprueba que el teléfono muestra {code}.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Sin cuenta: un teléfono con sesión iniciada que escanee esto pedirá añadir la computadora a su cuenta.",
"Pairing link or code": "Enlace o código",
"Or type this code in the app's pairing screen: {code}": "O escribe este código en la pantalla de emparejamiento de la app: {code}",
"That code isn't valid. Check it on the computer.": "Ese código no es válido. Revísalo en la computadora.",
@@ -1507,13 +1504,8 @@
"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",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este iPhone deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este teléfono deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes.",
"Paste this code on the sign-in page that opens next.": "Pega este código en la página de inicio de sesión que se abre a continuación.",
@@ -1844,5 +1836,48 @@
"Completions": "Autocompletados",
"Choose and arrange": "Elegir y ordenar",
"Move {name}": "Mover {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ elegir · J K ordenar · space alternar · esc cerrar"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ elegir · J K ordenar · space alternar · esc cerrar",
+ "Continue without an account": "Continuar sin cuenta",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Solo en la misma Wi-Fi o Tailscale que tu ordenador",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Se conecta por Wi-Fi o Tailscale. Cifrado de extremo a extremo.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Comprueba también que Red local esté activada para Codync en los ajustes de iOS y que la Wi-Fi no sea una red de invitados.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Comprueba también que la Wi-Fi no sea una red de invitados y que ningún cortafuegos del ordenador bloquee Codync.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "No se puede conectar con tu ordenador. Comprueba que estés en la misma red o que Tailscale esté activado.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "Este ordenador no tiene dirección de Wi-Fi ni de Tailscale. Conéctalo a una red o inicia sesión para emparejarlo por Cloudflare.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "Los códigos cortos necesitan una cuenta. Escanea el código QR del ordenador o inicia sesión.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Conéctate a este ordenador desde cualquier lugar, no solo por Wi-Fi o Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Confírmalo en el ordenador. Muestra {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Este ordenador no está en ninguna cuenta, así que solo él puede enviar a esta dirección. Añádelo a tu cuenta para tener una pública.",
+ "These phones lose access and must pair again: {names}.": "Estos teléfonos pierden el acceso y deben emparejarse de nuevo: {names}.",
+ "Check {name} shows {code}.": "Comprueba que {name} muestre {code}.",
+ "It can connect only over Wi-Fi or Tailscale.": "Solo podrá conectarse por Wi-Fi o Tailscale.",
+ "Add this computer to {email}'s account?": "¿Añadir este ordenador a la cuenta de {email}?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Si no, este teléfono solo podrá conectarse por Wi-Fi o Tailscale.",
+ "{name} wants to add it.": "{name} quiere añadirlo.",
+ "Wi-Fi or Tailscale only": "Solo Wi-Fi o Tailscale",
+ "Add this computer to your account?": "¿Añadir este ordenador a tu cuenta?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Si no, los teléfonos solo podrán conectarse por Wi-Fi o Tailscale.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "Los teléfonos solo se conectarán por Wi-Fi o Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "Sin cuenta: solo se llega por Wi-Fi y Tailscale.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "Sin cuenta: los teléfonos solo se conectan por Wi-Fi o Tailscale hasta que un teléfono con sesión iniciada lo añada a su cuenta.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} quiere usar este ordenador. ¿Añadirlo a la cuenta de {email}? Si no, este teléfono solo podrá conectarse por Wi-Fi o Tailscale. Comprueba que el teléfono muestre {code}.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} quiere añadir este ordenador a la cuenta de {email}. Comprueba que el teléfono muestre {code}.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} quiere usar este ordenador. Solo podrá conectarse por Wi-Fi o Tailscale. Comprueba que el teléfono muestre {code}.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Este ordenador está en una cuenta de Codync. Inicia sesión en esa cuenta para conectarte.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Inicia sesión para emparejar por Internet, o conéctate a la misma Wi-Fi o Tailscale que el ordenador.",
+ "The computer stayed out of this account.": "El ordenador no se ha unido a esta cuenta.",
+ "This computer can't join an account now.": "Este ordenador no puede unirse a una cuenta ahora.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Tu ordenador sigue emparejado. Si inicias sesión con una cuenta ya usada en este teléfono, vuelve a escanear su código. «Añadir a la cuenta» lo lleva a tu cuenta.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "Tus {count} ordenadores siguen emparejados. Si inicias sesión con una cuenta ya usada en este teléfono, vuelve a escanear sus códigos. «Añadir a la cuenta» lleva cada uno a tu cuenta.",
+ "Couldn't confirm your Codync account. Sign in again.": "No se pudo confirmar tu cuenta de Codync. Vuelve a iniciar sesión.",
+ "This computer can't join that phone's account.": "Este ordenador no puede unirse a la cuenta de ese teléfono.",
+ "This phone can only connect if the computer joins its account.": "Este teléfono solo puede conectarse si el ordenador se une a su cuenta.",
+ "Couldn't add this computer to your account. Scan the code again.": "No se pudo añadir este ordenador a tu cuenta. Vuelve a escanear el código.",
+ "Copied a curl command (not in an account: this computer only)": "Comando curl copiado (fuera de una cuenta: solo este ordenador)",
+ "Add {name} to your account?": "¿Añadir {name} a tu cuenta?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Comprueba que este iPhone y la computadora estén en la misma red Wi-Fi o ambos en Tailscale.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Comprueba que este teléfono y la computadora estén en la misma red Wi-Fi o ambos en Tailscale.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta cuenta ya tiene su propia clave en este iPhone. Vuelve a escanear el código de cada ordenador que emparejaste sin cuenta; tus mensajes se conservan.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta cuenta ya tiene su propia clave en este teléfono. Vuelve a escanear el código de cada ordenador que emparejaste sin cuenta; tus mensajes se conservan.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} quiere usar este ordenador, que luego se une a la cuenta de {email}."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 22c7386d..e2e6d9e4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "Si l'ordinateur le demande, vérifiez qu'il affiche {code}.",
"Connect to the internet to pair, so Codync can confirm your account.": "Connectez-vous à Internet pour appairer, afin que Codync confirme votre compte.",
"Let {name} in?": "Laisser entrer {name} ?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} veut utiliser cet ordinateur, qui rejoint alors le compte de {email}. Vérifiez que {name} affiche {code}.",
"Let in": "Laisser entrer",
"Don't allow": "Ne pas autoriser",
"A Codync account": "Un compte Codync",
"Every device of {email}'s account loses access.": "Tous les appareils du compte de {email} perdent l’accès.",
"Every device of that account loses access.": "Tous les appareils de ce compte perdent l’accès.",
"Access comes back only when you add {name} to the account again on {name} itself.": "L’accès ne revient que si vous ajoutez de nouveau {name} au compte depuis {name} lui-même.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} veut utiliser cet ordinateur. Il rejoint le compte de {email}. Vérifiez que le téléphone affiche {code}.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Dans aucun compte : un téléphone connecté qui scanne ceci demande à ajouter l’ordinateur à son compte.",
"Pairing link or code": "Lien ou code d'appairage",
"Or type this code in the app's pairing screen: {code}": "Ou saisissez ce code dans l'écran d'appairage de l'app : {code}",
"That code isn't valid. Check it on the computer.": "Ce code n'est pas valide. Vérifiez-le sur l'ordinateur.",
@@ -1507,13 +1504,8 @@
"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",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Cet iPhone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Ce téléphone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages.",
"Paste this code on the sign-in page that opens next.": "Collez ce code sur la page de connexion qui s’ouvre ensuite.",
@@ -1844,5 +1836,48 @@
"Completions": "Complétions",
"Choose and arrange": "Choisir et organiser",
"Move {name}": "Déplacer {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ choisir · J K organiser · space basculer · esc fermer"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ choisir · J K organiser · space basculer · esc fermer",
+ "Continue without an account": "Continuer sans compte",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Uniquement sur le même Wi-Fi ou Tailscale que votre ordinateur",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Connexion en Wi-Fi ou via Tailscale. Chiffré de bout en bout.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Vérifiez aussi que Réseau local est activé pour Codync dans les réglages iOS, et que le Wi-Fi n'est pas un réseau invité.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Vérifiez aussi que le Wi-Fi n'est pas un réseau invité et qu'aucun pare-feu de l'ordinateur ne bloque Codync.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "Impossible de joindre votre ordinateur. Vérifiez que vous êtes sur le même réseau ou que Tailscale est activé.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "Cet ordinateur n'a aucune adresse Wi-Fi ou Tailscale. Connectez-le à un réseau, ou connectez-vous pour le jumeler via Cloudflare.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "Les codes courts nécessitent un compte. Scannez plutôt le QR code de l'ordinateur, ou connectez-vous.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Joignez cet ordinateur de partout, pas seulement en Wi-Fi ou via Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Confirmez sur l'ordinateur. Il affiche {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Cet ordinateur n'est dans aucun compte : lui seul peut envoyer à cette adresse. Ajoutez-le à votre compte pour en obtenir une publique.",
+ "These phones lose access and must pair again: {names}.": "Ces téléphones perdent l'accès et devront être jumelés à nouveau : {names}.",
+ "Check {name} shows {code}.": "Vérifiez que {name} affiche {code}.",
+ "It can connect only over Wi-Fi or Tailscale.": "Il ne pourra se connecter qu'en Wi-Fi ou via Tailscale.",
+ "Add this computer to {email}'s account?": "Ajouter cet ordinateur au compte de {email} ?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Sinon, ce téléphone ne pourra se connecter qu'en Wi-Fi ou via Tailscale.",
+ "{name} wants to add it.": "{name} souhaite l'ajouter.",
+ "Wi-Fi or Tailscale only": "Wi-Fi ou Tailscale uniquement",
+ "Add this computer to your account?": "Ajouter cet ordinateur à votre compte ?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Sinon, les téléphones ne pourront se connecter qu'en Wi-Fi ou via Tailscale.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "Les téléphones se connecteront alors uniquement en Wi-Fi ou via Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "Dans aucun compte : joignable uniquement en Wi-Fi et via Tailscale.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "Dans aucun compte : les téléphones se connectent uniquement en Wi-Fi ou via Tailscale, jusqu'à ce qu'un téléphone connecté l'ajoute à son compte.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} souhaite utiliser cet ordinateur. L'ajouter au compte de {email} ? Sinon, ce téléphone ne pourra se connecter qu'en Wi-Fi ou via Tailscale. Vérifiez que le téléphone affiche {code}.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} souhaite ajouter cet ordinateur au compte de {email}. Vérifiez que le téléphone affiche {code}.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} souhaite utiliser cet ordinateur. Il ne pourra se connecter qu'en Wi-Fi ou via Tailscale. Vérifiez que le téléphone affiche {code}.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Cet ordinateur est dans un compte Codync. Connectez-vous à ce compte pour y accéder.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Connectez-vous pour jumeler via Internet, ou rejoignez le même Wi-Fi ou Tailscale que l'ordinateur.",
+ "The computer stayed out of this account.": "L'ordinateur n'a pas rejoint ce compte.",
+ "This computer can't join an account now.": "Cet ordinateur ne peut pas rejoindre de compte pour le moment.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Votre ordinateur reste jumelé. Si vous vous connectez avec un compte déjà utilisé sur ce téléphone, scannez à nouveau son code. « Ajouter au compte » l’amène dans votre compte.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "Vos {count} ordinateurs restent jumelés. Si vous vous connectez avec un compte déjà utilisé sur ce téléphone, scannez à nouveau leurs codes. « Ajouter au compte » amène chacun dans votre compte.",
+ "Couldn't confirm your Codync account. Sign in again.": "Impossible de confirmer votre compte Codync. Reconnectez-vous.",
+ "This computer can't join that phone's account.": "Cet ordinateur ne peut pas rejoindre le compte de ce téléphone.",
+ "This phone can only connect if the computer joins its account.": "Ce téléphone ne peut se connecter que si l’ordinateur rejoint son compte.",
+ "Couldn't add this computer to your account. Scan the code again.": "Impossible d’ajouter cet ordinateur à votre compte. Scannez à nouveau le code.",
+ "Copied a curl command (not in an account: this computer only)": "Commande curl copiée (hors d’un compte : cet ordinateur uniquement)",
+ "Add {name} to your account?": "Ajouter {name} à votre compte ?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Vérifiez que cet iPhone et l’ordinateur sont sur le même Wi-Fi ou tous deux sur Tailscale.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Vérifiez que ce téléphone et l’ordinateur sont sur le même Wi-Fi ou tous deux sur Tailscale.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "Ce compte a déjà sa propre clé sur cet iPhone. Scannez à nouveau le code de chaque ordinateur jumelé sans compte ; vos messages sont conservés.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Ce compte a déjà sa propre clé sur ce téléphone. Scannez à nouveau le code de chaque ordinateur jumelé sans compte ; vos messages sont conservés.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} veut utiliser cet ordinateur, qui rejoint alors le compte de {email}."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index 44bf9cea..52f5d05f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -768,7 +768,6 @@
"Normal": "Normale",
"Not complete": "Non completato",
"Not in a network.": "Non è in una rete.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Non è in un account: un telefono con accesso effettuato che scansiona questo codice chiede di portare il computer nel suo account.",
"Not in the network": "Non è nella rete",
"Not in your account": "Non è nel tuo account",
"Not installed": "Non installato",
@@ -1108,8 +1107,6 @@
"Sign in so bots can use it": "Accedi in modo che i bot possano usarlo",
"Sign in to ChatGPT by opening a verification page and entering a one-time code": "Accedi a ChatGPT aprendo una pagina di verifica e inserendo un codice monouso",
"Sign in to add it to your account": "Accedi per aggiungerlo al tuo account",
- "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "Accedi per continuare a usare il tuo computer. Si sposta nel tuo account, quindi non dovrai più scansionare.",
- "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "Accedi per continuare a usare i tuoi {count} computer. Si spostano nel tuo account, quindi non dovrai più scansionare.",
"Sign in to reach your computers from anywhere": "Accedi per raggiungere i tuoi computer da qualsiasi luogo",
"Sign in to see the computers in your account.": "Accedi per vedere i computer nel tuo account.",
"Sign in to see the other computers in your account.": "Accedi per vedere gli altri computer nel tuo account.",
@@ -1238,9 +1235,6 @@
"This computer is in {name}'s account": "Questo computer è nell'account di {name}",
"This computer is offline.": "Questo computer è offline.",
"This computer is the owner now. Remove the lost computer from the list; if it was stolen, also remove the computers it invited.": "Ora il proprietario è questo computer. Rimuovi dall'elenco il computer perso; se è stato rubato, rimuovi anche i computer che ha invitato.",
- "This computer isn't in an account: it uses a private relay": "Questo computer non è in un account: usa un relay privato",
- "This computer isn't in an account: its cloud is off": "Questo computer non è in un account: il suo cloud è disattivato",
- "This computer isn't in your account": "Questo computer non è nel tuo account",
"This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "Questo computer esce da {network}. Gli altri continuano a elencarlo finché il proprietario o un amministratore non lo rimuove da lì; per rientrare serve un nuovo invito.",
"This computer was removed": "Questo computer è stato rimosso",
"This connection request needs a newer app.": "Questa richiesta di connessione richiede un'app più recente.",
@@ -1484,7 +1478,6 @@
"{count} installed": "{count} installati",
"{count} viewers": "{count} spettatori",
"{done} of {total} ready": "{done} di {total} pronti",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} vuole usare questo computer, che entrerà quindi nell'account di {email}. Controlla che {name} mostri {code}.",
"{error} Draft kept; Enter retries, Ctrl+C clears text.": "{error} Bozza conservata; Invio riprova, Ctrl+C cancella il testo.",
"{name} (not installed)": "{name} (non installato)",
"{name} can be used by": "{name} può essere utilizzato da",
@@ -1496,7 +1489,6 @@
"{name} keeps notes apart from Codync's memory, and Codync can't turn them off for one bot.": "{name} conserva note separate dalla memoria di Codync, e Codync non può disattivarle per un singolo bot.",
"{name} keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see all of it here.": "{name} conserva note separate dalla memoria di Codync. È disattivata per impostazione predefinita, quindi questo bot ha una sola memoria e la vedi tutta qui.",
"{name} runs on Node.js. Codync adds its own copy.": "{name} funziona su Node.js. Codync aggiunge la propria copia.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} vuole usare questo computer. Entrerà nell'account di {email}. Controlla che il telefono mostri {code}.",
"{name}'s own memory": "La memoria propria di {name}",
"{name}, 1 bot": "{name}, 1 bot",
"{name}, 1 bot, {unread} unread": "{name}, 1 bot, {unread} non letti",
@@ -1844,5 +1836,48 @@
"Completions": "Completamenti",
"Choose and arrange": "Scegli e ordina",
"Move {name}": "Sposta {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ scegli · J K ordina · space attiva · esc chiudi"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ scegli · J K ordina · space attiva · esc chiudi",
+ "Continue without an account": "Continua senza account",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Solo sulla stessa Wi-Fi o Tailscale del computer",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Si connette tramite Wi-Fi o Tailscale. Crittografia end-to-end.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Controlla anche che Rete locale sia attiva per Codync nelle impostazioni di iOS e che la Wi-Fi non sia una rete ospiti.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Controlla anche che la Wi-Fi non sia una rete ospiti e che nessun firewall del computer blocchi Codync.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "Impossibile raggiungere il computer. Controlla di essere sulla stessa rete o che Tailscale sia attivo.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "Questo computer non ha un indirizzo Wi-Fi o Tailscale. Collegalo a una rete o accedi per associarlo tramite Cloudflare.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "I codici brevi richiedono un account. Scansiona il codice QR del computer oppure accedi.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Raggiungi questo computer ovunque, non solo tramite Wi-Fi o Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Conferma sul computer. Mostra {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Questo computer non è in un account, quindi solo lui può inviare a questo indirizzo. Aggiungilo al tuo account per averne uno pubblico.",
+ "These phones lose access and must pair again: {names}.": "Questi telefoni perdono l'accesso e devono essere associati di nuovo: {names}.",
+ "Check {name} shows {code}.": "Controlla che {name} mostri {code}.",
+ "It can connect only over Wi-Fi or Tailscale.": "Potrà connettersi solo tramite Wi-Fi o Tailscale.",
+ "Add this computer to {email}'s account?": "Aggiungere questo computer all'account di {email}?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Altrimenti questo telefono potrà connettersi solo tramite Wi-Fi o Tailscale.",
+ "{name} wants to add it.": "{name} vuole aggiungerlo.",
+ "Wi-Fi or Tailscale only": "Solo Wi-Fi o Tailscale",
+ "Add this computer to your account?": "Aggiungere questo computer al tuo account?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Altrimenti i telefoni potranno connettersi solo tramite Wi-Fi o Tailscale.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "I telefoni si connetteranno solo tramite Wi-Fi o Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "Non è in un account: raggiungibile solo tramite Wi-Fi e Tailscale.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "Non è in un account: i telefoni si connettono solo tramite Wi-Fi o Tailscale finché un telefono con accesso non lo aggiunge al suo account.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} vuole usare questo computer. Aggiungerlo all'account di {email}? Altrimenti questo telefono potrà connettersi solo tramite Wi-Fi o Tailscale. Controlla che il telefono mostri {code}.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} vuole aggiungere questo computer all'account di {email}. Controlla che il telefono mostri {code}.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} vuole usare questo computer. Potrà connettersi solo tramite Wi-Fi o Tailscale. Controlla che il telefono mostri {code}.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Questo computer è in un account Codync. Accedi a quell'account per connetterti.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Accedi per associare tramite Internet, oppure connettiti alla stessa Wi-Fi o Tailscale del computer.",
+ "The computer stayed out of this account.": "Il computer non è entrato in questo account.",
+ "This computer can't join an account now.": "Questo computer non può entrare in un account ora.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Il computer resta associato. Se accedi con un account già usato su questo telefono, scansiona di nuovo il suo codice. “Aggiungi all'account” lo porta nel tuo account.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "I tuoi {count} computer restano associati. Se accedi con un account già usato su questo telefono, scansiona di nuovo i loro codici. “Aggiungi all'account” porta ciascuno nel tuo account.",
+ "Couldn't confirm your Codync account. Sign in again.": "Impossibile confermare il tuo account Codync. Accedi di nuovo.",
+ "This computer can't join that phone's account.": "Questo computer non può entrare nell'account di quel telefono.",
+ "This phone can only connect if the computer joins its account.": "Questo telefono può connettersi solo se il computer entra nel suo account.",
+ "Couldn't add this computer to your account. Scan the code again.": "Impossibile aggiungere questo computer al tuo account. Scansiona di nuovo il codice.",
+ "Copied a curl command (not in an account: this computer only)": "Comando curl copiato (fuori da un account: solo questo computer)",
+ "Add {name} to your account?": "Aggiungere {name} al tuo account?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Controlla che questo iPhone e il computer siano sullo stesso Wi-Fi o entrambi su Tailscale.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Controlla che questo telefono e il computer siano sullo stesso Wi-Fi o entrambi su Tailscale.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "Questo account ha già una propria chiave su questo iPhone. Scansiona di nuovo il codice di ogni computer associato senza account; i tuoi messaggi restano.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Questo account ha già una propria chiave su questo telefono. Scansiona di nuovo il codice di ogni computer associato senza account; i tuoi messaggi restano.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} vuole usare questo computer, che poi entra nell'account di {email}."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index cac2fab8..defc056a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "コンピュータに確認を求められたら、{code} と表示されているか確かめてください。",
"Connect to the internet to pair, so Codync can confirm your account.": "ペアリングするにはインターネットに接続してください。Codync がアカウントを確認します。",
"Let {name} in?": "{name} を許可しますか?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} がこのコンピュータを使おうとしています。許可すると、このコンピュータは {email} のアカウントに加わります。{name} に {code} と表示されているか確かめてください。",
"Let in": "許可",
"Don't allow": "許可しない",
"A Codync account": "Codync アカウント",
"Every device of {email}'s account loses access.": "{email} のアカウントのすべてのデバイスがアクセスできなくなります。",
"Every device of that account loses access.": "そのアカウントのすべてのデバイスがアクセスできなくなります。",
"Access comes back only when you add {name} to the account again on {name} itself.": "{name} 自体で {name} を再びアカウントに追加したときだけ、アクセスが戻ります。",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} がこのコンピュータを使おうとしています。このコンピュータは {email} のアカウントに加わります。スマートフォンに {code} と表示されているか確かめてください。",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "アカウントに入っていません:サインイン済みのスマートフォンがこれをスキャンすると、このコンピュータをそのアカウントに加えるよう求めます。",
"Pairing link or code": "ペアリングリンクまたはコード",
"Or type this code in the app's pairing screen: {code}": "またはアプリのペアリング画面でこのコードを入力:{code}",
"That code isn't valid. Check it on the computer.": "このコードは無効です。コンピューターで確認してください。",
@@ -1507,13 +1504,8 @@
"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": "このコンピュータはあなたのアカウントにありません",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "この iPhone はアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "このスマートフォンはアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。",
"Paste this code on the sign-in page that opens next.": "このコードを、次に開くサインイン ページに貼り付けてください。",
@@ -1844,5 +1836,48 @@
"Completions": "補完",
"Choose and arrange": "選択と並べ替え",
"Move {name}": "{name} を移動",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選択 · J K 並べ替え · space 切替 · esc 閉じる"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選択 · J K 並べ替え · space 切替 · esc 閉じる",
+ "Continue without an account": "アカウントなしで続ける",
+ "Only on the same Wi-Fi or Tailscale as your computer": "コンピュータと同じ Wi-Fi または Tailscale でのみ",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Wi-Fi または Tailscale で接続します。エンドツーエンドで暗号化されます。",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "iOS の設定で Codync の「ローカルネットワーク」がオンになっていること、Wi-Fi がゲストネットワークでないことも確認してください。",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Wi-Fi がゲストネットワークでないこと、コンピュータのファイアウォールが Codync をブロックしていないことも確認してください。",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "コンピュータに接続できません。同じネットワークにいるか、Tailscale がオンになっているか確認してください。",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "このコンピュータには Wi-Fi または Tailscale のアドレスがありません。ネットワークに接続するか、サインインして Cloudflare 経由でペアリングしてください。",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "短いコードにはアカウントが必要です。代わりにコンピュータの QR コードをスキャンするか、サインインしてください。",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Wi-Fi や Tailscale だけでなく、どこからでもこのコンピュータに接続できます。",
+ "Confirm on the computer. It shows {code}.": "コンピュータで確認してください。{code} と表示されます。",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "このコンピュータはアカウントに入っていないため、このアドレスに送信できるのはコンピュータ自身だけです。アカウントに追加すると公開アドレスを使えます。",
+ "These phones lose access and must pair again: {names}.": "これらのスマートフォンはアクセスを失い、再度ペアリングが必要です:{names}。",
+ "Check {name} shows {code}.": "{name} に {code} と表示されていることを確認してください。",
+ "It can connect only over Wi-Fi or Tailscale.": "Wi-Fi または Tailscale でのみ接続できます。",
+ "Add this computer to {email}'s account?": "このコンピュータを {email} のアカウントに追加しますか?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "追加しない場合、このスマートフォンは Wi-Fi または Tailscale でのみ接続できます。",
+ "{name} wants to add it.": "{name} が追加しようとしています。",
+ "Wi-Fi or Tailscale only": "Wi-Fi または Tailscale のみ",
+ "Add this computer to your account?": "このコンピュータをアカウントに追加しますか?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "追加しない場合、スマートフォンは Wi-Fi または Tailscale でのみ接続できます。",
+ "Phones then connect only over Wi-Fi or Tailscale.": "その場合、スマートフォンは Wi-Fi または Tailscale でのみ接続します。",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "アカウントに入っていません:Wi-Fi と Tailscale からのみ接続できます。",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "アカウントに入っていません:サインイン済みのスマートフォンが追加するまで、スマートフォンは Wi-Fi または Tailscale でのみ接続します。",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} がこのコンピュータを使おうとしています。{email} のアカウントに追加しますか?追加しない場合、このスマートフォンは Wi-Fi または Tailscale でのみ接続できます。スマートフォンに {code} と表示されていることを確認してください。",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} がこのコンピュータを {email} のアカウントに追加しようとしています。スマートフォンに {code} と表示されていることを確認してください。",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} がこのコンピュータを使おうとしています。Wi-Fi または Tailscale でのみ接続できます。スマートフォンに {code} と表示されていることを確認してください。",
+ "This computer is in a Codync account. Sign in to that account to connect.": "このコンピュータは Codync アカウントに入っています。接続するにはそのアカウントにサインインしてください。",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "インターネット経由でペアリングするにはサインインするか、コンピュータと同じ Wi-Fi または Tailscale に接続してください。",
+ "The computer stayed out of this account.": "コンピュータはこのアカウントに追加されませんでした。",
+ "This computer can't join an account now.": "このコンピュータは現在アカウントに追加できません。",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "コンピュータはペアリングされたままです。この電話で使ったことのあるアカウントでサインインする場合は、コードをもう一度スキャンしてください。「アカウントに追加」でアカウントに追加できます。",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "{count} 台のコンピュータはペアリングされたままです。この電話で使ったことのあるアカウントでサインインする場合は、それぞれのコードをもう一度スキャンしてください。「アカウントに追加」でそれぞれアカウントに追加できます。",
+ "Couldn't confirm your Codync account. Sign in again.": "Codync アカウントを確認できませんでした。もう一度サインインしてください。",
+ "This computer can't join that phone's account.": "このコンピュータはその電話のアカウントに参加できません。",
+ "This phone can only connect if the computer joins its account.": "この電話は、コンピュータがそのアカウントに参加した場合にのみ接続できます。",
+ "Couldn't add this computer to your account. Scan the code again.": "このコンピュータをアカウントに追加できませんでした。コードをもう一度スキャンしてください。",
+ "Copied a curl command (not in an account: this computer only)": "curl コマンドをコピーしました (アカウント外: このコンピュータのみ)",
+ "Add {name} to your account?": "{name} をアカウントに追加しますか?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "この iPhone とコンピュータが同じ Wi-Fi 上にあるか、どちらも Tailscale に接続していることを確認してください。",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "この電話とコンピュータが同じ Wi-Fi 上にあるか、どちらも Tailscale に接続していることを確認してください。",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "このアカウントはこの iPhone に独自のキーを持っています。アカウントなしでペアリングした各コンピュータのコードをもう一度スキャンしてください。メッセージは保持されます。",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "このアカウントはこの電話に独自のキーを持っています。アカウントなしでペアリングした各コンピュータのコードをもう一度スキャンしてください。メッセージは保持されます。",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} がこのコンピュータを使おうとしています。このコンピュータは {email} のアカウントに参加します。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index aeabcd3e..58f51288 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "컴퓨터가 물으면 {code}가 표시되는지 확인하세요.",
"Connect to the internet to pair, so Codync can confirm your account.": "페어링하려면 인터넷에 연결하세요. Codync가 계정을 확인해야 합니다.",
"Let {name} in?": "{name}의 접속을 허용할까요?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email}에서 이 컴퓨터를 사용하려고 합니다. 허용하면 이 컴퓨터가 {email} 계정에 추가됩니다. {name}에 {code}가 표시되는지 확인하세요.",
"Let in": "허용",
"Don't allow": "허용 안 함",
"A Codync account": "Codync 계정",
"Every device of {email}'s account loses access.": "{email} 계정의 모든 기기가 접근 권한을 잃습니다.",
"Every device of that account loses access.": "그 계정의 모든 기기가 접근 권한을 잃습니다.",
"Access comes back only when you add {name} to the account again on {name} itself.": "{name}에서 직접 {name}을(를) 다시 계정에 추가해야만 접근 권한이 돌아옵니다.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name}에서 이 컴퓨터를 사용하려고 합니다. 이 컴퓨터는 {email} 계정에 추가됩니다. 휴대폰에 {code}가 표시되는지 확인하세요.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "계정에 속해 있지 않음: 로그인된 휴대폰이 이것을 스캔하면 이 컴퓨터를 그 계정에 추가하도록 요청합니다.",
"Pairing link or code": "페어링 링크 또는 코드",
"Or type this code in the app's pairing screen: {code}": "또는 앱의 페어링 화면에 이 코드를 입력하세요: {code}",
"That code isn't valid. Check it on the computer.": "유효하지 않은 코드입니다. 컴퓨터에서 확인하세요.",
@@ -1507,13 +1504,8 @@
"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": "이 컴퓨터는 내 계정에 없습니다",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 iPhone은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 휴대폰은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요.",
"Paste this code on the sign-in page that opens next.": "다음에 열리는 로그인 페이지에 이 코드를 붙여 넣으세요.",
@@ -1844,5 +1836,48 @@
"Completions": "자동 완성",
"Choose and arrange": "선택 및 정렬",
"Move {name}": "{name} 이동",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 선택 · J K 정렬 · space 전환 · esc 닫기"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 선택 · J K 정렬 · space 전환 · esc 닫기",
+ "Continue without an account": "계정 없이 계속",
+ "Only on the same Wi-Fi or Tailscale as your computer": "컴퓨터와 같은 Wi-Fi 또는 Tailscale에서만",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Wi-Fi 또는 Tailscale로 연결합니다. 종단간 암호화됩니다.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "iOS 설정에서 Codync의 로컬 네트워크가 켜져 있는지, Wi-Fi가 게스트 네트워크가 아닌지도 확인하세요.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Wi-Fi가 게스트 네트워크가 아닌지, 컴퓨터의 방화벽이 Codync를 차단하지 않는지도 확인하세요.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "컴퓨터에 연결할 수 없습니다. 같은 네트워크에 있는지, Tailscale이 켜져 있는지 확인하세요.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "이 컴퓨터에는 Wi-Fi 또는 Tailscale 주소가 없습니다. 네트워크에 연결하거나 로그인하여 Cloudflare로 페어링하세요.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "짧은 코드에는 계정이 필요합니다. 컴퓨터의 QR 코드를 스캔하거나 로그인하세요.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Wi-Fi나 Tailscale뿐 아니라 어디서나 이 컴퓨터에 연결할 수 있습니다.",
+ "Confirm on the computer. It shows {code}.": "컴퓨터에서 확인하세요. {code}이(가) 표시됩니다.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "이 컴퓨터는 계정에 없으므로 이 주소로는 컴퓨터 자신만 보낼 수 있습니다. 계정에 추가하면 공개 주소를 받습니다.",
+ "These phones lose access and must pair again: {names}.": "다음 휴대폰은 접근 권한을 잃으며 다시 페어링해야 합니다: {names}.",
+ "Check {name} shows {code}.": "{name}에 {code}이(가) 표시되는지 확인하세요.",
+ "It can connect only over Wi-Fi or Tailscale.": "Wi-Fi 또는 Tailscale로만 연결할 수 있습니다.",
+ "Add this computer to {email}'s account?": "이 컴퓨터를 {email} 계정에 추가할까요?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "추가하지 않으면 이 휴대폰은 Wi-Fi 또는 Tailscale로만 연결할 수 있습니다.",
+ "{name} wants to add it.": "{name}에서 추가하려고 합니다.",
+ "Wi-Fi or Tailscale only": "Wi-Fi 또는 Tailscale만",
+ "Add this computer to your account?": "이 컴퓨터를 계정에 추가할까요?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "추가하지 않으면 휴대폰은 Wi-Fi 또는 Tailscale로만 연결할 수 있습니다.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "이 경우 휴대폰은 Wi-Fi 또는 Tailscale로만 연결됩니다.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "계정에 없음: Wi-Fi와 Tailscale로만 연결할 수 있습니다.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "계정에 없음: 로그인한 휴대폰이 계정에 추가할 때까지 휴대폰은 Wi-Fi 또는 Tailscale로만 연결됩니다.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name}에서 이 컴퓨터를 사용하려고 합니다. {email} 계정에 추가할까요? 추가하지 않으면 이 휴대폰은 Wi-Fi 또는 Tailscale로만 연결할 수 있습니다. 휴대폰에 {code}이(가) 표시되는지 확인하세요.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name}에서 이 컴퓨터를 {email} 계정에 추가하려고 합니다. 휴대폰에 {code}이(가) 표시되는지 확인하세요.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name}에서 이 컴퓨터를 사용하려고 합니다. Wi-Fi 또는 Tailscale로만 연결할 수 있습니다. 휴대폰에 {code}이(가) 표시되는지 확인하세요.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "이 컴퓨터는 Codync 계정에 있습니다. 연결하려면 해당 계정으로 로그인하세요.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "인터넷으로 페어링하려면 로그인하거나, 컴퓨터와 같은 Wi-Fi 또는 Tailscale에 연결하세요.",
+ "The computer stayed out of this account.": "컴퓨터가 이 계정에 추가되지 않았습니다.",
+ "This computer can't join an account now.": "이 컴퓨터는 지금 계정에 추가할 수 없습니다.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "컴퓨터는 페어링된 상태로 유지됩니다. 이 휴대폰에서 사용한 적 있는 계정으로 로그인하면 코드를 다시 스캔하세요. '계정에 추가'로 계정에 추가할 수 있습니다.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "컴퓨터 {count}대는 페어링된 상태로 유지됩니다. 이 휴대폰에서 사용한 적 있는 계정으로 로그인하면 각 코드를 다시 스캔하세요. '계정에 추가'로 각각 계정에 추가할 수 있습니다.",
+ "Couldn't confirm your Codync account. Sign in again.": "Codync 계정을 확인할 수 없습니다. 다시 로그인하세요.",
+ "This computer can't join that phone's account.": "이 컴퓨터는 해당 휴대폰의 계정에 참여할 수 없습니다.",
+ "This phone can only connect if the computer joins its account.": "이 휴대폰은 컴퓨터가 해당 계정에 참여해야 연결할 수 있습니다.",
+ "Couldn't add this computer to your account. Scan the code again.": "이 컴퓨터를 계정에 추가하지 못했습니다. 코드를 다시 스캔하세요.",
+ "Copied a curl command (not in an account: this computer only)": "curl 명령을 복사했습니다(계정 밖: 이 컴퓨터만)",
+ "Add {name} to your account?": "{name}을(를) 계정에 추가할까요?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "이 iPhone과 컴퓨터가 같은 Wi-Fi에 있거나 둘 다 Tailscale에 연결되어 있는지 확인하세요.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "이 휴대폰과 컴퓨터가 같은 Wi-Fi에 있거나 둘 다 Tailscale에 연결되어 있는지 확인하세요.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "이 계정은 이 iPhone에 자체 키가 이미 있습니다. 계정 없이 페어링한 각 컴퓨터의 코드를 다시 스캔하세요. 메시지는 유지됩니다.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "이 계정은 이 휴대폰에 자체 키가 이미 있습니다. 계정 없이 페어링한 각 컴퓨터의 코드를 다시 스캔하세요. 메시지는 유지됩니다.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email}이(가) 이 컴퓨터를 사용하려고 합니다. 컴퓨터는 {email} 계정에 참여합니다."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
index c6e1346c..141d8bd1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "Se o computador pedir, confira se ele mostra {code}.",
"Connect to the internet to pair, so Codync can confirm your account.": "Conecte-se à internet para parear, para que o Codync possa confirmar sua conta.",
"Let {name} in?": "Permitir o acesso de {name}?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} quer usar este computador, que passará a fazer parte da conta de {email}. Confira se {name} mostra {code}.",
"Let in": "Permitir acesso",
"Don't allow": "Não permitir",
"A Codync account": "Uma conta do Codync",
"Every device of {email}'s account loses access.": "Todos os dispositivos da conta de {email} perdem o acesso.",
"Every device of that account loses access.": "Todos os dispositivos dessa conta perdem o acesso.",
"Access comes back only when you add {name} to the account again on {name} itself.": "O acesso só volta quando você adicionar {name} à conta novamente no próprio {name}.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} quer usar este computador. Ele passará a fazer parte da conta de {email}. Confira se o celular mostra {code}.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Fora de uma conta: um celular conectado a uma conta que escanear isto pedirá para adicionar o computador à conta dele.",
"Pairing link or code": "Link ou código de pareamento",
"Or type this code in the app's pairing screen: {code}": "Ou digite este código na tela de pareamento do aplicativo: {code}",
"That code isn't valid. Check it on the computer.": "Esse código não é válido. Confira no computador.",
@@ -1507,13 +1504,8 @@
"Delete your Codync account?": "Excluir sua conta do 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.": "Sua conta, a lista de computadores dela e o acesso de todos os dispositivos por ela serão excluídos. Seus computadores mantêm os bots e as conversas. Isso não pode ser desfeito.",
"Couldn't delete your account. Check your connection and try again.": "Não foi possível excluir sua conta. Verifique sua conexão e tente novamente.",
- "Sign in to keep using your computer. It moves into your account, so you won't need to scan again.": "Entre na sua conta para continuar usando seu computador. Ele passa a fazer parte da sua conta, então você não precisará escanear de novo.",
- "Sign in to keep using your {count} computers. They move into your account, so you won't need to scan again.": "Entre na sua conta para continuar usando seus {count} computadores. Eles passam a fazer parte da sua conta, então você não precisará escanear de novo.",
"This computer is in {name}'s account": "Este computador está na conta de {name}",
"This computer is in another account": "Este computador está em outra conta",
- "This computer isn't in an account: its cloud is off": "Este computador não está em uma conta: a nuvem dele está desativada",
- "This computer isn't in an account: it uses a private relay": "Este computador não está em uma conta: ele usa um relay privado",
- "This computer isn't in your account": "Este computador não está na sua conta",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este iPhone deixa de receber as notificações da conta e mantém seus computadores, então não será preciso escanear para entrar de novo. Para removê-lo dos computadores, use Recomeçar em Configurações.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este celular deixa de receber as notificações da conta e mantém seus computadores, então não será preciso escanear para entrar de novo. Para removê-lo dos computadores, use Recomeçar em Configurações.",
"Paste this code on the sign-in page that opens next.": "Cole este código na página de login que será aberta a seguir.",
@@ -1844,5 +1836,48 @@
"Completions": "Preenchimentos",
"Choose and arrange": "Escolher e organizar",
"Move {name}": "Mover {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ escolher · J K ordenar · space alternar · esc fechar"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ escolher · J K ordenar · space alternar · esc fechar",
+ "Continue without an account": "Continuar sem conta",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Só no mesmo Wi-Fi ou Tailscale do seu computador",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Conecta por Wi-Fi ou Tailscale. Criptografia de ponta a ponta.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Verifique também se Rede Local está ativada para o Codync nos Ajustes do iOS e se o Wi-Fi não é uma rede de convidados.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Verifique também se o Wi-Fi não é uma rede de convidados e se nenhum firewall do computador bloqueia o Codync.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "Não foi possível acessar seu computador. Verifique se você está na mesma rede ou se o Tailscale está ativado.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "Este computador não tem endereço de Wi-Fi nem de Tailscale. Conecte-o a uma rede ou entre na conta para parear pelo Cloudflare.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "Códigos curtos precisam de uma conta. Escaneie o QR code do computador ou entre na conta.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Acesse este computador de qualquer lugar, não só por Wi-Fi ou Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Confirme no computador. Ele mostra {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Este computador não está em nenhuma conta, então só ele pode enviar para este endereço. Adicione-o à sua conta para ter um público.",
+ "These phones lose access and must pair again: {names}.": "Estes celulares perdem o acesso e precisam parear de novo: {names}.",
+ "Check {name} shows {code}.": "Verifique se {name} mostra {code}.",
+ "It can connect only over Wi-Fi or Tailscale.": "Ele só poderá conectar por Wi-Fi ou Tailscale.",
+ "Add this computer to {email}'s account?": "Adicionar este computador à conta de {email}?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Sem isso, este celular só poderá conectar por Wi-Fi ou Tailscale.",
+ "{name} wants to add it.": "{name} quer adicioná-lo.",
+ "Wi-Fi or Tailscale only": "Só Wi-Fi ou Tailscale",
+ "Add this computer to your account?": "Adicionar este computador à sua conta?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Sem isso, os celulares só poderão conectar por Wi-Fi ou Tailscale.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "Os celulares só vão conectar por Wi-Fi ou Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "Fora de uma conta: só é acessível por Wi-Fi e Tailscale.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "Fora de uma conta: os celulares só conectam por Wi-Fi ou Tailscale até um celular conectado adicioná-lo à conta.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} quer usar este computador. Adicionar à conta de {email}? Sem isso, este celular só poderá conectar por Wi-Fi ou Tailscale. Verifique se o celular mostra {code}.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} quer adicionar este computador à conta de {email}. Verifique se o celular mostra {code}.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} quer usar este computador. Ele só poderá conectar por Wi-Fi ou Tailscale. Verifique se o celular mostra {code}.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Este computador está em uma conta do Codync. Entre nessa conta para conectar.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Entre na conta para parear pela internet ou conecte-se ao mesmo Wi-Fi ou Tailscale do computador.",
+ "The computer stayed out of this account.": "O computador não entrou nesta conta.",
+ "This computer can't join an account now.": "Este computador não pode entrar em uma conta agora.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Seu computador continua pareado. Se entrar com uma conta já usada neste celular, escaneie o código dele de novo. “Adicionar à conta” o leva para sua conta.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "Seus {count} computadores continuam pareados. Se entrar com uma conta já usada neste celular, escaneie os códigos deles de novo. “Adicionar à conta” leva cada um para sua conta.",
+ "Couldn't confirm your Codync account. Sign in again.": "Não foi possível confirmar sua conta Codync. Entre novamente.",
+ "This computer can't join that phone's account.": "Este computador não pode entrar na conta desse celular.",
+ "This phone can only connect if the computer joins its account.": "Este celular só pode se conectar se o computador entrar na conta dele.",
+ "Couldn't add this computer to your account. Scan the code again.": "Não foi possível adicionar este computador à sua conta. Escaneie o código de novo.",
+ "Copied a curl command (not in an account: this computer only)": "Comando curl copiado (fora de uma conta: só este computador)",
+ "Add {name} to your account?": "Adicionar {name} à sua conta?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Confira se este iPhone e o computador estão na mesma rede Wi-Fi ou ambos no Tailscale.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Confira se este celular e o computador estão na mesma rede Wi-Fi ou ambos no Tailscale.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta conta já tem a própria chave neste iPhone. Escaneie de novo o código de cada computador que você pareou sem conta; suas mensagens são mantidas.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "Esta conta já tem a própria chave neste celular. Escaneie de novo o código de cada computador que você pareou sem conta; suas mensagens são mantidas.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} quer usar este computador, que depois entra na conta de {email}."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index c26526de..cf3d5175 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "Если компьютер спросит, проверьте, что на нём код {code}.",
"Connect to the internet to pair, so Codync can confirm your account.": "Подключитесь к интернету, чтобы Codync подтвердил ваш аккаунт при подключении.",
"Let {name} in?": "Впустить {name}?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} хочет пользоваться этим компьютером, и он перейдёт в аккаунт {email}. Проверьте, что на {name} код {code}.",
"Let in": "Впустить",
"Don't allow": "Не разрешать",
"A Codync account": "Аккаунт Codync",
"Every device of {email}'s account loses access.": "Все устройства аккаунта {email} потеряют доступ.",
"Every device of that account loses access.": "Все устройства этого аккаунта потеряют доступ.",
"Access comes back only when you add {name} to the account again on {name} itself.": "Доступ вернётся, только если снова добавить {name} в аккаунт на самом {name}.",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} хочет пользоваться этим компьютером. Он перейдёт в аккаунт {email}. Проверьте, что на телефоне код {code}.",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "Не в аккаунте: телефон с выполненным входом, отсканировав код, предложит добавить компьютер в свой аккаунт.",
"Pairing link or code": "Ссылка или код подключения",
"Or type this code in the app's pairing screen: {code}": "Или введите этот код на экране подключения в приложении: {code}",
"That code isn't valid. Check it on the computer.": "Код неверный. Проверьте его на компьютере.",
@@ -1507,13 +1504,8 @@
"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": "Этот компьютер не в вашем аккаунте",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "iPhone перестанет получать уведомления аккаунта, но сохранит компьютеры, и при повторном входе сканировать код не придётся. Чтобы отключить его от компьютеров, используйте «Начать заново» в настройках.",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Телефон перестанет получать уведомления аккаунта, но сохранит компьютеры, и при повторном входе сканировать код не придётся. Чтобы отключить его от компьютеров, используйте «Начать заново» в настройках.",
"Paste this code on the sign-in page that opens next.": "Вставьте этот код на странице входа, которая откроется далее.",
@@ -1844,5 +1836,48 @@
"Completions": "Автодополнения",
"Choose and arrange": "Выбрать и упорядочить",
"Move {name}": "Переместить {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ выбор · J K порядок · space переключить · esc закрыть"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ выбор · J K порядок · space переключить · esc закрыть",
+ "Continue without an account": "Продолжить без аккаунта",
+ "Only on the same Wi-Fi or Tailscale as your computer": "Только в одной сети Wi-Fi или Tailscale с компьютером",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "Подключение по Wi-Fi или через Tailscale. Сквозное шифрование.",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "Также проверьте, что для Codync включена «Локальная сеть» в настройках iOS и что Wi-Fi не гостевая сеть.",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "Также проверьте, что Wi-Fi не гостевая сеть и что брандмауэр на компьютере не блокирует Codync.",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "Не удаётся подключиться к компьютеру. Проверьте, что вы в той же сети или что Tailscale включён.",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "У этого компьютера нет адреса Wi-Fi или Tailscale. Подключите его к сети или войдите, чтобы выполнить сопряжение через Cloudflare.",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "Для коротких кодов нужен аккаунт. Отсканируйте QR-код компьютера или войдите.",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "Подключайтесь к этому компьютеру откуда угодно, а не только по Wi-Fi или через Tailscale.",
+ "Confirm on the computer. It shows {code}.": "Подтвердите на компьютере. На нём показан код {code}.",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "Этот компьютер не в аккаунте, поэтому на этот адрес может отправлять только он сам. Добавьте его в аккаунт, чтобы получить публичный адрес.",
+ "These phones lose access and must pair again: {names}.": "Эти телефоны потеряют доступ, и их нужно будет сопрячь заново: {names}.",
+ "Check {name} shows {code}.": "Проверьте, что на {name} показан код {code}.",
+ "It can connect only over Wi-Fi or Tailscale.": "Подключиться можно будет только по Wi-Fi или через Tailscale.",
+ "Add this computer to {email}'s account?": "Добавить этот компьютер в аккаунт {email}?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "Без этого телефон сможет подключаться только по Wi-Fi или через Tailscale.",
+ "{name} wants to add it.": "{name} хочет его добавить.",
+ "Wi-Fi or Tailscale only": "Только Wi-Fi или Tailscale",
+ "Add this computer to your account?": "Добавить этот компьютер в ваш аккаунт?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "Без этого телефоны смогут подключаться только по Wi-Fi или через Tailscale.",
+ "Phones then connect only over Wi-Fi or Tailscale.": "Тогда телефоны будут подключаться только по Wi-Fi или через Tailscale.",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "Не в аккаунте: доступен только по Wi-Fi и через Tailscale.",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "Не в аккаунте: телефоны подключаются только по Wi-Fi или через Tailscale, пока телефон с выполненным входом не добавит его в свой аккаунт.",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} хочет использовать этот компьютер. Добавить его в аккаунт {email}? Без этого телефон сможет подключаться только по Wi-Fi или через Tailscale. Проверьте, что на телефоне показан код {code}.",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} хочет добавить этот компьютер в аккаунт {email}. Проверьте, что на телефоне показан код {code}.",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} хочет использовать этот компьютер. Подключиться можно будет только по Wi-Fi или через Tailscale. Проверьте, что на телефоне показан код {code}.",
+ "This computer is in a Codync account. Sign in to that account to connect.": "Этот компьютер находится в аккаунте Codync. Войдите в этот аккаунт, чтобы подключиться.",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "Войдите, чтобы выполнить сопряжение через интернет, или подключитесь к той же сети Wi-Fi или Tailscale, что и компьютер.",
+ "The computer stayed out of this account.": "Компьютер не был добавлен в этот аккаунт.",
+ "This computer can't join an account now.": "Этот компьютер сейчас нельзя добавить в аккаунт.",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "Компьютер останется сопряжённым. Если вы войдёте в аккаунт, который уже использовался на этом телефоне, отсканируйте его код снова. «Добавить в аккаунт» добавит его в ваш аккаунт.",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "Компьютеры останутся сопряжёнными (всего: {count}). Если вы войдёте в аккаунт, который уже использовался на этом телефоне, отсканируйте их коды снова. «Добавить в аккаунт» добавит каждый в ваш аккаунт.",
+ "Couldn't confirm your Codync account. Sign in again.": "Не удалось подтвердить ваш аккаунт Codync. Войдите снова.",
+ "This computer can't join that phone's account.": "Этот компьютер не может присоединиться к аккаунту этого телефона.",
+ "This phone can only connect if the computer joins its account.": "Этот телефон сможет подключиться, только если компьютер присоединится к его аккаунту.",
+ "Couldn't add this computer to your account. Scan the code again.": "Не удалось добавить этот компьютер в ваш аккаунт. Отсканируйте код снова.",
+ "Copied a curl command (not in an account: this computer only)": "Команда curl скопирована (вне аккаунта: только этот компьютер)",
+ "Add {name} to your account?": "Добавить {name} в ваш аккаунт?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "Проверьте, что этот iPhone и компьютер в одной сети Wi-Fi или оба подключены к Tailscale.",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "Проверьте, что этот телефон и компьютер в одной сети Wi-Fi или оба подключены к Tailscale.",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "У этого аккаунта уже есть свой ключ на этом iPhone. Снова отсканируйте код каждого компьютера, сопряжённого без аккаунта; ваши сообщения сохранятся.",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "У этого аккаунта уже есть свой ключ на этом телефоне. Снова отсканируйте код каждого компьютера, сопряжённого без аккаунта; ваши сообщения сохранятся.",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} хочет использовать этот компьютер, который затем присоединится к аккаунту {email}."
}
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 54cdda8a..3287178e 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "如果电脑问你,确认它显示 {code}。",
"Connect to the internet to pair, so Codync can confirm your account.": "请连上网络再配对,Codync 才能确认你的账户。",
"Let {name} in?": "要让 {name} 进入吗?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} 想使用这台电脑,之后这台电脑会加入 {email} 的账户。请确认 {name} 显示 {code}。",
"Let in": "允许进入",
"Don't allow": "不允许",
"A Codync account": "一个 Codync 账户",
"Every device of {email}'s account loses access.": "{email} 账户的所有设备都会失去访问。",
"Every device of that account loses access.": "该账户的所有设备都会失去访问。",
"Access comes back only when you add {name} to the account again on {name} itself.": "只有在 {name} 本机上将 {name} 重新加入账户,访问才会恢复。",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} 想使用这台电脑。这台电脑会加入 {email} 的账户。请确认手机显示 {code}。",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "不在任何账户中:已登录的手机扫描这个码时,会请求把这台电脑加入它的账户。",
"Pairing link or code": "配对链接或代码",
"Or type this code in the app's pairing screen: {code}": "或在 App 的配对页面输入这个代码:{code}",
"That code isn't valid. Check it on the computer.": "代码无效,请在电脑上核对。",
@@ -1507,13 +1504,8 @@
"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": "这台电脑不在你的账户里",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台 iPhone 不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台手机不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。",
"Paste this code on the sign-in page that opens next.": "把这组代码粘贴到接下来打开的登录页。",
@@ -1844,5 +1836,48 @@
"Completions": "补全",
"Choose and arrange": "选择与排序",
"Move {name}": "移动 {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 选择 · J K 排序 · space 切换 · esc 关闭"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 选择 · J K 排序 · space 切换 · esc 关闭",
+ "Continue without an account": "不登录继续",
+ "Only on the same Wi-Fi or Tailscale as your computer": "仅限与电脑在同一 Wi-Fi 或 Tailscale",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "通过 Wi-Fi 或 Tailscale 连接。端到端加密。",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "另请确认已在 iOS 设置中为 Codync 打开“本地网络”,且 Wi-Fi 不是访客网络。",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "另请确认 Wi-Fi 不是访客网络,且电脑上的防火墙没有阻挡 Codync。",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "无法连接到电脑。请确认在同一网络,或 Tailscale 已打开。",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "这台电脑没有 Wi-Fi 或 Tailscale 地址。请将它连接到网络,或登录后通过 Cloudflare 配对。",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "短代码需要账户。请改为扫描电脑上的二维码,或登录。",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "随时随地连接这台电脑,不只通过 Wi-Fi 或 Tailscale。",
+ "Confirm on the computer. It shows {code}.": "请在电脑上确认。电脑会显示 {code}。",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "这台电脑不在账户中,因此只有它能发送到此地址。将它加入账户即可获得公开地址。",
+ "These phones lose access and must pair again: {names}.": "这些手机将失去访问权限,必须重新配对:{names}。",
+ "Check {name} shows {code}.": "请确认 {name} 显示 {code}。",
+ "It can connect only over Wi-Fi or Tailscale.": "它只能通过 Wi-Fi 或 Tailscale 连接。",
+ "Add this computer to {email}'s account?": "将这台电脑加入 {email} 的账户?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "不加入的话,这部手机只能通过 Wi-Fi 或 Tailscale 连接。",
+ "{name} wants to add it.": "{name} 想要加入它。",
+ "Wi-Fi or Tailscale only": "仅 Wi-Fi 或 Tailscale",
+ "Add this computer to your account?": "将这台电脑加入你的账户?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "不加入的话,手机只能通过 Wi-Fi 或 Tailscale 连接。",
+ "Phones then connect only over Wi-Fi or Tailscale.": "这样手机只能通过 Wi-Fi 或 Tailscale 连接。",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "不在账户中:只能通过 Wi-Fi 和 Tailscale 连接。",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "不在账户中:手机只能通过 Wi-Fi 或 Tailscale 连接,直到已登录的手机将它加入账户。",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} 想使用这台电脑。要将它加入 {email} 的账户吗?不加入的话,这部手机只能通过 Wi-Fi 或 Tailscale 连接。请确认手机显示 {code}。",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} 想将这台电脑加入 {email} 的账户。请确认手机显示 {code}。",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} 想使用这台电脑。它只能通过 Wi-Fi 或 Tailscale 连接。请确认手机显示 {code}。",
+ "This computer is in a Codync account. Sign in to that account to connect.": "这台电脑在一个 Codync 账户中。请登录该账户以连接。",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "请登录以通过互联网配对,或连接到与电脑相同的 Wi-Fi 或 Tailscale。",
+ "The computer stayed out of this account.": "电脑没有加入这个账户。",
+ "This computer can't join an account now.": "这台电脑现在无法加入账户。",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "电脑仍保持配对。如果用这部手机用过的账户登录,请重新扫描它的二维码。「加入账户」可把它加入你的账户。",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "{count} 台电脑仍保持配对。如果用这部手机用过的账户登录,请重新扫描它们的二维码。「加入账户」可把每台加入你的账户。",
+ "Couldn't confirm your Codync account. Sign in again.": "无法确认你的 Codync 账户。请重新登录。",
+ "This computer can't join that phone's account.": "这台电脑无法加入那部手机的账户。",
+ "This phone can only connect if the computer joins its account.": "只有电脑加入这部手机的账户,手机才能连接。",
+ "Couldn't add this computer to your account. Scan the code again.": "无法将这台电脑加入你的账户。请重新扫描二维码。",
+ "Copied a curl command (not in an account: this computer only)": "已复制 curl 命令(不在账户中:仅限这台电脑)",
+ "Add {name} to your account?": "将 {name} 加入你的账户?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "确认这台 iPhone 和电脑在同一个 Wi-Fi,或都开了 Tailscale。",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "确认这台手机和电脑在同一个 Wi-Fi,或都开了 Tailscale。",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "这个账户在这台 iPhone 上已有自己的密钥。请重新扫描每台未登录时配对的电脑的二维码;消息会保留。",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "这个账户在这部手机上已有自己的密钥。请重新扫描每台未登录时配对的电脑的二维码;消息会保留。",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} 想使用这台电脑,电脑随后会加入 {email} 的账户。"
}
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 f0807412..658208e7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1484,15 +1484,12 @@
"If the computer asks, check it shows {code}.": "如果電腦問你,確認它顯示 {code}。",
"Connect to the internet to pair, so Codync can confirm your account.": "請連上網路再配對,Codync 才能確認你的賬戶。",
"Let {name} in?": "要讓 {name} 進入嗎?",
- "{email} wants to use this computer, which then joins {email}'s account. Check {name} shows {code}.": "{email} 想使用這臺電腦,之後這臺電腦會加入 {email} 的賬戶。請確認 {name} 顯示 {code}。",
"Let in": "允許進入",
"Don't allow": "不允許",
"A Codync account": "一個 Codync 賬戶",
"Every device of {email}'s account loses access.": "{email} 賬戶的所有裝置都會失去訪問。",
"Every device of that account loses access.": "該賬戶的所有裝置都會失去訪問。",
"Access comes back only when you add {name} to the account again on {name} itself.": "只有在 {name} 本機上將 {name} 重新加入賬戶,訪問才會恢復。",
- "{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}.": "{name} 想使用這臺電腦。這臺電腦會加入 {email} 的賬戶。請確認手機顯示 {code}。",
- "Not in an account: a signed-in phone that scans this asks to bring the computer into its account.": "不在任何賬戶中:已登入的手機掃描這個碼時,會請求把這臺電腦加入它的賬戶。",
"Pairing link or code": "配對連結或代碼",
"Or type this code in the app's pairing screen: {code}": "或在 App 的配對頁面輸入這個代碼:{code}",
"That code isn't valid. Check it on the computer.": "代碼無效,請到電腦上確認。",
@@ -1507,13 +1504,8 @@
"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": "這臺電腦不在你的賬戶裡",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這臺 iPhone 不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。",
"This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這支手機不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。",
"Paste this code on the sign-in page that opens next.": "把這組代碼貼到接下來開啟的登入頁。",
@@ -1844,5 +1836,48 @@
"Completions": "自動完成",
"Choose and arrange": "選擇與排序",
"Move {name}": "移動 {name}",
- "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選擇 · J K 排序 · space 切換 · esc 關閉"
+ "↑↓ select · J K arrange · space toggle · esc close": "↑↓ 選擇 · J K 排序 · space 切換 · esc 關閉",
+ "Continue without an account": "不登入繼續",
+ "Only on the same Wi-Fi or Tailscale as your computer": "僅限與電腦在同一 Wi-Fi 或 Tailscale",
+ "Connects on Wi-Fi or over Tailscale. End-to-end encrypted.": "透過 Wi-Fi 或 Tailscale 連線。端對端加密。",
+ "Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network.": "另請確認已在 iOS 設定中為 Codync 開啟「區域網路」,且 Wi-Fi 不是訪客網路。",
+ "Also check that the Wi-Fi isn't a guest network, and that no firewall on the computer blocks Codync.": "另請確認 Wi-Fi 不是訪客網路,且電腦上的防火牆沒有阻擋 Codync。",
+ "Can't reach your computer. Check you're on the same network or that Tailscale is on.": "無法連線到電腦。請確認在同一網路,或 Tailscale 已開啟。",
+ "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.": "這台電腦沒有 Wi-Fi 或 Tailscale 位址。請將它連上網路,或登入後透過 Cloudflare 配對。",
+ "Short codes need an account. Scan the computer's QR code instead, or sign in.": "短代碼需要賬戶。請改為掃描電腦上的 QR 碼,或登入。",
+ "Reach this computer from anywhere, not only over Wi-Fi or Tailscale.": "隨時隨地連線這台電腦,不只透過 Wi-Fi 或 Tailscale。",
+ "Confirm on the computer. It shows {code}.": "請在電腦上確認。電腦會顯示 {code}。",
+ "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one.": "這台電腦不在賬戶裡,因此只有它能傳送到此位址。將它加入賬戶即可取得公開位址。",
+ "These phones lose access and must pair again: {names}.": "這些手機將失去存取權,必須重新配對:{names}。",
+ "Check {name} shows {code}.": "請確認 {name} 顯示 {code}。",
+ "It can connect only over Wi-Fi or Tailscale.": "它只能透過 Wi-Fi 或 Tailscale 連線。",
+ "Add this computer to {email}'s account?": "要將這台電腦加入 {email} 的賬戶嗎?",
+ "Without it, this phone can connect only over Wi-Fi or Tailscale.": "不加入的話,這支手機只能透過 Wi-Fi 或 Tailscale 連線。",
+ "{name} wants to add it.": "{name} 想要加入它。",
+ "Wi-Fi or Tailscale only": "僅 Wi-Fi 或 Tailscale",
+ "Add this computer to your account?": "要將這台電腦加入你的賬戶嗎?",
+ "Without it, phones can connect only over Wi-Fi or Tailscale.": "不加入的話,手機只能透過 Wi-Fi 或 Tailscale 連線。",
+ "Phones then connect only over Wi-Fi or Tailscale.": "這樣手機只能透過 Wi-Fi 或 Tailscale 連線。",
+ "Not in an account: only Wi-Fi and Tailscale reach it.": "不在賬戶裡:只能透過 Wi-Fi 和 Tailscale 連線。",
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.": "不在賬戶裡:手機只能透過 Wi-Fi 或 Tailscale 連線,直到已登入的手機將它加入賬戶。",
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} 想使用這台電腦。要將它加入 {email} 的賬戶嗎?不加入的話,這支手機只能透過 Wi-Fi 或 Tailscale 連線。請確認手機顯示 {code}。",
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.": "{name} 想將這台電腦加入 {email} 的賬戶。請確認手機顯示 {code}。",
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.": "{name} 想使用這台電腦。它只能透過 Wi-Fi 或 Tailscale 連線。請確認手機顯示 {code}。",
+ "This computer is in a Codync account. Sign in to that account to connect.": "這台電腦在一個 Codync 賬戶裡。請登入該賬戶以連線。",
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.": "請登入以透過網際網路配對,或連上與電腦相同的 Wi-Fi 或 Tailscale。",
+ "The computer stayed out of this account.": "電腦沒有加入這個賬戶。",
+ "This computer can't join an account now.": "這台電腦現在無法加入賬戶。",
+ "Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.": "電腦仍保持配對。如果用這支手機用過的賬戶登入,請重新掃描它的 QR 碼。「加入賬戶」可把它加入你的賬戶。",
+ "Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.": "{count} 台電腦仍保持配對。如果用這支手機用過的賬戶登入,請重新掃描它們的 QR 碼。「加入賬戶」可把每台加入你的賬戶。",
+ "Couldn't confirm your Codync account. Sign in again.": "無法確認你的 Codync 賬戶。請重新登入。",
+ "This computer can't join that phone's account.": "這台電腦無法加入那支手機的賬戶。",
+ "This phone can only connect if the computer joins its account.": "只有電腦加入這支手機的賬戶,手機才能連線。",
+ "Couldn't add this computer to your account. Scan the code again.": "無法將這台電腦加入你的賬戶。請重新掃描 QR 碼。",
+ "Copied a curl command (not in an account: this computer only)": "已複製 curl 指令(不在賬戶中:僅限這台電腦)",
+ "Add {name} to your account?": "要將 {name} 加入你的賬戶嗎?",
+ "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale.": "確認這臺 iPhone 和電腦在同一個 Wi-Fi,或都開了 Tailscale。",
+ "Check that this phone and the computer are on the same Wi-Fi or both on Tailscale.": "確認這臺手機和電腦在同一個 Wi-Fi,或都開了 Tailscale。",
+ "This account already has its own key on this iPhone. Scan the code of each computer you paired without an account again; your messages are kept.": "這個賬戶在這臺 iPhone 上已有自己的金鑰。請重新掃描每台未登入時配對的電腦的 QR 碼;訊息會保留。",
+ "This account already has its own key on this phone. Scan the code of each computer you paired without an account again; your messages are kept.": "這個賬戶在這支手機上已有自己的金鑰。請重新掃描每台未登入時配對的電腦的 QR 碼;訊息會保留。",
+ "{email} wants to use this computer, which then joins {email}'s account.": "{email} 想使用這台電腦,電腦隨後會加入 {email} 的賬戶。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift
index 048c798a..4f632c41 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift
@@ -47,7 +47,9 @@ struct RoutineWebhookPanel: View {
private func note(_ webhook: RoutineWebhook) -> String {
guard webhook.url != nil else {
- return "The Codync cloud is off, so only this computer can send to it."
+ return webhook.needsAccount == true
+ ? "This computer isn't in an account, so only it can send to this address. Add it to your account for a public one."
+ : "The Codync cloud is off, so only this computer can send to it."
}
return "POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. "
+ "Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them."
diff --git a/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swift b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swift
index 5601ee1f..2bda1ece 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swift
@@ -65,13 +65,17 @@ public final class ScreenSession {
try await connect()
} catch {
guard phase == .connecting else { return }
- fail(error.localizedDescription)
+ guard await client.screenFallsBack() else { return fail(error.localizedDescription) }
+ // TURN may be what failed: the other way gets a try before this gives up.
+ lastError = error.localizedDescription
+ phase = .reconnecting
+ scheduleRecovery(after: .zero)
}
}
private func connect() async throws {
let preparing = generation
- let connection = try await client.screenPrepare()
+ let connection = try await client.screenPrepare(failedAttempts: recoveryAttempts)
guard generation == preparing, phase != .closed, !Task.isCancelled else {
try? await client.screenClose(session: connection.session)
throw CancellationError()
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore+Pairing.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore+Pairing.swift
new file mode 100644
index 00000000..925d07a2
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore+Pairing.swift
@@ -0,0 +1,117 @@
+import CodyncKit
+import Foundation
+import os
+
+private let log = Logger(subsystem: "com.pokai.Codync", category: "Account")
+
+/// Pairing with a computer, and bringing one into this account (docs/plans/optional-sign-in.md).
+extension AccountStore {
+ /// QR pairing (§4.1). Signed in, with this account's certificate: a computer in another account turns the phone
+ /// away, one in none asks its user, who may have it join this account. Signed out: only a computer in no account
+ /// lets it in, and not over the Codync relay. The computer is saved in this context and connected.
+ public func pair(_ pairing: Pairing, deviceName: String, platform: String) async throws -> Computer {
+ let identity = try DeviceIdentity.load(context: storage)
+ let pairing = cloud == nil ? pairing.withoutRelay : pairing
+ guard !pairing.computer.urls.isEmpty || pairing.computer.cloud != nil else { throw Self.noDirectAddress }
+ var certificate: DeviceCertificate?
+ var claim: CloudClaim?
+ if let cloud {
+ certificate = try await pairingCertificate(cloud, deviceName: deviceName, platform: platform)
+ // Without a claim the computer still pairs and stays out of the account; the phone can add it later.
+ do { claim = try await cloud.createClaim() } catch {
+ log.info("pairing without a claim: \(error.localizedDescription, privacy: .public)")
+ }
+ }
+ pairingCheck = pairing.checkCode(for: identity)
+ defer { pairingCheck = nil }
+ let paired = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform,
+ certificate: certificate, claim: claim)
+ guard !retired else { throw CancellationError() }
+ var computer = paired.computer
+ if let previous = saved.first(where: { $0.id == computer.id }) { computer.keepDevicePicks(from: previous) }
+ save(computer)
+ open(computer)
+ if let claim, let signed = paired.claim {
+ Task {
+ do { try await joinAccount(computer.id) { _ in (claim, signed) } } catch {
+ log.error("paired computer didn't join the account: \(error.localizedDescription, privacy: .public)")
+ }
+ }
+ }
+ return computer
+ }
+
+ public static let noCertificate = CloudError(status: 0, code: "noCertificate",
+ message: "Connect to the internet to pair, so Codync can confirm your account.")
+ public static let noDirectAddress = CloudError(status: 0, code: "noDirectAddress",
+ message: "This computer shows no Wi-Fi or Tailscale address. Connect it to a network, or sign in to pair through Cloudflare.")
+ public static let signInForShortCode = CloudError(status: 0, code: "signInForShortCode",
+ message: "Short codes need an account. Scan the computer's QR code instead, or sign in.")
+
+ /// This device's certificate: the one held while more than a day is left, else a new one, registering
+ /// the device again if the cloud doesn't know it. Offline, one that is still valid will do.
+ func pairingCertificate(_ cloud: CloudClient, deviceName: String, platform: String) async throws -> DeviceCertificate {
+ if let certificate, certificate.isFresh() { return certificate }
+ do {
+ let fresh: DeviceCertificate
+ do {
+ fresh = try await cloud.deviceCertificate()
+ } catch let error as CloudError where error.status == 403 {
+ try await cloud.registerDevice(name: deviceName, platform: platform)
+ fresh = try await cloud.deviceCertificate()
+ }
+ certificate = fresh
+ return fresh
+ } catch let error as CloudError where !error.isTransient {
+ throw error
+ } catch {
+ if let certificate, certificate.isValid() { return certificate }
+ log.info("no device certificate: \(error.localizedDescription, privacy: .public)")
+ throw Self.noCertificate
+ }
+ }
+
+ /// Whether this phone can offer to add a computer it reaches to its account: it's signed in, and the computer is
+ /// in no account yet.
+ public func canAddToAccount(_ store: BotStore) -> Bool {
+ cloud != nil && store.connection == .online && store.hello?.canJoinAccount == true
+ }
+
+ /// The 6 digits the computer shows while it's asked to join this account; nil when it isn't being asked.
+ public func addToAccountCheck(_ id: ComputerID) -> String? { addingToAccount[id] }
+
+ /// Add to account: the computer asks its user, then signs the claim. Without it, the computer stays reachable
+ /// only directly.
+ public func addToAccount(_ id: ComputerID, deviceName: String, platform: String) {
+ guard let store = stores[id], let client = store.client, addingToAccount[id] == nil, !joining.contains(id),
+ let identity = try? DeviceIdentity.load(context: storage) else { return }
+ Analytics.shared.capture(.addToAccountAsked)
+ addingToAccount[id] = store.computer.checkCode(for: identity)
+ Task {
+ defer { addingToAccount[id] = nil }
+ do {
+ try await joinAccount(id) { cloud in
+ let certificate = try await self.pairingCertificate(cloud, deviceName: deviceName, platform: platform)
+ let claim = try await cloud.createClaim()
+ return (claim, try await client.joinAccount(claim, certificate: certificate))
+ }
+ Analytics.shared.capture(.addToAccountCompleted)
+ } catch {
+ log.error("computer didn't join the account: \(error.localizedDescription, privacy: .public)")
+ Analytics.shared.capture(.addToAccountFailed(.init(error)))
+ if !retired { lastError = error.localizedDescription }
+ }
+ }
+ }
+
+ /// The computer signs this account's claim (`sign`: while letting this phone in, or later when asked to from
+ /// here), and the phone, which holds the account's session, completes it. One at a time per computer.
+ private func joinAccount(_ id: ComputerID, sign: @MainActor (CloudClient) async throws -> (CloudClaim, Data)) async throws {
+ guard let cloud, !retired, joining.insert(id).inserted else { return }
+ defer { joining.remove(id) }
+ let (claim, signed) = try await sign(cloud)
+ try await cloud.completeClaim(claimId: claim.claimId, claim: signed)
+ guard !retired else { return }
+ await refreshCloud()
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
index 7c453e30..636d490a 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -39,7 +39,7 @@ public final class AccountStore {
public private(set) var approvedAccess: [ComputerID: String] = [:]
public var lastError: String?
/// While pairing: the code the computer shows if it asks whether to let this phone in.
- public private(set) var pairingCheck: String?
+ public internal(set) var pairingCheck: String?
public var selection: BotReference? {
didSet {
guard !retired else { return }
@@ -56,22 +56,24 @@ public final class AccountStore {
/// The combined roster changed: a bot came, changed or went, or a computer did.
public var onRosterChanged: (@MainActor ([RosterItem]) -> Void)?
- private let cloud: CloudClient?
+ let cloud: CloudClient?
private let computerOrder: ComputerOrderStore
private let makeStore: @MainActor (Computer) -> BotStore
/// Persisted in the context (channel route).
- private var saved: [Computer]
+ var saved: [Computer]
private var accessPolls: [ComputerID: Task<Void, Never>] = [:]
/// A list that comes back after a newer request was started is out of date.
private var cloudListVersion = 0
/// Access requests still waiting for their code, joined by a second ask.
private var asks: [ComputerID: Task<AccessTicket, any Error>] = [:]
/// The account's word for this device's key, kept in memory for this context.
- private var certificate: DeviceCertificate?
+ var certificate: DeviceCertificate?
/// Computers joining this account (`joinAccount`).
- private var joining: Set<ComputerID> = []
+ var joining: Set<ComputerID> = []
+ /// Computers asked from here to join this account, with the code they show meanwhile.
+ var addingToAccount: [ComputerID: String] = [:]
private var isActive = true
- private var retired = false
+ private(set) var retired = false
public convenience init(storage: SharedStore.Context, cloud: CloudClient?) {
self.init(storage: storage, cloud: cloud) { computer in
@@ -108,78 +110,6 @@ public final class AccountStore {
// MARK: computers
- /// QR pairing (§4.1) with this account's certificate: a computer in another account turns the phone away,
- /// one in none asks its user, then joins this account. The computer is saved in this context and connected.
- public func pair(_ pairing: Pairing, deviceName: String, platform: String) async throws -> Computer {
- let identity = try DeviceIdentity.load(context: storage)
- guard let cloud else { throw Self.noCertificate }
- let certificate = try await pairingCertificate(cloud, deviceName: deviceName, platform: platform)
- // Without a claim the computer still pairs; it joins the account on a later connection (`Hello.joinAccount`).
- let claim: CloudClaim?
- do { claim = try await cloud.createClaim() } catch {
- log.info("pairing without a claim: \(error.localizedDescription, privacy: .public)")
- claim = nil
- }
- pairingCheck = pairing.checkCode(for: identity)
- defer { pairingCheck = nil }
- let paired = try await HostConnector.pair(pairing, identity: identity, deviceName: deviceName, platform: platform,
- certificate: certificate, claim: claim)
- guard !retired else { throw CancellationError() }
- var computer = paired.computer
- if let previous = saved.first(where: { $0.id == computer.id }) { computer.keepDevicePicks(from: previous) }
- save(computer)
- open(computer)
- if let claim, let signed = paired.claim {
- joinAccount(computer.id) { _ in (claim, signed) }
- }
- return computer
- }
-
- public static let noCertificate = CloudError(status: 0, code: "noCertificate",
- message: "Connect to the internet to pair, so Codync can confirm your account.")
-
- /// This device's certificate: the one held while more than a day is left, else a new one, registering
- /// the device again if the cloud doesn't know it. Offline, one that is still valid will do.
- func pairingCertificate(_ cloud: CloudClient, deviceName: String, platform: String) async throws -> DeviceCertificate {
- if let certificate, certificate.isFresh() { return certificate }
- do {
- let fresh: DeviceCertificate
- do {
- fresh = try await cloud.deviceCertificate()
- } catch let error as CloudError where error.status == 403 {
- try await cloud.registerDevice(name: deviceName, platform: platform)
- fresh = try await cloud.deviceCertificate()
- }
- certificate = fresh
- return fresh
- } catch let error as CloudError where !error.isTransient {
- throw error
- } catch {
- if let certificate, certificate.isValid() { return certificate }
- log.info("no device certificate: \(error.localizedDescription, privacy: .public)")
- throw Self.noCertificate
- }
- }
-
- /// The computer signs this account's claim (`sign`: while letting this phone in, or later through
- /// `joinAccount` when its `hello` asks), and the phone, which holds the account's session, completes it.
- /// One at a time per computer; the computer decides whether a join that failed here is asked for again.
- private func joinAccount(_ id: ComputerID, sign: @escaping @MainActor (CloudClient) async throws -> (CloudClaim, Data)) {
- guard let cloud, !retired, joining.insert(id).inserted else { return }
- Task {
- defer { joining.remove(id) }
- do {
- let (claim, signed) = try await sign(cloud)
- try await cloud.completeClaim(claimId: claim.claimId, claim: signed)
- } catch {
- log.error("paired computer didn't join the account: \(error.localizedDescription, privacy: .public)")
- return
- }
- guard !retired else { return }
- await refreshCloud()
- }
- }
-
public func forget(_ id: ComputerID) {
saved.removeAll { $0.id == id }
persist()
@@ -233,6 +163,7 @@ public final class AccountStore {
let list = try await cloud.computers()
guard !retired, version == cloudListVersion else { return }
if list != cloudComputers { Motion.animate { cloudComputers = list } }
+ learnRelay(from: list, cloud: cloud)
} catch let error as CloudError where !error.isTransient {
lastError = error.localizedDescription
} catch {
@@ -242,6 +173,17 @@ public final class AccountStore {
}
}
+ /// A computer that joined this account while this phone couldn't hear its `hello` still has the relay, or a phone
+ /// away from its network could never reach it to find out. Listed online, it's on the relay; a phone connected to it
+ /// goes by its `hello`.
+ private func learnRelay(from list: [CloudComputer], cloud: CloudClient) {
+ for computer in saved where computer.cloud == nil && stores[computer.id]?.connection != .online
+ && list.contains(where: { $0.computerId == computer.id && $0.isOnline }) {
+ updateSaved(computer.id) { $0.cloud = cloud.baseURL }
+ stores[computer.id]?.restartStream()
+ }
+ }
+
/// Asks the computer for access; the code arrives in `pendingAccess`, where it must match the one
/// the computer shows. The request runs here, not in the caller: it outlives a closed sheet, so the
/// computer never waits on a request nobody reveals, and asking again while it runs joins it
@@ -428,7 +370,7 @@ public final class AccountStore {
// MARK: plumbing
- private func open(_ computer: Computer) {
+ func open(_ computer: Computer) {
close(computer.id)
let store = makeStore(computer)
let id = computer.id
@@ -446,12 +388,6 @@ public final class AccountStore {
}
store.onComputerChanged = { [weak self] computer in self?.computerChanged(computer) }
store.onRosterChanged = { [weak self] in self?.rosterChanged() }
- store.onJoinAccount = { [weak self] client in
- self?.joinAccount(id) { cloud in
- let claim = try await cloud.createClaim()
- return (claim, try await client.joinAccount(claim))
- }
- }
stores[id] = store
if isActive { store.setActive(true) }
}
@@ -469,7 +405,7 @@ public final class AccountStore {
refreshList()
}
- private func save(_ computer: Computer) {
+ func save(_ computer: Computer) {
saved.removeAll { $0.id == computer.id }
saved.insert(computer, at: 0)
persist()
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
index 2632957a..79f29ce7 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift
@@ -21,7 +21,6 @@ extension BotStore {
onSent = nil
onRosterChanged = nil
onComputerChanged = nil
- onJoinAccount = nil
client = nil
selection = nil
screenRequest = nil
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
index efc81c4d..764f0cb5 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift
@@ -75,6 +75,7 @@ extension BotStore {
lastSentNonce = nonce
var data = EntryData(text: trimmed, status: "sending", clientNonce: nonce)
data.call = call
+ data.pasted = pasted.isEmpty ? nil : pasted
// Shown at once; the computer's own quote replaces it.
data.replyTo = replyTo
if !files.isEmpty {
@@ -124,8 +125,10 @@ extension BotStore {
return .delivered
} catch {
if outgoingFiles[nonce] != nil { lastError = "Couldn't send the files: \(error.localizedDescription)" }
- markLocal(nonce: nonce, botId: botId, status: "failed")
- return .failed
+ // With no relay holding it, a message waits here until the computer can be reached (`sendHeld`).
+ let holds = computer.cloud == nil && (error as? HostError)?.isTransient == true
+ markLocal(nonce: nonce, botId: botId, status: holds ? "waiting" : "failed")
+ return holds ? .queued : .failed
}
}
}
@@ -185,6 +188,13 @@ extension BotStore {
/// Takes a waiting message back out of the mailbox, unless the computer already has it.
public func cancelQueued(_ entry: Entry) {
+ if computer.cloud == nil {
+ // No relay holds it: it only waits on this phone.
+ discard(entry)
+ if let bot = bots[entry.botId] { onSent?(bot, .cancelled) }
+ saveCache()
+ return
+ }
guard let nonce = entry.data.clientNonce, let remote = transport as? any RemoteTransport else { return }
Task {
switch await remote.cancelQueued(clientNonce: nonce) {
@@ -216,6 +226,7 @@ extension BotStore {
func reconcileQueued(_ remote: any RemoteTransport) async {
let waiting = entries.values.flatMap { $0 }.filter { $0.data.status == "waiting" }
guard !waiting.isEmpty else { return }
+ guard computer.cloud != nil else { return sendHeld(waiting) }
let heldItems: [QueuedItem]
do {
heldItems = try await remote.listQueued()
@@ -236,6 +247,20 @@ extension BotStore {
saveCache()
}
+ /// The computer is back, and it has no relay: what waited on this phone goes now, with the same nonces. Files are
+ /// kept only in memory: a message whose files went with the app stays for the user to resend, not half sent.
+ private func sendHeld(_ waiting: [Entry]) {
+ for entry in waiting.sorted(by: { $0.createdAt < $1.createdAt }) {
+ let filesGone = entry.data.attachments?.isEmpty == false && entry.data.clientNonce.flatMap { outgoingFiles[$0] } == nil
+ if filesGone, let nonce = entry.data.clientNonce {
+ markLocal(nonce: nonce, botId: entry.botId, status: "failed")
+ } else {
+ retry(entry)
+ }
+ }
+ saveCache()
+ }
+
public func retry(_ entry: Entry) {
let files = entry.data.clientNonce.flatMap { outgoingFiles[$0] } ?? []
guard let text = entry.data.text, !text.isEmpty || !files.isEmpty else { return }
@@ -243,7 +268,7 @@ extension BotStore {
// The same clientNonce: if the computer got it after all, it won't run twice (the host
// skips a nonce it has). Every seal still takes a fresh ephemeral key (§6.4).
send(text, to: entry.botId, replyTo: entry.data.replyTo, nonce: entry.data.clientNonce ?? UUID().uuidString,
- files: files)
+ files: files, pasted: entry.data.pasted ?? [], call: entry.data.call)
}
/// A sent file's bytes: on disk after the first fetch (sent files never change).
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
index c0cd50d9..262c89cb 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
@@ -66,7 +66,6 @@ extension BotStore {
hello = h
applyIcons(h.icons ?? [:], revision: h.iconsRevision ?? 0)
noteHostVersion(HostVersion(version: h.version, minApp: h.minApp))
- if h.joinAccount == true { onJoinAccount?(client) }
}
private func noteHostVersion(_ new: HostVersion) {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
index a55fb834..14d0e50e 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift
@@ -106,8 +106,6 @@ public final class BotStore {
var onRosterChanged: (@MainActor () -> Void)?
/// The computer's addresses or keys changed (merged from its `hello`); persist it.
var onComputerChanged: (@MainActor (Computer) -> Void)?
- /// Its `hello` says this phone paired without the computer joining the account (`Hello.joinAccount`).
- var onJoinAccount: (@MainActor (HostClient) -> Void)?
public let storage: SharedStore.Context
/// Opens a channel to the computer as it is now: its route, and the addresses and keys merged since.
@@ -190,6 +188,15 @@ public final class BotStore {
if case .computerOffline = heldDrop ?? connection { computer.boxKey != nil && transport is any RemoteTransport } else { false }
}
+ /// Can't reach a computer with no relay: text waits on this phone until it can (`sendHeld`).
+ public var holdsOnPhone: Bool {
+ guard computer.cloud == nil else { return false }
+ switch connection {
+ case .connecting, .offline: return true
+ default: return false
+ }
+ }
+
/// What headers show: a reconnect the grace period keeps quiet reads "Connecting…"
/// as soon as an action is waiting on it.
public var shownConnection: Connection { waiting > 0 && connection == .online ? .connecting : connection }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
index b7985ced..c93b43af 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
@@ -46,8 +46,8 @@ struct Composer: View {
private var isEmpty: Bool { draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && files.isEmpty }
private var canSend: Bool {
- // Offline computers still take messages when the relay can hold them for it (text only).
- !isEmpty && (model.connection == .online || (model.canQueue && files.isEmpty))
+ // Offline computers still take text: the relay holds it for them, or with no relay this phone does.
+ !isEmpty && (model.connection == .online || ((model.canQueue || model.holdsOnPhone) && files.isEmpty))
}
private var canAttach: Bool { bot != nil }
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
index 11c102b2..ce9db5dc 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AnalyticsTests.swift
@@ -66,6 +66,7 @@ import Testing
#expect(try json(.settingChanged(.liveActivities, on: true)) == #"{"on":true,"setting":"live_activities"}"#)
// Multi-word values are snake_case, as in the catalog.
#expect(try json(.signInFailed(.google, reason: .cancelled)) == #"{"provider":"google","reason":"cancelled"}"#)
+ #expect(try json(.addToAccountFailed(.declined)) == #"{"reason":"declined"}"#)
#expect(try json(.screenViewed(.botDetails)) == #"{"screen":"bot_details"}"#)
#expect(try json(.voiceCallStarted(.onDevice)) == #"{"engine":"on_device"}"#)
#expect(try json(.voiceCallQuality(.gemini, readyMs: 1200, reconnects: 1, stuck: .none, failure: .connection))
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
index a38faadd..eaa80d55 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swift
@@ -138,6 +138,21 @@ private func waitFor(_ states: AsyncStream<LinkState>, _ match: (LinkState) -> B
return nil
}
+@Test(.timeLimit(.minutes(1))) func withNoRelayAnAddressFoundOnTheNetworkIsDialed() async throws {
+ let (dial, sockets) = fakeDialer()
+ var computer = v.computer
+ computer.cloud = nil
+ computer.urls = []
+ let t = ChannelTransport(computer: computer, identity: v.identity, pairingCode: nil, dial: dial, watchesNetwork: false,
+ discovered: { _ in ["http://192.168.1.9:19222"] })
+ await t.start()
+ var socketIterator = sockets.makeAsyncIterator()
+ let socket = try #require(await socketIterator.next())
+ guard case let .direct(url) = socket.endpoint else { Issue.record("not direct"); return }
+ #expect(url.absoluteString == "ws://192.168.1.9:19222/channel?v=1")
+ await t.shutdown()
+}
+
@Test(.timeLimit(.minutes(1))) func directChannelMultiplexesCallsAndStreams() async throws {
let (dial, sockets) = fakeDialer()
var computer = v.computer
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift
index 2c910c8b..a1dd5fbb 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift
@@ -37,7 +37,9 @@ struct RelayCopyTests {
URLQueryItem(name: "code", value: v.str("pairing", "code")),
URLQueryItem(name: "cloud", value: "https://relay.example.com"),
]
- #expect(RelayCopy.pairing(pasted: comps.string!).contains("Private relay (relay.example.com)"))
- #expect(RelayCopy.pairing(pasted: "not a link").contains("through Cloudflare"))
+ #expect(RelayCopy.pairing(pasted: comps.string!, signedIn: true).contains("Private relay (relay.example.com)"))
+ #expect(RelayCopy.pairing(pasted: "not a link", signedIn: true).contains("through Cloudflare"))
+ #expect(RelayCopy.pairing(pasted: comps.string!, signedIn: false).contains("Private relay (relay.example.com)"), "a private relay is the user's own")
+ #expect(!RelayCopy.pairing(pasted: "not a link", signedIn: false).contains("from anywhere"), "signed out, there's no Codync relay")
}
}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ScreenRouteTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ScreenRouteTests.swift
new file mode 100644
index 00000000..53b97701
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/ScreenRouteTests.swift
@@ -0,0 +1,73 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+struct ScreenRouteTests {
+ private func turn(onRelay: Bool = false, _ route: ConnectionRoute, hasTurn: Bool = true, failed: Int = 0) -> Bool {
+ ScreenRoute.asksForTurn(channelOnRelay: onRelay, route: route, hasTurn: hasTurn, failedAttempts: failed)
+ }
+
+ @Test func autoGoesDirectThenThroughTurn() {
+ #expect(!turn(.automatic))
+ #expect(turn(.automatic, failed: 1))
+ #expect(!turn(.automatic, failed: 2))
+ #expect(turn(onRelay: true, .automatic), "chat came through the relay: there's no direct way to start with")
+ #expect(turn(onRelay: true, .automatic, failed: 1))
+ }
+
+ @Test func cloudflareFirstGoesThroughTurnThenDirect() {
+ #expect(turn(.cloudflareFirst))
+ #expect(!turn(.cloudflareFirst, failed: 1))
+ #expect(turn(onRelay: true, .cloudflareFirst))
+ }
+
+ @Test func directOnlyNeverAsks() {
+ for failed in 0...2 { #expect(!turn(.directOnly, failed: failed)) }
+ }
+
+ @Test func aComputerInNoAccountHasNoTurn() {
+ for route in ConnectionRoute.allCases {
+ for failed in 0...2 { #expect(!turn(route, hasTurn: false, failed: failed)) }
+ }
+ }
+
+ @Test func aPrivateRelayStillSaysItHasNoScreen() {
+ // Chat over a private relay asks, and the host explains that it has no TURN.
+ #expect(turn(onRelay: true, .automatic, hasTurn: false))
+ }
+}
+
+struct LocalDiscoveryTests {
+ @Test func keepsOnlyValidAddresses() throws {
+ let entry = try #require(LocalDiscovery.entry(id: "c1", urls: "http://192.168.1.5:19222,not a url,http://10.0.0.2:19222"))
+ #expect(entry.id == "c1")
+ #expect(entry.urls == ["http://192.168.1.5:19222", "http://10.0.0.2:19222"])
+ #expect(LocalDiscovery.entry(id: nil, urls: "http://192.168.1.5:19222") == nil)
+ #expect(LocalDiscovery.entry(id: "c1", urls: nil) == nil)
+ #expect(LocalDiscovery.entry(id: "c1", urls: "nope") == nil)
+ }
+}
+
+struct SignedOutPairingTests {
+ private func pairing(cloud: String?) -> Pairing {
+ let computer = Computer(id: "c", name: "Mac", signKey: "k", urls: ["http://192.168.1.5:19222"], cloud: cloud.flatMap(URL.init(string:)))
+ return Pairing(computer: computer, code: "code")
+ }
+
+ @Test func aSignedOutPhoneLeavesOutOnlyTheCodyncRelay() {
+ #expect(pairing(cloud: "https://api.codync.dev").withoutRelay.computer.cloud == nil)
+ let own = pairing(cloud: "https://relay.example.com").withoutRelay.computer
+ #expect(own.cloud?.host() == "relay.example.com", "a private relay is the user's own")
+ #expect(own.urls == ["http://192.168.1.5:19222"])
+ }
+
+ @Test func aFailedAddToAccountSaysWhy() {
+ typealias Failure = AnalyticsEvent.AddToAccountFailure
+ #expect(Failure(HostError.http(500, "The computer stayed out of this account.")) == .declined)
+ #expect(Failure(HostError.http(500, "Couldn't confirm your Codync account. Sign in again.")) == .certificate)
+ #expect(Failure(CloudError(status: 0, code: "noCertificate", message: nil)) == .certificate)
+ #expect(Failure(HostError.unreachable) == .unreachable)
+ #expect(Failure(URLError(.notConnectedToInternet)) == .unreachable)
+ #expect(Failure(CancellationError()) == .other)
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
index a9f639e7..03022577 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/SignedOutAdoptionTests.swift
@@ -56,6 +56,28 @@ import Testing
#expect(local.computers.isEmpty && !DeviceIdentity.exists(context: local))
}
+ @Test func aUsedAccountContextTakesTheChatsOfTheComputersItGains() throws {
+ let (local, account, suite) = contexts()
+ defer { account.erase(); UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ _ = try DeviceIdentity.load(context: account)
+ account.computers = [v.computer]
+ _ = try DeviceIdentity.load(context: local)
+ var other = v.computer
+ other.id = "other"
+ local.computers = [v.computer, other]
+ func cache(_ context: SharedStore.Context, _ id: String) -> URL {
+ URL.cachesDirectory.appending(path: "codync-mirror-tests-\(context.id)-\(id).json")
+ }
+ try Data("waiting".utf8).write(to: cache(local, "other"))
+ try Data("signed out".utf8).write(to: cache(local, v.computer.id))
+ try Data("account".utf8).write(to: cache(account, v.computer.id))
+
+ #expect(account.adopt(from: local)?.keys == .rescan)
+ #expect(try Data(contentsOf: cache(account, "other")) == Data("waiting".utf8), "waiting messages aren't lost")
+ #expect(try Data(contentsOf: cache(account, v.computer.id)) == Data("account".utf8), "a computer it has keeps its chat")
+ #expect(!FileManager.default.fileExists(atPath: cache(local, "other").path()))
+ }
+
@Test func nothingToMove() {
let (local, account, suite) = contexts()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
diff --git a/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
index 5f495349..88261330 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/AccessRenewalTests.swift
@@ -65,7 +65,8 @@ struct AccessRenewalTests {
session: URLSession(configuration: config)) { "token" }
let storage = SharedStore.Context(accountID: "account", suite: suite)
let id = RelayCrypto.computerId(signKey: renewalHostKey)
- var computer = Computer(id: id, name: "Desk", signKey: renewalHostKey.base64URL, urls: ["http://192.168.1.20:19223"])
+ var computer = Computer(id: id, name: "Desk", signKey: renewalHostKey.base64URL, urls: ["http://192.168.1.20:19223"],
+ cloud: URL(string: "https://cloud.test"))
computer.color = "blue"
computer.route = .directOnly
computer.notifications = false
diff --git a/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
index a3c7eaaa..5e97ef95 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/JoinAccountTests.swift
@@ -4,29 +4,14 @@ import Testing
@testable import CodyncKit
@testable import CodyncUI
-private let askingHello = #"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0,"joinAccount":true}"#
-
-/// A computer whose `hello` says this phone paired without it joining the account asks the account to finish the
-/// join; one that doesn't say so (or an older host) doesn't.
-@MainActor @Test(arguments: [false, true]) func helloAsksToFinishJoiningTheAccount(asks: Bool) async throws {
- let suite = "JoinAccountTests.\(UUID().uuidString)"
- defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
- let remote = FakeRemote(.ready(.direct))
- if asks { await remote.setHello(askingHello) }
- let computer = Computer(id: UUID().uuidString, name: "Mac", signKey: "unused", boxKey: "unused")
- let store = BotStore(computer: computer, storage: SharedStore.Context(accountID: "account", suite: suite)) { _ in remote }
- defer { store.retire() }
- var asked = 0
- store.onJoinAccount = { _ in asked += 1 }
- store.setActive(true)
- #expect(await until { store.hello != nil })
- #expect(asked == (asks ? 1 : 0))
-}
+private let joinableHello = #"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0,"canJoinAccount":true}"#
/// Answers the claim calls (counting them) and every other request as an empty account.
private final class ClaimCloudStub: URLProtocol {
static let created = OSAllocatedUnfairLock(initialState: 0)
static let completed = OSAllocatedUnfairLock(initialState: 0)
+ /// The computer the account lists.
+ static let listed = OSAllocatedUnfairLock<Computer?>(initialState: nil)
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
@@ -42,7 +27,11 @@ private final class ClaimCloudStub: URLProtocol {
case "/v1/claims/clm_1/complete":
Self.completed.withLock { $0 += 1 }
json = "{}"
- case "/v1/computers": json = #"{"computers":[]}"#
+ case "/v1/computers":
+ json = Self.listed.withLock { $0 }.map {
+ #"{"computers":[{"computerId":"\#($0.id)","name":"Mac","signKey":"\#($0.signKey)","online":true}]}"#
+ } ?? #"{"computers":[]}"#
+ case "/v1/devices/certificate": json = #"{"certificate":{"payload":"{\"exp\":99999999999999}","sig":"s"}}"#
default: json = "{}"
}
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
@@ -52,24 +41,112 @@ private final class ClaimCloudStub: URLProtocol {
}
}
-/// The account finishes the join its `hello` asks for: a claim, the computer's signature, then the completion.
-@MainActor @Test func theAccountFinishesTheJoinTheComputerAsksFor() async throws {
- let suite = "JoinAccountTests.\(UUID().uuidString)"
- defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+@MainActor private func accounts(suite: String, computerCloud: URL? = URL(string: "https://cloud.example.dev"), listed: Bool = false,
+ link: LinkState = .ready(.direct)) async -> (AccountStore, FakeRemote) {
+ Keychain.memory.withLock { $0 = $0 ?? [:] }
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [ClaimCloudStub.self]
let cloud = CloudClient(baseURL: URL(string: "https://cloud.test")!, identity: DeviceIdentity(signing: .init(), push: .init()),
session: URLSession(configuration: config)) { "token" }
let storage = SharedStore.Context(accountID: "account", suite: suite)
- storage.computers = [randomComputer("Mac")]
- let remote = FakeRemote(.ready(.direct))
- await remote.setHello(askingHello)
+ var paired = randomComputer("Mac")
+ paired.cloud = computerCloud
+ storage.computers = [paired]
+ let computer = paired
+ ClaimCloudStub.listed.withLock { $0 = listed ? computer : nil }
+ let remote = FakeRemote(link)
+ await remote.setHello(joinableHello)
let accounts = AccountStore(storage: storage, cloud: cloud) { computer in
BotStore(computer: computer, storage: storage) { _ in remote }
}
- defer { accounts.retire() }
+ return (accounts, remote)
+}
+
+@MainActor private func online(_ remote: FakeRemote) async {
+ #expect(await until { await remote.subscribed })
+ await remote.emit(botEvent("b1", name: "Bot", rev: 1))
+}
+
+@Suite(.serialized) @MainActor struct JoinAccountTests {
+ /// A computer in no account stays out of one until someone asks: the phone only offers.
+ @Test func aComputerThatCouldJoinIsOnlyOffered() async throws {
+ let suite = "JoinAccountTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let created = ClaimCloudStub.created.withLock { $0 }
+ let (accounts, remote) = await accounts(suite: suite)
+ defer { accounts.retire() }
+ let store = try #require(accounts.computers.first.flatMap { accounts.store(for: $0.id) })
+ await online(remote)
+ #expect(await until { accounts.canAddToAccount(store) })
+ #expect(ClaimCloudStub.created.withLock { $0 } == created)
+ #expect(await remote.calls.filter { $0 == "joinAccount" }.isEmpty)
+ }
+
+ /// Asked to: a claim, the computer's signature (it asks its user), then the completion.
+ @Test func addToAccountAsksTheComputerThenCompletesTheClaim() async throws {
+ let suite = "JoinAccountTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let completed = ClaimCloudStub.completed.withLock { $0 }
+ let (accounts, remote) = await accounts(suite: suite)
+ defer { accounts.retire() }
+ let store = try #require(accounts.computers.first.flatMap { accounts.store(for: $0.id) })
+ await online(remote)
+ #expect(await until { accounts.canAddToAccount(store) })
+ accounts.addToAccount(store.computer.id, deviceName: "iPhone", platform: "ios")
+ #expect(await until { ClaimCloudStub.completed.withLock { $0 } == completed + 1 })
+ #expect(await remote.calls.filter { $0 == "joinAccount" }.count == 1)
+ #expect(await until { accounts.addToAccountCheck(store.computer.id) == nil }, "the code goes once it's answered")
+ }
- #expect(await until { ClaimCloudStub.completed.withLock { $0 } == 1 })
- #expect(ClaimCloudStub.created.withLock { $0 } == 1)
- #expect(await remote.calls.filter { $0 == "joinAccount" }.count == 1)
+ /// It joined while this phone was away: the account's list brings the relay its `hello` couldn't.
+ @Test func aComputerListedInTheAccountGetsTheRelay() async throws {
+ let suite = "JoinAccountTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let (accounts, _) = await accounts(suite: suite, computerCloud: nil, listed: true, link: .failed("Can't reach it."))
+ defer { accounts.retire() }
+ let store = try #require(accounts.computers.first.flatMap { accounts.store(for: $0.id) })
+ #expect(store.computer.cloud == nil)
+ await accounts.refreshCloud()
+ #expect(store.computer.cloud?.host() == "cloud.test")
+ #expect(accounts.storage.computers.first?.cloud?.host() == "cloud.test", "and it stays")
+ }
+
+ /// Signed out, the Codync relay isn't a way in: with no other address there's nothing to dial.
+ @Test func signedOutAComputerReachableOnlyThroughTheCodyncRelayCantPair() async throws {
+ let suite = "JoinAccountTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ Keychain.memory.withLock { $0 = $0 ?? [:] }
+ let storage = SharedStore.Context(accountID: nil, suite: suite)
+ defer { storage.erase() }
+ let accounts = AccountStore(storage: storage, cloud: nil) { computer in
+ BotStore(computer: computer, storage: storage) { _ in FakeRemote(.connecting) }
+ }
+ defer { accounts.retire() }
+ var computer = randomComputer("Mac")
+ computer.urls = []
+ computer.cloud = URL(string: "https://api.codync.dev")
+ do {
+ _ = try await accounts.pair(Pairing(computer: computer, code: "CAgICAgICAgICAgICAgICA"), deviceName: "iPhone", platform: "ios")
+ Issue.record("it paired")
+ } catch let error as CloudError {
+ #expect(error.code == AccountStore.noDirectAddress.code)
+ }
+ }
+
+ /// With no account there's nothing to add it to.
+ @Test func signedOutThereIsNothingToOffer() async throws {
+ let suite = "JoinAccountTests.\(UUID().uuidString)"
+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
+ let storage = SharedStore.Context(accountID: nil, suite: suite)
+ storage.computers = [randomComputer("Mac")]
+ let remote = FakeRemote(.ready(.direct))
+ await remote.setHello(joinableHello)
+ let accounts = AccountStore(storage: storage, cloud: nil) { computer in
+ BotStore(computer: computer, storage: storage) { _ in remote }
+ }
+ defer { accounts.retire() }
+ let store = try #require(accounts.computers.first.flatMap { accounts.store(for: $0.id) })
+ #expect(await until { store.hello != nil })
+ #expect(!accounts.canAddToAccount(store))
+ }
}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
index 1315e1ec..6dd3e3b8 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift
@@ -102,6 +102,104 @@ import Testing
#expect(await fake.sent.isEmpty)
}
+/// A computer in no account has no relay: the phone holds the message, and sends it when the computer is back.
+/// Each try at reaching it makes a new link; the computer's back on the latest (`back`).
+@MainActor private final class NoRelay {
+ let (storage, suite) = context()
+ private(set) var links: [FakeRemote] = []
+ private var state = LinkState.failed("Can't reach your computer.")
+ private(set) lazy var store: BotStore = {
+ var computer = randomComputer("Mac")
+ computer.cloud = nil
+ return BotStore(computer: computer, storage: storage) { [unowned self] _ in
+ let link = FakeRemote(state)
+ links.append(link)
+ return link
+ }
+ }()
+
+ func start() async {
+ store.setActive(true)
+ #expect(await until { store.isOffline })
+ }
+
+ func back() async {
+ state = .ready(.direct)
+ guard let link = links.last else { return }
+ await link.set(state)
+ #expect(await until { await link.subscribed })
+ await link.emit(botEvent("b1", name: "Bot", rev: 1))
+ }
+
+ func sent() async -> [String] {
+ var all: [String] = []
+ for link in links { all += await link.sent }
+ return all
+ }
+
+ func end() {
+ store.retire()
+ UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
+ }
+}
+
+@MainActor @Test func withNoRelayAMessageWaitsOnThePhoneAndGoesWithTheSameNonce() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ #expect(store.holdsOnPhone && !store.canQueue)
+
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "waiting" })
+ let nonce = try #require(store.chat("b1").first?.data.clientNonce)
+ let enqueued = await phone.links.last?.enqueued
+ #expect(enqueued?.isEmpty == true, "there's no relay to hold it")
+
+ await phone.back()
+ #expect(await until { await phone.sent() == ["hi"] })
+ #expect(store.chat("b1").first?.data.clientNonce == nonce)
+ #expect(!store.holdsOnPhone)
+}
+
+@MainActor @Test func withNoRelayCancellingAWaitingMessageStaysOnThePhone() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1")
+ #expect(await until { store.chat("b1").first?.data.status == "waiting" })
+ store.cancelQueued(try #require(store.chat("b1").first))
+ #expect(store.chat("b1").isEmpty)
+ await phone.back()
+ try await Task.sleep(for: .milliseconds(100))
+ #expect(await phone.sent().isEmpty, "a message taken back never goes")
+}
+
+@MainActor @Test func aHeldMessageWhoseFilesWentWithTheAppWaitsForTheUser() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ var data = EntryData(text: "see this", status: "waiting", clientNonce: "n1")
+ data.attachments = [Attachment(id: UUID().uuidString, name: "a.txt", size: 1)]
+ store.upsert(Entry(id: "local-n1", seq: .max, botId: "b1", rev: 0, kind: "user", turn: 0, data: data, createdAt: 1, updatedAt: 0))
+ await phone.back()
+ #expect(await until { store.chat("b1").first?.data.status == "failed" })
+ #expect(await phone.sent().isEmpty, "not without its files")
+}
+
+@MainActor @Test func aResendKeepsTheCallItWasSaidIn() async throws {
+ let phone = NoRelay()
+ defer { phone.end() }
+ await phone.start()
+ let store = phone.store
+ store.send("hi", to: "b1", call: "call-1")
+ #expect(await until { store.chat("b1").first?.data.status == "waiting" })
+ store.retry(try #require(store.chat("b1").first))
+ #expect(store.chat("b1").first?.data.call == "call-1")
+}
+
@MainActor @Test func offlineSendsWaitInTheMailbox() async throws {
let (storage, suite) = context()
defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }
diff --git a/apps/ios/Resources/Info.plist b/apps/ios/Resources/Info.plist
index f80677a8..e6812fc5 100644
--- a/apps/ios/Resources/Info.plist
+++ b/apps/ios/Resources/Info.plist
@@ -34,6 +34,10 @@
<array>
<string>audio</string>
</array>
+ <key>NSBonjourServices</key>
+ <array>
+ <string>_codync._tcp</string>
+ </array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
diff --git a/apps/ios/Views/ComputerConnectionRows.swift b/apps/ios/Views/ComputerConnectionRows.swift
new file mode 100644
index 00000000..3ae843f9
--- /dev/null
+++ b/apps/ios/Views/ComputerConnectionRows.swift
@@ -0,0 +1,97 @@
+import CodyncKit
+import CodyncUI
+import SwiftUI
+
+/// How this iPhone reaches the computer: the short name on the row, the whole route in the menu. With no relay
+/// (a computer in no account) there's nothing to choose.
+struct ComputerConnectionRow: View {
+ let store: BotStore
+ @Environment(AccountStore.self) private var accounts
+
+ var body: some View {
+ if store.computer.cloud == nil {
+ ConnectionRowLabel(route: .directOnly, cloud: nil, showsChevron: false)
+ } else {
+ DropdownMenu {
+ ConnectionRoute.allCases.map { route in
+ MenuItem(RelayCopy.routeTitle(route, cloud: store.computer.cloud), icon: route.icon, selected: route == preference) {
+ accounts.setRoute(store.computer.id, route)
+ }
+ }
+ } label: {
+ ConnectionRowLabel(route: preference, cloud: store.computer.cloud, showsChevron: true)
+ .contentShape(Rectangle())
+ }
+ }
+ }
+
+ private var preference: ConnectionRoute { store.computer.route ?? .automatic }
+}
+
+private struct ConnectionRowLabel: View {
+ let route: ConnectionRoute
+ let cloud: URL?
+ let showsChevron: Bool
+
+ var body: some View {
+ HStack(spacing: 12) {
+ Image(systemName: route.icon).font(.system(size: 17)).frame(width: 26)
+ Text(L10n.tr("Connection"))
+ Spacer(minLength: 8)
+ Text(L10n.tr(RelayCopy.routeShortTitle(route, cloud: cloud)))
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(1)
+ if showsChevron {
+ Image(systemName: "chevron.up.chevron.down").font(.caption.weight(.semibold)).foregroundStyle(Palette.tertiary)
+ }
+ }
+ .foregroundStyle(Palette.text)
+ }
+}
+
+/// A computer in no account: adding it lets this iPhone reach it from anywhere. The computer confirms.
+struct AddToAccountRow: View {
+ let store: BotStore
+ @Environment(AccountStore.self) private var accounts
+
+ var body: some View {
+ if let check = accounts.addToAccountCheck(store.computer.id) {
+ HStack(spacing: 12) {
+ Spinner(size: 17).frame(width: 26)
+ Text(L10n.tr("Confirm on the computer. It shows {code}.").replacingOccurrences(of: "{code}", with: check))
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ } else if accounts.canAddToAccount(store) {
+ Button {
+ accounts.addToAccount(store.computer.id, deviceName: UIDevice.current.name, platform: "ios")
+ } label: {
+ HStack(spacing: 12) {
+ Image(systemName: "person.crop.circle.badge.plus").font(.system(size: 17)).frame(width: 26)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(L10n.tr("Add to account"))
+ Text(L10n.tr("Reach this computer from anywhere, not only over Wi-Fi or Tailscale."))
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 0)
+ }
+ .foregroundStyle(Palette.text)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+}
+
+private extension ConnectionRoute {
+ var icon: String {
+ switch self {
+ case .automatic: "arrow.triangle.branch"
+ case .cloudflareFirst: "cloud"
+ case .directOnly: "wifi"
+ }
+ }
+}
diff --git a/apps/ios/Views/ComputersView.swift b/apps/ios/Views/ComputersView.swift
index 13948d7f..bf6f040f 100644
--- a/apps/ios/Views/ComputersView.swift
+++ b/apps/ios/Views/ComputersView.swift
@@ -174,7 +174,8 @@ private struct ComputerRows: View {
}
}
ComputerNotificationsRow(store: store)
- connection
+ ComputerConnectionRow(store: store)
+ AddToAccountRow(store: store)
// Kept while an update asked from here restarts the computer: its spinner says it's updating.
if store.connection == .online || store.isUpdating, store.hello != nil {
CodyncVersionRow(store: store)
@@ -243,37 +244,12 @@ private struct ComputerRows: View {
}
}
- /// How this iPhone reaches the computer: the short name on the row, the whole route in the menu.
- private var connection: some View {
- DropdownMenu {
- ConnectionRoute.allCases.map { route in
- MenuItem(RelayCopy.routeTitle(route, cloud: store.computer.cloud), icon: route.icon, selected: route == preference) {
- accounts.setRoute(store.computer.id, route)
- }
- }
- } label: {
- HStack(spacing: 12) {
- Image(systemName: preference.icon).font(.system(size: 17)).frame(width: 26)
- Text(L10n.tr("Connection"))
- Spacer(minLength: 8)
- Text(L10n.tr(RelayCopy.routeShortTitle(preference, cloud: store.computer.cloud)))
- .foregroundStyle(Palette.secondary)
- .lineLimit(1)
- Image(systemName: "chevron.up.chevron.down").font(.caption.weight(.semibold)).foregroundStyle(Palette.tertiary)
- }
- .foregroundStyle(Palette.text)
- .contentShape(Rectangle())
- }
- }
-
private var connectionDetail: some View {
Text(L10n.tr(detail)).font(.footnote)
.foregroundStyle(store.isOffline && !store.isUpdating ? Palette.warning : Palette.secondary)
.fixedSize(horizontal: false, vertical: true)
}
- private var preference: ConnectionRoute { store.computer.route ?? .automatic }
-
/// In a network of the user's computers, or cloud assistants on (hosts before it say nothing).
private var showsNetwork: Bool { store.network?.hasContent == true }
@@ -413,16 +389,6 @@ private struct SwatchPanel: View {
}
}
-private extension ConnectionRoute {
- var icon: String {
- switch self {
- case .automatic: "arrow.triangle.branch"
- case .cloudflareFirst: "cloud"
- case .directOnly: "wifi"
- }
- }
-}
-
/// System permission gates the computer preference without changing its saved value.
private struct ComputerNotificationsRow: View {
let store: BotStore
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index 8fecb84a..b2d4c1c9 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -292,10 +292,16 @@ private struct ScanPage: View {
VStack(alignment: .leading, spacing: 6) {
Text(L10n.tr(error)).font(.footnote).foregroundStyle(Palette.danger)
// The usual cause: the phone has no road to the computer yet.
- if unreachable { Label(L10n.tr("Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer."),
+ if unreachable { Label(L10n.tr(account.isSignedIn
+ ? "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer."
+ : "Check that this iPhone and the computer are on the same Wi-Fi or both on Tailscale."),
systemImage: "wifi.exclamationmark")
.font(.footnote)
.foregroundStyle(Palette.secondary) }
+ if unreachable { Label(L10n.tr("Also check that Local Network is on for Codync in iOS Settings, and that the Wi-Fi isn't a guest network."),
+ systemImage: "lock.shield")
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary) }
}
.transition(.opacity)
}
@@ -305,7 +311,7 @@ private struct ScanPage: View {
// How it connects is never a choice here: every paired computer gets every route.
VStack(alignment: .leading, spacing: 8) {
- Label(L10n.tr(RelayCopy.pairing(pasted: pasted)), systemImage: "lock.fill")
+ Label(L10n.tr(RelayCopy.pairing(pasted: pasted, signedIn: account.isSignedIn)), systemImage: "lock.fill")
if tailscaleOn {
Label(L10n.tr("Tailscale is on: Codync connects over it directly."), systemImage: "checkmark.circle.fill")
} else {
diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swift
index b6f5f2c1..468e5604 100644
--- a/apps/ios/Views/RootView.swift
+++ b/apps/ios/Views/RootView.swift
@@ -8,6 +8,8 @@ struct RootView: View {
@Environment(AccountStore.self) private var accounts
@Environment(AccountSession.self) private var account
@AppStorage("onboardingCompleted") private var onboardingCompleted = false
+ /// Chose to go on without signing in (docs/plans/optional-sign-in.md); signing in or starting over ends it.
+ @AppStorage("withoutAccount") private var withoutAccount = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// First launch only: past the welcome, on to setup.
@State private var welcomed = false
@@ -24,9 +26,12 @@ struct RootView: View {
var body: some View {
Group {
if mustSignIn {
- // Computers paired before sign-in was required wait in the signed-out context.
- WelcomeView(signedOutComputers: accounts.computers.count) {}
- .transition(.opacity)
+ // Computers paired signed out wait in the signed-out context.
+ WelcomeView(signedOutComputers: accounts.computers.count) {
+ Analytics.shared.capture(.continuedWithoutAccount)
+ animateSetup { withoutAccount = true }
+ }
+ .transition(.opacity)
} else if !onboardingCompleted && accounts.computers.isEmpty {
setup
} else {
@@ -35,6 +40,9 @@ struct RootView: View {
}
.background(Palette.background)
.reviewInvitation()
+ .onChange(of: account.isSignedIn) { _, signedIn in
+ if signedIn { withoutAccount = false }
+ }
.onChange(of: accounts.computers.isEmpty, initial: true) { _, empty in
// Reaching a computer (paired, or approved through the account) or explicitly skipping completes
// setup. Keep this device-level milestone across account changes and unpairing.
@@ -65,7 +73,7 @@ struct RootView: View {
/// First run, until a computer is reached or setup is skipped.
@ViewBuilder
private var setup: some View {
- if !welcomed && !account.isSignedIn {
+ if !welcomed && !account.isSignedIn && !withoutAccount {
WelcomeView { animateSetup { welcomed = true } }
.transition(.move(edge: .leading).combined(with: .opacity))
} else if account.isSignedIn && !accounts.cloudListLoaded {
@@ -86,7 +94,12 @@ struct RootView: View {
} else if account.isSignedIn {
AccountSwitcherButton()
} else {
- BackButton { animateSetup { welcomed = false } }
+ BackButton {
+ animateSetup {
+ welcomed = false
+ withoutAccount = false
+ }
+ }
}
}
.transition(.move(edge: .trailing).combined(with: .opacity))
@@ -131,10 +144,10 @@ 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.
+ /// Signed out, a build with accounts offers signing in or going on without one. 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)
+ account.isConfigured && !account.isSignedIn && !withoutAccount && (account.isReady || accounts.accountId == nil)
}
/// What the choice page offers: an older copy of a computer doesn't count as one more.
diff --git a/apps/ios/Views/WelcomeView.swift b/apps/ios/Views/WelcomeView.swift
index 4c83da5a..bcb267f2 100644
--- a/apps/ios/Views/WelcomeView.swift
+++ b/apps/ios/Views/WelcomeView.swift
@@ -2,10 +2,10 @@ import CodyncKit
import CodyncUI
import SwiftUI
-/// 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.
+/// Before any setup, and whenever signed out: who the bots are, a glimpse of talking to one, the way forward.
+/// With accounts that's signing in, or going on without one; 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.
+ /// Computers paired signed out; this phone keeps them when it signs in.
var signedOutComputers = 0
let start: () -> Void
@Environment(AccountSession.self) private var account
@@ -62,8 +62,8 @@ struct WelcomeView: View {
VStack(spacing: 10) {
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.")
+ ? L10n.tr("Your computer stays paired. If you sign in with an account used on this phone before, scan its code again. Add to account brings it into your account.")
+ : L10n.tr("Your {count} computers stay paired. If you sign in with an account used on this phone before, scan their codes again. Add to account brings each into your account.")
.replacingOccurrences(of: "{count}", with: String(signedOutComputers)))
.font(.footnote)
.foregroundStyle(Palette.secondary)
@@ -73,6 +73,18 @@ struct WelcomeView: View {
}
if account.isConfigured {
SignInButtons().disabled(!account.isReady)
+ Button(action: start) {
+ VStack(spacing: 2) {
+ Text(L10n.tr("Continue without an account")).font(.subheadline.weight(.medium))
+ .foregroundStyle(Palette.text)
+ Text(L10n.tr("Only on the same Wi-Fi or Tailscale as your computer"))
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ }
+ .frame(maxWidth: .infinity, minHeight: 44)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(PressScale())
} else {
Button(action: start) {
Text(L10n.tr("Get started")).font(.headline).frame(maxWidth: .infinity, minHeight: 50)
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 9b6143a4..5765cd6d 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -6,6 +6,17 @@ 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.41.0
+### zh-Hant
+- 不登入也能用了:在歡迎畫面選擇「不登入繼續」,手機掃電腦的 QR 碼就能配對,透過 Wi-Fi 或 Tailscale 連線。之後登入,配對會留在手機上;到「管理電腦」按「加入帳號」,電腦確認後就能從任何地方連線。
+- 電腦可以不加入帳號。配對時電腦會詢問;不加入的話,手機只能用 Wi-Fi 或 Tailscale 連線,之後也能在「管理電腦」加入帳號。
+- 遠端畫面會照連線設定換路:自動是先直連再走 Cloudflare,Cloudflare 優先則相反。
+
+### en-US
+- Use Codync without an account: choose Continue without an account on the welcome screen, then scan your computer's QR code. It connects over Wi-Fi or Tailscale. Sign in later and your computers stay paired; Add to account in Manage computers brings each into your account once the computer confirms.
+- A computer can stay out of your account. It asks when you pair; without it, your phone connects only over Wi-Fi or Tailscale, and you can add it later in Manage computers.
+- Remote screen now follows the Connection setting: Auto tries direct first, then Cloudflare, and Cloudflare first does the reverse.
+
## 2.40.3
### zh-Hant
- bot 現在可以讓 dev server 持續在電腦上執行,不會因為 bot 閒置或重新啟動而中斷。port 會顯示在聊天標題下方;點 bot 的名稱,就能看記錄、重新啟動或停止;手機連得到電腦時,也能直接開啟。
diff --git a/apps/maestro/computer-choice-skip.yaml b/apps/maestro/computer-choice-skip.yaml
index 47839836..eac85016 100644
--- a/apps/maestro/computer-choice-skip.yaml
+++ b/apps/maestro/computer-choice-skip.yaml
@@ -1,6 +1,6 @@
# First-run setup, signed in to an account that already has a computer: Skip opens the tabs, and the choice page
# doesn't come back after a relaunch.
-# Starts where computer-choice.yaml does (a phone that hasn't finished setup, `npm run phone-account`, `npm run dev -- --cloud`).
+# Starts where computer-choice.yaml does (a phone that hasn't finished setup, `npm run phone-account`, `npm run dev -- --cloud`, then **Add to account** in its window).
# Skipping finishes setup, so it runs on its own fresh setup, apart from `smoke` and computer-choice.
# One flow for iPhone and Android (docs/guides/test-stack.md):
# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags computer-choice-skip apps/maestro
diff --git a/apps/maestro/computer-choice.yaml b/apps/maestro/computer-choice.yaml
index 8336ce4e..b44826bc 100644
--- a/apps/maestro/computer-choice.yaml
+++ b/apps/maestro/computer-choice.yaml
@@ -1,7 +1,7 @@
# First-run setup, signed in to an account that already has a computer: nothing is asked by itself, the first page
# offers that computer or a new one, and the new one's install page has the download link to send.
# Needs a phone that hasn't finished setup, signed in with `npm run phone-account`, and a computer in that account
-# (`npm run dev -- --cloud`, docs/guides/dev-app.md), so it keeps the app's state: run it apart from `smoke`,
+# (`npm run dev -- --cloud`, then **Add to account** in its window, docs/guides/dev-app.md), so it keeps the app's state: run it apart from `smoke`,
# whose welcome flow clears that state. It ends with a request on the computer: each computer-choice flow starts from
# its own fresh setup, in its own run.
# One flow for iPhone and Android (docs/guides/test-stack.md):
diff --git a/apps/maestro/continue-without-account.yaml b/apps/maestro/continue-without-account.yaml
new file mode 100644
index 00000000..734146ed
--- /dev/null
+++ b/apps/maestro/continue-without-account.yaml
@@ -0,0 +1,28 @@
+# Going on without an account leads to pairing, directly (docs/plans/optional-sign-in.md).
+# On a signed-in simulator, run `xcrun simctl keychain <device> reset` first: clearing the app's state keeps the
+# iPhone's sign-in (docs/guides/test-stack.md).
+appId: com.pokai.Codync.ios.dev
+tags:
+ - smoke
+ - onboarding
+---
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+ clearState: true
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.android.dev
+ clearState: true
+- tapOn: "Continue without an account"
+# The install page first; the line is on the scan page, under its sign-in buttons.
+- tapOn: "Continue"
+- scrollUntilVisible:
+ element: "Connects on Wi-Fi or over Tailscale\\. End-to-end encrypted\\."
+ direction: DOWN
diff --git a/apps/maestro/signed-out-pairing.yaml b/apps/maestro/signed-out-pairing.yaml
new file mode 100644
index 00000000..690e50bc
--- /dev/null
+++ b/apps/maestro/signed-out-pairing.yaml
@@ -0,0 +1,39 @@
+# Signed out, a phone pairs with a computer in no account and connects only over Wi-Fi or Tailscale
+# (docs/plans/optional-sign-in.md). Needs a sandbox host in no account (`npm run dev` without `--cloud`) that the phone
+# can reach, a signed-out phone (`xcrun simctl keychain <device> reset` on a simulator), the link from
+# `codync-host pair --json`, and, while it runs, `codync-host access approve <code>` with the code the phone shows.
+# Pairing finishes setup, so it runs on its own, apart from `smoke`:
+# maestro --device "<simulator udid>" test --include-tags signed-out-pairing -e PAIRING_URL="<link>" apps/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - signed-out-pairing
+---
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+ clearState: true
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.android.dev
+ clearState: true
+- tapOn: "Continue without an account"
+- tapOn: "Continue"
+- tapOn: "Pairing link or code"
+- inputText: ${PAIRING_URL}
+- tapOn: "Pair"
+- assertVisible: "If the computer asks, check it shows.*"
+# Up to the 90 seconds the computer has to answer.
+- extendedWaitUntil:
+ visible: "Settings"
+ timeout: 100000
+- tapOn: ".*connected"
+- tapOn: "Manage computers"
+- assertVisible: "Connection"
+- assertVisible: "Wi-Fi/Tailscale only"
+- assertNotVisible: "Add to account"
diff --git a/apps/maestro/welcome.yaml b/apps/maestro/welcome.yaml
index 854a08ca..c0b296a8 100644
--- a/apps/maestro/welcome.yaml
+++ b/apps/maestro/welcome.yaml
@@ -23,3 +23,4 @@ tags:
- assertVisible: "Your coding agents,\\s+as teammates\\."
- assertVisible: "Continue with Google"
- assertVisible: "Continue with GitHub"
+- assertVisible: "Continue without an account"
diff --git a/cloud/src/index.ts b/cloud/src/index.ts
index a1560a43..dc2feb37 100644
--- a/cloud/src/index.ts
+++ b/cloud/src/index.ts
@@ -36,6 +36,8 @@ export interface Env {
CLERK_WEBHOOK_SECRET?: string;
/** Ed25519 private key (JWK JSON) that signs device certificates; hosts compile in its public half. */
DEVICE_CERT_KEY?: string;
+ /** "1": the relay and public webhooks are only for computers in an account (`relayNeedsAccount`). */
+ RELAY_NEEDS_ACCOUNT?: string;
/** GitHub token (Actions: write) that wakes the release gate; unset outside production. */
RELEASE_GATE_TOKEN?: string;
}
diff --git a/cloud/src/routes/common.ts b/cloud/src/routes/common.ts
index ff0723e9..6a41955e 100644
--- a/cloud/src/routes/common.ts
+++ b/cloud/src/routes/common.ts
@@ -21,6 +21,7 @@ const STATUS: Record<string, number> = {
badSignature: 401,
forbidden: 403,
accountDeleted: 403,
+ needsAccount: 403,
notFound: 404,
unknownComputer: 404,
alreadyClaimed: 409,
diff --git a/cloud/src/routes/relay.ts b/cloud/src/routes/relay.ts
index 22fce78d..2cddf93c 100644
--- a/cloud/src/routes/relay.ts
+++ b/cloud/src/routes/relay.ts
@@ -3,6 +3,7 @@
import { COMPUTER_ID, computerIdFor, fromB64url, verifySig, type SignedRequest } from "../auth";
import { HOOK_ID, HOOK_MAX_BODY } from "../hooks";
+import type { Env } from "../index";
import { ApiError, type Ctx } from "./common";
function checkUpgrade(c: Ctx): void {
@@ -10,6 +11,25 @@ function checkUpgrade(c: Ctx): void {
if (c.req.headers.get("Upgrade")?.toLowerCase() !== "websocket") throw new ApiError("badRequest", "Expected a WebSocket upgrade");
}
+/**
+ * Whether the relay and public webhooks are only for computers in an account (docs/plans/optional-sign-in.md). A
+ * switch so a release can turn it on once phones and hosts that follow the rule have shipped.
+ */
+export const relayNeedsAccount = (env: Env) => env.RELAY_NEEDS_ACCOUNT === "1";
+
+/**
+ * Whether a device key may open a socket on a computer's relay. In use: the computer is in an account and the device
+ * is signed in to that account. Pairing: the device has an account, which the computer is then asked to join.
+ */
+export async function mayUseRelay(db: D1Database, owner: string | null, key: string, pair: boolean): Promise<boolean> {
+ const { results } = await db
+ .prepare("SELECT owner_user_id, signed_out_at FROM devices WHERE sign_pub = ? AND revoked_at IS NULL")
+ .bind(key)
+ .all<{ owner_user_id: string; signed_out_at: number | null }>();
+ if (pair) return results.length > 0;
+ return owner !== null && results.some((d) => d.owner_user_id === owner && d.signed_out_at === null);
+}
+
/** Forwards the upgrade to the computer's DO in a request the Worker builds itself; the client's URL never reaches it. */
async function forward(c: Ctx, computerId: string, role: "host" | "device", s: SignedRequest, pair: string): Promise<Response> {
const headers = new Headers({
@@ -49,8 +69,13 @@ export async function relayDevice(c: Ctx, [computerId]: string[]): Promise<Respo
const s = await verifySig(c.req, c.raw, c.now);
if (!s) throw new ApiError("badSignature");
// Only registered computers get a DO; random IDs never create one.
- const row = await c.env.DB.prepare("SELECT status FROM computers WHERE id = ?").bind(computerId).first<{ status: string }>();
+ const row = await c.env.DB.prepare("SELECT status, owner_user_id FROM computers WHERE id = ?")
+ .bind(computerId)
+ .first<{ status: string; owner_user_id: string | null }>();
if (!row || row.status !== "active") throw new ApiError("unknownComputer");
+ if (relayNeedsAccount(c.env) && !(await mayUseRelay(c.env.DB, row.owner_user_id, s.kid, pair !== ""))) {
+ throw new ApiError("needsAccount", "This computer and this device must be in the same Codync account to use the relay.");
+ }
return forward(c, computerId!, "device", s, pair);
}
@@ -68,8 +93,13 @@ export async function routineHook(c: Ctx, [computerId, hookId]: string[]): Promi
if (!(await c.env.HOOK_LIMITER.limit({ key: `${ip}|${computerId}/${hookId}` })).success) throw new ApiError("rateLimited");
}
// Only registered computers get a DO; random IDs never create one.
- const row = await c.env.DB.prepare("SELECT status FROM computers WHERE id = ?").bind(computerId).first<{ status: string }>();
+ const row = await c.env.DB.prepare("SELECT status, owner_user_id FROM computers WHERE id = ?")
+ .bind(computerId)
+ .first<{ status: string; owner_user_id: string | null }>();
if (!row || row.status !== "active") throw new ApiError("notFound");
+ if (relayNeedsAccount(c.env) && !row.owner_user_id) {
+ throw new ApiError("needsAccount", "Public webhooks need this computer in a Codync account.");
+ }
const headers = new Headers(c.req.headers);
headers.set("X-Codync-Internal", "1");
headers.set("X-Codync-Hook", hookId!);
diff --git a/cloud/test/relay-account.test.ts b/cloud/test/relay-account.test.ts
new file mode 100644
index 00000000..f550416e
--- /dev/null
+++ b/cloud/test/relay-account.test.ts
@@ -0,0 +1,63 @@
+// The relay and public webhooks are only for computers in an account (docs/plans/optional-sign-in.md).
+
+import { describe, expect, it } from "vitest";
+import { mayUseRelay, relayNeedsAccount, routineHook } from "../src/routes/relay";
+import type { Ctx } from "../src/routes/common";
+import { env, newHost, ORIGIN } from "./helpers";
+
+async function account(id: string) {
+ await env.DB.prepare("INSERT OR IGNORE INTO accounts(user_id, created_at) VALUES (?, 0)").bind(id).run();
+}
+
+async function device(id: string, owner: string, key: string, o: { revoked?: boolean; signedOut?: boolean } = {}) {
+ await account(owner);
+ await env.DB.prepare(
+ `INSERT INTO devices(id, owner_user_id, sign_pub, name, platform, created_at, revoked_at, signed_out_at)
+ VALUES (?, ?, ?, 'Phone', 'ios', 0, ?, ?)`,
+ )
+ .bind(id, owner, key, o.revoked ? 1 : null, o.signedOut ? 1 : null)
+ .run();
+}
+
+describe("mayUseRelay", () => {
+ it("lets in only a device signed in to the computer's account", async () => {
+ await device("dev_a", "user_a", "key_a");
+ await device("dev_b", "user_b", "key_b");
+ await device("dev_gone", "user_a", "key_gone", { revoked: true });
+ await device("dev_out", "user_a", "key_out", { signedOut: true });
+
+ expect(await mayUseRelay(env.DB, "user_a", "key_a", false)).toBe(true);
+ expect(await mayUseRelay(env.DB, "user_a", "key_b", false), "another account's phone").toBe(false);
+ expect(await mayUseRelay(env.DB, "user_a", "key_none", false), "a phone with no account").toBe(false);
+ expect(await mayUseRelay(env.DB, "user_a", "key_gone", false), "a revoked phone").toBe(false);
+ expect(await mayUseRelay(env.DB, "user_a", "key_out", false), "a signed-out phone").toBe(false);
+ expect(await mayUseRelay(env.DB, null, "key_a", false), "a computer in no account").toBe(false);
+ });
+
+ it("lets a signed-in phone pair through it, so a computer with no other route can join its account", async () => {
+ await device("dev_p", "user_p", "key_p");
+ expect(await mayUseRelay(env.DB, null, "key_p", true)).toBe(true);
+ expect(await mayUseRelay(env.DB, "user_other", "key_p", true), "the computer turns it away itself").toBe(true);
+ expect(await mayUseRelay(env.DB, null, "key_stranger", true), "a phone with no account").toBe(false);
+ });
+});
+
+describe("the switch", () => {
+ it("is off unless set", () => {
+ expect(relayNeedsAccount(env)).toBe(false);
+ expect(relayNeedsAccount({ ...env, RELAY_NEEDS_ACCOUNT: "1" })).toBe(true);
+ });
+
+ it("refuses a public webhook for a computer in no account", async () => {
+ const host = await newHost();
+ const url = new URL(`${ORIGIN}/v1/hooks/${host.cid}/rtn_1`);
+ const ctx = {
+ env: { ...env, RELAY_NEEDS_ACCOUNT: "1" },
+ req: new Request(url, { method: "POST" }),
+ raw: new Uint8Array(),
+ url,
+ now: Date.now(),
+ } as unknown as Ctx;
+ await expect(routineHook(ctx, [host.cid, "rtn_1"])).rejects.toMatchObject({ code: "needsAccount", status: 403 });
+ });
+});
diff --git a/cloud/vitest.config.ts b/cloud/vitest.config.ts
index b4c3399d..937b3503 100644
--- a/cloud/vitest.config.ts
+++ b/cloud/vitest.config.ts
@@ -17,6 +17,8 @@ export default defineConfig(async () => ({
// The pool's bundled workerd trails wrangler's; pin to the newest date it supports.
compatibilityDate: "2026-08-22",
bindings: {
+ // The switch's two sides are tested directly (test/relay-account.test.ts).
+ RELAY_NEEDS_ACCOUNT: "",
TEST_MIGRATIONS: await readD1Migrations("./migrations"),
CLERK_JWT_KEY: publicKey.export({ type: "spki", format: "pem" }).toString(),
TEST_CLERK_PRIVATE_JWK: JSON.stringify(privateKey.export({ format: "jwk" })),
diff --git a/cloud/wrangler.toml b/cloud/wrangler.toml
index bc78195a..81c245d1 100644
--- a/cloud/wrangler.toml
+++ b/cloud/wrangler.toml
@@ -73,7 +73,7 @@ crons = ["*/15 * * * *", "*/5 * * * *"]
name = "codync-cloud-dev"
r2_buckets = [{ binding = "ICONS", bucket_name = "codync-icons-dev" }]
routes = [{ pattern = "dev-api.codync.dev", custom_domain = true }, { pattern = "dev-mcp.codync.dev", custom_domain = true }]
-vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }
+vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev", RELAY_NEEDS_ACCOUNT = "1" }
d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "0c03c398-3cec-4f06-a76e-998176ca19ae", migrations_dir = "migrations" }]
durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]
ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1042", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }, { name = "PAIRING_CODE_LIMITER", namespace_id = "1052", simple = { limit = 10, period = 60 } }]
diff --git a/docs/README.md b/docs/README.md
index b204e013..0e1e2882 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -61,6 +61,8 @@ Source review, a passing build, local integration tests and production acceptanc
## Plans
+- [Optional sign-in](plans/optional-sign-in.md) (signed-out phones, computers in no account, the relay only within an account; built, the rollout steps remain)
+- [Windows remote screen](plans/windows-remote-screen.md) (a screen helper for Windows; planned)
- [Android parity and acceptance](plans/android-app.md)
- [codync-network and cloud assistants: what's left](plans/codync-network-next.md) (network screens in every app, access rules, Codync's own relays, and the rest, in build order)
- [Harness memory](plans/harness-memory.md) (the switch that keeps a harness's own memory on; a choice of it instead of Codync's, planned)
diff --git a/docs/architecture/connections.md b/docs/architecture/connections.md
index 13b2b19f..18a4d79e 100644
--- a/docs/architecture/connections.md
+++ b/docs/architecture/connections.md
@@ -1,15 +1,15 @@
# Connections and accounts
-Who may reach a computer, how, and what each state is called. Agreed 2026-11-02 as the target design; [Work](#work) lists what is built and what isn't yet. Wire details stay in [remote relay](../reference/remote-relay.md).
+Who may reach a computer, how, and what each state is called. Agreed 2026-11-02; [optional sign-in](../plans/optional-sign-in.md) changed rules 2 and 3 on 2026-11-06. [Work](#work) lists what is built and what isn't yet. Wire details stay in [remote relay](../reference/remote-relay.md).
-**People sign in; computers join an account.** An app someone uses (iPhone, Android, desktop) signs in. A host never signs in: it is *in* an account, which the cloud records as the computer's owner. The computer keeps no account credentials, so a compromised server gives up its own bots, never the account.
+**People sign in; computers join an account.** An app someone uses (iPhone, Android, desktop) may sign in. A host never signs in: it may be *in* an account, which the cloud records as the computer's owner. The computer keeps no account credentials, so a compromised server gives up its own bots, never the account.
## Terms
| Term | Meaning | Code today |
| --- | --- | --- |
| Account | One person's Codync sign-in (Clerk user) | `userId` |
-| App | iPhone, Android or desktop app. Must be signed in | — |
+| App | iPhone, Android or desktop app. May stay signed out | — |
| Computer | One `codync-host`, known by its own key. In at most one account | `computerId`, `signKey` |
| Device | An app instance allowed to use a computer, with its own key | `Device`, `deviceKey` |
| In an account | The account a host belongs to (its owner in the cloud). Joining is a claim the host signs. "The host changed its account" means joining, moving or leaving, never an app signing in to another account | `claim`, `owner_user_id` |
@@ -36,8 +36,8 @@ The terminal UI and the CLI are the computer's own console, not apps in this sen
## Rules
1. **The computer decides.** The cloud can only shorten access, never grant it.
-2. **Every app is signed in.** No signed-out mode remains, on any phone or desktop build that ships.
-3. **One account per link.** A device may use a computer only when both are in the same account.
+2. **Apps may stay signed out.** A signed-out phone pairs only with a computer in no account, and only directly: Wi-Fi, Tailscale or anything else off Codync's infrastructure.
+3. **The Codync relay needs one account at both ends.** A computer in an account takes only phones of that account, and they may use the relay. A computer in no account takes any phone it confirms, directly only, whether the phone is signed in or not.
4. **A computer is in at most one account.** Changing accounts means leaving one and joining the other.
5. **Manage comes from the OS account.** Whoever sits at a computer can read `~/.codync/token`; Codync doesn't pretend to stop them. A managed computer keeps every setting of its own.
6. **Signing out affects only that app.** A phone keeps its key, computers and drafts and only stops getting alerts, so signing back in needs no scan or check; **Start over** and **Delete account** hand the key back and erase the data ([accounts on a phone](#accounts-on-a-phone)). The computer stays in its account; leaving takes **Remove from account**.
@@ -48,13 +48,12 @@ The phone finds and pairs every computer itself. A computer the phone hasn't pai
| Where you are | How | The computer |
| --- | --- | --- |
-| At the computer | Scan the QR it shows (`codync-host pair`, the desktop's **Pair iPhone**, an SSH computer's card), or type its short code when scanning a terminal is awkward | In your account: the phone gets in. In no account: asks once (desktop dialog, terminal `y/N` with a matching code), then joins the phone's account and lets the phone in. In another account: refuses, "This computer is in another account" |
+| At the computer | Scan the QR it shows (`codync-host pair`, the desktop's **Pair iPhone**, an SSH computer's card), or, signed in, type its short code when scanning a terminal is awkward | In your account: the phone gets in. In no account: asks, with a matching code. A signed-in phone: **Add to account**, **Wi-Fi or Tailscale only** or no (over the relay there is no middle choice: it would have no route afterwards). A signed-out phone: let in or not. In another account, or in any account for a signed-out phone: refuses |
| Away | Tap it in the account list, compare 6 digits on the computer, Allow (or **Skip the 6-digit check**) | Must already be in your account |
-- Only a signed-in phone scans, and the host checks the phone's account from a proof the cloud signed, never from what the phone says. The check works offline (a signature), so computers with the cloud off or on a private relay still pair in person.
-- A QR pairing records the phone's account on the computer. When a host changes the account it belongs to, it drops every device of the old account, QR-paired ones too.
-- Joining an account on the first scan is how a headless computer "signs in": there is no `codync-host login`. A computer may also join through a manager's **Add to account**, which uses the manager app's account.
-- A phone let in without the host signing a claim for its account (the phone couldn't start one, or the cloud was off or a private relay) finishes the join on a later connection: the host's `hello` says `joinAccount: true` while it is in no account on the Codync cloud (this connection's state pulled), the phone recorded an account, no device of another account is on it, and the host signed no claim for that account since its own account last changed; the phone then makes a claim, the host's `joinAccount` signs it for that recorded account, and the phone completes it (`owner::joinable_by`). The host notes every account it signs a claim for (`owner::note_signed`, any path: pairing, `joinAccount`, the desktop's Add to account) until its account changes, because a claim may complete and the computer be taken out again before it pulls its state, which then still says no account. So a computer taken out never comes back this way: one seen leaving dropped every device, and one taken out before it heard it had joined signed for that account. The cost: a claim the host signed that then failed to complete isn't retried; pairing again joins.
+- The host checks a signed-in phone's account from a proof the cloud signed, never from what the phone says. The check works offline (a signature), so computers with the cloud off or on a private relay still pair in person. A phone with no proof is a signed-out phone; a proof that doesn't check out is refused, never treated as none.
+- A QR pairing records the phone's account on the computer, or that it has none. When a host changes the account it belongs to, it drops every device of another account and every phone with none, after a warning that names them.
+- Joining an account on a scan is how a headless computer "signs in": there is no `codync-host login`. A computer may also join through a manager's **Add to account**, which uses the manager app's account, or later through a paired signed-in phone's **Add to account**, which asks on the computer again.
## Accounts on a phone
@@ -62,7 +61,8 @@ Decided 2026-11-02. A computer is in one account at most; a phone may know sever
| What happens | On the phone | Computers and cloud |
| --- | --- | --- |
-| The Clerk session ends on its own (expired, revoked elsewhere) | The sign-in screen; the account's key, computers and drafts stay. Signing in to the same account connects as before: no scan, no 6-digit check | Unchanged |
+| The Clerk session ends on its own (expired, revoked elsewhere) | The welcome screen; the account's key, computers and drafts stay. Signing in to the same account connects as before: no scan, no 6-digit check | Unchanged |
+| **Continue without an account** | A separate signed-out space with its own key. It starts empty, and signing in moves it into the account (`adopt`) | Its computers record a phone with no account |
| **Sign out** | The key, computers and drafts stay; signing back in to the same account connects as before, no scan, no check | The phone stays a device. Its alerts stop: the computers it reaches drop its push tickets (`unregisterDevice`), the account marks it signed out (`POST /v1/devices/sign-out`) and the other computers drop those registered before it on their next state pull (`signedOutDevices`). Registering again at sign-in clears the mark |
| Using another account | Only after signing out: both Clerk instances stay single-session (`single_session_mode`) | As signing out: the first account's computers keep the phone, without alerts, until it comes back |
| **Start over**, **Delete account** | Start over erases every account's keys and data, accounts signed out here included; Delete account erases that account's | The open account's computers drop the phone (`forgetDevice`), the cloud revokes it (Delete account: Clerk's webhook does) |
@@ -85,18 +85,18 @@ The desktop app runs on a computer with its own host, so its account and the com
| --- | --- | --- |
| 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, 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 |
+| In no account | Signed in | Asked once, **Add this computer to your account?** (*Not now* is remembered; Settings → Computers can still add it). No notice: being in no account is a choice |
-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.
+The app manages its computer through loopback either way. A computer in an account lets in only phones of that account (rule 3), so a B phone that tries is told which account the computer is in and how to move it.
## Headless computers
A computer with only the host (SSH-only server, VPS) never signs in. It joins an account in one of two ways:
-- A manager's desktop app adds it over SSH: add the SSH computer, install the host in one click, then it joins the manager app's account on its own.
-- A signed-in phone scans `codync-host pair` (or types its short code) and the terminal confirms.
+- A manager's desktop app adds it over SSH: add the SSH computer, install the host in one click, then answer **Add to account** when the app asks.
+- A signed-in phone scans `codync-host pair` (or types its short code) and the terminal confirms, or a phone already paired taps **Add to account** and `codync-host access approve <code>` confirms.
-`codync-host cloud` says which account the computer is in, or how to add it to one, and `--leave` takes it out (`unclaim`, after a yes in a terminal); the terminal UI's pair sheet says when a scanning phone would bring it into its account.
+`codync-host cloud` says which account the computer is in, or how to add it to one, and `--leave` takes it out (`unclaim`, after a yes in a terminal); the terminal UI's pair sheet says when it is in no account, and opens on its own when a phone asks.
### Using a Linux VPS
@@ -109,7 +109,7 @@ The agents themselves (Claude Code, Codex, …) always sign in over SSH, as the
| 1 | VPS | Install the agents and sign them in | Same |
| 2 | Desktop | Settings → Computers → Over SSH → **Add SSH computer**, pick the host from `~/.ssh/config`, compare the host key, **Trust and connect** | Built |
| 3 | Desktop | **Install** on the card: `install.sh --host-only` and `codync-host install` over SSH. Linger is turned on where the system lets the user do it (Ubuntu 24.04 does); otherwise the card shows `sudo loginctl enable-linger "$USER"` | Built (2.36.0); Codync Dev shows the command instead |
-| 4 | Desktop | The VPS joins the desktop app's account on its own | Built (2.36.0) |
+| 4 | Desktop | The app asks once, then the VPS joins the desktop app's account | Built (2.41.0) |
| 5 | Phone | The VPS appears in the account list: **Ask for access**, then compare the 6 digits on the desktop and Allow. Or open **Pair iPhone** on the VPS card and scan | Built |
| 6 | Desktop | Optionally add it to the network in one click | Built |
@@ -123,14 +123,14 @@ The agents themselves (Claude Code, Codex, …) always sign in over SSH, as the
| 4 | Phone (signed in) | Scan, or type the code in the paste field. The terminal asks to add the VPS to this account and let this phone in, with a matching code; answer `y` | Built (2.36.0) |
| 5 | Later | Other phones of the same account scan once and are in. Phones that ask remotely are approved with `codync-host access approve` over SSH, or by turning on **Skip the 6-digit check** (`codync-host cloud approval auto`) | Built (2.36.0) |
-Either way the VPS uses the Codync relay by default, with no port to open; Tailscale on both ends gives a direct route. A headless VPS has no remote screen, and its new bots start without connectors (no credential store). `codync-host tui` over SSH chats on the VPS itself.
+In an account the VPS uses the Codync relay, with no port to open; in no account, or with Tailscale on both ends, phones take a direct route. A headless VPS has no remote screen, and its new bots start without connectors (no credential store). `codync-host tui` over SSH chats on the VPS itself.
## States
| Belongs to | States | Code today |
| --- | --- | --- |
| Computer's account | Not in an account · In your account · In another account; also: Cloud off | `cloud.owner`, `cloud.enabled` |
-| App vs its computer | Same · Computer in another account · Computer in no account | `accountMismatch` (desktop) |
+| App vs its computer | Same · Computer in another account (`accountMismatch`, desktop) · Computer in no account (`mayOfferJoin`) | `lib/join-offer.ts` |
| Manage (SSH) | Idle → Connecting → Check host key → Not installed → Installing → Connected; on errors: Retrying · Failed | `SSHStatus` |
| Use: access (device × computer) | None → Waiting for OK → Can use (in person / remote); later: Can't confirm right now · Removed | `unpaired`, `pending`, `local` / `account`, `leaseExpired`, `revoked` |
| Use: connection | Connecting · Online · Computer offline · Offline | `Connection` |
@@ -138,7 +138,6 @@ Either way the VPS uses the Codync relay by default, with no port to open; Tails
Words retired with this design:
-- **Signed-out mode**, the phone's local context.
- **`owner`** in three senses: a computer's account is "in your account", a network's first member is the Creator, and the manager is the manager.
- **`local`** in four senses: loopback stays loopback, QR-paired devices are "in person", the signed-out context goes, the desktop's own computer is "this computer".
- **"{name} can use"** in desktop settings, which lists computers managed over SSH; it becomes Manage.
@@ -159,14 +158,15 @@ Phases, file-level steps, tests and risks: [require sign-in](../plans/require-si
| --- | --- | --- |
| 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 stops the phone's alerts and keeps its key (the desktop revokes its cloud device); Start over and Delete account hand it back | Built (2.36.0) |
-| 3 | Sign-in required in every app; the phone's signed-out pairings move into the account on first sign-in (with their device and push keys when the account context is new on that phone, otherwise a list to scan again). Builds without Clerk keep the signed-out context | Built (2.35.0) |
+| 3 | Sign-in required in every app (optional again, row 11); the phone's signed-out pairings move into the account on first sign-in (with their device and push keys when the account context is new on that phone, otherwise a list to scan again). Builds without Clerk keep the signed-out context | Built (2.35.0) |
| 4 | Same-account QR: the cloud-signed account proof, the host recording each device's account, joining an unowned computer on first scan with a confirmation, short codes, the refusal message | Built (2.36.0) |
| 5 | Changing accounts drops every old-account device; the move dialog's text says so | Built (2.36.0); joining a first account keeps the phones paired before 2.36.0 |
| 6 | The main-window notice for an app and computer in different accounts; the phone's refusal text | Built (2.35.0, 2.36.0) |
-| 7 | One-click host install over SSH, then **Add to account** on its own | Built (2.36.0) |
+| 7 | One-click host install over SSH, then the app asks about **Add to account** | Built (2.41.0) |
| 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 |
| 10 | Desktop apps as devices (encrypted channel), so one computer can use another's bots | Not built |
+| 11 | [Optional sign-in](../plans/optional-sign-in.md): signed-out phones, computers in no account, the relay only within an account | Built (2.41.0); the relay check is off on the main cloud until the release steps run |
## Prior art (checked 2026-11-02)
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index 49978fd5..8752af94 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -113,7 +113,7 @@ Codync/
| Account aggregation / one host mirror | `apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift` / `BotStore.swift` (+ `BotStore+Connection`, `+Sync`, `+Sending`, `+Actions`, `+Plugins`, `+Cache`, `+Shortcuts`) |
| iPhone chat, replies, composer and trace | `apps/ios/Kit/Sources/CodyncUI/Thread/` |
| Reusable iPhone UI chrome | `apps/ios/Kit/Sources/CodyncUI/Chrome.swift`, `Controls.swift`, `MenuItem.swift` (system menus: `MenuItem`, `.contextActions`, `DropdownMenu`), `Platform.swift` |
-| iOS navigation, pairing, account, settings, computer management | `apps/ios/Views/RootView.swift`, `BotListView.swift`, `ChooseComputerView.swift`, `PairingView.swift`, `AccountSwitcherView.swift`, `SettingsView.swift`, `ComputersView.swift` |
+| iOS navigation, pairing, account, settings, computer management | `apps/ios/Views/RootView.swift`, `BotListView.swift`, `ChooseComputerView.swift`, `PairingView.swift`, `AccountSwitcherView.swift`, `SettingsView.swift`, `ComputersView.swift`, `ComputerConnectionRows.swift` |
| Apple account sessions / public environment config | `apps/ios/App/AccountSession.swift`, `apps/shared/Config/` |
| Desktop local host / SSH lifecycle | `apps/desktop/src/main/host-controller.ts`, `ssh.ts` |
| Desktop store, chat and controls | `apps/desktop/src/renderer/store/bot-store.ts` (actions; state in `bot-mirror.ts`, events stream in `bot-sync.ts`), `views/thread/`, `components/` |
diff --git a/docs/features/remote-screen.md b/docs/features/remote-screen.md
index 9974ff0e..5fbee4e8 100644
--- a/docs/features/remote-screen.md
+++ b/docs/features/remote-screen.md
@@ -4,7 +4,7 @@ Remote screen lets an authorized phone view and control a computer. Signaling tr
## Connection path
-1. The phone calls `screenPrepare {relay, trickle: true}`. `relay` is true when its active host channel uses Cloudflare; direct LAN/Tailscale connections do not contact a STUN/TURN provider.
+1. The phone calls `screenPrepare {relay, trickle: true}`. `relay` asks for TURN: when the host channel uses Cloudflare, and by the computer's Connection choice when an attempt fails (`ScreenRoute`, both phones): **Auto** goes direct, then through TURN; **Cloudflare first** the other way round; **Wi-Fi or Tailscale only** never asks. Direct LAN/Tailscale connections do not contact a STUN/TURN provider. A computer in no account has no TURN: its phones go direct only.
2. The host checks the `screen` scope and that screen access is enabled. For relay connections it signs `POST /v1/host/screen-ice {deviceKey}`. The Worker requires a registered, active computer belonging to an active account. The host attests the device's local authorization, so account grants and local QR pairing both work on a claimed computer.
3. The Worker issues Cloudflare Realtime credentials with a one-hour TTL, tags usage with `computerId:deviceFingerprint` (the fingerprint is the base64url encoding of the first 16 bytes of SHA-256 of the device public key; the resulting 45-character tag fits Cloudflare’s 64-character limit), and returns `Cache-Control: no-store`. Permanent TURN keys stay in Worker secrets.
4. The host reserves a random session ID bound to the calling device and helper connection, and keeps the exact ICE configuration in memory. It returns `trickle: true` only when the phone requests it and the helper advertises support. The negotiated mode stays with that session. Clients cannot supply arbitrary ICE servers to the host.
diff --git a/docs/features/routines.md b/docs/features/routines.md
index 4897294e..507d4ec8 100644
--- a/docs/features/routines.md
+++ b/docs/features/routines.md
@@ -67,7 +67,7 @@ A routine has an OR list of triggers:
- `interval`: `seconds` (1 second through 365 days).
- `once`: `at` (Unix milliseconds, in the future when created).
- `cron`: a five-field `expression` and IANA `timeZone`, including DST.
-- `webhook`: every authenticated JSON delivery runs the routine.
+- `webhook`: every authenticated JSON delivery runs the routine. The public address needs the computer in an account (`needsAccount` in `routine_webhook`); otherwise only the local address works.
- `event`: `source`, `event` (`*` matches all), and optional exact-match `filters`.
`messageContains` matches a substring of `text`. Source names are `slack`,
`github`, `origin`, `microsoftTeams`, `linear`, `sentry`, `pagerduty`, and `email`.
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index cfcfcd3c..6b5a377a 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -107,12 +107,10 @@ 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.
-Every build with Clerk requires sign-in on the phone and the desktop app
-([require sign-in](../plans/require-sign-in.md)). Pairing needs a signed-in build
-against a cloud that issues device certificates (or a self-hosted cloud, with
-`CODYNC_DEVICE_CERT_KEY` on the host); builds without Clerk only keep the
-pairings moved over from older versions in the signed-out context, and can't pair.
-QR pairing requires the phone and the computer to be in the same account
+Signing in is optional on the phone and the desktop app ([optional sign-in](../plans/optional-sign-in.md)).
+A signed-in phone proves its account with a device certificate from the cloud (or a self-hosted cloud, with
+`CODYNC_DEVICE_CERT_KEY` on the host). A signed-out phone, and any phone in a build without Clerk, pairs without one,
+only with a computer in no account and only directly. A computer in an account lets in phones of that account only
(phase 2, below). First-run setup on the phones waits for the account's answer, then starts
from it. With computers in the account, the first page lists them (**Ask for access**: nothing
is requested until the tap, since the user may be here to set up another computer) next to
@@ -248,14 +246,14 @@ on that computer), and phones manage only their own access (pair or forget, revo
*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud; when the host's
`cloudStatus` says `joinsAccountOnEnable`, read from what it saved since the status names no owner or
relay with the cloud off, turning it on first asks: *Add to account* turns it on too, *Use your own
-relay* turns it on and keeps this identity out of auto-claim (`keptOutOfAccount`) until the address is saved; older hosts just turn on),
+relay* turns it on and keeps this identity from being asked about (`keptOutOfAccount`) until the address is saved; older hosts just turn on),
*Relay address* and, for a private relay, a write-only *Relay token* (`setCloudUrl`; the
host's `cloudStatus` says `relay: "private"` and `tokenSet`, and there the account rows are hidden
-and auto-claim never runs), *Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) and
+and nothing asks about an account), *Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) and
*Remove from account* (`unclaim`), a pairing QR, and, for this computer only, the computers it can use (its SSH computers, each with its own settings) and the devices that can use it, with revoke.
-Signed in, this computer joins the account on its own once per host identity; an identity
-that was already in the account and was removed (here or from a phone) is never re-added
-silently, only through *Add to account*. Signed in with a different account than the one this
+Signed in, the app asks once per host identity whether to add this computer to the account
+(`JoinAccountPrompt`, `lib/join-offer.ts`); an identity that was already in the account and was
+removed (here or from a phone) isn't asked about again, only added through *Add to account*. Signed in with a different account than the one this
computer is in, the app asks once to move it (`mayOfferMove`): *Move here* leaves the old account
(`unclaim`, which revokes that account's grants) and claims it for this one; *Keep it there* is
remembered for this account (`keptOutOfAccount`). Out of an account, by any path, the host turns
@@ -287,7 +285,7 @@ released development host): two SSH commands from `main/ssh-command.ts`, the rel
host into `~/.local/bin` (`packaging/install.sh --host-only`), then `codync-host install`
on the profile's port. On Linux that step also turns on linger without sudo when it can;
when it can't, the card shows the one `sudo loginctl enable-linger "$USER"` command. Once
-the installed computer connects, *Add to account* runs on its own when the app is signed in
+the installed computer connects, the app asks whether to add it to the account when it is signed in
and the computer is in no account and not on a private relay (`CloudModel.joinAfterInstall`).
*Over SSH* also offers the `Host` entries of `~/.ssh/config` and the files it `Include`s
diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.md
index 701d6b57..2065d9c0 100644
--- a/docs/guides/dev-app.md
+++ b/docs/guides/dev-app.md
@@ -33,7 +33,7 @@ Flags go after `npm run dev --`: `--shared` takes the default Codync Dev from a
A sandbox starts past onboarding (welcome and computer-access setup, only where the window hasn't chosen yet); `--onboarding` clears those two settings once per start, so the flow comes back (a signed-in sandbox passes the welcome screen by itself and lands on computer-access setup). With `CODYNC_CLERK_SECRET_KEY` (the Clerk **development** instance's `sk_test_...` key) in the git-ignored `.env.development` at the main checkout's root (copy `.env.development.example`) (every worktree reads that one file) or the environment, it also signs in its own Clerk test account `sandbox-<name>[email protected]`: `tools/dev-account.mjs` finds or creates that user through the Backend API and mints a one-time sign-in token, which `account.ts` trades for a session (`ticket` strategy, unpackaged Dev runs only). The token is minted at every start and used only while the sandbox has no active session; the app also requires a `pk_test_` publishable key, and the key never reaches the host or the agents. Keys that aren't `sk_test_` are refused. Without a key a sandbox starts signed out; it never borrows Codync Dev's login.
-Phones follow the same rule. In the main checkout, a simulator's or emulator's Codync Dev keeps your own account. From a worktree, on the worktree's test device (below), `npm run phone-account -- --ios <simulator udid>` or `-- --android <adb serial>` (in `apps/desktop`, beside `npm run dev`) signs it into the sandbox's test account, so the phone sees the sandbox computer in its account (run the sandbox with `--cloud`). It mints a one-time token with the same `tools/dev-account.mjs`. On iOS the token goes in through the `CODYNC_DEV_SIGN_IN_TICKET` launch variable (`AccountSession.swift`). On Android it goes into a file that only adb's `run-as` can write (`NativeAccounts.signInForDevelopment`, debug builds only). Both apps trade it only against Clerk's development instance, and only while signed out. In the main checkout the tool needs an explicit `--name`. It only signs into a sandbox that has run once, so `--prune` can delete its account; `npm run dev` prints the exact command.
+Phones follow the same rule. In the main checkout, a simulator's or emulator's Codync Dev keeps your own account. From a worktree, on the worktree's test device (below), `npm run phone-account -- --ios <simulator udid>` or `-- --android <adb serial>` (in `apps/desktop`, beside `npm run dev`) signs it into the sandbox's test account, so the phone sees the sandbox computer in its account (run the sandbox with `--cloud`, and answer **Add to account** when its window asks: a computer joins an account only when told to). It mints a one-time token with the same `tools/dev-account.mjs`. On iOS the token goes in through the `CODYNC_DEV_SIGN_IN_TICKET` launch variable (`AccountSession.swift`). On Android it goes into a file that only adb's `run-as` can write (`NativeAccounts.signInForDevelopment`, debug builds only). Both apps trade it only against Clerk's development instance, and only while signed out. In the main checkout the tool needs an explicit `--name`. It only signs into a sandbox that has run once, so `--prune` can delete its account; `npm run dev` prints the exact command.
Test devices for a worktree:
diff --git a/docs/guides/environments-and-deployment.md b/docs/guides/environments-and-deployment.md
index 4f4c447d..858d427f 100644
--- a/docs/guides/environments-and-deployment.md
+++ b/docs/guides/environments-and-deployment.md
@@ -62,6 +62,8 @@ A migration that changes what the database accepts goes out before the Worker co
## Releasing cloud changes
+`RELAY_NEEDS_ACCOUNT` is on for dev and off for main. It keeps the relay and public webhooks to computers in an account ([optional sign-in](../plans/optional-sign-in.md#compatibility-and-rollout)). Turn it on for main with a `[vars]` entry in `wrangler.toml` once both stores have the apps from 2.41.0.
+
CI only tests `cloud/`; nothing deploys it. A dev → main PR that changes `cloud/` (routes, bindings, migrations) goes out in this order:
1. Before the PR merges: create any new binding in dev (R2 bucket, rate limit, D1 migration), `npm run deploy:dev`, and test the changed flows end to end against `dev-api.codync.dev` with the dev apps.
diff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.md
index 7a0213c4..9282bda7 100644
--- a/docs/guides/linux-servers.md
+++ b/docs/guides/linux-servers.md
@@ -35,7 +35,7 @@ Other commands work the same as on a desktop: `codync-host pair`, `codync-host t
The phone connects over the encrypted device channel. The pairing link lists only **Tailscale** and **private (LAN/VPC)** addresses, plus any you set in `CODYNC_EXTERNAL_URL`; the host never advertises a public IP on its own.
- **Tailscale (recommended for VMs):** install Tailscale on the VM and on the phone, then `codync-host pair`. The Tailscale name comes first in the link. You don't need to open port 19222 in the cloud firewall.
-- **Codync relay (on by default):** a release host connects to the production cloud (`https://api.codync.dev`), so a paired phone reaches it from anywhere with nothing to open. `codync-host cloud --disable` turns it off; `codync-host cloud --url https://relay.example.com --token` points it at a [private relay](../../private-relay/README.md) you run yourself (the token is read without echo or from stdin); `CODYNC_CLOUD_URL=https://…` points the host at a Codync cloud you run yourself (see [environments](environments-and-deployment.md)).
+- **Codync relay, for a server in an account:** a release host talks to the production cloud (`https://api.codync.dev`), so a phone signed in to the server's account reaches it from anywhere with nothing to open. In no account the host holds no socket on the relay and phones go directly ([optional sign-in](../plans/optional-sign-in.md)). `codync-host cloud --disable` turns it off; `codync-host cloud --url https://relay.example.com --token` points it at a [private relay](../../private-relay/README.md) you run yourself (the token is read without echo or from stdin); `CODYNC_CLOUD_URL=https://…` points the host at a Codync cloud you run yourself (see [environments](environments-and-deployment.md)).
- **Your own HTTPS reverse proxy:** forward only `/channel` (WebSocket upgrade) at the root of a hostname to the host; don't forward `/api`, `/events`, `/term` or `/oauth`: through a local proxy every request looks like it comes from this computer, so the loopback-only checks no longer protect them. Then set `CODYNC_EXTERNAL_URL=https://codync.example.com` (comma-separated for several) in the host's environment: `systemctl --user edit codync-host`, add `[Service]` and `Environment=CODYNC_EXTERNAL_URL=https://codync.example.com`, then `systemctl --user restart codync-host`. The host advertises those URLs first, in the pairing link and on every connection, so the phone keeps them (a phone keeps only the addresses the host advertises). Under your own supervisor, `CODYNC_EXTERNAL_URL=… codync-host serve --bind 127.0.0.1` keeps the host on loopback behind the proxy. The phone dials `<url>/channel?v=1`. Opening `/channel` in a browser or with `curl` gets `400` (no WebSocket upgrade), and an upgrade without `?v=1` gets `426` `upgradeRequired`: that means the proxy works. A working proxy answers the phone's upgrade with `101`.
- **Desktop app over SSH:** the desktop app (macOS, Linux or Windows) can attach an SSH computer and tunnel to its loopback API ([Accounts and SSH](accounts-and-ssh.md)). From any terminal: `ssh -L 19222:127.0.0.1:19222 vm`, then `codync-host tui` locally.
diff --git a/docs/guides/test-stack.md b/docs/guides/test-stack.md
index 78f003f6..c4e249cd 100644
--- a/docs/guides/test-stack.md
+++ b/docs/guides/test-stack.md
@@ -38,7 +38,7 @@ maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-ta
The devices are the worktree's own simulator `Codync <sandbox name>` and the shared `codync_worktree` emulator, under its lock ([worktree sandboxes](dev-app.md#worktree-sandboxes)). Install the worktree's builds first: `xcodebuild … -scheme "iOS Dev" -configuration DevDebug -derivedDataPath build/dd` for the simulator, `./gradlew :app:assembleDebug` for the emulator.
-A flow past the welcome screen (`agent-logos.yaml`) needs the phone signed in with `npm run phone-account` and keeps the app's state. `welcome.yaml` (`smoke`) clears it. That signs the Android app out, but the iPhone's sign-in stays in the simulator's Keychain, so run `xcrun simctl keychain <device> reset` before `smoke` on a signed-in simulator. Run a flow past the welcome screen in a Maestro run of its own, after the sign-in. Signed in isn't past first-run setup: `agent-logos.yaml` skips the choice page when it's there. The `computer-choice` flows need setup unfinished (fresh app data) and each finishes or changes it, so each gets its own run with its own start: `computer-choice` and `computer-choice-skip` with a computer in the account (`npm run dev -- --cloud`), `computer-choice-empty` without one.
+A flow past the welcome screen (`agent-logos.yaml`) needs the phone signed in with `npm run phone-account` and keeps the app's state. `welcome.yaml` (`smoke`) clears it. That signs the Android app out, but the iPhone's sign-in stays in the simulator's Keychain, so run `xcrun simctl keychain <device> reset` before `smoke` on a signed-in simulator. `signed-out-pairing.yaml` needs a sandbox in no account and the phone signed out, and takes the pairing link as `PAIRING_URL`. Run a flow past the welcome screen in a Maestro run of its own, after the sign-in. Signed in isn't past first-run setup: `agent-logos.yaml` skips the choice page when it's there. The `computer-choice` flows need setup unfinished (fresh app data) and each finishes or changes it, so each gets its own run with its own start: `computer-choice` and `computer-choice-skip` with a computer in the account (`npm run dev -- --cloud`), `computer-choice-empty` without one.
Two things that look like failures but aren't the app's:
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 0e45dc95..3f5b23c9 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -105,7 +105,7 @@ the Dynamic Island) with its feature graphic, per language.
- [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
+- [ ] Reviewer access: pairing needs a computer, and signing in is optional (2.41.0). 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).
diff --git a/docs/plans/optional-sign-in.md b/docs/plans/optional-sign-in.md
new file mode 100644
index 00000000..fe651594
--- /dev/null
+++ b/docs/plans/optional-sign-in.md
@@ -0,0 +1,48 @@
+# Optional sign-in
+
+Agreed 2026-11-06, built in 2.41.0. Reverses part of [require sign-in](require-sign-in.md): apps may stay signed out and a computer may stay out of any account. [Connections and accounts](../architecture/connections.md) has the result; this page has the decisions and the steps left.
+
+## Decisions
+
+- **The Codync relay needs an account on both ends:** the computer in an account and the phone signed in to that same account. A computer in no account is direct only, whoever the phone is.
+- **A signed-out phone may pair only with a computer in no account.** A computer in an account refuses it, or leaving out the certificate would get around the same-account check.
+- **A signed-in phone scanning a computer in no account gets asked once:** "Add this computer to your account? Without it, this phone can connect only over Wi-Fi or Tailscale."
+- **A computer in no account may have phones of different accounts.** It confirms each one.
+- **TURN stays relay only.** `hostScreenIce` already requires an account and doesn't change. A direct session contacts no STUN or TURN provider ([remote screen](../features/remote-screen.md)).
+- **Public webhooks need a computer in an account.**
+- **A computer that joins an account removes its signed-out phones and other accounts' phones.** A dialog warns first and names them. They pair again, signed in to that account.
+- **The screen follows the Connection choice:** Auto goes direct, then TURN; Cloudflare first the other way round; Wi-Fi or Tailscale only never asks. A computer in no account shows no choice.
+
+| Phone | Computer in no account | In the phone's account | In another account |
+| --- | --- | --- | --- |
+| Signed out | Direct only | Refused | Refused |
+| Signed in | Direct only, until the computer joins | Direct and relay | Refused |
+
+## Defaults taken
+
+These follow the recommendations already given. Say if one is wrong.
+
+- Desktop sign-in and SSH install ask the same question instead of joining on their own.
+- Push stays open to signed-out phones. `relay/` has no account concept; the phone opens to the unreachable state when it can't connect.
+- Direct means anything off Codync's infrastructure: LAN, Tailscale, `CODYNC_EXTERNAL_URL`, the user's own tunnel, a private relay.
+- Signing out returns to the welcome screen. The account's computers and chats stay locked, and the signed-out space is separate and starts empty.
+- LAN discovery ships in the first version, because any phone of a computer in no account has no other way to find a changed address. It advertises only while the computer is in no account, so a computer in an account never needs a multicast permission.
+- A message that can't leave a phone with no relay waits there and goes when the computer is back, with the same nonce.
+
+## How it's built
+
+- **Cloud:** `relayDevice` checks `mayUseRelay`: outside pairing, the computer needs an owner and the device key a row under that owner, not revoked and not signed out; a pairing socket needs a registered key. `POST /v1/hooks/...` needs an owner. Both sit behind `RELAY_NEEDS_ACCOUNT` (below).
+- **Host:** a missing certificate is a signed-out phone (`channel/pairing.rs`); an invalid one is refused. `pairing_requests` answers `Join | PhoneOnly | Decline`. `devices.no_account` tells signed-out phones from rows before 2.36.0. `hello` sends `cloud` only where a phone may use it and `canJoinAccount` for the offer; `joinAccount` asks the computer. `relay::run` holds no socket in no account except for a live pairing code or a claim just signed, and pulls state every 5 minutes without one. `remote/discovery.rs` advertises `_codync._tcp` with the computer's addresses in TXT.
+- **Phones:** **Continue without an account** on the welcome screen opens the `local` context, which `adopt` moves into an account at sign-in: its pairings and messages, and its key only when the account is new on this phone. Otherwise the computers ask to be scanned again. **Add to account** on the computer's row. `ScreenRoute` picks the screen's way. `LocalDiscovery` feeds found addresses to the direct race.
+- **Desktop and terminal:** `JoinAccountPrompt` asks once for this computer and for each **Add to account**. `PairingRequestPrompt`, the terminal UI (`y`/`w`/`n`), `codync-host pair` and `codync-host access approve --phone-only` take the new answers.
+
+## Compatibility and rollout
+
+Additive, so `minApp` stays. `hello.joinAccount` stays, always `false`, so older apps never call `joinAccount`, which takes a certificate now. Older apps on a computer in no account lose the relay and have no **Add to account** row ([compatibility](../reference/compatibility.md)). A signed-out phone against an older host gets `UnsupportedVersion` and shows "update the computer". Older signed-in apps always send a claim; on `PhoneOnly` the host ignores it, and those apps already handle pairing without one.
+
+Left to do, in order:
+
+1. Ship 2.41.0. `phone_connected.route` starts counting how many people depend on the relay.
+2. `npm run deploy:dev` with the release PR, and test on dev: `RELAY_NEEDS_ACCOUNT` is already on there in `wrangler.toml`.
+3. Once both stores have the apps, count computers with no owner that still use the relay (D1 and the DOs) and tell those users how to join. Hosts before 2.41.0 still hold a socket with no owner. The message also names public webhooks: a 2.41.0 host in no account holds no socket, so until step 4 the cloud accepts a delivery to an old public URL with `202` and nothing picks it up; it expires after 72 hours.
+4. Set `RELAY_NEEDS_ACCOUNT = "1"` in main's `[vars]`, then `npm run deploy:main`. Later, remove the switch.
diff --git a/docs/plans/require-sign-in.md b/docs/plans/require-sign-in.md
index 2f4a3325..6cc868b0 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. All three phases are built (2.36.0). Phase 2 needs the cloud's certificate key before it works against a cloud: see [Release steps](#release-steps).
+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. All three phases are built (2.36.0). Phase 2 needs the cloud's certificate key before it works against a cloud: see [Release steps](#release-steps). [Optional sign-in](optional-sign-in.md) has since made signing in optional; where the two differ, that one holds.
## Decisions
@@ -116,11 +116,11 @@ After either case the signed-out context is erased (on iOS except a mirror cache
### 5. Desktop: computer in another account
-- **Logic:** a pure function next to `mayOfferMove` in `lib/auto-claim.ts`, `accountMismatch(host, userId, keptOut, seen)`. It returns one of three values:
+- **Logic:** a pure function next to `mayOfferMove` in `lib/join-offer.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`.
+ Tested in `join-offer.test.ts`.
- **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.
diff --git a/docs/plans/windows-remote-screen.md b/docs/plans/windows-remote-screen.md
new file mode 100644
index 00000000..8df248e0
--- /dev/null
+++ b/docs/plans/windows-remote-screen.md
@@ -0,0 +1,37 @@
+# Windows remote screen
+
+Planned 2026-11-06, not built. Phones can view and control macOS and Linux computers; a Windows computer has no screen helper, so its phones have no remote screen. Bots can already operate Windows through the computer-use driver ([computer use](../features/computer-use.md)). This plan comes after [optional sign-in](optional-sign-in.md), which it shares no code with.
+
+## Decisions so far
+
+- **A helper, like the other two.** `codync-screen` on Windows speaks the same [helper protocol](../features/remote-screen.md#boundaries), so the host and both phone viewers stay as they are, apart from the "not yet supported" text.
+- **Both routes come with it.** The helper takes `iceServers` and encoding limits from the host, so direct (no STUN or TURN) and relayed sessions need no Windows-specific work.
+
+## What's there to build on
+
+`apps/screen-linux` is 2,423 lines of Rust on GStreamer `webrtcbin`. By file, about 600 lines are tied to Linux: `portal.rs`, `input.rs`, `a11y.rs`. The sessions, trickle ICE, negotiation and H.264 code (`sessions.rs`, `candidates.rs`, `negotiation.rs`, `connection.rs`, `video.rs`, most of `stream.rs`) should carry over. This comes from reading the file layout; nothing has been ported yet.
+
+## Work
+
+| Area | Change |
+| --- | --- |
+| Capture | `d3d12screencapturesrc` (or `d3d11screencapturesrc`) in place of `pipewiresrc` |
+| Encoding | A Windows encoder list ahead of the software ones: `mfh264enc`, then the vendor encoders, then `openh264enc` or `x264enc` |
+| Input | `SendInput`, through a maintained crate such as `enigo`, since the helper forbids `unsafe` |
+| Host | `serve_helpers` is empty on Windows: accept the helper on a named pipe (`screen/cua.rs` already uses one), start the helper beside the host as on Linux, and make `graphical_session` true |
+| Packaging | Bundle the needed GStreamer plugins in both installers |
+| Clients | Remove "phone screen viewing is not yet supported" from setup; update [desktop app](../architecture/desktop-app.md) and the user manual |
+| Analytics | `screen_*` events gain nothing new, but failures need a Windows `stage` |
+
+## Risks to check first
+
+Run these as a spike in the Windows VM before building anything else:
+
+1. **ARM64 coverage.** GStreamer's download page lists official MSVC installers for x86_64 and arm64 (checked for 1.28.8). It doesn't say whether the arm64 one has every plugin above: `gst-inspect-1.0` in the VM answers that. The pipeline to prove: capture, H.264, `webrtcbin`, a phone showing a picture.
+2. **Installer size.** The whole GStreamer runtime is large; measure the plugin subset.
+3. **Signing.** An unsigned program that captures the screen and injects input is what antivirus software looks for. [SignPath](../../docs/guides/windows-testing.md) isn't wired into CI yet, and this probably needs it first.
+4. **Test hardware.** The UTM VM has no hardware encoder, so it only proves software encoding. `mfh264enc` and the vendor encoders need a real Windows PC.
+
+## Limits to accept
+
+These come from Windows itself, from memory rather than tested here: a helper running as the user can't capture the UAC prompt or the lock screen (the secure desktop), and can't click into a window running as administrator. A service running as SYSTEM could, at a much higher security cost. The first version doesn't try; the viewer says so when the picture stops.
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 8ff87a0f..7620525c 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -38,7 +38,7 @@ host answers and sends it once the host is up.
| `window_recovery` | host `track` (desktop) | A window's page crashed (`RendererGone` in error tracking): it loaded again, or crashed too often and stays down | `outcome` (`reloaded`/`gave_up`) |
| `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 | 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`/`choose`/`install`/`scan`; `choose`: the account has computers, ask one or pair a new one) |
+| `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: count persons, or the first one per person, for first runs | `step` (`welcome`/`choose`/`install`/`scan`; `choose`: the account has computers, ask one or pair a new one) |
| `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 reached, or skipped). | desktop `signed_in`; phones `via` (`paired`: by its code; `account`: approved after asking; `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`/`github`/`hosted`) |
@@ -46,15 +46,23 @@ host answers and sends it once the host is up.
| `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) |
+| `continued_without_account` | host `track` (desktop), iOS, Android | **Continue without an account** on the welcome screen | — |
+| `add_to_account_asked` | iOS, Android | **Add to account** on a computer in no account | — |
+| `add_to_account_completed` | iOS, Android | That ended with the computer in the account | — |
+| `add_to_account_failed` | iOS, Android | That ended without the computer joining | `reason` (`declined`/`certificate`/`unreachable`/`other`) |
+| `join_from_phone_answered` | host (`joinAccount`) | The computer answered a paired phone's **Add to account** | `outcome` (`approved`/`declined`) |
+| `discovery_failed` | host | A computer in no account couldn't advertise on the local network, reported once per host run | `stage` (`start`/`update`) |
+| `join_offer_answered` | host `track` (desktop) | The ask to add a computer to the signed-in account ended | `outcome` (`added`/`kept_out`/`failed`) |
+| `computer_found_on_network` | iOS, Android | A phone reached a computer in no account at an address it found on the local network | — |
| `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` |
-| `device_paired` | host | A phone was added: a pairing code redeemed or an account request approved | `via` (`qr`/`account`), `platform`, `automatic` (approved without a tap) |
+| `device_paired` | host | A phone was added: a pairing code redeemed or an account request approved | `via` (`qr`/`account`), `platform`, `automatic` (approved without a tap), `account` (`joined`: in the computer's account, or the computer joined the phone's; `phone_only`: signed in, the computer stayed out; `signed_out`) |
| `access_requested` | iOS, Android | The phone asks an account computer for access | — |
| `access_request_failed` | iOS, Android | The request ended without access | `reason` (`denied`/`expired`/`cancelled`) |
| `access_request_denied` | host (`decideAccessRequest`) | The computer's owner denied a phone | `client` |
| `device_revoked` | host (`revokeDevice`) | A phone's access was removed | `client` |
-| `phone_connected` | host | A paired phone connects, at most once per phone per UTC day | `platform` |
+| `phone_connected` | host | A paired phone connects, at most once per phone per UTC day | `platform`, `route` (`direct`/`relay`: how that first connection of the day came in) |
| `notifications_answered` | iOS, Android | The system notification prompt was answered | `granted`, `source` (`settings`/`widgets`/`automatic`) |
| `notification_opened` | iOS, Android | A Codync notification was tapped | `kind` (`done`/`needs_input`/`failed`) |
| `star_prompt_answered` | host `track` (desktop) | The GitHub star setup invitation or the fifth-prompt invitation was answered or closed | `ask` (`first`/`second`), `starred` |
@@ -151,7 +159,7 @@ The *Onboarding & conversion* dashboard in PostHog reads these steps, each per `
`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`; an account with computers goes `choose` → `access_requested` → `computer_paired` (`via = account`), or `choose` → `install`. The sign-in steps are the gate's sign-in rate (sign-in is required since 2.35.0).
+ `computer`; an account with computers goes `choose` → `access_requested` → `computer_paired` (`via = account`), or `choose` → `install`. The sign-in steps are the welcome screen's sign-in rate (required 2.35.0 to 2.40.x); `continued_without_account` takes the other way from 2.41.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/compatibility.md b/docs/reference/compatibility.md
index 4ac87198..5a9573e2 100644
--- a/docs/reference/compatibility.md
+++ b/docs/reference/compatibility.md
@@ -42,6 +42,8 @@ The iPhone and desktop apps also treat **undecodable data from a newer host** as
that stays undecodable after the one rewind, or a `hello` whose other fields can't be decoded
(its `version` and `minApp` are still read). From an older or equal host it's only logged.
+Apps older than 2.41.0 on a computer in no account lose the relay: `hello.cloud` is null there, which they save, and they have no **Add to account** row. They reach it over Wi-Fi or Tailscale until the computer joins an account some other way, and `hello.joinAccount` stays `false` so they never call `joinAccount`, which takes a certificate now. It raises no floor: a computer in an account is unchanged for them.
+
Apps older than 2.39.0 don't read `removed`: a queued message taken back on a newer client (`unqueue`) stays in their
chat as *Not sent — stopped*. Nothing breaks and the message never went out, so it raises no floor.
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index d268de9d..d85fbb76 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -11,7 +11,7 @@ Shared deterministic [vectors](fixtures/remote-relay-vectors.json) and their [ge
| D1 | **Cloudflare 中繼是離家連線的主要路徑**;LAN/Tailscale 直連是替代:client 先平行試直連(1.5 秒內完成握手就用),否則走中繼。Tailscale 永遠不是必要條件。 | 使用者不用裝 VPN、不用開 port。 |
| D2 | **端對端加密(locked box)**。直連和中繼**用同一套 channel 協定**:Ed25519 簽章的臨時 X25519 ECDH → HKDF-SHA256 → ChaCha20-Poly1305。Worker/DO 只看得到密文與路由 metadata。 | 一套協定、一份測試向量;LAN 上也不再有明文 token。 |
| D3 | 每台 computer 一個 Durable Object(SQLite storage、WebSocket Hibernation):presence、轉送密文、離線 mailbox(手機→電腦,24h TTL,可取消,依序投遞,ack 後刪除)。電腦→手機的補送仍由 host 的 `rev`/events 語意負責。 | 符合產品決策;DO 不保存聊天。 |
-| D4 | **Host 是授權的唯一權威**。host 在本機 SQLite 保存「已授權裝置」表;**只有兩條路能新增列**:本機 QR 配對(§4.1)與 host 自己的核准動作(`decideAccessRequest` approve,§4.2 B)。雲端 state **只能縮短**授權(刪除列、延長既有列的 lease),永遠不能新增。host 把此表簽成 **ACL** 發佈到自己的 DO,DO 據此放行 WebSocket;E2E 握手時 host 再驗一次。 | 無帳號模式也能用中繼(host 以機器金鑰向雲端註冊,不需帳號);雲端被攻破也無法新增可解密的裝置(新增要 host 本機的使用者動作、ACL 要 host 簽、握手要 host 私鑰);撤權有兩道即時關卡(DO 封鎖 + host 關 channel)。 |
+| D4 | **Host 是授權的唯一權威**(中繼本身只給帳號內的電腦與同帳號手機用,見 [optional sign-in](../plans/optional-sign-in.md))。host 在本機 SQLite 保存「已授權裝置」表;**只有兩條路能新增列**:本機 QR 配對(§4.1)與 host 自己的核准動作(`decideAccessRequest` approve,§4.2 B)。雲端 state **只能縮短**授權(刪除列、延長既有列的 lease),永遠不能新增。host 把此表簽成 **ACL** 發佈到自己的 DO,DO 據此放行 WebSocket;E2E 握手時 host 再驗一次。 | host 以機器金鑰向雲端註冊,不需帳號;雲端被攻破也無法新增可解密的裝置(新增要 host 本機的使用者動作、ACL 要 host 簽、握手要 host 私鑰);撤權有兩道即時關卡(DO 封鎖 + host 關 channel)。 |
| D5 | **Computer ID 由 host 簽章公鑰推導**:`computerId = b64url(SHA-256(hostSignPub)[0..16])`。不由雲端分配。 | 自我驗證、離線可得、無法被搶註;DO 名稱可直接推導。代價:換 host 金鑰 = 新 computer(見 §3.5)。 |
| D6 | 帳號 → Computers → Bots:`AccountStore`(`[ComputerID: BotStore]`),`BotReference = accountId + computerId + botId`。 | 依帳號與電腦隔離狀態。 |
| D7 | 共用 bearer token(`~/.codync/token`)**只接受 loopback 連線**(桌面 App 本機、SSH tunnel、statusline、MCP、TUI)。手機與其他遠端 client 一律走 E2E channel。 | 移除「一個 token 開所有手機」的舊模型;不留相容路徑。 |
@@ -89,7 +89,7 @@ See [architecture](../architecture/overview.md) and [file structure](../architec
- iOS App、Widgets、NotificationService 共用 access group `$(AppIdentifierPrefix)com.pokai.Codync`(`project.yml` 對這三個 target 加 `keychain-access-groups` entitlement;`CodyncKit` 從 Info.plist `CodyncKeychainGroup` 讀 group,缺值則不設 group)。
- 私鑰永不離開 Keychain/process;雲端只存公鑰。
- 帳號登出:先在 Clerk 登出(失敗就什麼都不變)。成功後只停通知、保留金鑰:連得到的電腦呼叫 `unregisterDevice` 刪掉 push tickets;雲端 `POST /v1/devices/sign-out`(用登出前先取的 session token)標記這台裝置已登出,帳號的其他電腦下次拉 `/v1/host/state` 時依 `signedOutDevices` 刪掉它在登出前登記的 push tickets。各自最多數秒、失敗不擋登出。該 context 的 device key、computers、草稿都留著,同一帳號登回來直接連上(`POST /v1/devices` 清掉標記)。**Start over**/刪除帳號才交還金鑰:連得到的電腦呼叫 `forgetDevice`(舊版 host 改呼叫 `unregisterDevice`),雲端 `DELETE /v1/devices/{id}`(刪除帳號由 `user.deleted` webhook 處理),再刪除 device key、computers 快取、mailbox 草稿、widget snapshot;Start over 連這支手機上登出過的帳號一起刪。刪除帳號先在 Clerk 刪除使用者,成功後才交還給電腦。
-- 有 Clerk 的 build 一律要求登入([require sign-in](../plans/require-sign-in.md)):`local` context 只留給沒有 Clerk 的 build,以及登入前遷移的來源。某個帳號 context 第一次使用時,若 `local` 有電腦或金鑰:該 context 在這支手機上是新的(沒有金鑰、沒有電腦)就整包搬過去,金鑰一起搬,電腦不用重新掃;已有自己的金鑰就只合併電腦清單,那些電腦會顯示需要重新配對。之後清掉 `local`(iOS `SharedStore.Context.adopt(from:)`、Android `LocalStore.adopt`)。
+- 有 Clerk 的 build 可以不登入([optional sign-in](../plans/optional-sign-in.md)):`local` context 是未登入空間,只走直連、配對不帶憑證。某個帳號 context 第一次使用時,若 `local` 有電腦或金鑰:該 context 在這支手機上是新的(沒有金鑰、沒有電腦)就整包搬過去,金鑰一起搬,電腦不用重新掃;已有自己的金鑰就只合併電腦清單,那些電腦會顯示需要重新配對。之後清掉 `local`(iOS `SharedStore.Context.adopt(from:)`、Android `LocalStore.adopt`)。
### 3.3 Per-(device, host) E2E 金鑰
@@ -152,12 +152,14 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair
"certificate":{"payload":"…","sig":"…"},"claim":{"claimId":"clm_…","nonce":"…"}}}
```
`certificate` 是雲端簽的裝置憑證(`POST /v1/devices/certificate`,payload `{v:1, deviceKey, userId, email, exp}`,簽 `"codync/device-cert/v1\n" + payload`,host 用編譯進去的公鑰離線驗證,`host/src/remote/certificate.rs`)。`claim` 是手機先向雲端要的 claim(`POST /v1/claims`),選填。
-4. host 先驗憑證與帳號,再花掉 code([require sign-in](../plans/require-sign-in.md#phase-2-same-account-pairing)):沒有憑證 → `reject unsupportedVersion`;憑證不是這把 device key 的 → 403;電腦在別的帳號 → 403,訊息帶 owner 遮罩過的 email;電腦在手機的帳號 → 直接放行;電腦不在任何帳號 → 在電腦上問(loopback 的 `pairingRequests` 事件/方法、`decidePairing`,最多 2 分鐘,兩邊顯示同一組 6 位數 `sha256("codync/pair-check/v1" ‖ dk ‖ hostSignKey)`),同意後 host 簽手機的 claim,回應帶 `claim`,手機自己 `POST /v1/claims/{id}/complete`。接著驗 code(常數時間比較、未過期、未用過)→ 刪除該 code → 新增裝置列(`source=local`,`grant_id=NULL`,`account=<userId>`,`scopes=["control","screen"]`,無 lease)→ 回 `{"id":1,"ok":{"computerId":"…","name":"…","claim":{…}|null}}` → **關閉這條 channel,close code `4100 paired`**(中繼:host 依序送 `data`(回應)→ `close {link, code:4100}` → 新 ACL(移除 offer、加入 dk);同一條 host socket 保序,所以回應一定先到)。
+4. host 先驗憑證與帳號,再花掉 code([optional sign-in](../plans/optional-sign-in.md)):沒有憑證的是未登入手機:經 Codync 中繼 → 403;電腦在帳號裡 → 403;電腦不在帳號 → 在電腦上問。憑證不是這把 device key 的 → 403,絕不當成沒有憑證。電腦在別的帳號 → 403,訊息帶 owner 遮罩過的 email;電腦在手機的帳號 → 直接放行;電腦不在任何帳號 → 在電腦上問(loopback 的 `pairingRequests` 事件/方法、`decidePairing {requestId, approve, join?}`,最多 2 分鐘,兩邊顯示同一組 6 位數 `sha256("codync/pair-check/v1" ‖ dk ‖ hostSignKey)`;問題帶 `canJoin`、`phoneOnly`、`removes`)。回答加入帳號時 host 簽手機的 claim,回應帶 `claim`,手機自己 `POST /v1/claims/{id}/complete`;回答只讓手機連時不簽,電腦留在帳號外,手機只能直連。問之前:經 Codync 中繼、又沒帶 claim 的已登入手機 → 403(加入帳號是它唯一的路,不問也不花 code);直連而沒帶 claim 的是 `canJoin: false`。claim 簽不了 → 403,不花 code。
5. client 收到 `4100` 立即以一般模式重連(§7.5,不帶 `pair`)。直連與中繼行為相同;DO 不需要「升級」pairing socket。
-**之後補完加入帳號**:手機進來了但 host 沒替它的帳號簽 claim(手機沒拿到 claim,或當時雲端關著/用 private relay)時,host 之後回給這台裝置的 `hello` 帶 `joinAccount: true`,條件是 `owner::joinable_by`:用 Codync 雲端(不是 private relay)、這次連線已拉過 state(`cloud_synced`)、電腦不在任何帳號、這台裝置記了帳號(`devices.account`)、電腦上沒有別的帳號的裝置,而且 host 從自己的帳號上次改變以來沒替這個帳號簽過 claim。手機接著 `POST /v1/claims`,呼叫 control scope 的 `joinAccount {claimId, nonce}`;host 再查一次同樣的條件,替這台裝置記的帳號簽 claim(`owner::sign_claim`,回傳內容與 `claimSign` 相同),手機再 `POST /v1/claims/{id}/complete`。
+**之後加入帳號**:`hello` 帶 `canJoinAccount`(用 Codync 雲端、電腦不在任何帳號)時,已登入的手機顯示 **Add to account**。手機 `POST /v1/claims`,呼叫 control scope 的 `joinAccount {claimId, nonce, certificate}`;host 驗憑證後在電腦上問(`canJoin: true, phoneOnly: false`),同意才記下這台裝置的帳號並簽 claim(`owner::join_from_phone`),手機完成 claim。host 不再自己要求加入。
-`sign_claim` 簽之前把帳號記進 kv `account_claims_signed`(`owner::note_signed`,配對、`joinAccount`、桌面 App 的 Add to account 都走這裡),帳號改變時(`owner::remember` 看到 user id 不同)清掉。原因:claim 完成後、host 還沒拉到 state 前,電腦可能又被移出帳號,下一次 pull 仍是「沒有帳號」,`remember` 不會刪任何裝置;有這筆紀錄,任何一支手機都不能再用 `joinAccount` 把它加回去。代價是 host 簽過、但 `complete` 失敗的 claim 不會自動重試,重新配對即可。
+`sign_claim` 簽之後 5 分鐘內,host 保持中繼連線並在 `hello` 給中繼位址(`owner::wants_relay`、`url_for_phones`),讓手機完成 claim、讓雲端通知 host。電腦不在帳號時 `hello.cloud` 是空的,host 也不掛中繼 socket,只有配對碼有效或剛簽 claim 時才連;平時每 5 分鐘用 HTTP 拉一次 state。帳號改變時,host 關閉 channel(`4011`)讓手機重讀 `hello`,並移除沒有帳號的手機。
+
+**區網探索**:電腦不在帳號時,host 用 mDNS 廣播 service `_codync._tcp`(`remote/discovery.rs`),instance 名稱是 computer ID,TXT 帶 `id`(computer ID)與 `urls`(逗號分隔、只放區網位址、最多 240 bytes;Tailscale 名稱與位址不放,那些位址本來就不靠區網探索)。手機(`LocalDiscovery`)把找到的位址加進直連競速;handshake 仍驗 pin 住的 key,所以找到的內容不被信任。電腦在帳號裡就不廣播。
`Caller::Pairing` 的 channel 只接受 `pair`:第一個 inner 訊息不是 `pair`、或 `pair` 之後還有任何訊息 → 關閉 `4002 protocolError`。
@@ -175,7 +177,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair
3. 桌面 App `POST /v1/claims/{claimId}/complete`(Clerk)帶上 host 回傳的內容。Worker 驗 Clerk、claim、簽章,原子化設定 owner。
4. Worker 通知 DO `cloud.changed` → host 拉 state 得知 owner。
-手機也會讓 host 簽 claim:配對時(§4.1 第 4 步),以及配對沒加入帳號時之後的 control scope `joinAccount`(§4.1「之後補完加入帳號」)。
+手機也會讓 host 簽 claim:配對時(§4.1 第 4 步),以及配對沒加入帳號時之後的 control scope `joinAccount`(§4.1「之後加入帳號」)。
**B. 手機取得存取權**(commit-then-reveal SAS,ZRTP/BLE numeric comparison 同型):
1. 手機登入後 `POST /v1/devices`(Clerk + 該 device key 的 `Codync-Sig`)。
@@ -355,7 +357,7 @@ sealed = b64url(epk ‖ ct)
| 用途 | URL | 認證 |
|---|---|---|
| host | `GET {cloud}/v1/relay/host?v=1`(Upgrade: websocket) | `Codync-Sig`,kid = hostSignPub;Worker 由 kid 推導 `computerId`,D1 `computers` 必須存在且 `status='active'`(先 `/v1/host/register`) |
-| device | `GET {cloud}/v1/relay/device/{computerId}?v=1[&pair=<offerId>]` | `Codync-Sig`,kid = deviceKey;DO 以 ACL 判斷 |
+| device | `GET {cloud}/v1/relay/device/{computerId}?v=1[&pair=<offerId>]` | `Codync-Sig`,kid = deviceKey;`RELAY_NEEDS_ACCOUNT=1` 時 Worker 先查:一般 socket 要電腦有 owner,且 deviceKey 在 D1 `devices` 屬於同一個 owner、未撤銷、未登出;pairing socket 要 deviceKey 屬於任一帳號;否則 `403 needsAccount`。接著 DO 以 ACL 判斷 |
`v` 不是 `1` → HTTP `426 {"error":{"code":"upgradeRequired"}}`。`{computerId}` 必須符合 `^[A-Za-z0-9_-]{22}$`,否則 `400`(不轉給 DO)。
@@ -461,7 +463,7 @@ Close code 總表:`1000` 正常、`1011` 內部錯誤/逾時、`4001 unautho
### 7.8 公開 routine webhook
-讓外部服務(GitHub、監控、腳本)觸發 routine,不需要公網 IP、開 port 或使用者自己的 tunnel:沿用 host 主動連出的 relay socket。
+讓外部服務(GitHub、監控、腳本)觸發 routine,不需要公網 IP、開 port 或使用者自己的 tunnel:沿用 host 主動連出的 relay socket。只給帳號內的電腦:host 對不在帳號的電腦不給網址(`needsAccount`),`RELAY_NEEDS_ACCOUNT=1` 時 Worker 回 `403 needsAccount`。
- **網址**:`POST {cloud}/v1/hooks/{computerId}/{routineId}`。Worker 檢查兩個 id 的格式、body ≤ 64 KiB(否則 `413 tooLarge`)、`HOOK_LIMITER`(每「來源 IP + hook」每分鐘 60 次 → `429`)、computer 存在且 `active`(否則 `404`,不為隨機 id 建 DO),再把原 request 轉給該 computer 的 DO `/internal/hook`。
- **註冊**:host 在 `ready` 後送 `hooks`,之後每當集合改變(新增/刪除 webhook routine、暫停/恢復、換 key)就重送整個集合。只含有 `webhook` 或 `event` trigger 的 routine。
@@ -551,7 +553,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. 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).
+The iOS app (ClerkKit) and the desktop app (Clerk Frontend API) sign in to the same Clerk instance. Signing in is optional ([optional sign-in](../plans/optional-sign-in.md)); QR pairing works without the cloud for a computer in no account, 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 68f3e022..64af9c8a 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -757,6 +757,7 @@ dependencies = [
"keyring",
"libc",
"listeners",
+ "mdns-sd",
"portable-pty",
"qrcode",
"ratatui",
@@ -1558,6 +1559,17 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+[[package]]
+name = "flume"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "spin 0.9.9",
+]
+
[[package]]
name = "fnv"
version = "1.0.7"
@@ -1635,7 +1647,7 @@ dependencies = [
"diatomic-waker",
"futures-core",
"pin-project-lite",
- "spin",
+ "spin 0.10.1",
]
[[package]]
@@ -2783,6 +2795,21 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+[[package]]
+name = "mdns-sd"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6743ed743ff2bada2b8651ef298d3f98addb0b74844f19cdd57137d8bd0219e"
+dependencies = [
+ "fastrand",
+ "flume",
+ "if-addrs",
+ "log",
+ "mio",
+ "socket-pktinfo",
+ "socket2",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -4780,6 +4807,17 @@ version = "1.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"
+[[package]]
+name = "socket-pktinfo"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
+dependencies = [
+ "libc",
+ "socket2",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "socket2"
version = "0.6.5"
@@ -4807,6 +4845,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "spin"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+dependencies = [
+ "lock_api",
+]
+
[[package]]
name = "spin"
version = "0.10.1"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 04e6421f..73517af5 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -68,6 +68,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
resvg = { version = "0.49", default-features = false }
zip = { version = "9.2.0", default-features = false, features = ["deflate"] }
listeners = "0.6.1"
+mdns-sd = "0.21.7"
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3.6.3", features = ["apple-native"] }
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index c6ab3d76..40e3bb19 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -21,7 +21,10 @@ pub mod reported;
mod session;
mod turns;
-pub use lifecycle::{KV_STARTED, Via, device_paired, host_started, phone_connected};
+pub use lifecycle::{
+ DiscoveryStage, KV_STARTED, PairedAccount, Via, device_paired, discovery_failed, host_started,
+ join_from_phone_answered, phone_connected,
+};
pub use observe::{answered, failed, observe_call};
pub use reported::track;
pub use turns::{Steer, TurnOutcome, TurnSource, agent_fell_back, message_steered, turn_finished};
@@ -115,6 +118,12 @@ pub enum Event {
SettingChanged,
/// The desktop app's ask before Reach from anywhere turns on for a computer in no account.
ReachAccountAnswered,
+ ContinuedWithoutAccount,
+ JoinOfferAnswered,
+ /// A paired phone asked to add this computer to its account, and the computer answered.
+ JoinFromPhoneAnswered,
+ /// Advertising on the local network failed, so a computer in no account can't be found at a new address.
+ DiscoveryFailed,
HostUpdateInstalled,
/// `networkCreate` or `networkJoin`: this computer is in a network of the user's computers.
NetworkJoined,
@@ -191,6 +200,10 @@ impl Event {
Self::AgentSignedIn => "agent_signed_in",
Self::SettingChanged => "setting_changed",
Self::ReachAccountAnswered => "reach_account_answered",
+ Self::ContinuedWithoutAccount => "continued_without_account",
+ Self::JoinOfferAnswered => "join_offer_answered",
+ Self::JoinFromPhoneAnswered => "join_from_phone_answered",
+ Self::DiscoveryFailed => "discovery_failed",
Self::HostUpdateInstalled => "host_update_installed",
Self::NetworkJoined => "network_joined",
Self::NetworkChanged => "network_changed",
diff --git a/host/src/analytics/lifecycle.rs b/host/src/analytics/lifecycle.rs
index 3842dfde..3d20a082 100644
--- a/host/src/analytics/lifecycle.rs
+++ b/host/src/analytics/lifecycle.rs
@@ -3,6 +3,7 @@
use super::{Analytics, Event, capture, platform, platform_of};
use crate::LockExt as _;
use crate::hub::Hub;
+use crate::remote::pairing_requests::Answer;
use serde_json::{Map, Value};
/// The version this host last started as (`host_started.updated_from`); empty when the install
@@ -40,25 +41,77 @@ fn started(last: Option<&str>, version: &str, service: bool) -> Map<String, Valu
p
}
+/// How a phone stands with this computer's account after pairing (`device_paired`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PairedAccount {
+ /// In the computer's account, or the computer joined the phone's.
+ Joined,
+ /// Signed in, and the computer stayed out of its account.
+ PhoneOnly,
+ /// A phone with no account.
+ SignedOut,
+}
+
+impl PairedAccount {
+ /// From whether the phone is signed in, and what the computer answered if it asked (in the phone's account, it
+ /// doesn't).
+ pub fn of(signed_in: bool, answer: Option<Answer>) -> Self {
+ match (signed_in, answer) {
+ (false, _) => Self::SignedOut,
+ (true, Some(Answer::PhoneOnly)) => Self::PhoneOnly,
+ (true, _) => Self::Joined,
+ }
+ }
+}
+
/// `device_paired`: a phone was added to this computer.
-pub fn device_paired(hub: &Hub, via: Via, device_platform: &str, automatic: bool) {
+pub fn device_paired(hub: &Hub, via: Via, device_platform: &str, automatic: bool, account: PairedAccount) {
let mut p = Map::new();
p.insert("via".into(), (if via == Via::Qr { "qr" } else { "account" }).into());
p.insert("platform".into(), platform(device_platform).into());
p.insert("automatic".into(), automatic.into());
+ let account = match account {
+ PairedAccount::Joined => "joined",
+ PairedAccount::PhoneOnly => "phone_only",
+ PairedAccount::SignedOut => "signed_out",
+ };
+ p.insert("account".into(), account.into());
capture(hub, Event::DevicePaired, p);
}
-/// `phone_connected`: a paired phone opened a channel, counted once per phone per UTC day.
-pub fn phone_connected(hub: &Hub, key: &str) {
+/// `phone_connected`: a paired phone opened a channel, counted once per phone per UTC day. `relayed`: it came through
+/// a relay rather than over Wi-Fi or Tailscale.
+pub fn phone_connected(hub: &Hub, key: &str, relayed: bool) {
if !hub.analytics.first_today(key, chrono::Utc::now().date_naive()) {
return;
}
let mut p = Map::new();
p.insert("platform".into(), platform_of(hub, key).into());
+ p.insert("route".into(), (if relayed { "relay" } else { "direct" }).into());
capture(hub, Event::PhoneConnected, p);
}
+/// `join_from_phone_answered`: the computer answered a paired phone's Add to account.
+pub fn join_from_phone_answered(hub: &Hub, approved: bool) {
+ let mut p = Map::new();
+ p.insert("outcome".into(), (if approved { "approved" } else { "declined" }).into());
+ capture(hub, Event::JoinFromPhoneAnswered, p);
+}
+
+/// Where advertising on the local network failed (`discovery_failed`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum DiscoveryStage {
+ Start,
+ Update,
+}
+
+/// `discovery_failed`: a computer in no account couldn't advertise on the local network.
+pub fn discovery_failed(hub: &Hub, stage: DiscoveryStage) {
+ let mut p = Map::new();
+ p.insert("stage".into(), (if stage == DiscoveryStage::Start { "start" } else { "update" }).into());
+ capture(hub, Event::DiscoveryFailed, p);
+}
+
impl Analytics {
/// Whether `phone` connects for the first time on `day`. Memory only: a restart may count one more.
fn first_today(&self, phone: &str, day: chrono::NaiveDate) -> bool {
@@ -71,6 +124,14 @@ mod tests {
use super::*;
use serde_json::json;
+ #[test]
+ fn a_pairing_says_how_the_phone_stands_with_the_account() {
+ assert_eq!(PairedAccount::of(false, Some(Answer::PhoneOnly)), PairedAccount::SignedOut);
+ assert_eq!(PairedAccount::of(true, Some(Answer::PhoneOnly)), PairedAccount::PhoneOnly);
+ assert_eq!(PairedAccount::of(true, Some(Answer::Join)), PairedAccount::Joined);
+ assert_eq!(PairedAccount::of(true, None), PairedAccount::Joined, "the computer is in the phone's account");
+ }
+
#[test]
fn a_phone_counts_once_a_day() {
let store = crate::store::Store::open(std::path::Path::new(":memory:")).unwrap();
diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rs
index ae988a9f..f728cec5 100644
--- a/host/src/analytics/observe/tests.rs
+++ b/host/src/analytics/observe/tests.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::store::{Device, DeviceSource, Store};
+use crate::store::{Device, DeviceAccount, DeviceSource, Store};
use serde_json::json;
fn temp_hub() -> (std::sync::Arc<Hub>, std::path::PathBuf) {
@@ -280,7 +280,7 @@ async fn store_lookups_add_fields_choice_and_platform() {
lease_until: None,
created_at: 0,
last_seen_at: None,
- account: None,
+ account: DeviceAccount::Unrecorded,
})
.unwrap();
let (event, p) = observe_call(&hub, &phone, "respondPermission", &answer).unwrap();
diff --git a/host/src/analytics/reported.rs b/host/src/analytics/reported.rs
index 9a47524e..146d9df3 100644
--- a/host/src/analytics/reported.rs
+++ b/host/src/analytics/reported.rs
@@ -63,6 +63,7 @@ pub enum Reported {
provider: Option<Provider>,
},
SignedOut,
+ ContinuedWithoutAccount,
StarPromptAnswered {
ask: Ask,
starred: bool,
@@ -94,6 +95,9 @@ pub enum Reported {
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<ClaimFailure>,
},
+ JoinOfferAnswered {
+ outcome: JoinOutcome,
+ },
}
// Value lists. A value a newer client adds arrives as `other` instead of being refused.
@@ -233,6 +237,17 @@ pub enum ReachOutcome {
Other,
}
+/// How the ask to add this computer to the signed-in account ended.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum JoinOutcome {
+ Added,
+ KeptOut,
+ Failed,
+ #[serde(other)]
+ Other,
+}
+
/// What the apps do with a dev server on their own (the host's methods report the rest).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -353,6 +368,11 @@ mod tests {
),
(json!({"event": "window_recovery", "app": "desktop", "outcome": "reloaded"}), Event::WindowRecovery),
(json!({"event": "window_recovery", "app": "desktop", "outcome": "gave_up"}), Event::WindowRecovery),
+ (json!({"event": "continued_without_account", "app": "desktop"}), Event::ContinuedWithoutAccount),
+ (
+ json!({"event": "join_offer_answered", "app": "desktop", "outcome": "kept_out"}),
+ Event::JoinOfferAnswered,
+ ),
(
json!({"event": "reach_account_answered", "app": "desktop", "outcome": "own_relay"}),
Event::ReachAccountAnswered,
diff --git a/host/src/api/devices.rs b/host/src/api/devices.rs
index 492ffdce..3c758d90 100644
--- a/host/src/api/devices.rs
+++ b/host/src/api/devices.rs
@@ -69,6 +69,8 @@ const LOCAL_ONLY: &[&str] = &[
"pairingRequests",
"decidePairing",
"pairingCodeOpen",
+ // Names the other phones of this computer, which a phone has no business reading.
+ "joinWouldRemove",
"cloudStatus",
"setCloud",
"setCloudUrl",
@@ -276,6 +278,8 @@ mod tests {
assert!(permit(&both, m).is_err(), "{m} is loopback only");
}
assert!(permit(&both, "send").is_ok());
+ assert!(permit(&control, "joinWouldRemove").is_err(), "a phone doesn't learn the other phones' names");
+ assert!(permit(&control, "joinAccount").is_ok(), "a paired phone can ask to add the computer");
assert!(permit(&both, "networkView").is_ok(), "phones read the network");
assert!(permit(&both, "screenOffer").is_ok());
assert!(permit(&both, "screenPrepare").is_ok());
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index b4bf44e1..cfc543be 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -58,16 +58,13 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
"hello" => {
let port = hub.port;
let icons = crate::icons::snapshot(&hub.store)?;
- let join_account = crate::remote::owner::joinable_by(hub, caller.device_key()).unwrap_or_else(|e| {
- tracing::warn!(error = format!("{e:#}"), "couldn't check whether this phone can finish joining");
- None
- });
json!({
"hostId": hub.host_id,
"computerId": hub.identity.computer_id(),
"signKey": hub.identity.sign_pub_b64(),
"boxKey": hub.identity.box_pub_b64(),
- "cloud": crate::remote::cloud::url(&hub.store),
+ // Only where a phone may use it: in no account, phones go over Wi-Fi or Tailscale.
+ "cloud": crate::remote::owner::url_for_phones(hub, caller.device_key()),
"name": crate::service::host_name(),
"version": env!("CARGO_PKG_VERSION"),
"minApp": crate::compat::MIN_APP,
@@ -84,8 +81,11 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
"rev": hub.store.current_rev(),
"screen": hub.screen.state(),
"analytics": hub.analytics.state(),
- // This phone paired without the computer joining its account: it calls `joinAccount` to finish.
- "joinAccount": join_account.is_some(),
+ // Before 2.41.0, apps called `joinAccount` when this was true. It takes a certificate now, which they
+ // don't send, so they aren't told to.
+ "joinAccount": false,
+ // A signed-in phone may offer to bring this computer into its account (`joinAccount`).
+ "canJoinAccount": crate::remote::owner::can_join(hub),
// Shells out to `tailscale`: keep it off the async workers.
"urls": tokio::task::spawn_blocking(move || crate::service::addresses(port)).await?,
})
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index b848477c..88c48f38 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -88,7 +88,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
"pairingCodeOpen" => json!({"open": hub.pairing.locked().valid(str_arg(&b, "code")?)}),
"decidePairing" => {
let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;
- crate::remote::pairing_requests::decide(hub, str_arg(&b, "requestId")?, approve)?;
+ crate::remote::pairing_requests::decide(hub, str_arg(&b, "requestId")?, approve, b["join"].as_bool())?;
json!({})
}
"decideAccessRequest" => {
@@ -127,11 +127,14 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
let (claim_id, nonce, user_id) = (str_arg(&b, "claimId")?, str_arg(&b, "nonce")?, str_arg(&b, "userId")?);
crate::remote::owner::sign_claim(hub, claim_id, nonce, user_id).await?
}
- // A phone finishing a join its pairing didn't complete (hello's `joinAccount`).
+ // The phones the desktop app's Add to account would remove, for its warning.
+ "joinWouldRemove" => {
+ json!({"names": crate::remote::owner::removed_by_joining(hub, str_arg(&b, "userId")?, "")})
+ }
+ // A paired phone bringing this computer into its account (hello's `canJoinAccount`).
"joinAccount" => {
- let user_id = crate::remote::owner::joinable_by(hub, caller.device_key())?
- .ok_or_else(|| anyhow!("This computer can't join this phone's account now."))?;
- crate::remote::owner::sign_claim(hub, str_arg(&b, "claimId")?, str_arg(&b, "nonce")?, &user_id).await?
+ let (claim_id, nonce) = (str_arg(&b, "claimId")?, str_arg(&b, "nonce")?);
+ crate::remote::owner::join_from_phone(hub, caller.device_key(), &b["certificate"], claim_id, nonce).await?
}
_ => return Ok(ControlFlow::Continue(b)),
}))
@@ -158,6 +161,8 @@ async fn pairing(hub: &Arc<Hub>, short_code: bool) -> Result<Value> {
}
let issued = hub.pairing.locked().issue();
hub.auth_changed();
+ // A computer in no account connects to the relay for as long as this code lives.
+ hub.cloud.relay_wake.notify_one();
let url = crate::service::pairing_url(&crate::service::PairingQr {
name: &crate::service::host_name(),
computer_id: &hub.identity.computer_id(),
@@ -184,7 +189,7 @@ mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::remote::identity::Identity;
- use crate::store::{Device, Scope, Store};
+ use crate::store::{Device, DeviceAccount, Scope, Store};
#[tokio::test]
async fn a_device_forgets_only_itself() {
@@ -202,7 +207,7 @@ mod tests {
lease_until: None,
created_at: 1,
last_seen_at: None,
- account: None,
+ account: DeviceAccount::Unrecorded,
};
hub.store.put_device(&phone).unwrap();
hub.store.put_device(&Device { key: "other".into(), ..phone.clone() }).unwrap();
diff --git a/host/src/background.rs b/host/src/background.rs
index 740cd161..cc75faa7 100644
--- a/host/src/background.rs
+++ b/host/src/background.rs
@@ -32,6 +32,7 @@ pub fn start(hub: &Arc<Hub>) -> JoinSet<()> {
tokio::spawn(update::release_watch());
tokio::spawn(screen::serve_helpers(hub.screen.clone()));
tokio::spawn(relay::run(hub.clone()));
+ tokio::spawn(crate::remote::discovery::run(hub.clone()));
#[cfg(target_os = "linux")]
tokio::spawn(screen::supervise_linux_helper(hub.screen.clone()));
agent_checks
diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rs
index 893f2a3d..fc61e4a9 100644
--- a/host/src/cloud_cli.rs
+++ b/host/src/cloud_cli.rs
@@ -124,7 +124,7 @@ fn account_hint(status: &Value) -> Option<&'static str> {
return None;
}
Some(if status["canJoinAccount"] == true {
- "Not in an account. Add it from a signed-in phone: run `codync-host pair` and scan the code, or type the short code it prints. Or, from a desktop app that reaches this computer over SSH, choose Add to account."
+ "Not in an account, so phones connect only over Wi-Fi or Tailscale. Add it from a signed-in phone: run `codync-host pair` and scan the code, or type the short code it prints; or, on a phone already paired, tap Add to account and answer with `codync-host access approve <code>`. Or, from a desktop app that reaches this computer over SSH, choose Add to account."
} else {
"Not in an account. Phones pair with `codync-host pair` and a QR code; joining an account needs the Codync cloud (`codync-host cloud --enable`)."
})
diff --git a/host/src/pair_cli.rs b/host/src/pair_cli.rs
index c3e81be6..b427ab7f 100644
--- a/host/src/pair_cli.rs
+++ b/host/src/pair_cli.rs
@@ -1,8 +1,9 @@
//! `codync-host pair` and `codync-host access`: letting phones and devices in from a terminal. A computer in no
-//! account asks before a signed-in phone comes in and brings it into its account (docs/plans/require-sign-in.md,
-//! phase 2): `pair` answers in a terminal, `access approve` / `deny` anywhere (scripts, SSH without a terminal).
+//! account asks before a phone comes in, and whether to join its account (docs/plans/optional-sign-in.md): `pair`
+//! answers in a terminal, `access approve` / `deny` anywhere (scripts, SSH without a terminal).
use crate::local_api::local_call;
+use crate::remote::pairing_requests::Answer;
use anyhow::{Result, bail};
use serde_json::{Value, json};
use std::io::IsTerminal as _;
@@ -14,25 +15,32 @@ pub enum AccessAction {
/// shows (the default).
List,
/// Approve a request, by its id or by the 6-digit code shown on the device.
- Approve { request: String },
+ Approve {
+ request: String,
+ /// Let a pairing phone in without joining its account: it connects only over Wi-Fi or Tailscale.
+ #[arg(long)]
+ phone_only: bool,
+ },
/// Deny a request.
Deny { request: String },
}
const ASKS: &str = "This computer isn't in an account, so it asks before a phone comes in. Answer within 90 seconds \
- with `codync-host access approve <code>` (the 6 digits the phone shows), or in the Codync desktop \
- app or the terminal UI.";
+ with `codync-host access approve <code>` (the 6 digits the phone shows; add `--phone-only` to stay \
+ out of the phone's account), or in the Codync desktop app or the terminal UI.";
+const WIFI_ONLY: &str = "Without it, this phone can connect only over Wi-Fi or Tailscale.";
pub async fn pair(port: u16, as_json: bool) -> Result<()> {
let hello = local_call(port, "hello", json!({})).await?;
let p = local_call(port, "pairing", json!({"shortCode": true})).await?;
- let asks = local_call(port, "cloudStatus", json!({})).await?["owner"].is_null();
+ let status = local_call(port, "cloudStatus", json!({})).await?;
+ let asks = status["owner"].is_null();
if as_json {
println!(
"{}",
json!({
"name": hello["name"], "computerId": hello["computerId"], "signKey": hello["signKey"],
- "boxKey": hello["boxKey"], "urls": p["urls"], "cloud": hello["cloud"],
+ "boxKey": hello["boxKey"], "urls": p["urls"], "cloud": status["url"],
"pairingUrl": p["pairingUrl"], "expiresAt": p["expiresAt"], "shortCode": p["shortCode"],
})
);
@@ -44,20 +52,12 @@ pub async fn pair(port: u16, as_json: bool) -> Result<()> {
let url = p["pairingUrl"].as_str().unwrap_or_default();
let code = qrcode::QrCode::new(url.as_bytes())?;
println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build());
- println!("Scan with the Codync iOS app within 10 minutes, or open this link on the phone:\n{url}\n");
+ println!("Scan with the Codync app within 10 minutes, or open this link on the phone:\n{url}\n");
if let Some(code) = p["shortCode"].as_str() {
println!("Or type this code where the app's pairing screen asks for a link: {code}\n");
}
- if hello["cloud"].is_null()
- && p["urls"].as_array().is_none_or(|u| {
- !u.iter().any(|u| {
- u.as_str().is_some_and(|u| u.contains("://100.") || u.contains(".ts.net") || u.starts_with("https://"))
- })
- })
- {
- println!(
- "Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere."
- );
+ if let Some(tip) = reach_tip(&status, &p["urls"]) {
+ println!("{tip}");
}
if !std::io::stdin().is_terminal() {
if asks {
@@ -80,16 +80,15 @@ async fn wait(port: u16, url: &str, expires_at: i64) -> Result<()> {
let requests = local_call(port, "pairingRequests", json!({})).await?;
if let Some(r) = requests["requests"].as_array().and_then(|r| r.first()) {
println!(
- "\n{} wants to use this computer. It joins {}'s account.\nCheck the phone shows {}.",
+ "\n{} wants to use this computer.\nCheck the phone shows {}.",
r["deviceName"].as_str().unwrap_or("A phone"),
- r["email"].as_str().unwrap_or("a Codync account"),
spaced(r["code"].as_str().unwrap_or_default()),
);
- let approve = crate::prompt::ask_yes_no("Let it in? [y/N] ").await?;
- let answered = local_call(port, "decidePairing", json!({"requestId": r["requestId"], "approve": approve}));
+ let answer = answer(r).await?;
+ let answered = local_call(port, "decidePairing", answer.body(&r["requestId"]));
if answered.await.is_err() {
println!("The phone stopped waiting, or it was answered elsewhere.");
- } else if !approve {
+ } else if answer == Answer::Decline {
println!("Turned away.");
return Ok(());
}
@@ -103,6 +102,55 @@ async fn wait(port: u16, url: &str, expires_at: i64) -> Result<()> {
Ok(())
}
+/// How far a phone gets from this computer, when that's less than anywhere: `None` with a relay phones may use, or an
+/// address that reaches past this network.
+fn reach_tip(status: &Value, urls: &Value) -> Option<&'static str> {
+ let far = |u: &Value| {
+ u.as_str().is_some_and(|u| u.contains("://100.") || u.contains(".ts.net") || u.starts_with("https://"))
+ };
+ let relay_is_on = !status["url"].is_null();
+ if (relay_is_on && !status["owner"].is_null())
+ || status["relay"] == "private"
+ || urls.as_array().is_some_and(|u| u.iter().any(far))
+ {
+ return None;
+ }
+ Some(if status["canJoinAccount"] == true {
+ "Tip: the phone reaches this computer on the same network only. Add it to your account, or use Tailscale, to reach it from anywhere."
+ } else {
+ "Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere."
+ })
+}
+
+/// Asks in the terminal: whether the phone gets in, and whether this computer joins its account when it has the choice.
+async fn answer(request: &Value) -> Result<Answer> {
+ let (can_join, phone_only) = (request["canJoin"] == true, request["phoneOnly"] == true);
+ let or_decline = |yes: bool, answer: Answer| if yes { answer } else { Answer::Decline };
+ if !can_join {
+ let prompt = "Let it in? It can connect only over Wi-Fi or Tailscale. [y/N] ";
+ return Ok(or_decline(crate::prompt::ask_yes_no(prompt).await?, Answer::PhoneOnly));
+ }
+ let email = request["email"].as_str().unwrap_or("a Codync account");
+ if let Some(removes) = removes_line(request) {
+ println!("{removes}");
+ }
+ if !phone_only {
+ let prompt = format!("Add this computer to {email}'s account and let the phone in? [y/N] ");
+ return Ok(or_decline(crate::prompt::ask_yes_no(&prompt).await?, Answer::Join));
+ }
+ if !crate::prompt::ask_yes_no("Let it in? [y/N] ").await? {
+ return Ok(Answer::Decline);
+ }
+ let prompt = format!("Add this computer to {email}'s account? {WIFI_ONLY} [y/N] ");
+ Ok(if crate::prompt::ask_yes_no(&prompt).await? { Answer::Join } else { Answer::PhoneOnly })
+}
+
+/// The phones that lose access if this computer joins, as one line.
+fn removes_line(request: &Value) -> Option<String> {
+ let names: Vec<&str> = request["removes"].as_array()?.iter().filter_map(Value::as_str).collect();
+ (!names.is_empty()).then(|| format!("These phones lose access and must pair again: {}.", names.join(", ")))
+}
+
/// `123 456`, as the phone shows it.
fn spaced(code: &str) -> String {
match code.split_at_checked(3) {
@@ -121,28 +169,44 @@ async fn requests(port: u16) -> Result<Vec<(Value, &'static str)>> {
Ok(all)
}
+/// What a pairing request adds to its line in `access list`.
+fn pairing_note(request: &Value) -> &'static str {
+ match (request["canJoin"] == true, request["phoneOnly"] == true) {
+ (true, true) => " pairing: the computer joins this account (or --phone-only)",
+ (true, false) => " pairing: the computer joins this account",
+ (false, _) => " pairing: Wi-Fi or Tailscale only",
+ }
+}
+
+fn print_requests(requests: &[(Value, &str)]) {
+ if requests.is_empty() {
+ println!("No devices are asking for access.");
+ }
+ for (r, decide) in requests {
+ println!(
+ "{} {} ({}, {}) code {}{}",
+ r["requestId"].as_str().unwrap_or_default(),
+ r["deviceName"].as_str().unwrap_or_default(),
+ r["platform"].as_str().unwrap_or_default(),
+ r["email"].as_str().unwrap_or("no email"),
+ r["code"].as_str().unwrap_or("(waiting for the device)"),
+ if *decide == "decidePairing" { pairing_note(r) } else { "" },
+ );
+ if let Some(removes) = removes_line(r) {
+ println!(" {removes}");
+ }
+ }
+}
+
pub async fn access(port: u16, action: AccessAction) -> Result<()> {
let requests = requests(port).await?;
- let (request, approve) = match action {
+ let (request, approve, phone_only) = match action {
AccessAction::List => {
- if requests.is_empty() {
- println!("No devices are asking for access.");
- }
- for (r, decide) in &requests {
- println!(
- "{} {} ({}, {}) code {}{}",
- r["requestId"].as_str().unwrap_or_default(),
- r["deviceName"].as_str().unwrap_or_default(),
- r["platform"].as_str().unwrap_or_default(),
- r["email"].as_str().unwrap_or("no email"),
- r["code"].as_str().unwrap_or("(waiting for the device)"),
- if *decide == "decidePairing" { " pairing: the computer joins this account" } else { "" },
- );
- }
+ print_requests(&requests);
return Ok(());
}
- AccessAction::Approve { request } => (request, true),
- AccessAction::Deny { request } => (request, false),
+ AccessAction::Approve { request, phone_only } => (request, true, phone_only),
+ AccessAction::Deny { request } => (request, false, false),
};
// A 6-digit code picks the request showing it; it must be the only one.
let matching: Vec<_> =
@@ -150,7 +214,14 @@ pub async fn access(port: u16, action: AccessAction) -> Result<()> {
let [(r, decide)] = matching.as_slice() else {
bail!("No single request matches {request}. See `codync-host access list`.");
};
- local_call(port, decide, json!({"requestId": r["requestId"], "approve": approve})).await?;
+ let mut body = json!({"requestId": r["requestId"], "approve": approve});
+ if phone_only {
+ if *decide != "decidePairing" {
+ bail!("--phone-only is for a phone that's pairing with this computer.");
+ }
+ body["join"] = json!(false);
+ }
+ local_call(port, decide, body).await?;
println!("{}", if approve { "Approved." } else { "Denied." });
Ok(())
}
@@ -159,6 +230,36 @@ pub async fn access(port: u16, action: AccessAction) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn a_question_names_the_phones_a_join_removes() {
+ assert_eq!(removes_line(&json!({"removes": []})), None);
+ assert_eq!(removes_line(&json!({})), None);
+ let line = removes_line(&json!({"removes": ["Pixel", "iPhone"]})).unwrap();
+ assert!(line.ends_with("must pair again: Pixel, iPhone."), "{line}");
+ }
+
+ #[test]
+ fn the_list_says_what_a_pairing_answer_does() {
+ assert!(pairing_note(&json!({"canJoin": true, "phoneOnly": true})).contains("--phone-only"));
+ assert!(pairing_note(&json!({"canJoin": true, "phoneOnly": false})).ends_with("joins this account"));
+ assert!(pairing_note(&json!({"canJoin": false, "phoneOnly": true})).contains("Wi-Fi or Tailscale only"));
+ }
+
+ #[test]
+ fn the_tip_says_how_to_reach_further() {
+ let urls = json!(["http://192.168.1.5:19222"]);
+ let no_account =
+ json!({"url": "https://api.codync.dev", "owner": null, "relay": "codync", "canJoinAccount": true});
+ assert!(reach_tip(&no_account, &urls).unwrap().contains("Add it to your account"));
+ let off = json!({"url": null, "owner": null, "relay": "codync", "canJoinAccount": false});
+ assert!(reach_tip(&off, &urls).unwrap().contains("Turn on the Codync cloud"));
+ let in_account = json!({"url": "https://api.codync.dev", "owner": {"userId": "u"}, "relay": "codync"});
+ assert_eq!(reach_tip(&in_account, &urls), None);
+ assert_eq!(reach_tip(&no_account, &json!(["http://100.101.1.1:19222"])), None, "Tailscale reaches it");
+ let private = json!({"url": "https://relay.example.com", "owner": null, "relay": "private"});
+ assert_eq!(reach_tip(&private, &urls), None, "a private relay is the user's own");
+ }
+
#[test]
fn the_check_code_reads_as_on_the_phone() {
assert_eq!(spaced("165780"), "165 780");
diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rs
index 1f7c8e78..15c61e92 100644
--- a/host/src/remote/channel.rs
+++ b/host/src/remote/channel.rs
@@ -16,7 +16,7 @@ use crate::api;
use crate::api::devices::{self, Caller, RejectCode};
use crate::hub::Hub;
use crate::remote::crypto::{self, FrameError, Opener, Sealer};
-use crate::store::{Device, DeviceSource, Scope, now_ms};
+use crate::store::{Device, DeviceAccount, DeviceSource, Scope, now_ms};
use axum::extract::ws::{CloseFrame, Message, WebSocket};
use futures::{SinkExt as _, StreamExt as _};
use serde_json::{Value, json};
@@ -188,6 +188,7 @@ pub async fn run(hub: Arc<Hub>, t: Transport, kind: ChannelKind) {
caller: Arc::new(Caller::Local),
lease: None,
online: None,
+ relayed: matches!(kind, ChannelKind::Relay { .. }),
};
let opener = Opener::new(hs.keys.d2h, if hs.device.is_some() { MAX_INBOUND } else { 1 << 20 });
let (code, reason) = if let Some(d) = hs.device {
@@ -195,7 +196,7 @@ pub async fn run(hub: Arc<Hub>, t: Transport, kind: ChannelKind) {
ch.serve(&mut incoming, opener, &mut writer).await
} else {
ch.caller = Arc::new(Caller::Pairing { key: ch.key.clone() });
- ch.pair(&mut incoming, opener, &kind.source()).await
+ ch.pair(&mut incoming, opener, &kind).await
};
for job in ch.jobs.locked().drain() {
if let (_, Job::Sub(h)) = job {
@@ -317,12 +318,12 @@ enum Job {
struct Online(Arc<Hub>, String);
impl Online {
- fn new(hub: Arc<Hub>, key: String) -> Self {
+ fn new(hub: Arc<Hub>, key: String, relayed: bool) -> Self {
*hub.connected.locked().entry(key.clone()).or_default() += 1;
if let Err(error) = hub.store.touch_device(&key) {
tracing::warn!(error = format!("{error:#}"), "couldn't record when a device was last seen");
}
- crate::analytics::phone_connected(&hub, &key);
+ crate::analytics::phone_connected(&hub, &key, relayed);
Self(hub, key)
}
}
@@ -347,6 +348,8 @@ struct Channel {
caller: Arc<Caller>,
lease: Option<Instant>,
online: Option<Online>,
+ /// It came through a relay, not over Wi-Fi or Tailscale.
+ relayed: bool,
}
type CloseWith = (u16, &'static str);
@@ -411,6 +414,7 @@ impl Channel {
// A new relay address (or the relay on or off) reaches phones only in `hello`: reconnecting
// reads it again, over this route or the old relay while it is still up (`relay::MOVE_GRACE`).
let mut cloud = self.hub.cloud.config.subscribe();
+ let mut account = self.hub.cloud.account_changed.subscribe();
let rekey_at = Instant::now() + MAX_AGE;
loop {
let lease = self.lease;
@@ -422,7 +426,7 @@ impl Channel {
Err(e) => return frame_close(&e),
};
if self.online.is_none() {
- self.online = Some(Online::new(self.hub.clone(), self.key.clone()));
+ self.online = Some(Online::new(self.hub.clone(), self.key.clone(), self.relayed));
}
if let Some(bytes) = message
&& let Err(close) = self.handle(&bytes).await
@@ -445,6 +449,7 @@ impl Channel {
}
() = sleep_until(rekey_at) => return (close::REKEY, "rekey"),
_ = cloud.changed() => return (close::REKEY, "relay"),
+ _ = account.changed() => return (close::REKEY, "account"),
_ = &mut *writer => return (close::NORMAL, ""),
}
}
@@ -820,7 +825,7 @@ mod tests {
lease_until: Some(now_ms() + 300),
created_at: now_ms(),
last_seen_at: None,
- account: None,
+ account: DeviceAccount::Unrecorded,
};
hub.store.put_device(&device).unwrap();
let mut p = Phone::direct(&hub, key.clone());
diff --git a/host/src/remote/channel/pairing.rs b/host/src/remote/channel/pairing.rs
index 0c507203..7d402850 100644
--- a/host/src/remote/channel/pairing.rs
+++ b/host/src/remote/channel/pairing.rs
@@ -1,14 +1,35 @@
-//! The pairing channel (§4.1): one `pair`, answered, then closed with `4100`. The phone proves its account with a
-//! certificate from the cloud (docs/plans/require-sign-in.md, phase 2): a computer in an account lets in phones of
-//! that account only; one in no account asks first, then joins the phone's account.
+//! The pairing channel (§4.1): one `pair`, answered, then closed with `4100`. A signed-in phone proves its account with
+//! a certificate from the cloud (docs/plans/require-sign-in.md, phase 2); a signed-out phone sends none
+//! (docs/plans/optional-sign-in.md). A computer in an account lets in phones of that account only; one in no account
+//! asks first, and joins the phone's account only when it's told to.
use super::*;
+use crate::analytics::PairedAccount;
use crate::remote::certificate::{self, Certified, Refusal};
-use crate::remote::cloud::Owner;
-use crate::remote::{owner, pairing_requests};
+use crate::remote::cloud::{self, Owner, RelayKind};
+use crate::remote::owner;
+use crate::remote::pairing_requests::{self, Answer, Question};
const PROTOCOL: CloseWith = (close::PROTOCOL, "protocolError");
const EXPIRED: &str = "This pairing code expired. Show a new one on the computer.";
+const IN_AN_ACCOUNT: &str = "This computer is in a Codync account. Sign in to that account to connect.";
+const SIGN_IN_FOR_RELAY: &str =
+ "Sign in to pair over the internet, or connect to the same Wi-Fi or Tailscale as the computer.";
+const TRY_AGAIN: &str = "Couldn't add this computer to your account. Scan the code again.";
+
+/// The phone's `pair`, checked.
+struct Request<'a> {
+ id: u64,
+ name: &'a str,
+ platform: &'a str,
+ code: &'a str,
+ account: Option<&'a Certified>,
+ /// The claim the phone made for its account: `(claimId, nonce)`.
+ claim: Option<(&'a str, &'a str)>,
+}
+
+/// What the phone's let in with: the computer's answer, if it asked, and the claim it signed, if it joins.
+type LetIn = (Option<Answer>, Option<Value>);
/// Why `let_in` left the phone out.
enum Kept {
@@ -25,53 +46,93 @@ impl Channel {
&mut self,
incoming: &mut mpsc::Receiver<Value>,
opener: Opener,
- source: &str,
+ kind: &ChannelKind,
) -> CloseWith {
let (id, b) = match read_pair(incoming, opener).await {
Ok(request) => request,
Err(close) => return close,
};
- let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100);
- let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"));
- let (Some(name), Some(platform)) = (name, platform) else {
+ let Some((name, platform)) = read_identity(&b) else {
self.send(err(id, 400, "`name` and `platform` (ios, macos or android) are required")).await;
return PROTOCOL;
};
let code = b["code"].as_str().unwrap_or_default();
- let account = match self.admit(id, &b, code, source).await {
+ let on_codync_relay = self.on_codync_relay(kind);
+ let account = match self.admit(id, &b, code, &kind.source(), on_codync_relay).await {
Ok(account) => account,
Err(close) => return close,
};
- let mut let_in = owner::while_unchanged(&self.hub, || self.let_in(&account, false, code, name, platform));
+ let claim = b["claim"]["claimId"].as_str().zip(b["claim"]["nonce"].as_str());
+ let request = Request { id, name, platform, code, account: account.as_ref(), claim };
+ let (answer, claim) = match self.let_in_or_ask(&request, on_codync_relay, incoming).await {
+ Ok(let_in) => let_in,
+ Err(close) => return close,
+ };
+ tracing::info!(device = self.key, platform, "device paired");
+ let paired = PairedAccount::of(account.is_some(), answer);
+ crate::analytics::device_paired(&self.hub, crate::analytics::Via::Qr, platform, false, paired);
+ let mut ok = json!({"computerId": self.hub.identity.computer_id(), "name": crate::service::host_name()});
+ if let Some(claim) = claim {
+ // Joining the phone's account: the phone, which holds the account's session, completes the claim.
+ ok["claim"] = claim;
+ }
+ self.send(json!({"id": id, "ok": ok})).await;
+ (close::PAIRED, "paired")
+ }
+
+ /// Lets the phone in, asking this computer first when it's in no account. A join's claim is signed before the
+ /// code is spent, so a failure leaves the code for another try.
+ async fn let_in_or_ask(
+ &self,
+ request: &Request<'_>,
+ on_codync_relay: bool,
+ incoming: &mut mpsc::Receiver<Value>,
+ ) -> Result<LetIn, CloseWith> {
+ let mut let_in = owner::while_unchanged(&self.hub, || self.let_in(request, None));
+ let (mut answer, mut claim) = (None, None);
if matches!(let_in, Err(Kept::Unasked)) {
- if let Err(close) = self.ask(id, name, platform, account.email.as_deref(), incoming).await {
- return close;
+ // Over the Codync relay, joining is the only way in, and joining takes a claim.
+ if on_codync_relay && request.claim.is_none() {
+ return Err(self.refuse(request.id, TRY_AGAIN, "unauthorized").await);
+ }
+ let about = Question::about(&self.hub, &self.key, request.name, request.platform, request.account)
+ .map_err(|_| PROTOCOL)?;
+ let can_join = request.account.is_some() && request.claim.is_some() && cloud::codync_url(&self.hub).is_ok();
+ let question = Question { can_join, phone_only: !on_codync_relay, ..about };
+ let said = self.ask(request.id, question, incoming).await?;
+ if said == Answer::Join {
+ claim = Some(self.sign_claim(request).await?);
}
- let_in = owner::while_unchanged(&self.hub, || self.let_in(&account, true, code, name, platform));
+ answer = Some(said);
+ let_in = owner::while_unchanged(&self.hub, || self.let_in(request, answer));
}
- let owner = match let_in {
- Ok(owner) => owner,
- Err(Kept::Out(message, reason)) => return self.refuse(id, &message, reason).await,
+ match let_in {
+ Ok(()) => Ok((answer, claim)),
+ Err(Kept::Out(message, reason)) => Err(self.refuse(request.id, &message, reason).await),
// `Unasked` only comes before the computer asked.
Err(Kept::Unsaved | Kept::Unasked) => {
- self.send(err(id, 500, "couldn't save this device")).await;
- return (close::NORMAL, "");
+ self.send(err(request.id, 500, "couldn't save this device")).await;
+ Err((close::NORMAL, ""))
}
- };
- tracing::info!(device = self.key, platform, "device paired");
- crate::analytics::device_paired(&self.hub, crate::analytics::Via::Qr, platform, false);
- let mut ok = json!({"computerId": self.hub.identity.computer_id(), "name": crate::service::host_name()});
- if owner.is_none() {
- // Joining the phone's account: the computer signs the claim the phone made; the phone, which holds
- // the account's session, completes it with the cloud.
- ok["claim"] = self.claim(&b["claim"], &account.user_id).await;
}
- self.send(json!({"id": id, "ok": ok})).await;
- (close::PAIRED, "paired")
}
- /// Before anything about this computer's account reaches the phone: a live code, then the phone's account.
- async fn admit(&self, id: u64, b: &Value, code: &str, source: &str) -> Result<Certified, CloseWith> {
+ /// Whether this channel came through the Codync relay, which a phone may use only with an account.
+ fn on_codync_relay(&self, kind: &ChannelKind) -> bool {
+ matches!(kind, ChannelKind::Relay { .. })
+ && cloud::current(&self.hub.store).is_some_and(|address| address.kind == RelayKind::Codync)
+ }
+
+ /// Before anything about this computer's account reaches the phone: a live code, then the phone's account, if it
+ /// has one.
+ async fn admit(
+ &self,
+ id: u64,
+ b: &Value,
+ code: &str,
+ source: &str,
+ on_codync_relay: bool,
+ ) -> Result<Option<Certified>, CloseWith> {
if !self.hub.pairing.locked().attempt(source) {
return Err(self.reject(RejectCode::RateLimited).await);
}
@@ -79,8 +140,9 @@ impl Channel {
return Err(self.refuse(id, EXPIRED, "unauthorized").await);
}
match certificate::check(&b["certificate"], &self.key, now_ms()) {
- Ok(account) => Ok(account),
- Err(Refusal::Missing) => Err(self.reject(RejectCode::UnsupportedVersion).await),
+ Ok(account) => Ok(Some(account)),
+ Err(Refusal::Missing) if on_codync_relay => Err(self.refuse(id, SIGN_IN_FOR_RELAY, "unauthorized").await),
+ Err(Refusal::Missing) => Ok(None),
Err(Refusal::Invalid) => {
let message = "Couldn't confirm your Codync account. Sign in again, then scan a new code.";
Err(self.refuse(id, message, "unauthorized").await)
@@ -90,45 +152,41 @@ impl Channel {
/// Run under `owner::while_unchanged`, so the account the phone is checked against is the one it is saved
/// under: a computer in an account lets in phones of that account only, one in no account only once it asked
- /// (`asked`). Returns this computer's account. The code is spent only now: a phone turned away leaves it to the
- /// right one, and while the computer asks the relay keeps the offer, and with it this socket.
- fn let_in(
- &self,
- account: &Certified,
- asked: bool,
- code: &str,
- name: &str,
- platform: &str,
- ) -> Result<Option<Owner>, Kept> {
- let owner = self.owner_for(account).map_err(|message| Kept::Out(message, "otherAccount"))?;
- if owner.is_none() && !asked {
+ /// (`answer`). The code is spent only now: a phone turned away leaves it to the right one, and while the computer
+ /// asks the relay keeps the offer, and with it this socket.
+ fn let_in(&self, request: &Request<'_>, answer: Option<Answer>) -> Result<(), Kept> {
+ let owner = self.owner_for(request.account).map_err(|message| Kept::Out(message, "otherAccount"))?;
+ if owner.is_none() && answer.is_none() {
return Err(Kept::Unasked);
}
- if !self.hub.pairing.locked().redeem(code) {
+ if !self.hub.pairing.locked().redeem(request.code) {
return Err(Kept::Out(EXPIRED.into(), "unauthorized"));
}
let device = Device {
key: self.key.clone(),
- name: name.to_owned(),
- platform: platform.to_owned(),
+ name: request.name.to_owned(),
+ platform: request.platform.to_owned(),
source: DeviceSource::Local,
grant_id: None,
scopes: vec![Scope::Control, Scope::Screen],
lease_until: None,
created_at: now_ms(),
last_seen_at: None,
- account: Some(account.user_id.clone()),
+ account: request.account.map_or(DeviceAccount::SignedOut, |a| DeviceAccount::Of(a.user_id.clone())),
};
if let Err(e) = self.hub.store.put_device(&device) {
tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");
return Err(Kept::Unsaved);
}
- Ok(owner)
+ Ok(())
}
- /// This computer's account, or what to tell a phone of another account.
- fn owner_for(&self, account: &Certified) -> Result<Option<Owner>, String> {
+ /// This computer's account, or what to tell a phone of another account, or one with none.
+ fn owner_for(&self, account: Option<&Certified>) -> Result<Option<Owner>, String> {
let owner = owner::owner(&self.hub.store);
+ let Some(account) = account else {
+ return if owner.is_some() { Err(IN_AN_ACCOUNT.to_owned()) } else { Ok(None) };
+ };
if let Some(owner) = owner.as_ref().filter(|o| o.user_id != account.user_id) {
let whose =
owner.email.as_deref().map_or_else(|| "another".into(), |e| format!("{}'s", certificate::masked(e)));
@@ -144,34 +202,32 @@ impl Channel {
async fn ask(
&self,
id: u64,
- name: &str,
- platform: &str,
- email: Option<&str>,
+ question: Question,
incoming: &mut mpsc::Receiver<Value>,
- ) -> Result<(), CloseWith> {
- let Ok(device_key) = crypto::unb64_n::<32>(&self.key) else { return Err(PROTOCOL) };
- let code = crypto::pair_check_code(&device_key, &self.hub.identity.sign_pub());
- let let_in = tokio::select! {
- let_in = pairing_requests::ask(&self.hub, name, platform, email, code) => let_in,
+ ) -> Result<Answer, CloseWith> {
+ let answer = tokio::select! {
+ answer = pairing_requests::ask(&self.hub, question) => answer,
// Nothing else comes on a pairing channel: its end means the phone gave up.
() = async { while incoming.recv().await.is_some() {} } => return Err((close::NORMAL, "")),
};
- if let_in { Ok(()) } else { Err(self.refuse(id, "The computer didn't let this phone in.", "declined").await) }
+ if answer == Answer::Decline {
+ return Err(self.refuse(id, "The computer didn't let this phone in.", "declined").await);
+ }
+ Ok(answer)
}
- /// The signed claim for `{claimId, nonce}`, or null without one, or with the Codync cloud off or a private
- /// relay here (no account to join).
- async fn claim(&self, claim: &Value, user_id: &str) -> Value {
- let (Some(claim_id), Some(nonce)) = (claim["claimId"].as_str(), claim["nonce"].as_str()) else {
- return Value::Null;
+ /// The computer said to join the phone's account: its signature on the phone's claim.
+ async fn sign_claim(&self, request: &Request<'_>) -> Result<Value, CloseWith> {
+ let (Some((claim_id, nonce)), Some(account)) = (request.claim, request.account) else {
+ return Err(self.refuse(request.id, TRY_AGAIN, "unauthorized").await);
};
- if crate::remote::cloud::codync_url(&self.hub).is_err() {
- return Value::Null;
+ match owner::sign_claim(&self.hub, claim_id, nonce, &account.user_id).await {
+ Ok(signed) => Ok(signed),
+ Err(e) => {
+ tracing::warn!(error = format!("{e:#}"), "couldn't sign a pairing phone's claim");
+ Err(self.refuse(request.id, TRY_AGAIN, "unauthorized").await)
+ }
}
- owner::sign_claim(&self.hub, claim_id, nonce, user_id).await.unwrap_or_else(|e| {
- tracing::info!(error = format!("{e:#}"), "paired without joining the account");
- Value::Null
- })
}
async fn refuse(&self, id: u64, message: &str, reason: &'static str) -> CloseWith {
@@ -180,6 +236,13 @@ impl Channel {
}
}
+/// The phone's name and platform, when they're usable.
+fn read_identity(b: &Value) -> Option<(&str, &str)> {
+ let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100)?;
+ let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"))?;
+ Some((name, platform))
+}
+
/// Waits for the phone's one `pair`: its id and body.
async fn read_pair(incoming: &mut mpsc::Receiver<Value>, mut opener: Opener) -> Result<(u64, Value), CloseWith> {
let deadline = Instant::now() + PAIRING_MAX_AGE;
diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rs
index ecd20501..1bbb17bd 100644
--- a/host/src/remote/channel/tests/accounts.rs
+++ b/host/src/remote/channel/tests/accounts.rs
@@ -1,6 +1,7 @@
//! Pairing proves the phone's account (docs/plans/require-sign-in.md, phase 2).
use super::*;
+use crate::store::DeviceAccount;
async fn pairing_phone(hub: &Arc<Hub>) -> (Phone, String) {
let code = hub.pairing.locked().issue().code;
@@ -18,16 +19,184 @@ async fn asked(hub: &Hub, p: &mut Phone, body: Value) -> Value {
hub.pairing_requests.json()[0].clone()
}
+fn signed_out_body(code: &str) -> Value {
+ json!({"code": code, "name": "Pixel", "platform": "android"})
+}
+
+fn decide(hub: &Hub, request: &Value, approve: bool, join: Option<bool>) {
+ crate::remote::pairing_requests::decide(hub, request["requestId"].as_str().unwrap(), approve, join).unwrap();
+}
+
#[tokio::test]
-async fn an_app_without_a_certificate_is_told_to_update_and_the_code_stays() {
+async fn a_computer_in_an_account_turns_away_a_signed_out_phone_and_the_code_stays() {
let hub = temp_hub();
let (mut p, code) = pairing_phone(&hub).await;
- p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Old app", "platform": "ios"}})).await;
- let (close, reject) = p.recv().await.unwrap_err();
- assert_eq!((close, reject["code"].as_str()), (4400, Some("unsupportedVersion")));
+ let reply = p.call(1, "pair", signed_out_body(&code)).await;
+ assert_eq!(reply["err"]["status"], 403);
+ assert!(reply["err"]["message"].as_str().unwrap().contains("Sign in to that account"));
+ assert!(hub.store.device(&p.dk()).is_none());
assert!(hub.pairing.locked().open(), "the code isn't used up");
}
+#[tokio::test]
+async fn a_computer_in_no_account_asks_about_a_signed_out_phone_and_never_joins() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let (mut p, code) = pairing_phone(&hub).await;
+ let mut body = signed_out_body(&code);
+ body["claim"] = json!({"claimId": "clm_1", "nonce": "n1"});
+ let request = asked(&hub, &mut p, body).await;
+ assert_eq!((request["canJoin"].as_bool(), request["phoneOnly"].as_bool()), (Some(false), Some(true)));
+ decide(&hub, &request, true, None);
+ let reply = p.recv().await.unwrap();
+ assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());
+ assert!(reply["ok"]["claim"].is_null(), "a phone with no account brings no join");
+ let device = hub.store.device(&p.dk()).unwrap();
+ assert_eq!(device.account, DeviceAccount::SignedOut);
+
+ let mut p = Phone::direct(&hub, p.key.clone());
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ assert!(p.call(1, "hello", json!({})).await["ok"]["cloud"].is_null(), "phones go over Wi-Fi or Tailscale");
+}
+
+#[tokio::test]
+async fn a_signed_out_phone_cant_pair_over_the_codync_relay() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let code = hub.pairing.locked().issue().code;
+ let key = SigningKey::from_bytes(&crypto::random());
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "p".into(), dk, pair: true });
+ p.hello(&hub, true).await;
+ let reply = p.call(1, "pair", signed_out_body(&code)).await;
+ assert_eq!(reply["err"]["status"], 403);
+ assert!(hub.pairing_requests.json().is_empty(), "the computer isn't even asked");
+}
+
+#[tokio::test]
+async fn a_signed_in_phone_on_the_relay_is_let_in_only_if_the_computer_joins() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let code = hub.pairing.locked().issue().code;
+ let key = SigningKey::from_bytes(&crypto::random());
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "p".into(), dk, pair: true });
+ p.hello(&hub, true).await;
+ let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");
+ body["claim"] = json!({"claimId": "clm_1", "nonce": "n1"});
+ let request = asked(&hub, &mut p, body).await;
+ assert_eq!((request["canJoin"].as_bool(), request["phoneOnly"].as_bool()), (Some(true), Some(false)));
+ decide(&hub, &request, true, None);
+ assert_eq!(p.recv().await.unwrap()["ok"]["claim"]["computerId"], hub.identity.computer_id());
+}
+
+#[tokio::test]
+async fn a_signed_in_phone_on_the_relay_without_a_claim_tries_again_and_the_code_stays() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let code = hub.pairing.locked().issue().code;
+ let key = SigningKey::from_bytes(&crypto::random());
+ let dk = crypto::b64(key.verifying_key().as_bytes());
+ let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "p".into(), dk, pair: true });
+ p.hello(&hub, true).await;
+ let reply = p.call(1, "pair", pair_body(&p, &code, "Pixel", "android", "user_2")).await;
+ assert_eq!(reply["err"]["status"], 403);
+ assert!(hub.pairing_requests.json().is_empty(), "the computer isn't asked about a join that can't happen");
+ assert!(hub.pairing.locked().valid(&code));
+}
+
+#[tokio::test]
+async fn without_a_claim_a_direct_phone_is_only_let_in_and_can_add_the_computer_later() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let (mut p, code) = pairing_phone(&hub).await;
+ let body = pair_body(&p, &code, "Pixel", "android", "user_2");
+ let request = asked(&hub, &mut p, body).await;
+ assert_eq!((request["canJoin"].as_bool(), request["phoneOnly"].as_bool()), (Some(false), Some(true)));
+ decide(&hub, &request, true, None);
+ assert!(p.recv().await.unwrap()["ok"].is_object());
+}
+
+#[tokio::test]
+async fn a_claim_that_cant_be_signed_leaves_the_phone_out_and_the_code_valid() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let (mut p, code) = pairing_phone(&hub).await;
+ let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");
+ body["claim"] = json!({"claimId": "clm\n1", "nonce": "n1"});
+ let request = asked(&hub, &mut p, body).await;
+ decide(&hub, &request, true, None);
+ assert_eq!(p.recv().await.unwrap()["err"]["status"], 403);
+ assert!(hub.store.device(&p.dk()).is_none());
+ assert!(hub.pairing.locked().valid(&code));
+}
+
+#[tokio::test]
+async fn a_signed_in_phone_may_stay_out_of_the_account_and_add_the_computer_later() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let (mut p, code) = pairing_phone(&hub).await;
+ let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");
+ body["claim"] = json!({"claimId": "clm_1", "nonce": "n1"});
+ let request = asked(&hub, &mut p, body).await;
+ assert_eq!((request["canJoin"].as_bool(), request["phoneOnly"].as_bool()), (Some(true), Some(true)));
+ decide(&hub, &request, true, Some(false));
+ assert!(p.recv().await.unwrap()["ok"]["claim"].is_null(), "not asked to join, the claim isn't signed");
+ assert_eq!(hub.store.device(&p.dk()).unwrap().account, DeviceAccount::Of("user_2".into()));
+
+ let mut p = Phone::direct(&hub, p.key.clone());
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ let hello = p.call(1, "hello", json!({})).await;
+ assert_eq!(hello["ok"]["canJoinAccount"], true);
+ assert!(hello["ok"]["cloud"].is_null());
+
+ // Adding it later asks the computer again; saying no signs nothing.
+ let join = json!({"claimId": "clm_2", "nonce": "n2",
+ "certificate": crate::remote::certificate::test_certificate(&p.dk(), "user_2")});
+ p.send(json!({"id": 2, "m": "joinAccount", "b": join})).await;
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ let request = hub.pairing_requests.json()[0].clone();
+ assert_eq!((request["canJoin"].as_bool(), request["phoneOnly"].as_bool()), (Some(true), Some(false)));
+ decide(&hub, &request, false, None);
+ assert!(p.recv().await.unwrap()["err"].is_object());
+
+ p.send(json!({"id": 3, "m": "joinAccount", "b": join})).await;
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ decide(&hub, &hub.pairing_requests.json()[0].clone(), true, None);
+ let claim = p.recv().await.unwrap();
+ let input = crypto::claim_input("clm_2", "n2", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());
+ let sig = crypto::unb64_n::<64>(claim["ok"]["sig"].as_str().unwrap()).unwrap();
+ crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();
+ assert!(p.call(4, "hello", json!({})).await["ok"]["cloud"].is_string(), "the relay is theirs once it has joined");
+}
+
+#[tokio::test]
+async fn a_signed_out_phone_that_signed_in_stays_when_it_brings_the_computer_along() {
+ let hub = unowned_hub();
+ hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
+ let (mut p, code) = pairing_phone(&hub).await;
+ let request = asked(&hub, &mut p, signed_out_body(&code)).await;
+ decide(&hub, &request, true, None);
+ p.recv().await.unwrap();
+ let mut p = Phone::direct(&hub, p.key.clone());
+ assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ let join = json!({"claimId": "clm_2", "nonce": "n2",
+ "certificate": crate::remote::certificate::test_certificate(&p.dk(), "user_2")});
+ p.send(json!({"id": 1, "m": "joinAccount", "b": join})).await;
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ decide(&hub, &hub.pairing_requests.json()[0].clone(), true, None);
+ assert!(p.recv().await.unwrap()["ok"]["sig"].is_string());
+ let owner = crate::remote::cloud::Owner { user_id: "user_2".into(), email: None };
+ crate::remote::owner::remember(&hub, Some(&owner)).unwrap();
+ assert!(hub.store.device(&p.dk()).is_some(), "it recorded its account before the computer joined");
+}
+
#[tokio::test]
async fn a_phone_of_another_account_is_refused_with_the_owner_masked() {
let hub = temp_hub();
@@ -84,22 +253,17 @@ async fn a_computer_in_no_account_asks_then_joins_the_phones() {
let device_key = crypto::unb64_n::<32>(&p.dk()).unwrap();
let expected = crypto::pair_check_code(&device_key, &hub.identity.sign_pub());
assert_eq!(request["code"], expected.as_str(), "the code the phone shows too");
- crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), approve).unwrap();
+ decide(&hub, &request, approve, None);
let reply = p.recv().await.unwrap();
if approve {
assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());
- assert_eq!(hub.store.device(&p.dk()).unwrap().account.as_deref(), Some("user_2"));
+ assert_eq!(hub.store.device(&p.dk()).unwrap().account, DeviceAccount::Of("user_2".into()));
let claim = &reply["ok"]["claim"];
assert_eq!(claim["computerId"], hub.identity.computer_id());
let input =
crypto::claim_input("clm_1", "n1", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());
let sig = crypto::unb64_n::<64>(claim["sig"].as_str().unwrap()).unwrap();
crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();
- // Taken out again before it pulled that it joined: a state pull that still says no account brings no
- // later join for the account it signed for.
- hub.cloud_synced.store(true, std::sync::atomic::Ordering::Release);
- crate::remote::owner::remember(&hub, None).unwrap();
- assert_eq!(crate::remote::owner::joinable_by(&hub, &p.dk()).unwrap(), None);
} else {
assert_eq!(reply["err"]["status"], 403);
assert!(hub.store.device(&p.dk()).is_none());
@@ -117,37 +281,10 @@ async fn a_phone_let_in_after_the_computer_joined_another_account_stays_out() {
// While the computer asks, another phone brings it into user_3's account.
let owner = crate::remote::cloud::Owner { user_id: "user_3".into(), email: Some("[email protected]".into()) };
crate::remote::owner::remember(&hub, Some(&owner)).unwrap();
- crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), true).unwrap();
+ decide(&hub, &request, true, None);
let reply = p.recv().await.unwrap();
assert_eq!(reply["err"]["status"], 403);
assert!(reply["err"]["message"].as_str().unwrap().contains("a•••@example.com's account"));
assert!(hub.store.device(&p.dk()).is_none(), "user_2's phone stays out of user_3's computer");
assert!(hub.pairing.locked().valid(&code), "a refused phone leaves the code");
}
-
-#[tokio::test]
-async fn a_phone_let_in_without_joining_finishes_the_join_later() {
- let hub = unowned_hub();
- hub.store.kv_set("test_cloud_url", "https://dev-api.codync.dev").unwrap();
- // Paired without a claim: the phone couldn't start one, so the computer stayed out of the account.
- let (mut p, code) = pairing_phone(&hub).await;
- let body = pair_body(&p, &code, "Pixel", "android", "user_2");
- let request = asked(&hub, &mut p, body).await;
- crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), true).unwrap();
- assert!(p.recv().await.unwrap()["ok"]["claim"].is_null());
- hub.cloud_synced.store(true, std::sync::atomic::Ordering::Release);
-
- let mut p = Phone::direct(&hub, p.key.clone());
- assert!(matches!(p.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
- assert_eq!(p.call(1, "hello", json!({})).await["ok"]["joinAccount"], true);
- let claim = p.call(2, "joinAccount", json!({"claimId": "clm_2", "nonce": "n2"})).await;
- let input = crypto::claim_input("clm_2", "n2", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());
- let sig = crypto::unb64_n::<64>(claim["ok"]["sig"].as_str().unwrap()).unwrap();
- crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();
-
- // Signed once: whether that claim completed (and the computer was taken out again) or not, a state pull that
- // still says no account brings no second join.
- crate::remote::owner::remember(&hub, None).unwrap();
- assert_eq!(p.call(3, "hello", json!({})).await["ok"]["joinAccount"], false);
- assert!(p.call(4, "joinAccount", json!({"claimId": "clm_3", "nonce": "n3"})).await["err"].is_object());
-}
diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rs
index ff1b644a..6aff5b6d 100644
--- a/host/src/remote/cloud.rs
+++ b/host/src/remote/cloud.rs
@@ -6,7 +6,7 @@
use crate::LockExt;
use crate::hub::Hub;
use crate::remote::crypto::{self, b64};
-use crate::store::{Device, DeviceSource, Scope, Store, now_ms};
+use crate::store::{Device, DeviceAccount, DeviceSource, Scope, Store, now_ms};
use anyhow::{Context, Result, anyhow, bail};
use reqwest::Method;
use serde::{Deserialize, Serialize};
@@ -63,8 +63,9 @@ pub struct CloudStatus {
pub assistants: bool,
/// Whose relay: on a private one there is no account, access request or relayed screen.
pub relay: RelayKind,
- /// In no account while it could join one (the Codync cloud on): a signed-in phone that pairs asks to bring it
- /// into its account. Kept by [`update_status`], so every app words it the same.
+ /// In no account while it could join one (the Codync cloud on): a signed-in phone that pairs is asked about it,
+ /// and phones reach it only over Wi-Fi or Tailscale until it joins. Kept by [`update_status`], so every app words
+ /// it the same.
pub can_join_account: bool,
/// Turned on, the cloud would leave this computer in no account on a Codync cloud, so the desktop app asks to add
/// it first. Known with the cloud off too, unlike the fields above; kept by [`update_status`].
@@ -122,6 +123,12 @@ pub struct Cloud {
pub(super) account: Mutex<()>,
/// Bumped when the cloud is turned on or off or pointed elsewhere: the relay restarts.
pub config: watch::Sender<u64>,
+ /// Bumped when this computer's account changes: phones read the relay address again.
+ pub account_changed: watch::Sender<u64>,
+ /// Wakes a computer without its relay socket: a pairing code or a claim needs it now.
+ pub relay_wake: tokio::sync::Notify,
+ /// When the relay no longer stays up for a claim just signed (`owner::wants_relay`).
+ pub(super) join_pending_until: Mutex<i64>,
}
impl Default for Cloud {
@@ -132,6 +139,9 @@ impl Default for Cloud {
pulling: tokio::sync::Mutex::new(()),
account: Mutex::default(),
config: watch::Sender::new(0),
+ account_changed: watch::Sender::new(0),
+ relay_wake: tokio::sync::Notify::new(),
+ join_pending_until: Mutex::default(),
}
}
}
@@ -588,11 +598,17 @@ pub async fn decide(hub: &Hub, id: &str, approve: bool, how: Approval) -> Result
created_at: now_ms(),
last_seen_at: None,
// Approved through the account the computer is in.
- account: super::owner::owner(&hub.store).map(|o| o.user_id),
+ account: super::owner::owner(&hub.store).map_or(DeviceAccount::Unrecorded, |o| DeviceAccount::Of(o.user_id)),
};
hub.store.put_device(&device)?;
tracing::info!(grant_id = grant, "account device approved");
- crate::analytics::device_paired(hub, crate::analytics::Via::Account, &device.platform, how == Approval::Auto);
+ crate::analytics::device_paired(
+ hub,
+ crate::analytics::Via::Account,
+ &device.platform,
+ how == Approval::Auto,
+ crate::analytics::PairedAccount::Joined,
+ );
hub.auth_changed();
Ok(())
}
@@ -687,7 +703,7 @@ mod tests {
lease_until: Some(now_ms() + 1000),
created_at: now_ms(),
last_seen_at: None,
- account: None,
+ account: DeviceAccount::Unrecorded,
}
}
diff --git a/host/src/remote/discovery.rs b/host/src/remote/discovery.rs
new file mode 100644
index 00000000..44fc1bdc
--- /dev/null
+++ b/host/src/remote/discovery.rs
@@ -0,0 +1,150 @@
+//! Lets phones find a computer in no account on the local network. Such a computer has no relay to tell its phones a
+//! new address (docs/plans/optional-sign-in.md), so it advertises its addresses over mDNS. A phone trusts nothing it
+//! finds this way: it dials the address and the handshake checks the computer's pinned key.
+//!
+//! A computer in an account advertises nothing: the relay carries its address, and multicast needs a permission on
+//! some systems that it shouldn't have to ask for.
+
+use crate::analytics::{self, DiscoveryStage};
+use crate::hub::Hub;
+use crate::remote::owner;
+use anyhow::{Context as _, Result};
+use mdns_sd::{ServiceDaemon, ServiceInfo};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// The service phones browse for; `NSBonjourServices` on iOS and `LocalDiscovery.kt` name it too.
+const SERVICE: &str = "_codync._tcp.local.";
+/// How often addresses are read again: a network change shows up within this.
+const EVERY: Duration = Duration::from_mins(1);
+/// One TXT entry holds 255 bytes, its key included.
+const MAX_URLS_LEN: usize = 240;
+
+/// Everyone on the network reads this, and it's for finding a computer there: Tailscale names and addresses stay out.
+fn on_this_network(url: &str) -> bool {
+ let host = url.split("://").nth(1).unwrap_or(url);
+ let tailscale_ip = host.split('.').take(2).map(str::parse::<u8>).collect::<Vec<_>>();
+ !host.contains(".ts.net") && !matches!(tailscale_ip[..], [Ok(100), Ok(64..=127)])
+}
+
+/// As many of this network's addresses as fit in one TXT entry, comma-separated, best first.
+fn urls_entry(urls: &[String]) -> String {
+ let mut entry = String::new();
+ for url in urls.iter().filter(|url| on_this_network(url)) {
+ if entry.len() + url.len() + 1 > MAX_URLS_LEN {
+ break;
+ }
+ if !entry.is_empty() {
+ entry.push(',');
+ }
+ entry.push_str(url);
+ }
+ entry
+}
+
+struct Advertising {
+ daemon: ServiceDaemon,
+ fullname: String,
+ urls: String,
+}
+
+impl Advertising {
+ fn start(hub: &Hub, urls: String) -> Result<Self> {
+ let daemon = ServiceDaemon::new().context("starting mDNS")?;
+ let fullname = publish(&daemon, hub, &urls)?;
+ Ok(Self { daemon, fullname, urls })
+ }
+
+ fn stop(self) {
+ if let Err(e) = self.daemon.unregister(&self.fullname) {
+ tracing::debug!(error = format!("{e:#}"), "couldn't withdraw the mDNS service");
+ }
+ if let Err(e) = self.daemon.shutdown() {
+ tracing::debug!(error = format!("{e:#}"), "couldn't stop mDNS");
+ }
+ }
+}
+
+/// Publishes (or, for the same name, replaces) this computer's record. Returns its full name.
+fn publish(daemon: &ServiceDaemon, hub: &Hub, urls: &str) -> Result<String> {
+ let id = hub.identity.computer_id();
+ let info = ServiceInfo::new(
+ SERVICE,
+ &id,
+ &format!("codync-{id}.local."),
+ "",
+ hub.port,
+ &[("id", id.as_str()), ("urls", urls)][..],
+ )
+ .context("describing the mDNS service")?
+ .enable_addr_auto();
+ let fullname = info.get_fullname().to_owned();
+ daemon.register(info).context("publishing the mDNS service")?;
+ Ok(fullname)
+}
+
+/// Keeps the record current while this computer is in no account.
+pub async fn run(hub: Arc<Hub>) {
+ let mut advertising: Option<Advertising> = None;
+ let mut account = hub.cloud.account_changed.subscribe();
+ // Tried again each round; analytics hears of it once.
+ let mut reported = false;
+ let mut failed = |hub: &Hub, stage, e: &anyhow::Error| {
+ tracing::info!(error = format!("{e:#}"), "not advertising on the local network");
+ if !std::mem::replace(&mut reported, true) {
+ analytics::discovery_failed(hub, stage);
+ }
+ };
+ loop {
+ let port = hub.port;
+ let urls =
+ tokio::task::spawn_blocking(move || crate::service::interface_addresses(port)).await.unwrap_or_default();
+ let urls = urls_entry(&urls);
+ let wanted = owner::owner(&hub.store).is_none() && !urls.is_empty();
+ advertising = match (advertising, wanted) {
+ (Some(running), false) => {
+ running.stop();
+ None
+ }
+ (None, false) => None,
+ (None, true) => Advertising::start(&hub, urls).inspect_err(|e| failed(&hub, DiscoveryStage::Start, e)).ok(),
+ (Some(mut running), true) => {
+ if running.urls != urls {
+ match publish(&running.daemon, &hub, &urls) {
+ Ok(_) => running.urls = urls,
+ Err(e) => failed(&hub, DiscoveryStage::Update, &e),
+ }
+ }
+ Some(running)
+ }
+ };
+ let _ = tokio::time::timeout(EVERY, account.changed()).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_this_networks_addresses_are_advertised() {
+ let urls = [
+ "http://kevins-mac.tail1234.ts.net:19222".to_owned(),
+ "http://100.101.102.103:19222".to_owned(),
+ "http://192.168.1.5:19222".to_owned(),
+ "http://100.200.1.1:19222".to_owned(),
+ ];
+ assert_eq!(urls_entry(&urls), "http://192.168.1.5:19222,http://100.200.1.1:19222");
+ }
+
+ #[test]
+ fn the_addresses_fit_one_txt_entry() {
+ let one = "http://192.168.1.5:19222".to_owned();
+ assert_eq!(urls_entry(std::slice::from_ref(&one)), one);
+ assert_eq!(urls_entry(&[one.clone(), "http://10.0.0.2:19222".into()]), format!("{one},http://10.0.0.2:19222"));
+ let many = vec![one; 40];
+ let entry = urls_entry(&many);
+ assert!(entry.len() <= MAX_URLS_LEN, "{}", entry.len());
+ assert!(entry.split(',').all(|url| url.ends_with(":19222")), "cut between addresses, not inside one");
+ }
+}
diff --git a/host/src/remote/mod.rs b/host/src/remote/mod.rs
index 37d28d84..425b2797 100644
--- a/host/src/remote/mod.rs
+++ b/host/src/remote/mod.rs
@@ -6,6 +6,7 @@ pub mod channel;
pub mod cloud;
mod cloud_url;
pub mod crypto;
+pub mod discovery;
pub mod identity;
pub mod owner;
pub mod pairing_requests;
diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rs
index 7a916ddf..d92eedff 100644
--- a/host/src/remote/owner.rs
+++ b/host/src/remote/owner.rs
@@ -3,18 +3,18 @@
//! (docs/architecture/connections.md: "the host changed its account").
use super::cloud::{self, Approval, Owner, RelayKind};
-use super::crypto;
+use super::pairing_requests::{self, Answer, Question};
+use super::{certificate, crypto};
use crate::LockExt;
use crate::chat::team::assistant;
use crate::hub::Hub;
-use crate::store::Store;
-use anyhow::{Result, bail};
+use crate::store::{DeviceAccount, Store, now_ms};
+use anyhow::{Context as _, Result, anyhow, bail};
use serde_json::{Value, json};
-use std::sync::atomic::Ordering;
const OWNER: &str = "account_owner";
-/// The accounts this computer signed a claim for since its account last changed (`note_signed`).
-const SIGNED: &str = "account_claims_signed";
+/// How long the relay stays up after signing a claim: the phone completes it, and the cloud says so over the relay.
+const JOIN_WAIT_MS: i64 = 5 * 60 * 1000;
/// The account as last seen from the cloud; `None` when the computer isn't in one (or never heard yet), and
/// with the Codync cloud off or a private relay, where it is in no account either (as its status says).
@@ -35,12 +35,20 @@ pub fn joins_account_on_enable(store: &Store) -> bool {
/// Records the account the cloud reports. When it is another one than before (joining one, moving, or leaving),
/// every device let in for another account goes; joining a first account keeps the phones paired before devices
-/// recorded their account. The first record after an upgrade only records. The devices go first, so a failure
-/// leaves the old account recorded and the next pull tries again. Any change of account also forgets the accounts
-/// claims were signed for before it (`note_signed`).
+/// recorded their account. In an account, phones that paired with no account always go, and a claim being completed
+/// is over, so it can't outlive the account. The first record after an upgrade only records. The devices go first, so
+/// a failure leaves the old account recorded and the next pull tries again.
pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
let saved = serde_json::to_string(&now)?;
let _change = hub.cloud.account.locked();
+ if now.is_some() {
+ *hub.cloud.join_pending_until.locked() = 0;
+ let gone = hub.store.drop_no_account_devices()?;
+ if !gone.is_empty() {
+ tracing::info!(devices = gone.len(), "the computer is in an account; phones with no account are gone");
+ hub.auth_changed();
+ }
+ }
let before = hub.store.kv_get(OWNER);
if before.as_deref() == Some(saved.as_str()) {
return Ok(());
@@ -48,20 +56,18 @@ pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {
let before_user =
before.as_deref().and_then(|b| serde_json::from_str::<Option<Owner>>(b).ok().flatten()).map(|o| o.user_id);
let now_user = now.map(|o| o.user_id.as_str());
- if before_user.as_deref() != now_user {
- if before.is_some() {
- let gone = hub.store.keep_devices_of(now_user, before_user.is_none())?;
- tracing::info!(
- devices = gone.len(),
- "the computer changed its account; the old account's devices are gone"
- );
- if !gone.is_empty() {
- hub.auth_changed();
- }
+ if before_user.as_deref() != now_user && before.is_some() {
+ let gone = hub.store.keep_devices_of(now_user, before_user.is_none())?;
+ tracing::info!(devices = gone.len(), "the computer changed its account; the old account's devices are gone");
+ if !gone.is_empty() {
+ hub.auth_changed();
}
- hub.store.kv_delete(SIGNED)?;
}
- hub.store.kv_set(OWNER, &saved)
+ hub.store.kv_set(OWNER, &saved)?;
+ // Phones read the relay address in `hello`, and the relay stays up only in an account.
+ hub.cloud.account_changed.send_modify(|n| *n += 1);
+ hub.cloud.relay_wake.notify_one();
+ Ok(())
}
/// Runs `f` while the account can't change (`remember` waits), so a phone `f` saves against the account it reads
@@ -83,40 +89,73 @@ pub fn out_of_account(hub: &Hub) -> Result<()> {
Ok(())
}
-/// The account the device `key` may bring this computer into (`joinAccount`), when a pairing let the phone in
-/// without the computer signing a claim for its account (the phone couldn't start one, or the cloud was off or a
-/// private relay). Only on the Codync cloud, with this connection's state pulled and no account yet, for the account
-/// the phone paired from, only when no device of another account would lose access by it, and never for an account
-/// this computer signed a claim for since its account last changed (`note_signed`).
-pub fn joinable_by(hub: &Hub, key: &str) -> Result<Option<String>> {
- if cloud::codync_url(hub).is_err() || !hub.cloud_synced.load(Ordering::Acquire) || owner(&hub.store).is_some() {
- return Ok(None);
- }
- let Some(account) = hub.store.device(key).and_then(|d| d.account) else { return Ok(None) };
- let devices = hub.store.devices()?;
- let alone = devices.iter().all(|d| d.account.as_ref().is_none_or(|a| *a == account));
- Ok((alone && !signed_for(&hub.store)?.contains(&account)).then_some(account))
+/// Whether this computer could join an account: on the Codync cloud, and in none yet.
+pub fn can_join(hub: &Hub) -> bool {
+ cloud::codync_url(hub).is_ok() && owner(&hub.store).is_none()
}
-/// Notes the account a claim is about to be signed for. That claim may complete and the computer be taken out of
-/// the account again before it pulls its state, which then still says no account: until its account changes, the
-/// computer doesn't offer that account a later join, so it never comes back into an account it was taken out of.
-fn note_signed(hub: &Hub, user_id: &str) -> Result<()> {
- let _change = hub.cloud.account.locked();
- let mut signed = signed_for(&hub.store)?;
- if !signed.iter().any(|u| u == user_id) {
- signed.push(user_id.to_owned());
- hub.store.kv_set(SIGNED, &serde_json::to_string(&signed)?)?;
- }
- Ok(())
+/// A claim was signed moments ago, and the phone or the app is completing it.
+fn joining(hub: &Hub) -> bool {
+ now_ms() < *hub.cloud.join_pending_until.locked()
+}
+
+/// A private relay is the user's own; the Codync relay is for a computer in an account
+/// (docs/plans/optional-sign-in.md).
+fn relay_is_open(hub: &Hub, address: &cloud::Address) -> bool {
+ address.kind == RelayKind::Private || owner(&hub.store).is_some()
+}
+
+/// The relay address the phone with `key` gets in `hello`: on an open relay, or while a claim is being completed if
+/// it has an account, as the phone finishing the join goes on through the relay.
+pub fn url_for_phones(hub: &Hub, key: &str) -> Option<String> {
+ let address = cloud::current(&hub.store)?;
+ let has_account = || hub.store.device(key).is_some_and(|d| matches!(d.account, DeviceAccount::Of(_)));
+ (relay_is_open(hub, &address) || (joining(hub) && has_account())).then_some(address.url)
+}
+
+/// Whether this computer needs its relay socket. In no account it has one only while a phone may be pairing or
+/// finishing a join through it, so an unused computer holds nothing open on the Codync relay.
+pub fn wants_relay(hub: &Hub, address: &cloud::Address) -> bool {
+ relay_is_open(hub, address) || joining(hub) || hub.pairing.locked().open()
+}
+
+/// The names of the phones that lose access if this computer joins `user_id`'s account, leaving out `key`, which
+/// asks to bring it there.
+pub fn removed_by_joining(hub: &Hub, user_id: &str, key: &str) -> Vec<String> {
+ let devices = hub.store.devices().unwrap_or_else(|e| {
+ tracing::warn!(error = format!("{e:#}"), "couldn't list the phones a join would remove");
+ vec![]
+ });
+ let goes = |d: &crate::store::Device| match &d.account {
+ DeviceAccount::Unrecorded => false,
+ DeviceAccount::SignedOut => true,
+ DeviceAccount::Of(account) => account != user_id,
+ };
+ devices.into_iter().filter(|d| d.key != key && goes(d)).map(|d| d.name).collect()
}
-fn signed_for(store: &Store) -> Result<Vec<String>> {
- store.kv_read(SIGNED)?.map_or(Ok(vec![]), |s| Ok(serde_json::from_str(&s)?))
+/// `joinAccount`: a paired phone asks to bring this computer into its account. The computer confirms, then signs the
+/// claim the phone made; the phone, which holds the account's session, completes it.
+pub async fn join_from_phone(hub: &Hub, key: &str, certificate: &Value, claim_id: &str, nonce: &str) -> Result<Value> {
+ if !can_join(hub) {
+ bail!("This computer can't join an account now.");
+ }
+ let account = certificate::check(certificate, key, now_ms())
+ .map_err(|_| anyhow!("Couldn't confirm your Codync account. Sign in again."))?;
+ let device = hub.store.device(key).context("this phone isn't paired with this computer")?;
+ let about = Question::about(hub, key, &device.name, &device.platform, Some(&account))?;
+ let answer = pairing_requests::ask(hub, Question { can_join: true, phone_only: false, ..about }).await;
+ crate::analytics::join_from_phone_answered(hub, answer == Answer::Join);
+ if answer != Answer::Join {
+ bail!("The computer stayed out of this account.");
+ }
+ // The phone stays when the computer joins, even if it paired with no account.
+ hub.store.set_device_account(key, &account.user_id)?;
+ sign_claim(hub, claim_id, nonce, &account.user_id).await
}
/// Signs this computer into an account claim (§4.2 A) for a signed-in app to complete: the desktop app's
-/// Add to account, a phone pairing with a computer in no account, or a phone finishing that join later.
+/// Add to account, or a phone pairing with a computer in no account or adding it later.
pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -> Result<Value> {
cloud::require_accounts(&hub.store)?;
for (k, v) in [("claimId", claim_id), ("nonce", nonce), ("userId", user_id)] {
@@ -125,7 +164,8 @@ pub async fn sign_claim(hub: &Hub, claim_id: &str, nonce: &str, user_id: &str) -
bail!("`{k}` is invalid");
}
}
- note_signed(hub, user_id)?;
+ *hub.cloud.join_pending_until.locked() = now_ms() + JOIN_WAIT_MS;
+ hub.cloud.relay_wake.notify_one();
let computer_id = hub.identity.computer_id();
let box_key = hub.identity.box_pub_b64();
let input = crypto::claim_input(claim_id, nonce, user_id, &computer_id, &box_key);
@@ -158,7 +198,7 @@ mod tests {
Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "t".into(), 0)
}
- fn device(hub: &Hub, key: &str, account: Option<&str>) {
+ fn device(hub: &Hub, key: &str, account: DeviceAccount) {
hub.store
.put_device(&Device {
key: key.into(),
@@ -170,11 +210,15 @@ mod tests {
lease_until: None,
created_at: 1,
last_seen_at: None,
- account: account.map(Into::into),
+ account,
})
.unwrap();
}
+ fn of(user: &str) -> DeviceAccount {
+ DeviceAccount::Of(user.into())
+ }
+
fn keys(hub: &Hub) -> Vec<String> {
hub.store.devices().unwrap().into_iter().map(|d| d.key).collect()
}
@@ -186,9 +230,9 @@ mod tests {
#[test]
fn changing_accounts_drops_the_old_accounts_devices() {
let hub = hub();
- device(&hub, "a", Some("user_a"));
- device(&hub, "b", Some("user_b"));
- device(&hub, "legacy", None);
+ device(&hub, "a", of("user_a"));
+ device(&hub, "b", of("user_b"));
+ device(&hub, "legacy", DeviceAccount::Unrecorded);
// An upgraded computer records what it finds and drops nothing.
remember(&hub, Some(&account("user_a"))).unwrap();
assert_eq!(keys(&hub), ["a", "b", "legacy"]);
@@ -209,57 +253,83 @@ mod tests {
fn joining_a_first_account_keeps_the_phones_it_had() {
let hub = hub();
remember(&hub, None).unwrap();
- device(&hub, "legacy", None);
- device(&hub, "mine", Some("user_a"));
- device(&hub, "theirs", Some("user_b"));
+ device(&hub, "legacy", DeviceAccount::Unrecorded);
+ device(&hub, "mine", of("user_a"));
+ device(&hub, "theirs", of("user_b"));
remember(&hub, Some(&account("user_a"))).unwrap();
assert_eq!(keys(&hub), ["legacy", "mine"]);
}
#[test]
- fn a_phone_brings_a_computer_in_no_account_into_the_account_it_paired_from() {
+ fn phones_with_no_account_go_when_the_computer_joins_one() {
let hub = hub();
- device(&hub, "mine", Some("user_a"));
- device(&hub, "legacy", None);
- assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "not before this connection's state pull");
- hub.cloud_synced.store(true, Ordering::Release);
- assert_eq!(joinable_by(&hub, "mine").unwrap().as_deref(), Some("user_a"));
- assert_eq!(
- joinable_by(&hub, "legacy").unwrap(),
- None,
- "a phone that paired before devices recorded their account"
- );
- assert_eq!(joinable_by(&hub, "local").unwrap(), None);
- device(&hub, "theirs", Some("user_b"));
- assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "another account's phone would lose access");
- hub.store.remove_device("theirs").unwrap();
- remember(&hub, Some(&account("user_a"))).unwrap();
- assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "already in an account");
remember(&hub, None).unwrap();
- device(&hub, "mine", Some("user_a"));
- hub.store.kv_set("cloud_enabled", "false").unwrap();
- assert_eq!(joinable_by(&hub, "mine").unwrap(), None, "no account with the cloud off");
+ device(&hub, "signed-out", DeviceAccount::SignedOut);
+ device(&hub, "legacy", DeviceAccount::Unrecorded);
+ device(&hub, "mine", of("user_a"));
+ remember(&hub, None).unwrap();
+ assert_eq!(keys(&hub), ["signed-out", "legacy", "mine"], "they stay while it is in no account");
+ remember(&hub, Some(&account("user_a"))).unwrap();
+ assert_eq!(keys(&hub), ["legacy", "mine"]);
}
#[test]
- fn a_computer_taken_out_before_it_heard_it_joined_stays_out() {
+ fn a_first_record_in_an_account_also_removes_phones_with_no_account() {
let hub = hub();
+ device(&hub, "signed-out", DeviceAccount::SignedOut);
+ device(&hub, "legacy", DeviceAccount::Unrecorded);
+ remember(&hub, Some(&account("user_a"))).unwrap();
+ assert_eq!(keys(&hub), ["legacy"]);
+ }
+
+ #[test]
+ fn a_join_warns_about_the_phones_it_removes() {
+ let hub = hub();
+ device(&hub, "signed-out", DeviceAccount::SignedOut);
+ device(&hub, "legacy", DeviceAccount::Unrecorded);
+ device(&hub, "mine", of("user_a"));
+ device(&hub, "theirs", of("user_b"));
+ let removed = |key| removed_by_joining(&hub, "user_a", key).len();
+ assert_eq!(removed(""), 2, "the signed-out phone and the other account's");
+ assert_eq!(removed("signed-out"), 1, "not the phone that asks");
+ }
+
+ #[test]
+ fn phones_get_the_relay_address_only_for_a_computer_in_an_account() {
+ let hub = hub();
+ device(&hub, "mine", of("user_a"));
+ device(&hub, "signed-out", DeviceAccount::SignedOut);
+ assert!(can_join(&hub));
+ assert_eq!(url_for_phones(&hub, "mine"), None);
+ *hub.cloud.join_pending_until.locked() = now_ms() + 60_000;
+ assert!(url_for_phones(&hub, "mine").is_some(), "the phone finishing a join goes on through the relay");
+ assert_eq!(url_for_phones(&hub, "signed-out"), None, "a signed-out phone couldn't use it");
+ remember(&hub, Some(&account("user_a"))).unwrap();
+ assert!(!can_join(&hub));
+ assert!(url_for_phones(&hub, "mine").is_some());
remember(&hub, None).unwrap();
- hub.cloud_synced.store(true, Ordering::Release);
- device(&hub, "a", Some("user_a"));
- device(&hub, "b", Some("user_a"));
- // Phone a's claim completes and the computer is taken out again, both between two state pulls.
- note_signed(&hub, "user_a").unwrap();
- remember(&hub, None).unwrap();
- assert_eq!(joinable_by(&hub, "a").unwrap(), None);
- assert_eq!(joinable_by(&hub, "b").unwrap(), None, "nor through another phone of that account");
+ device(&hub, "mine", of("user_a"));
+ assert_eq!(url_for_phones(&hub, "mine"), None, "the claim ended with the join, so leaving closes the relay");
+ hub.store.kv_set("test_cloud_token", "relay-token").unwrap();
+ assert!(url_for_phones(&hub, "local").is_some(), "a private relay is the user's own");
+ assert!(!can_join(&hub), "and has no accounts to join");
+ }
- // Seen in the account and taken out, its phones go: one let in again may bring it back.
+ #[test]
+ fn a_computer_in_no_account_holds_the_relay_only_for_a_pairing_or_a_join() {
+ let hub = hub();
+ let address = cloud::current(&hub.store).unwrap();
+ assert!(!wants_relay(&hub, &address));
+ let code = hub.pairing.locked().issue().code;
+ assert!(wants_relay(&hub, &address), "a phone may pair through it");
+ assert!(hub.pairing.locked().redeem(&code));
+ assert!(!wants_relay(&hub, &address));
+ *hub.cloud.join_pending_until.locked() = now_ms() + 60_000;
+ assert!(wants_relay(&hub, &address), "the cloud says over it that the claim completed");
remember(&hub, Some(&account("user_a"))).unwrap();
+ assert!(wants_relay(&hub, &address));
remember(&hub, None).unwrap();
- assert!(hub.store.device("a").is_none());
- device(&hub, "a", Some("user_a"));
- assert_eq!(joinable_by(&hub, "a").unwrap().as_deref(), Some("user_a"));
+ assert!(!wants_relay(&hub, &address), "the claim ended with the join");
}
#[test]
diff --git a/host/src/remote/pairing_requests.rs b/host/src/remote/pairing_requests.rs
index 2449d26e..79464019 100644
--- a/host/src/remote/pairing_requests.rs
+++ b/host/src/remote/pairing_requests.rs
@@ -1,29 +1,87 @@
-//! A signed-in phone scanning a computer that isn't in an account (docs/plans/require-sign-in.md, phase 2):
-//! the computer confirms in the desktop app, the terminal UI, `codync-host pair` or `codync-host access` before
-//! the phone gets in and the computer joins the phone's account. Both screens show the same 6-digit code
+//! A phone scanning a computer that isn't in an account (docs/plans/optional-sign-in.md): the computer confirms in
+//! the desktop app, the terminal UI, `codync-host pair` or `codync-host access` before the phone gets in, and says
+//! whether it joins the phone's account. Without joining, the phone connects only over Wi-Fi or Tailscale. A paired
+//! phone adding the computer to its account later asks the same way. Both screens show the same 6-digit code
//! ([`crate::remote::crypto::pair_check_code`]).
+use super::certificate::Certified;
+use super::{crypto, owner};
use crate::LockExt;
use crate::hub::Hub;
use crate::store::now_ms;
-use anyhow::{Result, anyhow};
+use anyhow::{Result, anyhow, bail};
+use serde::Serialize;
use serde_json::{Value, json};
use std::sync::Mutex;
use std::time::Duration;
use tokio::sync::oneshot;
+/// What this computer said to a phone.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Answer {
+ /// Let it in, and join its account.
+ Join,
+ /// Let it in; this computer stays out of an account, so the phone connects only over Wi-Fi or Tailscale.
+ PhoneOnly,
+ Decline,
+}
+
+impl Answer {
+ /// The `decidePairing` body that gives this answer to `request_id`.
+ pub fn body(self, request_id: &Value) -> Value {
+ match self {
+ Self::Join => json!({"requestId": request_id, "approve": true, "join": true}),
+ Self::PhoneOnly => json!({"requestId": request_id, "approve": true, "join": false}),
+ Self::Decline => json!({"requestId": request_id, "approve": false}),
+ }
+ }
+}
+
+/// What this computer is asked about one phone.
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Question {
+ pub device_name: String,
+ pub platform: String,
+ pub email: Option<String>,
+ pub code: String,
+ /// The phone is signed in and the Codync cloud is on, so this computer can join its account.
+ pub can_join: bool,
+ /// It can stay out of an account: not when the phone came over the Codync relay, which it couldn't use afterwards.
+ pub phone_only: bool,
+ /// The phones that lose access if it joins.
+ pub removes: Vec<String>,
+}
+
+impl Question {
+ /// The phone with `key`, signed in to `account` if it has one. The caller says which answers it may get.
+ pub fn about(hub: &Hub, key: &str, device_name: &str, platform: &str, account: Option<&Certified>) -> Result<Self> {
+ Ok(Self {
+ device_name: device_name.to_owned(),
+ platform: platform.to_owned(),
+ email: account.and_then(|a| a.email.clone()),
+ code: crypto::pair_check_code(&crypto::unb64_n::<32>(key)?, &hub.identity.sign_pub()),
+ can_join: false,
+ phone_only: false,
+ removes: account.map_or_else(Vec::new, |a| owner::removed_by_joining(hub, &a.user_id, key)),
+ })
+ }
+}
+
/// How long the computer has to answer: inside the 2 minutes the relay keeps a pairing socket open, so an
/// answer still reaches the phone, which waits longer.
pub const ASK_FOR: Duration = Duration::from_secs(90);
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
struct Pending {
+ #[serde(rename = "requestId")]
id: String,
- device_name: String,
- platform: String,
- email: Option<String>,
- code: String,
+ #[serde(flatten)]
+ question: Question,
expires_at: i64,
- answer: Option<oneshot::Sender<bool>>,
+ #[serde(skip)]
+ answer: Option<oneshot::Sender<Answer>>,
}
/// The phones waiting for this computer's answer (memory only: a restart declines them).
@@ -32,34 +90,24 @@ pub struct PairingRequests(Mutex<Vec<Pending>>);
impl PairingRequests {
pub fn json(&self) -> Vec<Value> {
- self.0
- .locked()
- .iter()
- .map(|p| {
- json!({"requestId": p.id, "deviceName": p.device_name, "platform": p.platform,
- "email": p.email, "code": p.code, "expiresAt": p.expires_at})
- })
- .collect()
+ self.0.locked().iter().map(|p| json!(p)).collect()
}
}
-/// Asks this computer whether the phone may come in and bring it into `email`'s account; false when it says
-/// no or nobody answers in time. Dropping the future (the phone left) withdraws the question.
-pub async fn ask(hub: &Hub, device_name: &str, platform: &str, email: Option<&str>, code: String) -> bool {
+/// Asks this computer about a phone; [`Answer::Decline`] when it says no or nobody answers in time. Dropping the
+/// future (the phone left) withdraws the question.
+pub async fn ask(hub: &Hub, question: Question) -> Answer {
let (tx, rx) = oneshot::channel();
let id = uuid::Uuid::new_v4().to_string();
hub.pairing_requests.0.locked().push(Pending {
id: id.clone(),
- device_name: device_name.to_owned(),
- platform: platform.to_owned(),
- email: email.map(str::to_owned),
- code,
+ question,
expires_at: now_ms() + i64::try_from(ASK_FOR.as_millis()).unwrap_or(i64::MAX),
answer: Some(tx),
});
emit(hub);
let _withdraw = Withdraw { hub, id };
- matches!(tokio::time::timeout(ASK_FOR, rx).await, Ok(Ok(true)))
+ tokio::time::timeout(ASK_FOR, rx).await.ok().and_then(Result::ok).unwrap_or(Answer::Decline)
}
/// Takes a question off every screen once it is answered, unanswered, or the phone is gone.
@@ -75,17 +123,20 @@ impl Drop for Withdraw<'_> {
}
}
-/// `decidePairing`: this computer's answer to one request.
-pub fn decide(hub: &Hub, id: &str, approve: bool) -> Result<()> {
- let answer = hub
- .pairing_requests
- .0
- .locked()
- .iter_mut()
- .find(|p| p.id == id)
- .and_then(|p| p.answer.take())
- .ok_or_else(|| anyhow!("That request is gone. Scan the code again on the phone."))?;
- let _ = answer.send(approve);
+/// `decidePairing`: this computer's answer to one request. `join` says whether it joins the phone's account; left
+/// out, it joins when it can.
+pub fn decide(hub: &Hub, id: &str, approve: bool, join: Option<bool>) -> Result<()> {
+ let mut requests = hub.pairing_requests.0.locked();
+ let gone = || anyhow!("That request is gone. Scan the code again on the phone.");
+ let request = requests.iter_mut().find(|p| p.id == id).ok_or_else(gone)?;
+ let answer = match (approve, join.unwrap_or(request.question.can_join)) {
+ (false, _) => Answer::Decline,
+ (true, true) if request.question.can_join => Answer::Join,
+ (true, false) if request.question.phone_only => Answer::PhoneOnly,
+ (true, true) => bail!("This computer can't join that phone's account."),
+ (true, false) => bail!("This phone can only connect if the computer joins its account."),
+ };
+ let _ = request.answer.take().ok_or_else(gone)?.send(answer);
Ok(())
}
@@ -113,38 +164,85 @@ mod tests {
)
}
+ fn question(can_join: bool, phone_only: bool) -> Question {
+ Question {
+ device_name: "Pixel".into(),
+ platform: "android".into(),
+ email: Some("[email protected]".into()),
+ code: "123456".into(),
+ can_join,
+ phone_only,
+ removes: vec!["Old phone".into()],
+ }
+ }
+
+ async fn asking(hub: &Arc<Hub>, can_join: bool, phone_only: bool) -> (tokio::task::JoinHandle<Answer>, String) {
+ let task = tokio::spawn({
+ let hub = Arc::clone(hub);
+ async move { ask(&hub, question(can_join, phone_only)).await }
+ });
+ while hub.pairing_requests.json().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ (task, hub.pairing_requests.json()[0]["requestId"].as_str().unwrap().to_owned())
+ }
+
+ #[test]
+ fn a_question_reads_the_same_on_every_screen() {
+ let requests = PairingRequests::default();
+ requests.0.locked().push(Pending {
+ id: "r1".into(),
+ question: question(true, false),
+ expires_at: 9,
+ answer: None,
+ });
+ assert_eq!(
+ requests.json(),
+ [json!({"requestId": "r1", "deviceName": "Pixel", "platform": "android", "email": "[email protected]",
+ "code": "123456", "canJoin": true, "phoneOnly": false, "removes": ["Old phone"], "expiresAt": 9})]
+ );
+ }
+
#[tokio::test]
async fn the_computer_answers() {
let hub = hub();
- for approve in [true, false] {
- let asking = tokio::spawn({
- let hub = Arc::clone(&hub);
- async move { ask(&hub, "Pixel", "android", Some("[email protected]"), "123456".into()).await }
- });
- while hub.pairing_requests.json().is_empty() {
- tokio::task::yield_now().await;
- }
+ for (approve, join, answer) in [
+ (true, Some(true), Answer::Join),
+ (true, None, Answer::Join),
+ (true, Some(false), Answer::PhoneOnly),
+ (false, None, Answer::Decline),
+ ] {
+ let (task, id) = asking(&hub, true, true).await;
let request = hub.pairing_requests.json()[0].clone();
assert_eq!((request["deviceName"].as_str(), request["code"].as_str()), (Some("Pixel"), Some("123456")));
- decide(&hub, request["requestId"].as_str().unwrap(), approve).unwrap();
- assert_eq!(asking.await.unwrap(), approve);
+ assert_eq!(request["removes"], json!(["Old phone"]));
+ decide(&hub, &id, approve, join).unwrap();
+ assert_eq!(task.await.unwrap(), answer);
assert!(hub.pairing_requests.json().is_empty(), "answered requests go");
}
- assert!(decide(&hub, "gone", true).is_err());
+ assert!(decide(&hub, "gone", true, None).is_err());
+ }
+
+ #[tokio::test]
+ async fn only_an_answer_it_was_asked_for_counts() {
+ let hub = hub();
+ let (task, id) = asking(&hub, true, false).await;
+ assert!(decide(&hub, &id, true, Some(false)).is_err(), "a phone on the relay can't stay out of the account");
+ decide(&hub, &id, true, None).unwrap();
+ assert_eq!(task.await.unwrap(), Answer::Join);
+
+ let (task, id) = asking(&hub, false, true).await;
+ assert!(decide(&hub, &id, true, Some(true)).is_err(), "a signed-out phone has no account to join");
+ decide(&hub, &id, true, None).unwrap();
+ assert_eq!(task.await.unwrap(), Answer::PhoneOnly, "left out, an approval lets it in without joining");
}
#[tokio::test]
async fn a_phone_that_leaves_takes_its_question_along() {
let hub = hub();
- let asking = tokio::spawn({
- let hub = Arc::clone(&hub);
- async move { ask(&hub, "Pixel", "android", None, "123456".into()).await }
- });
- while hub.pairing_requests.json().is_empty() {
- tokio::task::yield_now().await;
- }
- asking.abort();
- let _ = asking.await;
+ let (task, _) = asking(&hub, true, true).await;
+ task.abort();
+ let _ = task.await;
assert!(hub.pairing_requests.json().is_empty(), "no screen keeps asking about a phone that is gone");
}
}
diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rs
index 20612d6c..e42385ed 100644
--- a/host/src/remote/relay.rs
+++ b/host/src/remote/relay.rs
@@ -10,16 +10,13 @@
//! state.
use crate::LockExt;
-use crate::api;
-use crate::api::devices::{self, Caller};
use crate::hub::Hub;
use crate::remote::channel::{self, ChannelKind, Out, Transport};
-use crate::remote::cloud;
use crate::remote::crypto::{self, b64};
+use crate::remote::{cloud, owner};
use crate::store::DeviceSource;
use anyhow::{Context, Result, anyhow, bail};
use futures::{SinkExt as _, StreamExt as _};
-use serde::Serialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
@@ -33,6 +30,9 @@ use tokio_stream::wrappers::ReceiverStream;
use tokio_tungstenite::tungstenite::{self, Message, client::IntoClientRequest as _};
use tracing::Instrument as _;
+mod delivery;
+use delivery::{hook_item, mailbox_item};
+
const PATH: &str = "/v1/relay/host?v=1";
/// Must be exactly this string: the relay answers it without waking up.
const PING: &str = r#"{"t":"ping"}"#;
@@ -46,8 +46,6 @@ const STABLE: Duration = Duration::from_mins(1);
const REPLACED_WAIT: Duration = Duration::from_mins(5);
/// A device's messages waiting for its channel; the relay already rate-limits devices.
const LINK_BUFFER: usize = 256;
-/// A mailbox send older than this is refused (TTL 24 h + clock slack).
-const MAILBOX_MAX_AGE_MS: i64 = 25 * 60 * 60 * 1000;
const REPLACED: u16 = 4009;
const RATE_LIMITED: u16 = 4008;
@@ -72,7 +70,7 @@ pub async fn run(hub: Arc<Hub>) {
s.last_error = None;
} else if s.owner.is_none() {
// Until the cloud answers (or while it can't be reached), the account last seen.
- s.owner = super::owner::owner(&hub.store);
+ s.owner = owner::owner(&hub.store);
}
});
let restart = if let Some(address) = address {
@@ -139,9 +137,16 @@ async fn supervise(hub: &Arc<Hub>, address: &cloud::Address) {
registered = true;
register_wait.reset();
}
+ if !owner::wants_relay(hub, address) {
+ without_socket(hub, address).await;
+ continue;
+ }
let started = Instant::now();
let outcome = session(hub, address).await;
cloud::update_status(hub, |s| s.connected = false);
+ if !owner::wants_relay(hub, address) {
+ continue;
+ }
match outcome {
Ok(Some(REPLACED)) => {
tracing::error!(
@@ -169,6 +174,21 @@ async fn supervise(hub: &Arc<Hub>, address: &cloud::Address) {
}
}
+/// A computer in no account holds no socket on the Codync relay: it reads its state now and then, so it notices a
+/// claim completed elsewhere, until something needs the relay (`owner::wants_relay`).
+async fn without_socket(hub: &Arc<Hub>, address: &cloud::Address) {
+ while !owner::wants_relay(hub, address) {
+ match cloud::pull(hub, &address.url).await {
+ Ok(()) => hub.cloud_synced.store(true, Ordering::Release),
+ Err(e) => tracing::warn!(error = format!("{e:#}"), "couldn't get the cloud state"),
+ }
+ if owner::wants_relay(hub, address) {
+ return;
+ }
+ let _ = timeout(STATE_EVERY, hub.cloud.relay_wake.notified()).await;
+ }
+}
+
/// `https://x` → `wss://x/v1/relay/host?v=1`.
fn relay_url(base: &str) -> Result<String> {
let rest = base
@@ -255,6 +275,9 @@ async fn session(hub: &Arc<Hub>, address: &cloud::Address) -> Result<Option<u16>
}
}
_ = ping.tick() => {
+ if !owner::wants_relay(hub, address) {
+ return Ok(None);
+ }
if heard.elapsed() > SILENT {
bail!("the relay stopped answering");
}
@@ -479,486 +502,5 @@ fn signed_acl(hub: &Hub) -> Result<Value> {
Ok(json!({"t": "acl", "d": b64(acl.as_bytes()), "sig": b64(&hub.identity.sign(acl.as_bytes()))}))
}
-// MARK: routine webhooks (§7.8)
-
-/// Runs one public webhook delivery and says how it went:
-/// `{"t":"hook.ack","seq","ok"}`, plus `retry` (try again later) and `code` when refused.
-fn hook_item(hub: &Arc<Hub>, item: &Value) -> Value {
- let seq = item["seq"].clone();
- let hook = item["hook"].as_str().unwrap_or_default();
- let headers = item["headers"]
- .as_object()
- .map(|h| h.iter().filter_map(|(k, v)| Some((k.to_ascii_lowercase(), v.as_str()?.to_owned()))).collect())
- .unwrap_or_default();
- let Some(body) = item["body"].as_str().and_then(|b| crypto::unb64(b).ok()) else {
- return json!({"t": "hook.ack", "seq": seq, "ok": false, "code": "invalid"});
- };
- match hub.routines.receive(hub, hook, &headers, &body) {
- Ok(_) => json!({"t": "hook.ack", "seq": seq, "ok": true}),
- Err(e) => {
- tracing::info!(hook, code = e.code(), reason = %e, "refused a webhook delivery");
- json!({"t": "hook.ack", "seq": seq, "ok": false, "retry": e.retry(), "code": e.code()})
- }
- }
-}
-
-// MARK: mailbox (§6.4, §7.7)
-
-/// Why a queued send was refused (`mbox.ack.code`).
-#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-enum MailboxFailure {
- Unauthorized,
- UnknownBot,
- Invalid,
-}
-
-/// Delivers one queued send and says how it went: `{"t":"mbox.ack","seq","ok","code"?}`.
-async fn mailbox_item(hub: &Arc<Hub>, item: &Value) -> Value {
- let seq = item["seq"].clone();
- match deliver(hub, item).await {
- Ok(()) => json!({"t": "mbox.ack", "seq": seq, "ok": true}),
- Err(code) => {
- tracing::info!(?code, "refused a queued message");
- json!({"t": "mbox.ack", "seq": seq, "ok": false, "code": code})
- }
- }
-}
-
-async fn deliver(hub: &Arc<Hub>, item: &Value) -> Result<(), MailboxFailure> {
- use MailboxFailure::{Invalid, Unauthorized, UnknownBot};
- let from = item["from"].as_str().unwrap_or_default();
- let device = devices::authorize(hub, from).map_err(|_| Unauthorized)?;
- let dk = crypto::unb64_n::<32>(from).map_err(|_| Invalid)?;
- let nonce = item["nonce"].as_str().filter(|n| !n.is_empty()).ok_or(Invalid)?;
- let blob = item["d"].as_str().and_then(|d| crypto::unb64(d).ok()).ok_or(Invalid)?;
- let plain = crypto::open_mailbox(&hub.identity.box_secret, &hub.identity.cid_raw(), &dk, nonce, &blob)
- .map_err(|_| Invalid)?;
- let inner: Value = serde_json::from_slice(&plain).map_err(|_| Invalid)?;
- let b = &inner["b"];
- let fresh = inner["ts"].as_i64().is_some_and(|ts| crate::store::now_ms() - ts <= MAILBOX_MAX_AGE_MS);
- if inner["m"] != "send" || b["clientNonce"].as_str() != Some(nonce) || !fresh {
- return Err(Invalid);
- }
- let bot = b["botId"].as_str().ok_or(Invalid)?;
- if hub.store.bot(bot).ok().flatten().is_none_or(|r| r.deleted) {
- return Err(UnknownBot);
- }
- let caller = Caller::Device { key: device.key, scopes: device.scopes };
- // `send` skips a clientNonce it already has: a redelivery never runs twice.
- api::dispatch(hub, &caller, "send", b.clone())
- .await
- .map(drop)
- .map_err(|e| if e.is::<devices::Forbidden>() { Unauthorized } else { Invalid })
-}
-
#[cfg(test)]
-mod tests {
- #![allow(clippy::unwrap_used, clippy::expect_used)]
- use super::*;
- use crate::remote::identity::Identity;
- use crate::store::{BotConfig, Device, DeviceSource, Scope, Store, now_ms};
- use axum::extract::ws::{Message as AxMessage, WebSocket, WebSocketUpgrade};
- use axum::extract::{Request, State};
- use axum::routing::{any, get, post};
- use chacha20poly1305::aead::{Aead, KeyInit, Payload};
- use ed25519_dalek::SigningKey;
- use hkdf::Hkdf;
- use sha2::Sha256;
- use x25519_dalek::StaticSecret;
-
- fn temp_hub() -> Arc<Hub> {
- let dir = std::env::temp_dir().join(format!("codync-relay-{}", uuid::Uuid::new_v4()));
- std::fs::create_dir_all(&dir).unwrap();
- let store = Store::open(&dir.join("t.db")).unwrap();
- Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0)
- }
-
- /// What the fake cloud saw and does.
- #[derive(Default)]
- struct Fake {
- /// ACL version the "DO" already stored (a previous database).
- stored_ver: std::sync::Mutex<i64>,
- /// Messages from the host, in order.
- from_host: std::sync::Mutex<Vec<Value>>,
- /// Messages to push to the host after `ready`.
- script: std::sync::Mutex<Vec<Value>>,
- state: std::sync::Mutex<Value>,
- /// State pulls to fail (500) before answering.
- state_failures: std::sync::Mutex<u32>,
- signatures_ok: std::sync::Mutex<Vec<bool>>,
- /// Each request's path and its `Codync-Relay-Token`, in order.
- relay_tokens: std::sync::Mutex<Vec<(String, Option<String>)>>,
- }
-
- fn note_token(f: &Fake, req: &Request) {
- let token = req.headers().get("codync-relay-token").and_then(|v| v.to_str().ok()).map(str::to_owned);
- f.relay_tokens.lock().unwrap().push((req.uri().path().to_owned(), token));
- }
-
- fn check_sig(req: &Request, sign_pub: &[u8; 32], authority: &str) -> bool {
- let h = req.headers().get("codync-sig").and_then(|v| v.to_str().ok()).unwrap_or_default();
- let field = |k: &str| h.split(',').find_map(|p| p.strip_prefix(&format!("{k}="))).unwrap_or_default();
- let ts: i64 = field("ts").parse().unwrap_or(0);
- let path = req.uri().path_and_query().unwrap().as_str();
- let input = crypto::request_sig_input(req.method().as_str(), authority, path, ts, field("nonce"), b"");
- field("kid") == b64(sign_pub)
- && crypto::verify(sign_pub, input.as_bytes(), &crypto::unb64_n(field("sig")).unwrap()).is_ok()
- }
-
- async fn fake_cloud(fake: Arc<Fake>, hub: Arc<Hub>) -> String {
- use axum::response::IntoResponse as _;
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let authority = listener.local_addr().unwrap().to_string();
- let sign_pub = hub.identity.sign_pub();
- let cid = hub.identity.computer_id();
- let a1 = authority.clone();
- let app = axum::Router::new()
- .route(
- "/v1/host/register",
- post(move |State(f): State<Arc<Fake>>, req: Request| async move {
- note_token(&f, &req);
- let ok = req.headers().contains_key("codync-sig");
- f.signatures_ok.lock().unwrap().push(ok);
- axum::Json(json!({"computerId": cid, "owned": false}))
- }),
- )
- .route(
- "/v1/host/state",
- get(move |State(f): State<Arc<Fake>>, req: Request| async move {
- note_token(&f, &req);
- f.signatures_ok.lock().unwrap().push(check_sig(&req, &sign_pub, &a1));
- let mut failures = f.state_failures.lock().unwrap();
- if *failures > 0 {
- *failures -= 1;
- return (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(json!({}))).into_response();
- }
- axum::Json(f.state.lock().unwrap().clone()).into_response()
- }),
- )
- .route(
- "/v1/relay/host",
- any(move |State(f): State<Arc<Fake>>, ws: WebSocketUpgrade, req: Request| async move {
- note_token(&f, &req);
- ws.on_upgrade(move |socket| fake_do(f, socket))
- }),
- )
- .with_state(fake);
- tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
- format!("http://{authority}")
- }
-
- async fn fake_do(f: Arc<Fake>, mut ws: WebSocket) {
- while let Some(Ok(AxMessage::Text(t))) = ws.recv().await {
- let v: Value = serde_json::from_str(t.as_str()).unwrap();
- f.from_host.lock().unwrap().push(v.clone());
- let reply = match v["t"].as_str().unwrap() {
- "acl" => {
- let d = crypto::unb64(v["d"].as_str().unwrap()).unwrap();
- let acl: Value = serde_json::from_slice(&d).unwrap();
- let ver = acl["ver"].as_i64().unwrap();
- let mut stored = f.stored_ver.lock().unwrap();
- if ver <= *stored {
- json!({"t": "error", "code": "staleVersion", "ver": *stored})
- } else {
- *stored = ver;
- json!({"t": "acl.ok", "ver": ver})
- }
- }
- "ready" => {
- let script: Vec<Value> = f.script.lock().unwrap().drain(..).collect();
- for m in script {
- ws.send(AxMessage::Text(m.to_string().into())).await.unwrap();
- }
- continue;
- }
- _ => continue,
- };
- ws.send(AxMessage::Text(reply.to_string().into())).await.unwrap();
- }
- }
-
- /// Device side of §6.4, for the test.
- fn seal_mailbox(hub: &Hub, device: &SigningKey, nonce: &str, plain: &[u8]) -> String {
- let cid = hub.identity.cid_raw();
- let dk = device.verifying_key().to_bytes();
- let eph = StaticSecret::from(crypto::random::<32>());
- let epk = crypto::x25519_pub(&eph);
- let ss = crypto::x25519(&eph, &hub.identity.box_pub()).unwrap();
- let salt = [b"codync/mbox/v1".as_slice(), &cid, &dk, &epk].concat();
- let mut key = [0u8; 32];
- Hkdf::<Sha256>::new(Some(&salt), &ss).expand(b"codync/mbox-key/v1", &mut key).unwrap();
- let aad = [dk.as_slice(), nonce.as_bytes()].concat();
- let ct = chacha20poly1305::ChaCha20Poly1305::new(&key.into())
- .encrypt(&[0u8; 12].into(), Payload { msg: plain, aad: &aad })
- .unwrap();
- let sig = crypto::sign(device, &[b"codync/mbox/v1".as_slice(), &cid, &epk, &ct].concat());
- b64(&[epk.as_slice(), &sig, &ct].concat())
- }
-
- async fn wait_for(f: &Fake, pred: impl Fn(&[Value]) -> bool) {
- let deadline = Instant::now() + Duration::from_secs(10);
- while !pred(&f.from_host.lock().unwrap()) {
- assert!(Instant::now() < deadline, "timed out; host sent {:?}", f.from_host.lock().unwrap());
- sleep(Duration::from_millis(20)).await;
- }
- }
-
- #[tokio::test]
- async fn connects_publishes_acl_past_a_stale_version_and_delivers_mail() {
- let hub = temp_hub();
- let fake = Arc::new(Fake::default());
- // The relay remembers version 7 from before this database was deleted.
- *fake.stored_ver.lock().unwrap() = 7;
- let grant_key = SigningKey::from_bytes(&crypto::random());
- let phone = SigningKey::from_bytes(&crypto::random());
- let dk = b64(phone.verifying_key().as_bytes());
- hub.store
- .put_device(&Device {
- key: dk.clone(),
- name: "Phone".into(),
- platform: "ios".into(),
- source: DeviceSource::Local,
- grant_id: None,
- scopes: vec![Scope::Control, Scope::Screen],
- lease_until: None,
- created_at: now_ms(),
- last_seen_at: None,
- account: None,
- })
- .unwrap();
- let injected = b64(grant_key.verifying_key().as_bytes());
- *fake.state.lock().unwrap() = json!({"owner": null, "requests": [],
- "grants": [{"grantId": "grt_x", "deviceKey": injected, "deviceName": "x", "platform": "ios", "scopes": ["control"]}]});
-
- let cwd = std::env::temp_dir().to_string_lossy().into_owned();
- let cfg: BotConfig =
- serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
- .unwrap();
- let bot = hub.create_bot(cfg).unwrap();
- let bot_id = bot["id"].as_str().unwrap().to_owned();
- let nonce = "3F2504E0-4F89-11D3-9A0C-0305E82C3301";
- let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
- let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
- let stranger = SigningKey::from_bytes(&crypto::random());
- *fake.script.lock().unwrap() = vec![
- json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
- json!({"t": "mbox.item", "seq": 2, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
- json!({"t": "mbox.item", "seq": 3, "from": b64(stranger.verifying_key().as_bytes()), "nonce": nonce, "d": blob, "exp": 0}),
- json!({"t": "open", "link": "L1", "dk": b64(stranger.verifying_key().as_bytes()), "pair": false}),
- json!({"t": "data", "link": "L1", "m": {"t": "hello", "v": 1, "dk": dk}}),
- ];
-
- let base = fake_cloud(fake.clone(), hub.clone()).await;
- hub.store.kv_set("test_cloud_url", &base).unwrap();
- tokio::spawn(run(hub.clone()));
-
- wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "mbox.ack").count() == 3).await;
- wait_for(&fake, |m| m.iter().any(|v| v["t"] == "close" && v["link"] == "L1")).await;
- let sent = fake.from_host.lock().unwrap().clone();
- let kinds: Vec<&str> = sent.iter().map(|v| v["t"].as_str().unwrap()).collect();
- assert_eq!(&kinds[..3], ["acl", "acl", "ready"], "stale ACL is re-signed once, then ready");
- let acl: Value = serde_json::from_slice(&crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap()).unwrap();
- assert_eq!(acl["ver"], 8, "max(local, relay) + 1");
- assert_eq!(acl["devices"], json!([{"dk": dk, "grant": null}]), "a grant injected by the cloud isn't listed");
- crypto::verify(
- &hub.identity.sign_pub(),
- &crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap(),
- &crypto::unb64_n(sent[1]["sig"].as_str().unwrap()).unwrap(),
- )
- .unwrap();
- assert!(fake.signatures_ok.lock().unwrap().iter().all(|ok| *ok));
- assert!(hub.cloud_synced.load(Ordering::Acquire), "the state was applied on this connection");
-
- let acks: Vec<&Value> = sent.iter().filter(|v| v["t"] == "mbox.ack").collect();
- assert_eq!(acks[0]["ok"], true);
- assert_eq!(acks[1]["ok"], true, "a redelivery is acknowledged");
- assert_eq!((acks[2]["ok"].as_bool(), acks[2]["code"].as_str()), (Some(false), Some("unauthorized")));
- let history = hub.store.history(&bot_id, i64::MAX, 50).unwrap();
- assert_eq!(history.iter().filter(|e| e.data["clientNonce"] == nonce).count(), 1, "delivered exactly once");
-
- let close = sent.iter().find(|v| v["t"] == "close").unwrap();
- assert_eq!(close["code"], 4002, "hello.dk must match the link's open.dk");
- assert!(hub.cloud.status().connected);
- }
-
- #[tokio::test]
- async fn registers_webhooks_and_runs_public_deliveries_once() {
- let hub = temp_hub();
- let fake = Arc::new(Fake::default());
- let cwd = std::env::temp_dir().to_string_lossy().into_owned();
- let cfg: BotConfig =
- serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
- .unwrap();
- let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
- let saved = hub
- .routines
- .save(
- &hub,
- &bot_id,
- &json!({"name": "Hook", "instruction": "Report it", "triggers": [{"type": "webhook"}]}),
- )
- .unwrap();
- let id = saved["routine"]["id"].as_str().unwrap().to_owned();
- let key = hub.routines.hooks()[0].key.clone();
- let body = b64(br#"{"text":"deploy failed"}"#);
- let item = |seq: i64, auth: &str, delivery: &str| {
- json!({"t": "hook.item", "seq": seq, "hook": id, "delivery": delivery,
- "headers": {"Authorization": format!("Bearer {auth}"), "X-Delivery-Id": delivery}, "body": body, "at": now_ms()})
- };
- *fake.script.lock().unwrap() =
- vec![item(1, &key, "d1"), item(2, &key, "d1"), item(3, "wrong", "d2"), item(4, &key, "d3")];
-
- let base = fake_cloud(fake.clone(), hub.clone()).await;
- hub.store.kv_set("test_cloud_url", &base).unwrap();
- tokio::spawn(run(hub.clone()));
-
- wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "hook.ack").count() == 4).await;
- let sent = fake.from_host.lock().unwrap().clone();
- let hooks = sent.iter().find(|v| v["t"] == "hooks").unwrap();
- assert_eq!(hooks["hooks"], json!([{"id": id, "key": key, "enabled": true}]), "registered right after ready");
- let acks: Vec<(Option<bool>, Option<bool>, Option<&str>)> = sent
- .iter()
- .filter(|v| v["t"] == "hook.ack")
- .map(|v| (v["ok"].as_bool(), v["retry"].as_bool(), v["code"].as_str()))
- .collect();
- assert_eq!(
- acks,
- [
- (Some(true), None, None),
- (Some(true), None, None),
- (Some(false), Some(false), Some("unauthorized")),
- (Some(false), Some(true), Some("busy")),
- ],
- "a redelivery reuses its run; a wrong key is dropped; a busy routine is retried later"
- );
- let runs = hub.routines.list(&bot_id)["runs"].as_array().unwrap().clone();
- assert_eq!(runs.len(), 1);
- assert_eq!(runs[0]["event"], json!({"text": "deploy failed"}));
- assert_eq!(runs[0]["deliveryId"], "d1");
-
- // Pausing changes what the relay should refuse: the set goes out again.
- hub.routines.set_enabled(&hub.store, &bot_id, &id, false).unwrap();
- wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["enabled"] == false)).await;
- let creds = hub.routines.credentials(&hub, &bot_id, &id, true).unwrap();
- assert_ne!(creds["key"], key, "rotate replaces the key");
- assert_eq!(creds["url"], format!("{base}/v1/hooks/{}/{id}", hub.identity.computer_id()));
- wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["key"] == creds["key"])).await;
- }
-
- #[tokio::test]
- async fn account_mail_waits_for_a_state_pull_instead_of_failing() {
- let hub = temp_hub();
- let fake = Arc::new(Fake::default());
- let phone = SigningKey::from_bytes(&crypto::random());
- let dk = b64(phone.verifying_key().as_bytes());
- hub.store
- .put_device(&Device {
- key: dk.clone(),
- name: "Phone".into(),
- platform: "ios".into(),
- source: DeviceSource::Account,
- grant_id: Some("grt_a".into()),
- scopes: vec![Scope::Control, Scope::Screen],
- lease_until: Some(now_ms() + 60_000),
- created_at: now_ms(),
- last_seen_at: None,
- account: None,
- })
- .unwrap();
- *fake.state.lock().unwrap() =
- json!({"owner": null, "requests": [], "grants": [{"grantId": "grt_a", "deviceKey": dk}]});
- // The pull on connect fails: without the fix the item below would be refused for good.
- *fake.state_failures.lock().unwrap() = 1;
- let cwd = std::env::temp_dir().to_string_lossy().into_owned();
- let cfg: BotConfig =
- serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
- .unwrap();
- let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
- let nonce = "9A1B2C3D-4F89-11D3-9A0C-0305E82C3301";
- let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
- let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
- *fake.script.lock().unwrap() =
- vec![json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000})];
-
- let base = fake_cloud(fake.clone(), hub.clone()).await;
- hub.store.kv_set("test_cloud_url", &base).unwrap();
- tokio::spawn(run(hub.clone()));
-
- wait_for(&fake, |m| m.iter().any(|v| v["t"] == "mbox.ack")).await;
- let sent = fake.from_host.lock().unwrap().clone();
- let ack = sent.iter().find(|v| v["t"] == "mbox.ack").unwrap();
- assert_eq!(ack["ok"], true, "delivered once the retried pull confirmed the grant: {ack}");
- assert!(hub.cloud_synced.load(Ordering::Acquire));
- }
-
- #[tokio::test]
- async fn a_private_relay_gets_its_token_only_to_enroll_and_never_changes_account_devices() {
- let hub = temp_hub();
- let fake = Arc::new(Fake::default());
- let phone = SigningKey::from_bytes(&crypto::random());
- let dk = b64(phone.verifying_key().as_bytes());
- // Approved through the Codync cloud before this computer moved to its own relay.
- hub.store
- .put_device(&Device {
- key: dk.clone(),
- name: "Phone".into(),
- platform: "ios".into(),
- source: DeviceSource::Account,
- grant_id: Some("grt_a".into()),
- scopes: vec![Scope::Control, Scope::Screen],
- lease_until: Some(now_ms() + 60_000),
- created_at: now_ms(),
- last_seen_at: None,
- account: None,
- })
- .unwrap();
- *fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": []});
- let cwd = std::env::temp_dir().to_string_lossy().into_owned();
- let cfg: BotConfig =
- serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
- .unwrap();
- let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
- let nonce = "5D6E7F80-4F89-11D3-9A0C-0305E82C3301";
- let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
- let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
- *fake.script.lock().unwrap() =
- vec![json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000})];
- let routine = hub
- .routines
- .save(
- &hub,
- &bot_id,
- &json!({"name": "Hook", "instruction": "Report it", "triggers": [{"type": "webhook"}]}),
- )
- .unwrap();
- let routine_id = routine["routine"]["id"].as_str().unwrap().to_owned();
-
- let base = fake_cloud(fake.clone(), hub.clone()).await;
- hub.store.kv_set("test_cloud_url", &base).unwrap();
- hub.store.kv_set("test_cloud_token", "s3cret-token-value").unwrap();
- tokio::spawn(run(hub.clone()));
-
- wait_for(&fake, |m| m.iter().any(|v| v["t"] == "mbox.ack")).await;
- let sent = fake.from_host.lock().unwrap().clone();
- let ack = sent.iter().find(|v| v["t"] == "mbox.ack").unwrap();
- assert_eq!(
- (ack["ok"].as_bool(), ack["code"].as_str()),
- (Some(false), Some("unauthorized")),
- "refused, not held: {ack}"
- );
- assert_eq!(
- *fake.relay_tokens.lock().unwrap(),
- [
- ("/v1/host/register".to_owned(), Some("s3cret-token-value".to_owned())),
- ("/v1/relay/host".to_owned(), None)
- ],
- "only enrolling carries the token, and a private relay's state is never pulled"
- );
- assert!(hub.store.device(&dk).is_some(), "its empty grant list doesn't remove the account device");
- assert!(!hub.cloud_synced.load(Ordering::Acquire), "account devices stay out, as with the cloud off");
- assert_eq!(hub.cloud.status().relay, cloud::RelayKind::Private);
- let creds = hub.routines.credentials(&hub, &bot_id, &routine_id, false).unwrap();
- assert_eq!(creds["url"], Value::Null, "a private relay delivers no public webhook");
- }
-}
+mod tests;
diff --git a/host/src/remote/relay/delivery.rs b/host/src/remote/relay/delivery.rs
new file mode 100644
index 00000000..76c3f4f9
--- /dev/null
+++ b/host/src/remote/relay/delivery.rs
@@ -0,0 +1,84 @@
+//! What comes in through the relay one item at a time: public routine webhooks (§7.8) and queued mailbox sends
+//! (§6.4, §7.7).
+
+use crate::api;
+use crate::api::devices::{self, Caller};
+use crate::hub::Hub;
+use crate::remote::crypto;
+use serde::Serialize;
+use serde_json::{Value, json};
+use std::sync::Arc;
+
+/// A mailbox send older than this is refused (TTL 24 h + clock slack).
+const MAILBOX_MAX_AGE_MS: i64 = 25 * 60 * 60 * 1000;
+
+/// Runs one public webhook delivery and says how it went:
+/// `{"t":"hook.ack","seq","ok"}`, plus `retry` (try again later) and `code` when refused.
+pub(super) fn hook_item(hub: &Arc<Hub>, item: &Value) -> Value {
+ let seq = item["seq"].clone();
+ let hook = item["hook"].as_str().unwrap_or_default();
+ let headers = item["headers"]
+ .as_object()
+ .map(|h| h.iter().filter_map(|(k, v)| Some((k.to_ascii_lowercase(), v.as_str()?.to_owned()))).collect())
+ .unwrap_or_default();
+ let Some(body) = item["body"].as_str().and_then(|b| crypto::unb64(b).ok()) else {
+ return json!({"t": "hook.ack", "seq": seq, "ok": false, "code": "invalid"});
+ };
+ match hub.routines.receive(hub, hook, &headers, &body) {
+ Ok(_) => json!({"t": "hook.ack", "seq": seq, "ok": true}),
+ Err(e) => {
+ tracing::info!(hook, code = e.code(), reason = %e, "refused a webhook delivery");
+ json!({"t": "hook.ack", "seq": seq, "ok": false, "retry": e.retry(), "code": e.code()})
+ }
+ }
+}
+
+// MARK: mailbox (§6.4, §7.7)
+
+/// Why a queued send was refused (`mbox.ack.code`).
+#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+enum MailboxFailure {
+ Unauthorized,
+ UnknownBot,
+ Invalid,
+}
+
+/// Delivers one queued send and says how it went: `{"t":"mbox.ack","seq","ok","code"?}`.
+pub(super) async fn mailbox_item(hub: &Arc<Hub>, item: &Value) -> Value {
+ let seq = item["seq"].clone();
+ match deliver(hub, item).await {
+ Ok(()) => json!({"t": "mbox.ack", "seq": seq, "ok": true}),
+ Err(code) => {
+ tracing::info!(?code, "refused a queued message");
+ json!({"t": "mbox.ack", "seq": seq, "ok": false, "code": code})
+ }
+ }
+}
+
+async fn deliver(hub: &Arc<Hub>, item: &Value) -> Result<(), MailboxFailure> {
+ use MailboxFailure::{Invalid, Unauthorized, UnknownBot};
+ let from = item["from"].as_str().unwrap_or_default();
+ let device = devices::authorize(hub, from).map_err(|_| Unauthorized)?;
+ let dk = crypto::unb64_n::<32>(from).map_err(|_| Invalid)?;
+ let nonce = item["nonce"].as_str().filter(|n| !n.is_empty()).ok_or(Invalid)?;
+ let blob = item["d"].as_str().and_then(|d| crypto::unb64(d).ok()).ok_or(Invalid)?;
+ let plain = crypto::open_mailbox(&hub.identity.box_secret, &hub.identity.cid_raw(), &dk, nonce, &blob)
+ .map_err(|_| Invalid)?;
+ let inner: Value = serde_json::from_slice(&plain).map_err(|_| Invalid)?;
+ let b = &inner["b"];
+ let fresh = inner["ts"].as_i64().is_some_and(|ts| crate::store::now_ms() - ts <= MAILBOX_MAX_AGE_MS);
+ if inner["m"] != "send" || b["clientNonce"].as_str() != Some(nonce) || !fresh {
+ return Err(Invalid);
+ }
+ let bot = b["botId"].as_str().ok_or(Invalid)?;
+ if hub.store.bot(bot).ok().flatten().is_none_or(|r| r.deleted) {
+ return Err(UnknownBot);
+ }
+ let caller = Caller::Device { key: device.key, scopes: device.scopes };
+ // `send` skips a clientNonce it already has: a redelivery never runs twice.
+ api::dispatch(hub, &caller, "send", b.clone())
+ .await
+ .map(drop)
+ .map_err(|e| if e.is::<devices::Forbidden>() { Unauthorized } else { Invalid })
+}
diff --git a/host/src/remote/relay/tests.rs b/host/src/remote/relay/tests.rs
new file mode 100644
index 00000000..0a58d6a3
--- /dev/null
+++ b/host/src/remote/relay/tests.rs
@@ -0,0 +1,429 @@
+#![allow(clippy::unwrap_used, clippy::expect_used)]
+use super::*;
+use crate::remote::identity::Identity;
+use crate::store::{BotConfig, Device, DeviceAccount, DeviceSource, Scope, Store, now_ms};
+use axum::extract::ws::{Message as AxMessage, WebSocket, WebSocketUpgrade};
+use axum::extract::{Request, State};
+use axum::routing::{any, get, post};
+use chacha20poly1305::aead::{Aead, KeyInit, Payload};
+use ed25519_dalek::SigningKey;
+use hkdf::Hkdf;
+use sha2::Sha256;
+use x25519_dalek::StaticSecret;
+
+fn temp_hub() -> Arc<Hub> {
+ let dir = std::env::temp_dir().join(format!("codync-relay-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ Hub::new(store, "host".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0)
+}
+
+/// What the fake cloud saw and does.
+#[derive(Default)]
+struct Fake {
+ /// ACL version the "DO" already stored (a previous database).
+ stored_ver: std::sync::Mutex<i64>,
+ /// Messages from the host, in order.
+ from_host: std::sync::Mutex<Vec<Value>>,
+ /// Messages to push to the host after `ready`.
+ script: std::sync::Mutex<Vec<Value>>,
+ state: std::sync::Mutex<Value>,
+ /// State pulls to fail (500) before answering.
+ state_failures: std::sync::Mutex<u32>,
+ signatures_ok: std::sync::Mutex<Vec<bool>>,
+ /// Each request's path and its `Codync-Relay-Token`, in order.
+ relay_tokens: std::sync::Mutex<Vec<(String, Option<String>)>>,
+}
+
+fn note_token(f: &Fake, req: &Request) {
+ let token = req.headers().get("codync-relay-token").and_then(|v| v.to_str().ok()).map(str::to_owned);
+ f.relay_tokens.lock().unwrap().push((req.uri().path().to_owned(), token));
+}
+
+fn check_sig(req: &Request, sign_pub: &[u8; 32], authority: &str) -> bool {
+ let h = req.headers().get("codync-sig").and_then(|v| v.to_str().ok()).unwrap_or_default();
+ let field = |k: &str| h.split(',').find_map(|p| p.strip_prefix(&format!("{k}="))).unwrap_or_default();
+ let ts: i64 = field("ts").parse().unwrap_or(0);
+ let path = req.uri().path_and_query().unwrap().as_str();
+ let input = crypto::request_sig_input(req.method().as_str(), authority, path, ts, field("nonce"), b"");
+ field("kid") == b64(sign_pub)
+ && crypto::verify(sign_pub, input.as_bytes(), &crypto::unb64_n(field("sig")).unwrap()).is_ok()
+}
+
+async fn fake_cloud(fake: Arc<Fake>, hub: Arc<Hub>) -> String {
+ use axum::response::IntoResponse as _;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let authority = listener.local_addr().unwrap().to_string();
+ let sign_pub = hub.identity.sign_pub();
+ let cid = hub.identity.computer_id();
+ let a1 = authority.clone();
+ let app = axum::Router::new()
+ .route(
+ "/v1/host/register",
+ post(move |State(f): State<Arc<Fake>>, req: Request| async move {
+ note_token(&f, &req);
+ let ok = req.headers().contains_key("codync-sig");
+ f.signatures_ok.lock().unwrap().push(ok);
+ axum::Json(json!({"computerId": cid, "owned": false}))
+ }),
+ )
+ .route(
+ "/v1/host/state",
+ get(move |State(f): State<Arc<Fake>>, req: Request| async move {
+ note_token(&f, &req);
+ f.signatures_ok.lock().unwrap().push(check_sig(&req, &sign_pub, &a1));
+ let mut failures = f.state_failures.lock().unwrap();
+ if *failures > 0 {
+ *failures -= 1;
+ return (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(json!({}))).into_response();
+ }
+ axum::Json(f.state.lock().unwrap().clone()).into_response()
+ }),
+ )
+ .route(
+ "/v1/relay/host",
+ any(move |State(f): State<Arc<Fake>>, ws: WebSocketUpgrade, req: Request| async move {
+ note_token(&f, &req);
+ ws.on_upgrade(move |socket| fake_do(f, socket))
+ }),
+ )
+ .with_state(fake);
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{authority}")
+}
+
+async fn fake_do(f: Arc<Fake>, mut ws: WebSocket) {
+ while let Some(Ok(AxMessage::Text(t))) = ws.recv().await {
+ let v: Value = serde_json::from_str(t.as_str()).unwrap();
+ f.from_host.lock().unwrap().push(v.clone());
+ let reply = match v["t"].as_str().unwrap() {
+ "acl" => {
+ let d = crypto::unb64(v["d"].as_str().unwrap()).unwrap();
+ let acl: Value = serde_json::from_slice(&d).unwrap();
+ let ver = acl["ver"].as_i64().unwrap();
+ let mut stored = f.stored_ver.lock().unwrap();
+ if ver <= *stored {
+ json!({"t": "error", "code": "staleVersion", "ver": *stored})
+ } else {
+ *stored = ver;
+ json!({"t": "acl.ok", "ver": ver})
+ }
+ }
+ "ready" => {
+ let script: Vec<Value> = f.script.lock().unwrap().drain(..).collect();
+ for m in script {
+ ws.send(AxMessage::Text(m.to_string().into())).await.unwrap();
+ }
+ continue;
+ }
+ _ => continue,
+ };
+ ws.send(AxMessage::Text(reply.to_string().into())).await.unwrap();
+ }
+}
+
+/// Device side of §6.4, for the test.
+fn seal_mailbox(hub: &Hub, device: &SigningKey, nonce: &str, plain: &[u8]) -> String {
+ let cid = hub.identity.cid_raw();
+ let dk = device.verifying_key().to_bytes();
+ let eph = StaticSecret::from(crypto::random::<32>());
+ let epk = crypto::x25519_pub(&eph);
+ let ss = crypto::x25519(&eph, &hub.identity.box_pub()).unwrap();
+ let salt = [b"codync/mbox/v1".as_slice(), &cid, &dk, &epk].concat();
+ let mut key = [0u8; 32];
+ Hkdf::<Sha256>::new(Some(&salt), &ss).expand(b"codync/mbox-key/v1", &mut key).unwrap();
+ let aad = [dk.as_slice(), nonce.as_bytes()].concat();
+ let ct = chacha20poly1305::ChaCha20Poly1305::new(&key.into())
+ .encrypt(&[0u8; 12].into(), Payload { msg: plain, aad: &aad })
+ .unwrap();
+ let sig = crypto::sign(device, &[b"codync/mbox/v1".as_slice(), &cid, &epk, &ct].concat());
+ b64(&[epk.as_slice(), &sig, &ct].concat())
+}
+
+fn test_owner() -> Value {
+ json!({"userId": "user_1", "email": "[email protected]"})
+}
+
+/// The Codync relay is for a computer in an account.
+fn in_an_account(hub: &Hub) {
+ let owner = serde_json::from_value(test_owner()).unwrap();
+ owner::remember(hub, Some(&owner)).unwrap();
+}
+
+async fn wait_for(f: &Fake, pred: impl Fn(&[Value]) -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while !pred(&f.from_host.lock().unwrap()) {
+ assert!(Instant::now() < deadline, "timed out; host sent {:?}", f.from_host.lock().unwrap());
+ sleep(Duration::from_millis(20)).await;
+ }
+}
+
+#[tokio::test]
+async fn a_computer_in_no_account_connects_only_while_a_phone_may_pair() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ *fake.state.lock().unwrap() = json!({"owner": null, "requests": [], "grants": []});
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("test_cloud_url", &base).unwrap();
+ tokio::spawn(run(hub.clone()));
+ while !hub.cloud_synced.load(Ordering::Acquire) {
+ sleep(Duration::from_millis(10)).await;
+ }
+ assert!(fake.from_host.lock().unwrap().is_empty(), "it read its state without opening a socket");
+ assert!(!hub.cloud.status().connected);
+
+ hub.pairing.locked().issue();
+ hub.cloud.relay_wake.notify_one();
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "acl")).await;
+}
+
+#[tokio::test]
+async fn connects_publishes_acl_past_a_stale_version_and_delivers_mail() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ // The relay remembers version 7 from before this database was deleted.
+ *fake.stored_ver.lock().unwrap() = 7;
+ let grant_key = SigningKey::from_bytes(&crypto::random());
+ let phone = SigningKey::from_bytes(&crypto::random());
+ let dk = b64(phone.verifying_key().as_bytes());
+ hub.store
+ .put_device(&Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Local,
+ grant_id: None,
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: None,
+ created_at: now_ms(),
+ last_seen_at: None,
+ account: DeviceAccount::Unrecorded,
+ })
+ .unwrap();
+ let injected = b64(grant_key.verifying_key().as_bytes());
+ *fake.state.lock().unwrap() = json!({"owner": test_owner(), "requests": [],
+ "grants": [{"grantId": "grt_x", "deviceKey": injected, "deviceName": "x", "platform": "ios", "scopes": ["control"]}]});
+
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot = hub.create_bot(cfg).unwrap();
+ let bot_id = bot["id"].as_str().unwrap().to_owned();
+ let nonce = "3F2504E0-4F89-11D3-9A0C-0305E82C3301";
+ let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
+ let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
+ let stranger = SigningKey::from_bytes(&crypto::random());
+ *fake.script.lock().unwrap() = vec![
+ json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
+ json!({"t": "mbox.item", "seq": 2, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000}),
+ json!({"t": "mbox.item", "seq": 3, "from": b64(stranger.verifying_key().as_bytes()), "nonce": nonce, "d": blob, "exp": 0}),
+ json!({"t": "open", "link": "L1", "dk": b64(stranger.verifying_key().as_bytes()), "pair": false}),
+ json!({"t": "data", "link": "L1", "m": {"t": "hello", "v": 1, "dk": dk}}),
+ ];
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("test_cloud_url", &base).unwrap();
+ in_an_account(&hub);
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "mbox.ack").count() == 3).await;
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "close" && v["link"] == "L1")).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let kinds: Vec<&str> = sent.iter().map(|v| v["t"].as_str().unwrap()).collect();
+ assert_eq!(&kinds[..3], ["acl", "acl", "ready"], "stale ACL is re-signed once, then ready");
+ let acl: Value = serde_json::from_slice(&crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap()).unwrap();
+ assert_eq!(acl["ver"], 8, "max(local, relay) + 1");
+ assert_eq!(acl["devices"], json!([{"dk": dk, "grant": null}]), "a grant injected by the cloud isn't listed");
+ crypto::verify(
+ &hub.identity.sign_pub(),
+ &crypto::unb64(sent[1]["d"].as_str().unwrap()).unwrap(),
+ &crypto::unb64_n(sent[1]["sig"].as_str().unwrap()).unwrap(),
+ )
+ .unwrap();
+ assert!(fake.signatures_ok.lock().unwrap().iter().all(|ok| *ok));
+ assert!(hub.cloud_synced.load(Ordering::Acquire), "the state was applied on this connection");
+
+ let acks: Vec<&Value> = sent.iter().filter(|v| v["t"] == "mbox.ack").collect();
+ assert_eq!(acks[0]["ok"], true);
+ assert_eq!(acks[1]["ok"], true, "a redelivery is acknowledged");
+ assert_eq!((acks[2]["ok"].as_bool(), acks[2]["code"].as_str()), (Some(false), Some("unauthorized")));
+ let history = hub.store.history(&bot_id, i64::MAX, 50).unwrap();
+ assert_eq!(history.iter().filter(|e| e.data["clientNonce"] == nonce).count(), 1, "delivered exactly once");
+
+ let close = sent.iter().find(|v| v["t"] == "close").unwrap();
+ assert_eq!(close["code"], 4002, "hello.dk must match the link's open.dk");
+ assert!(hub.cloud.status().connected);
+}
+
+#[tokio::test]
+async fn registers_webhooks_and_runs_public_deliveries_once() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
+ let saved = hub
+ .routines
+ .save(&hub, &bot_id, &json!({"name": "Hook", "instruction": "Report it", "triggers": [{"type": "webhook"}]}))
+ .unwrap();
+ let id = saved["routine"]["id"].as_str().unwrap().to_owned();
+ let key = hub.routines.hooks()[0].key.clone();
+ let body = b64(br#"{"text":"deploy failed"}"#);
+ let item = |seq: i64, auth: &str, delivery: &str| {
+ json!({"t": "hook.item", "seq": seq, "hook": id, "delivery": delivery,
+ "headers": {"Authorization": format!("Bearer {auth}"), "X-Delivery-Id": delivery}, "body": body, "at": now_ms()})
+ };
+ *fake.script.lock().unwrap() =
+ vec![item(1, &key, "d1"), item(2, &key, "d1"), item(3, "wrong", "d2"), item(4, &key, "d3")];
+
+ *fake.state.lock().unwrap() = json!({"owner": test_owner(), "requests": [], "grants": []});
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("test_cloud_url", &base).unwrap();
+ in_an_account(&hub);
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().filter(|v| v["t"] == "hook.ack").count() == 4).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let hooks = sent.iter().find(|v| v["t"] == "hooks").unwrap();
+ assert_eq!(hooks["hooks"], json!([{"id": id, "key": key, "enabled": true}]), "registered right after ready");
+ let acks: Vec<(Option<bool>, Option<bool>, Option<&str>)> = sent
+ .iter()
+ .filter(|v| v["t"] == "hook.ack")
+ .map(|v| (v["ok"].as_bool(), v["retry"].as_bool(), v["code"].as_str()))
+ .collect();
+ assert_eq!(
+ acks,
+ [
+ (Some(true), None, None),
+ (Some(true), None, None),
+ (Some(false), Some(false), Some("unauthorized")),
+ (Some(false), Some(true), Some("busy")),
+ ],
+ "a redelivery reuses its run; a wrong key is dropped; a busy routine is retried later"
+ );
+ let runs = hub.routines.list(&bot_id)["runs"].as_array().unwrap().clone();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0]["event"], json!({"text": "deploy failed"}));
+ assert_eq!(runs[0]["deliveryId"], "d1");
+
+ // Pausing changes what the relay should refuse: the set goes out again.
+ hub.routines.set_enabled(&hub.store, &bot_id, &id, false).unwrap();
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["enabled"] == false)).await;
+ let creds = hub.routines.credentials(&hub, &bot_id, &id, true).unwrap();
+ assert_ne!(creds["key"], key, "rotate replaces the key");
+ assert_eq!(creds["url"], format!("{base}/v1/hooks/{}/{id}", hub.identity.computer_id()));
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "hooks" && v["hooks"][0]["key"] == creds["key"])).await;
+}
+
+#[tokio::test]
+async fn account_mail_waits_for_a_state_pull_instead_of_failing() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ let phone = SigningKey::from_bytes(&crypto::random());
+ let dk = b64(phone.verifying_key().as_bytes());
+ hub.store
+ .put_device(&Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Account,
+ grant_id: Some("grt_a".into()),
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: Some(now_ms() + 60_000),
+ created_at: now_ms(),
+ last_seen_at: None,
+ account: DeviceAccount::Unrecorded,
+ })
+ .unwrap();
+ *fake.state.lock().unwrap() =
+ json!({"owner": test_owner(), "requests": [], "grants": [{"grantId": "grt_a", "deviceKey": dk}]});
+ // The pull on connect fails: without the fix the item below would be refused for good.
+ *fake.state_failures.lock().unwrap() = 1;
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
+ let nonce = "9A1B2C3D-4F89-11D3-9A0C-0305E82C3301";
+ let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
+ let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
+ *fake.script.lock().unwrap() =
+ vec![json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000})];
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("test_cloud_url", &base).unwrap();
+ in_an_account(&hub);
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "mbox.ack")).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let ack = sent.iter().find(|v| v["t"] == "mbox.ack").unwrap();
+ assert_eq!(ack["ok"], true, "delivered once the retried pull confirmed the grant: {ack}");
+ assert!(hub.cloud_synced.load(Ordering::Acquire));
+}
+
+#[tokio::test]
+async fn a_private_relay_gets_its_token_only_to_enroll_and_never_changes_account_devices() {
+ let hub = temp_hub();
+ let fake = Arc::new(Fake::default());
+ let phone = SigningKey::from_bytes(&crypto::random());
+ let dk = b64(phone.verifying_key().as_bytes());
+ // Approved through the Codync cloud before this computer moved to its own relay.
+ hub.store
+ .put_device(&Device {
+ key: dk.clone(),
+ name: "Phone".into(),
+ platform: "ios".into(),
+ source: DeviceSource::Account,
+ grant_id: Some("grt_a".into()),
+ scopes: vec![Scope::Control, Scope::Screen],
+ lease_until: Some(now_ms() + 60_000),
+ created_at: now_ms(),
+ last_seen_at: None,
+ account: DeviceAccount::Unrecorded,
+ })
+ .unwrap();
+ *fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": []});
+ let cwd = std::env::temp_dir().to_string_lossy().into_owned();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "", "name": "B", "cwd": cwd, "backend": "custom", "command": "true"}))
+ .unwrap();
+ let bot_id = hub.create_bot(cfg).unwrap()["id"].as_str().unwrap().to_owned();
+ let nonce = "5D6E7F80-4F89-11D3-9A0C-0305E82C3301";
+ let inner = json!({"m": "send", "b": {"botId": bot_id, "text": "hi", "clientNonce": nonce}, "ts": now_ms()});
+ let blob = seal_mailbox(&hub, &phone, nonce, inner.to_string().as_bytes());
+ *fake.script.lock().unwrap() =
+ vec![json!({"t": "mbox.item", "seq": 1, "from": dk, "nonce": nonce, "d": blob, "exp": now_ms() + 1000})];
+ let routine = hub
+ .routines
+ .save(&hub, &bot_id, &json!({"name": "Hook", "instruction": "Report it", "triggers": [{"type": "webhook"}]}))
+ .unwrap();
+ let routine_id = routine["routine"]["id"].as_str().unwrap().to_owned();
+
+ let base = fake_cloud(fake.clone(), hub.clone()).await;
+ hub.store.kv_set("test_cloud_url", &base).unwrap();
+ hub.store.kv_set("test_cloud_token", "s3cret-token-value").unwrap();
+ tokio::spawn(run(hub.clone()));
+
+ wait_for(&fake, |m| m.iter().any(|v| v["t"] == "mbox.ack")).await;
+ let sent = fake.from_host.lock().unwrap().clone();
+ let ack = sent.iter().find(|v| v["t"] == "mbox.ack").unwrap();
+ assert_eq!(
+ (ack["ok"].as_bool(), ack["code"].as_str()),
+ (Some(false), Some("unauthorized")),
+ "refused, not held: {ack}"
+ );
+ assert_eq!(
+ *fake.relay_tokens.lock().unwrap(),
+ [("/v1/host/register".to_owned(), Some("s3cret-token-value".to_owned())), ("/v1/relay/host".to_owned(), None)],
+ "only enrolling carries the token, and a private relay's state is never pulled"
+ );
+ assert!(hub.store.device(&dk).is_some(), "its empty grant list doesn't remove the account device");
+ assert!(!hub.cloud_synced.load(Ordering::Acquire), "account devices stay out, as with the cloud off");
+ assert_eq!(hub.cloud.status().relay, cloud::RelayKind::Private);
+ let creds = hub.routines.credentials(&hub, &bot_id, &routine_id, false).unwrap();
+ assert_eq!(creds["url"], Value::Null, "a private relay delivers no public webhook");
+}
diff --git a/host/src/routines/mod.rs b/host/src/routines/mod.rs
index 00395ea2..3f6e088b 100644
--- a/host/src/routines/mod.rs
+++ b/host/src/routines/mod.rs
@@ -388,11 +388,14 @@ impl Routines {
.clone()
};
let cloud = hub.cloud.status();
+ // Public deliveries go through the relay, for a computer in an account (docs/plans/optional-sign-in.md).
let url = crate::remote::cloud::codync_url(hub)
.ok()
+ .filter(|_| crate::remote::owner::owner(&hub.store).is_some())
.map(|base| format!("{}/v1/hooks/{}/{id}", base.trim_end_matches('/'), hub.identity.computer_id()));
Ok(json!({
"url": url,
+ "needsAccount": crate::remote::owner::can_join(hub),
"localUrl": format!("http://127.0.0.1:{}/hooks/routines/{id}", hub.port),
"key": key,
"connected": url.is_some() && cloud.connected,
diff --git a/host/src/store/devices.rs b/host/src/store/devices.rs
index 7e73dc03..9b7ee12a 100644
--- a/host/src/store/devices.rs
+++ b/host/src/store/devices.rs
@@ -25,6 +25,17 @@ pub enum Scope {
Screen,
}
+/// How a device stands with accounts (columns `account`, `no_account`).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum DeviceAccount {
+ /// Paired before devices recorded their account (2.36.0): it stays when this computer joins its first account.
+ Unrecorded,
+ /// Paired signed out (docs/plans/optional-sign-in.md): it goes when this computer joins an account.
+ SignedOut,
+ /// Let in for this account (a Clerk user ID).
+ Of(String),
+}
+
/// One row of the authorized-device table (spec §4.3).
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
@@ -39,9 +50,8 @@ pub struct Device {
pub lease_until: Option<i64>,
pub created_at: i64,
pub last_seen_at: Option<i64>,
- /// The account this device was let in for (a Clerk user ID); none for devices paired before 2.36.0.
#[serde(skip)]
- pub account: Option<String>,
+ pub account: DeviceAccount,
}
/// A push ticket with the device's push key (§6.7) and account context.
@@ -52,7 +62,7 @@ pub struct PushTicket {
}
const DEVICE_COLS: &str =
- "key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at, account";
+ "key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at, account, no_account";
/// A device with its push and Live Activity tickets; the number of device rows removed.
fn delete_device(tx: &rusqlite::Transaction, key: &str) -> rusqlite::Result<usize> {
@@ -77,7 +87,11 @@ fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {
lease_until: r.get(6)?,
created_at: r.get(7)?,
last_seen_at: r.get(8)?,
- account: r.get(9)?,
+ account: match (r.get(9)?, r.get(10)?) {
+ (Some(account), _) => DeviceAccount::Of(account),
+ (None, true) => DeviceAccount::SignedOut,
+ (None, false) => DeviceAccount::Unrecorded,
+ },
})
}
@@ -96,12 +110,17 @@ impl Store {
/// Adds (or, for a key paired again, refreshes) an authorized device.
pub fn put_device(&self, d: &Device) -> Result<()> {
+ let (account, no_account) = match &d.account {
+ DeviceAccount::Unrecorded => (None, false),
+ DeviceAccount::SignedOut => (None, true),
+ DeviceAccount::Of(account) => (Some(account.as_str()), false),
+ };
let c = self.db.locked();
c.execute(
- "INSERT INTO devices(key, name, platform, source, grant_id, scopes, lease_until, created_at, account)
- VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
+ "INSERT INTO devices(key, name, platform, source, grant_id, scopes, lease_until, created_at, account, no_account)
+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
ON CONFLICT(key) DO UPDATE SET name = ?2, platform = ?3, source = ?4, grant_id = ?5,
- scopes = ?6, lease_until = ?7, account = ?9",
+ scopes = ?6, lease_until = ?7, account = ?9, no_account = ?10",
params![
d.key,
d.name,
@@ -111,7 +130,8 @@ impl Store {
serde_json::to_string(&d.scopes)?,
d.lease_until,
d.created_at,
- d.account
+ account,
+ no_account
],
)?;
Ok(())
@@ -131,13 +151,25 @@ impl Store {
/// stay only with `keep_unrecorded` (a computer joining its first account keeps the phones it had).
/// Returns the removed keys.
pub fn keep_devices_of(&self, account: Option<&str>, keep_unrecorded: bool) -> Result<Vec<String>> {
+ self.remove_devices_where(
+ "(account IS NULL AND NOT ?2) OR (account IS NOT NULL AND account IS NOT ?1)",
+ params![account, keep_unrecorded],
+ )
+ }
+
+ /// This computer joined an account: the phones that paired with no account go, with their tickets. Returns the
+ /// removed keys.
+ pub fn drop_no_account_devices(&self) -> Result<Vec<String>> {
+ self.remove_devices_where("no_account", [])
+ }
+
+ /// Removes the devices matching `condition`, with their tickets, as one change. Returns the removed keys.
+ fn remove_devices_where(&self, condition: &str, params: impl rusqlite::Params) -> Result<Vec<String>> {
let mut c = self.db.locked();
let tx = c.transaction()?;
let gone: Vec<String> = {
- let mut st = tx.prepare(
- "SELECT key FROM devices WHERE (account IS NULL AND NOT ?2) OR (account IS NOT NULL AND account IS NOT ?1)",
- )?;
- st.query_map(params![account, keep_unrecorded], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?
+ let mut st = tx.prepare(&format!("SELECT key FROM devices WHERE {condition}"))?;
+ st.query_map(params, |r| r.get(0))?.collect::<rusqlite::Result<_>>()?
};
for key in &gone {
delete_device(&tx, key)?;
@@ -146,6 +178,14 @@ impl Store {
Ok(gone)
}
+ /// A phone that paired with no account now brings this computer into `account`, so it stays when the computer joins.
+ pub fn set_device_account(&self, key: &str, account: &str) -> Result<()> {
+ self.db
+ .locked()
+ .execute("UPDATE devices SET account = ?2, no_account = 0 WHERE key = ?1", params![key, account])?;
+ Ok(())
+ }
+
/// Extends an account device's lease (the cloud still lists its grant).
pub fn set_lease(&self, key: &str, until: i64) -> Result<()> {
let c = self.db.locked();
@@ -274,7 +314,7 @@ mod tests {
lease_until: None,
created_at: 1,
last_seen_at: None,
- account: None,
+ account: DeviceAccount::Unrecorded,
};
s.put_device(&d).unwrap();
s.put_device(&Device { key: "dk2".into(), ..d.clone() }).unwrap();
diff --git a/host/src/store/mod.rs b/host/src/store/mod.rs
index d28391f9..a695c151 100644
--- a/host/src/store/mod.rs
+++ b/host/src/store/mod.rs
@@ -13,7 +13,7 @@ mod model;
mod schema;
mod workspaces;
-pub use devices::{Device, DeviceSource, Scope};
+pub use devices::{Device, DeviceAccount, DeviceSource, Scope};
pub use model::{
AVATAR_COLORS, AVATAR_SHAPES, BotConfig, BotKind, BotRow, Entry, EntryKind, Fallback, Lane, Permission,
message_text, run_session_key,
diff --git a/host/src/store/schema.rs b/host/src/store/schema.rs
index 62fece4e..074d3024 100644
--- a/host/src/store/schema.rs
+++ b/host/src/store/schema.rs
@@ -7,7 +7,7 @@ use std::path::Path;
use std::sync::Mutex;
/// Current schema version (kv `schema`).
-const SCHEMA: i64 = 7;
+const SCHEMA: i64 = 8;
/// 3: authorized devices (keys, not push tickets) with their push and Live Activity
/// tickets. The old ticket-only `devices` table is dropped; phones re-register on connect.
@@ -17,6 +17,7 @@ const SCHEMA: i64 = 7;
/// 6: the dividers that announced a fresh agent session go; the chat no longer shows session resets.
/// 7: each device records the account it was let in for (`devices.account`), so a computer that changes
/// accounts drops the old account's devices.
+/// 8: a phone that paired with no account is told apart from a device paired before 2.36.0 (`devices.no_account`).
fn migrate(c: &Connection) -> Result<()> {
let version: i64 =
c.query_row("SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'schema'", [], |r| r.get(0)).optional()?.unwrap_or(0);
@@ -35,7 +36,10 @@ fn migrate(c: &Connection) -> Result<()> {
if version < 6 {
migrate_6(c)?;
}
- migrate_7(c)
+ if version < 7 {
+ migrate_7(c)?;
+ }
+ migrate_8(c)
}
fn migrate_3(c: &Connection) -> Result<()> {
@@ -146,6 +150,18 @@ fn migrate_7(c: &Connection) -> Result<()> {
Ok(())
}
+fn migrate_8(c: &Connection) -> Result<()> {
+ let has: bool =
+ c.query_row("SELECT count(*) > 0 FROM pragma_table_info('devices') WHERE name = 'no_account'", [], |r| {
+ r.get(0)
+ })?;
+ if !has {
+ c.execute_batch("ALTER TABLE devices ADD COLUMN no_account INTEGER NOT NULL DEFAULT 0;")?;
+ }
+ c.execute_batch("INSERT INTO kv(k, v) VALUES('schema', '8') ON CONFLICT(k) DO UPDATE SET v = '8';")?;
+ Ok(())
+}
+
impl Store {
pub fn open(path: &Path) -> Result<Self> {
let c = Connection::open(path)?;
@@ -207,7 +223,7 @@ mod tests {
}
let s = Store::open(&db).unwrap();
assert!(s.devices().unwrap().is_empty());
- assert_eq!(s.kv_get("schema").as_deref(), Some("7"));
+ assert_eq!(s.kv_get("schema").as_deref(), Some("8"));
drop(s);
let s = Store::open(&db).unwrap();
assert!(s.devices().unwrap().is_empty(), "reopening keeps the new table");
@@ -230,7 +246,7 @@ mod tests {
let s = Store::open(&db).unwrap();
let chat: Vec<String> = s.history("b", i64::MAX, 10).unwrap().into_iter().map(|e| e.id).collect();
assert_eq!(chat, ["info"]);
- assert_eq!(s.kv_get("schema").as_deref(), Some("7"));
+ assert_eq!(s.kv_get("schema").as_deref(), Some("8"));
}
#[test]
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index ce7ceefb..cbc5bf5f 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -132,11 +132,15 @@ impl App {
Overlay::Analytics(s) => s.key(k),
Overlay::Network(n) => self.network_key(n, k),
// A phone that scanned the code waits for this computer to let it in.
- o @ Overlay::Pair(_) if matches!(k.code, KeyCode::Char('y' | 'n')) && !self.pairing_requests.is_empty() => {
- self.decide_pairing(k.code == KeyCode::Char('y'));
- Some(o)
+ o @ Overlay::Pair(_)
+ if !self.pairing_requests.is_empty() && matches!(k.code, KeyCode::Char('y' | 'w' | 'n')) =>
+ {
+ self.decide_pairing(k.code);
+ // Answering the last question closes a sheet opened only for it.
+ (!(matches!(o, Overlay::Pair(PairCode::QuestionOnly)) && self.pairing_requests.is_empty())).then_some(o)
}
// A new code: after a failure, or in place of the one shown.
+ o @ Overlay::Pair(PairCode::QuestionOnly) if k.code == KeyCode::Char('r') => Some(o),
Overlay::Pair(_) if k.code == KeyCode::Char('r') => {
self.request_pairing_code();
Some(Overlay::Pair(PairCode::Loading))
diff --git a/host/src/tui/app/pair.rs b/host/src/tui/app/pair.rs
index 921244bf..7b4a7995 100644
--- a/host/src/tui/app/pair.rs
+++ b/host/src/tui/app/pair.rs
@@ -1,9 +1,11 @@
//! The pair-a-phone sheet: its code, whether the computer is in an account, and the phones waiting for it to
-//! let them in, which brings it into their account (docs/plans/require-sign-in.md, phase 2).
+//! let them in, and whether it joins their account (docs/plans/optional-sign-in.md).
+use crossterm::event::KeyCode;
use serde_json::{Value, json};
use super::{After, App, Overlay, PairCode};
+use crate::remote::pairing_requests::Answer;
impl App {
pub(super) fn open_pair(&mut self) {
@@ -36,7 +38,7 @@ impl App {
}
}
(After::Cloud, Ok(v)) => self.cloud = v,
- (After::PairingRequests, Ok(v)) => self.pairing_requests = requests(&v),
+ (After::PairingRequests, Ok(v)) => self.pairing_requests_changed(&v),
// The host may not have the answer: its list brings the phone back while it still waits.
(After::PairingDecided, Err(e)) => {
self.flash(&e);
@@ -48,29 +50,46 @@ impl App {
}
}
- /// A `pairingRequests` event: the whole list, each time it changes.
+ /// A `pairingRequests` event: the whole list, each time it changes. A paired phone's Add to account needs no code,
+ /// so no sheet may be open when it asks: this opens one, and closes it once nobody's asking.
pub(super) fn pairing_requests_changed(&mut self, v: &Value) {
self.pairing_requests = requests(v);
- }
-
- /// `y` / `n` on the sheet: the first waiting phone gets in (and the computer joins its account), or doesn't.
- pub(super) fn decide_pairing(&mut self, approve: bool) {
if self.pairing_requests.is_empty() {
- return;
+ self.overlays.retain(|o| !matches!(o, Overlay::Pair(PairCode::QuestionOnly)));
+ } else if !self.overlays.iter().any(|o| matches!(o, Overlay::Pair(_))) {
+ self.overlays.push(Overlay::Pair(PairCode::QuestionOnly));
}
+ }
+
+ /// A key on the sheet about the first waiting phone. A key it isn't offered means nothing.
+ pub(super) fn decide_pairing(&mut self, key: KeyCode) {
+ let Some(request) = self.pairing_requests.first() else { return };
+ let Some(answer) = pairing_answer(key, request) else { return };
+ let body = answer.body(&request["requestId"]);
// Off the sheet at once; the host's event follows.
- let request = self.pairing_requests.remove(0);
- let answer = json!({"requestId": request["requestId"], "approve": approve});
- self.call("decidePairing", answer, After::PairingDecided);
+ self.pairing_requests.remove(0);
+ self.call("decidePairing", body, After::PairingDecided);
}
- /// Known to be in no account while it could join one (the host's `canJoinAccount`): a signed-in phone that
- /// scans the code asks to bring the computer into its own.
+ /// Known to be in no account while it could join one (the host's `canJoinAccount`): phones reach it only over
+ /// Wi-Fi or Tailscale until it joins.
pub fn outside_account(&self) -> bool {
self.cloud["canJoinAccount"] == true
}
}
+/// `y` lets the phone in, joining its account when that's possible, `w` lets it in with the computer out of an account,
+/// where that's a choice, and `n` turns it away.
+fn pairing_answer(key: KeyCode, request: &Value) -> Option<Answer> {
+ let can_join = request["canJoin"] == true;
+ match key {
+ KeyCode::Char('y') => Some(if can_join { Answer::Join } else { Answer::PhoneOnly }),
+ KeyCode::Char('w') if can_join && request["phoneOnly"] == true => Some(Answer::PhoneOnly),
+ KeyCode::Char('n') => Some(Answer::Decline),
+ _ => None,
+ }
+}
+
fn requests(v: &Value) -> Vec<Value> {
v["requests"].as_array().cloned().unwrap_or_default()
}
@@ -80,6 +99,36 @@ mod tests {
use super::super::test_app;
use super::*;
+ #[tokio::test]
+ async fn a_phone_asking_opens_a_sheet_that_goes_with_the_question() {
+ let mut app = test_app();
+ let is_question = |app: &App| matches!(app.overlays.last(), Some(Overlay::Pair(PairCode::QuestionOnly)));
+ app.pairing_requests_changed(&json!({"requests": [{"requestId": "a", "canJoin": true}]}));
+ assert!(is_question(&app), "with no sheet open, Add to account would go unseen");
+ app.pairing_requests_changed(&json!({"requests": []}));
+ assert!(app.overlays.is_empty());
+
+ app.overlays.push(Overlay::Pair(PairCode::Loading));
+ app.pairing_requests_changed(&json!({"requests": [{"requestId": "a", "canJoin": true}]}));
+ assert_eq!(app.overlays.len(), 1, "an open sheet shows it already");
+ app.pairing_requests_changed(&json!({"requests": []}));
+ assert_eq!(app.overlays.len(), 1, "and stays for its code");
+ }
+
+ #[test]
+ fn a_key_means_only_what_the_phone_was_offered() {
+ let both = json!({"canJoin": true, "phoneOnly": true});
+ let has_to_join = json!({"canJoin": true, "phoneOnly": false});
+ let signed_out = json!({"canJoin": false, "phoneOnly": true});
+ let (y, w, n) = (KeyCode::Char('y'), KeyCode::Char('w'), KeyCode::Char('n'));
+ assert_eq!(pairing_answer(y, &both), Some(Answer::Join));
+ assert_eq!(pairing_answer(w, &both), Some(Answer::PhoneOnly));
+ assert_eq!(pairing_answer(w, &has_to_join), None);
+ assert_eq!(pairing_answer(y, &signed_out), Some(Answer::PhoneOnly));
+ assert_eq!(pairing_answer(w, &signed_out), None);
+ assert_eq!(pairing_answer(n, &signed_out), Some(Answer::Decline));
+ }
+
#[tokio::test]
async fn waiting_phones_and_the_account_follow_the_host() {
let mut app = test_app();
@@ -91,15 +140,17 @@ mod tests {
app.pairing_requests_changed(&json!({"requests": [{"requestId": "a", "deviceName": "Pixel", "code": "123456"},
{"requestId": "b", "deviceName": "iPhone", "code": "654321"}]}));
- app.decide_pairing(true);
+ app.decide_pairing(KeyCode::Char('y'));
assert_eq!(app.pairing_requests.len(), 1, "an answered phone leaves the sheet at once");
assert_eq!(app.pairing_requests[0]["requestId"], "b");
app.pair_reply(&After::PairingDecided, Err("The host took too long to answer.".into()));
assert!(app.hint.is_some(), "a failed answer says why, and the host's list comes again");
app.pair_reply(&After::PairingRequests, Err("unknown method".into()));
assert_eq!(app.pairing_requests.len(), 1, "an older host's refusal changes nothing");
+ app.decide_pairing(KeyCode::Char('w'));
+ assert_eq!(app.pairing_requests.len(), 1, "not offered for this phone: nothing happens");
app.pairing_requests_changed(&json!({"requests": []}));
- app.decide_pairing(false);
+ app.decide_pairing(KeyCode::Char('n'));
assert_eq!(app.pairing_requests, Vec::<Value>::new());
}
}
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index 611797ad..c429c46e 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -311,8 +311,13 @@ pub struct GroupForm {
/// The pair-a-phone sheet's code: on its way, shown (its pairing link, and the short code to type when the
/// Codync cloud holds one), or why none came.
pub enum PairCode {
+ /// Opened for a phone asking: only the question shows, and no code is issued, which would wake the relay.
+ QuestionOnly,
Loading,
- Ready { url: String, short_code: Option<String> },
+ Ready {
+ url: String,
+ short_code: Option<String>,
+ },
Failed(String),
}
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 475834bf..851cc5fc 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -123,11 +123,7 @@ impl App {
s(&v, "key")
);
super::super::app::copy(&text);
- self.flash(if v["url"].is_string() {
- "Copied a curl command for the public URL (with its key)"
- } else {
- "Copied a curl command (the cloud is off: this computer only)"
- });
+ self.flash(webhook_copied(&v));
}
Reply::Registry { search, cursor } => self.with_market(|app, m| {
if !m.awaits(&search, cursor.as_deref()) {
@@ -439,6 +435,29 @@ impl App {
}
/// The entries in a host reply (`callEntries`, `botConversation`).
+/// What copying a routine's curl command says about where it works.
+fn webhook_copied(v: &Value) -> &'static str {
+ if v["url"].is_string() {
+ "Copied a curl command for the public URL (with its key)"
+ } else if v["needsAccount"] == true {
+ "Copied a curl command (not in an account: this computer only)"
+ } else {
+ "Copied a curl command (the cloud is off: this computer only)"
+ }
+}
+
fn entries_of(v: &Value) -> Vec<Entry> {
v["entries"].as_array().into_iter().flatten().filter_map(Entry::parse).map(|(_, e)| e).collect()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_copied_webhook_says_where_it_works() {
+ assert!(webhook_copied(&json!({"url": "https://x"})).contains("public URL"));
+ assert!(webhook_copied(&json!({"url": null, "needsAccount": true})).contains("not in an account"));
+ assert!(webhook_copied(&json!({"url": null, "needsAccount": false})).contains("the cloud is off"));
+ }
+}
diff --git a/host/src/tui/view/pair.rs b/host/src/tui/view/pair.rs
index 3bd04d87..f9f92fba 100644
--- a/host/src/tui/view/pair.rs
+++ b/host/src/tui/view/pair.rs
@@ -23,6 +23,8 @@ pub(super) fn pair(buf: &mut Buffer, area: Rect, app: &App, code: &PairCode) {
PairCode::Ready { url, short_code } => {
return qr(buf, area, url, short_code.as_deref(), app.outside_account());
}
+ // Only for a moment: the sheet closes with the last question.
+ PairCode::QuestionOnly => return,
PairCode::Loading => ("Getting the pairing code…", t.secondary),
PairCode::Failed(e) => (e.as_str(), t.red),
};
@@ -34,7 +36,7 @@ pub(super) fn pair(buf: &mut Buffer, area: Rect, app: &App, code: &PairCode) {
}
}
-/// A phone that scanned the code waits for this computer: `y` lets it in and the computer joins its account.
+/// A phone waits for this computer: `y` lets it in and joins its account when it can, `w` keeps the computer out of one.
fn ask(buf: &mut Buffer, area: Rect, request: &Value) {
let t = theme();
let name = request["deviceName"].as_str().unwrap_or("A phone");
@@ -46,17 +48,35 @@ fn ask(buf: &mut Buffer, area: Rect, request: &Value) {
Some((a, b)) if code.len() == 6 => format!("{a}\u{a0}{b}"),
_ => code.to_owned(),
};
- let text = fill(
- &tr("{name} wants to use this computer. It joins {email}'s account. Check the phone shows {code}."),
- &[("email", &email), ("code", &code), ("name", name)],
- );
- let lines = note(text, 52, t.text.patch(t.panel));
+ let (can_join, phone_only) = (request["canJoin"] == true, request["phoneOnly"] == true);
+ let (question, keys) = match (can_join, phone_only) {
+ (true, true) => (
+ "{name} wants to use this computer. Add it to {email}'s account? Without it, this phone can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.",
+ "y add · w Wi-Fi/Tailscale only · n don't allow",
+ ),
+ (true, false) => (
+ "{name} wants to add this computer to {email}'s account. Check the phone shows {code}.",
+ "y add to account · n don't allow",
+ ),
+ (false, _) => (
+ "{name} wants to use this computer. It can connect only over Wi-Fi or Tailscale. Check the phone shows {code}.",
+ "y let in · n don't allow",
+ ),
+ };
+ let text = fill(&tr(question), &[("email", &email), ("code", &code), ("name", name)]);
+ let mut lines = note(text, 52, t.text.patch(t.panel));
+ let removes: Vec<&str> = request["removes"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
+ if !removes.is_empty() {
+ let text =
+ fill(&tr("These phones lose access and must pair again: {names}."), &[("names", &removes.join(", "))]);
+ lines.extend(note(text, 52, t.amber.patch(t.panel)));
+ }
let r = centered(area, 56, u(lines.len() + 5));
let inner = frame_box(buf, r, t.text, t.panel, Some(("Pair a phone", t.text)));
for (y, line) in (inner.y + 1..).zip(&lines) {
put_line(buf, inner.x, y, inner.width, line);
}
- put(buf, inner.x, inner.bottom() - 1, inner.width, "y let in · n don't allow", t.dim.patch(t.panel));
+ put(buf, inner.x, inner.bottom() - 1, inner.width, keys, t.dim.patch(t.panel));
}
fn note(text: String, width: usize, style: Style) -> Vec<Line<'static>> {
@@ -84,8 +104,9 @@ fn qr(buf: &mut Buffer, area: Rect, url: &str, short_code: Option<&str>, outside
below.extend(note(text, width, t.text.patch(t.panel)));
}
if outside_account {
- let text =
- tr("Not in an account: a signed-in phone that scans this asks to bring the computer into its account.");
+ let text = tr(
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.",
+ );
below.extend(note(text.into_owned(), width, t.amber.patch(t.panel)));
}
below
@@ -130,19 +151,33 @@ mod tests {
#[test]
fn a_waiting_phone_shows_its_account_the_code_and_the_keys() {
let mut buf = Buffer::empty(Rect::new(0, 0, 80, 20));
- let request = json!({"requestId": "a", "deviceName": "Pixel", "email": "[email protected]", "code": "123456"});
+ let request = json!({"requestId": "a", "deviceName": "Pixel", "email": "[email protected]", "code": "123456",
+ "canJoin": true, "phoneOnly": true, "removes": ["Oldphone"]});
let area = buf.area;
ask(&mut buf, area, &request);
let text = shown(&buf);
- for part in ["Pixel", "[email protected]", "123\u{a0}456", "y let in · n don't allow"] {
+ for part in ["Pixel", "[email protected]", "123\u{a0}456", "Oldphone", "w Wi-Fi/Tailscale only"] {
assert!(text.contains(part), "{part} in\n{text}");
}
}
+ #[test]
+ fn a_signed_out_phone_is_only_let_in_or_turned_away() {
+ let mut buf = Buffer::empty(Rect::new(0, 0, 80, 20));
+ let request =
+ json!({"requestId": "a", "deviceName": "Pixel", "code": "123456", "canJoin": false, "phoneOnly": true});
+ let area = buf.area;
+ ask(&mut buf, area, &request);
+ let text = shown(&buf);
+ assert!(text.contains("y let in · n don't allow"), "{text}");
+ assert!(!text.contains("account"), "{text}");
+ }
+
#[test]
fn a_computer_in_no_account_says_so_under_the_code() {
- let note =
- tr("Not in an account: a signed-in phone that scans this asks to bring the computer into its account.");
+ let note = tr(
+ "Not in an account: phones connect only over Wi-Fi or Tailscale until a signed-in phone adds it to its account.",
+ );
// Its start, which fits on the first line in any language.
let first: String = note.chars().take(6).collect();
for (outside, says) in [(true, true), (false, false)] {
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index 8288eaaf..cb421357 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -213,6 +213,7 @@
"hello": "object",
"hello.analytics": "bool",
"hello.boxKey": "string",
+ "hello.canJoinAccount": "bool",
"hello.canUpdate": "bool",
"hello.cloud": "null",
"hello.computerId": "string",
diff --git a/web/app/components/questions.tsx b/web/app/components/questions.tsx
index da42b745..caf6b559 100644
--- a/web/app/components/questions.tsx
+++ b/web/app/components/questions.tsx
@@ -18,15 +18,15 @@ const questions: [string, string][] = [
],
[
"How do I start?",
- "Install Codync on the computer your agents run on and create a bot. Then sign in on your iPhone with Apple, Google or GitHub and pair it 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 pair your iPhone by scanning the code from the Mac menu bar, the Windows or Linux app, or codync-host pair. Signing in with Apple, Google or GitHub is optional.",
],
[
"Where does my data go?",
- "Bots, chats and memory stay on your computer. Your phone reaches it directly on the same network, or through an end-to-end encrypted relay anywhere else, which can't read your messages. Your agent's provider receives the prompts the agent sends.",
+ "Bots, chats and memory stay on your computer. Your phone reaches it directly on the same network or over Tailscale. With an account, it can also go through an end-to-end encrypted relay, which can't read your messages. Your agent's provider receives the prompts the agent sends.",
],
[
"Do I need an account?",
- "Yes, a free one: the apps ask you to sign in with Apple, Google or GitHub. 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.",
+ "No. Without one, your phone pairs by scanning a code and connects over Wi-Fi or Tailscale. A free account (Apple, Google or GitHub) adds the relay, which needs the computer and the phone in the same account, and lists your computers 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/privacy/page.tsx b/web/app/privacy/page.tsx
index 05735e1e..d8cb4278 100644
--- a/web/app/privacy/page.tsx
+++ b/web/app/privacy/page.tsx
@@ -37,7 +37,7 @@ export default function Privacy() {
</Section>
<Section title="Codync account">
- The Codync apps ask you to sign in with Apple, Google or GitHub, 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.
+ You can sign in to the Codync apps with Apple, Google or GitHub, so your phones can find your computers and reach them through our relay. You can also use them without an account, over Wi-Fi or Tailscale only; a computer in no account then advertises its computer ID and private network addresses on your local network, so your phones can find it there. 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">
diff --git a/web/content/docs/computer-use.mdx b/web/content/docs/computer-use.mdx
index 56f7f095..aa7c9d78 100644
--- a/web/content/docs/computer-use.mdx
+++ b/web/content/docs/computer-use.mdx
@@ -52,6 +52,7 @@ If the computer allows viewing but not control, the screen says "View only" and
- Video and input go over WebRTC and stay encrypted between your phone and Codync Screen. The setup messages travel over the same end-to-end encrypted connection as your chats.
- On a direct connection (same Wi-Fi, or Tailscale), Codync uses no STUN or TURN server. On a Mac, the picture is encoded at up to 16 Mbps and 60 fps.
- Through the Codync relay, the stream may be forwarded by Cloudflare's TURN service, which passes along encrypted packets and never sees your screen's content. This needs the computer linked to a signed-in account; otherwise the phone asks you to sign in on the computer. Relayed sessions are encoded at up to 4 Mbps and 30 fps, even if a direct path turns up later.
+- The screen follows the computer's **Connection** choice in **Manage computers**: **Auto** tries a direct path first, then Cloudflare's TURN service; **Cloudflare first** does the reverse; **Wi-Fi or Tailscale only** never asks for TURN. A computer in no account has no choice: the screen goes only directly.
- With updated iPhone and computer builds, an established screen connection can continue through a temporary chat reconnection. Setup failures reconnect with a fresh screen session.
- Revoking the phone's access or turning off remote screen stops the picture and input.
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index 17569c12..1304ddf0 100644
--- a/web/content/docs/conversations.mdx
+++ b/web/content/docs/conversations.mdx
@@ -31,7 +31,7 @@ Each chat keeps its own draft on each device, and the draft comes back when you
In the terminal, the waiting messages show above the input; press `esc`, then `S` to send the oldest one now or `D` to take back the newest.
-**When the computer is offline**, the iPhone can still take a text message: it shows **Waiting for the computer to come online** and goes out when the computer is back. It waits in the Codync relay, encrypted for your computer, for up to 24 hours; after that it shows **Failed to send**. Tap the cancel button beside it to take it back. A message with files can't wait; its send button stays off until the computer is online.
+**When the computer is offline**, the iPhone can still take a text message: it shows **Waiting for the computer to come online** and goes out when the computer is back. It waits in the Codync relay, encrypted for your computer, for up to 24 hours; after that it shows **Failed to send**. With no relay (a computer in no account), it waits on the phone instead and goes when the phone reaches the computer again. Tap the cancel button beside it to take it back. A message with files can't wait; its send button stays off until the computer is online.
If a message fails to send, it shows **Failed to send** with buttons to resend or delete it.
diff --git a/web/content/docs/getting-started.mdx b/web/content/docs/getting-started.mdx
index dd62fafd..b5b3b4ec 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 you to sign in with Apple, Google or GitHub. 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).
+The app first offers to sign in with Apple, Google or GitHub. Signed in, it asks to add the computer to your account, so your phone can find it there and reach it from anywhere. Without an account, choose **Continue on this Mac** (or **this computer**): phones then connect only over Wi-Fi or Tailscale. 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 invites you once more when you've sent your fifth message from that computer. That invitation 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 invitation ends the invitations 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. The phone needs to be signed in first, with Apple, Google or GitHub, and with the same account as the desktop app: a computer in another account turns the phone away. Apple with Hide My Email on one and Google on the other are two different accounts (more in [Remote access](/docs/remote-access#pairing)).
+Pairing connects your phone to your computer with a QR code. Signing in is optional, with one limit: without an account on both ends, the phone connects only over Wi-Fi or Tailscale. A computer in an account takes only phones of that account. Apple with Hide My Email on one and Google on the other are two different accounts (more in [Remote access](/docs/remote-access#pairing)).
On the computer, show the pairing code:
@@ -79,13 +79,13 @@ 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 sign in with Apple, Google or GitHub. If your account already has a computer, the first page offers it: tap **Pair a new computer** to set up another one here, or see below to use that one. 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**.
+On the iPhone, open Codync and sign in with Apple, Google or GitHub, or choose **Continue without an account**. If your account already has a computer, the first page offers it: tap **Pair a new computer** to set up another one here, or see below to use that one. 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**).
A pairing code expires. If pairing fails, show a new code on the computer and scan again.
-After pairing, the phone connects directly when it's on the same Wi-Fi or Tailscale network as the computer. Anywhere else it goes through the Codync relay, end-to-end encrypted, while **Reach from anywhere** is on in the computer's Codync settings. See [Remote access](/docs/remote-access).
+After pairing, the phone connects directly when it's on the same Wi-Fi or Tailscale network as the computer. Anywhere else it goes through the Codync relay, end-to-end encrypted, if the computer is in the phone's account and **Reach from anywhere** is on. A computer in no account stays reachable only directly; a signed-in phone can add it later with **Add to account** in **Manage computers**. See [Remote access](/docs/remote-access).
If you signed in to the same account on the computer and the phone, the phone can ask the computer for access instead of scanning: the first page lists your account's computers with **Ask for access**. The computer then shows the request and a code for you to check. See [Remote access](/docs/remote-access).
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index 8864ed39..1abf6713 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -42,7 +42,9 @@ codync-host status
## Pair your phone
-With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, signed in, scan the QR code during first-time setup (tap **Continue** on the install page, after **Pair a new computer** if your account already has a computer) or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**), or type the short code into the field under the scanner. A server that isn't in an account yet asks in the terminal whether to let the phone in and join your account: check the phone shows the same 6-digit code, then answer `y` within 90 seconds. With `codync-host pair --json`, or SSH without a terminal, answer with `codync-host access approve <code>` instead. A server that lets the phone in but can't join your account at that moment (its cloud is off, or the phone couldn't reach the Codync cloud) joins it the next time the phone connects with the Codync cloud on. If it still isn't in your account after that, pair it again. `codync-host cloud` says which account the server is in, and `codync-host cloud --leave` takes the server out of it: every phone paired with it loses access and pairs again with a new code.
+With the host running, run `codync-host pair` over SSH. It prints a QR code and a short code like `QRTX-4821`. On the iPhone, scan the QR code during first-time setup (tap **Continue** on the install page, after **Pair a new computer** if your account already has a computer) or later from **Manage computers → Pair a computer** (tap the connection status at the top of the Bots tab, such as **1 connected**). Signed in, you can type the short code into the field under the scanner instead.
+
+A server that isn't in an account asks in the terminal whether to let the phone in and, for a signed-in phone, whether to join its account: check the phone shows the same 6-digit code, then answer within 90 seconds. Without joining, the phone connects only over Wi-Fi or Tailscale. With `codync-host pair --json`, or SSH without a terminal, answer with `codync-host access approve <code>` (add `--phone-only` to stay out of the account). To join later, tap **Add to account** on the signed-in phone and answer the same way. `codync-host cloud` says which account the server is in, and `codync-host cloud --leave` takes the server out of it: every phone paired with it loses access and pairs again with a new code.
The code works once and expires after 10 minutes. More about pairing and accounts: [Remote access](/docs/remote-access).
@@ -71,13 +73,13 @@ On Windows, enable **OpenSSH Client** in **Windows Settings → Optional feature
You have three options, and you can combine them:
-- **Codync relay (on by default).** The host connects out to the relay, so the phone reaches the server from anywhere with nothing to open or configure.
+- **Codync relay, for a server in your account.** With the server in your account and the phone signed in to it, the host connects out to the relay, so the phone reaches the server from anywhere with nothing to open or configure.
- **Tailscale (recommended for a direct connection).** Install Tailscale on the server and on the phone, then pair. The pairing code includes the server's Tailscale address. You don't need to open any port in the cloud firewall.
- **Your own HTTPS reverse proxy.** Forward only `/channel` to the host and set `CODYNC_EXTERNAL_URL` with a systemd drop-in. Follow the steps and security rules in [Remote access](/docs/remote-access) exactly.
The pairing code lists only Tailscale and private network addresses, plus any URL you set yourself. The host never advertises the server's public IP.
-To keep the server off the relay, run `codync-host cloud --disable`. The phone then needs Tailscale, a private network or your own URL, and devices approved through your account can't connect.
+A server in no account is off the relay already; phones reach it over Tailscale, a private network or your own URL. To turn the relay off for a server in your account, run `codync-host cloud --disable`. The phone then needs one of those too, and devices approved through your account can't connect.
## Firewall
@@ -87,6 +89,8 @@ The host listens on port 19222 on every interface. Its API (the one apps on the
- a health check that reports the host's version, environment and identifiers (its install path and whether a bot is working are reported only to callers on the server itself);
- local routine webhooks, which need the routine's key.
+While the server is in no account, the host also advertises itself on the local network over mDNS (UDP port 5353): the service `_codync._tcp`, with its computer ID and private network addresses. Anyone on that network can read them. Nothing is advertised once it's in an account.
+
Keep port 19222 closed in your cloud firewall anyway, unless you deliberately connect over a VPN or private network. Tailscale and the relay don't need it open.
The firewall is also what protects a [dev server](/docs/dev-servers) a bot runs on all interfaces: on a server with a public address, the app shows that address, and anyone can open the port unless your firewall blocks it.
diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdx
index a2adeec7..23bae573 100644
--- a/web/content/docs/privacy.mdx
+++ b/web/content/docs/privacy.mdx
@@ -30,6 +30,8 @@ The relay can't add a device to your computer. A new device needs either a pairi
**Remote screen** sessions are encrypted between your phone and your computer. When there's no direct path, the video goes through a Cloudflare relay that can't see what's on your screen.
+**Local network advertising.** A computer in no account has no relay to tell a phone its new address, so it advertises its computer ID and private network addresses on the local network over mDNS. Anyone on that network can read them; Tailscale names and addresses are left out, and nothing is advertised once the computer is in an account. They go nowhere beyond the network.
+
**codync-network**, your computers' network ([bots on your other computers](/docs/teamwork#bots-on-your-other-computers)) doesn't use the Codync relay. Your computers connect to each other directly, encrypted end to end. When two can't, the default connector sends their encrypted traffic through iroh's public relays, run by n0, and they find each other through n0's address lookup; these see your computers' IP addresses and when they connect, not what they say. With your own `iroh-relay` or the private connector, nothing reaches n0.
## Push notifications
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index a6e16ae0..b7272322 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -1,21 +1,23 @@
-Your bots run on your computer. The iPhone app reaches that computer in one of two ways: **directly** (same Wi-Fi or local network, Tailscale, or an address you publish yourself) or through a **relay** that passes encrypted traffic between your phone and your computer when they can't see each other. By default that is the Codync relay on Cloudflare. You can point the computer at a relay you run yourself. Both routes use the same end-to-end encrypted connection, and the phone picks one on its own.
+Your bots run on your computer. The iPhone app reaches that computer in one of two ways: **directly** (same Wi-Fi or local network, Tailscale, or an address you publish yourself) or through a **relay** that passes encrypted traffic between your phone and your computer when they can't see each other. By default that is the Codync relay on Cloudflare, for a computer in your account and a phone signed in to that account. You can point the computer at a relay you run yourself. Both routes use the same end-to-end encrypted connection, and the phone picks one on its own.
The desktop app and the terminal UI work differently: they talk to the host on the same computer, or to another computer over SSH. They don't use the relay.
## How the phone picks a route
-Each time it connects, the phone first tries the computer's direct addresses. If none answers, it connects through the relay. When your network changes or you return to the app, it tries again, so it moves back to a direct connection when one becomes available.
+Each time it connects, the phone first tries the computer's direct addresses. If none answers, it connects through the relay, if it has one. When your network changes or you return to the app, it tries again, so it moves back to a direct connection when one becomes available.
| Route | When it works | What you set up |
| --- | --- | --- |
| Wi-Fi or local network | Phone and computer are on the same network | Nothing |
| Tailscale | Phone and computer are both on your Tailscale network | Tailscale on both |
| Your own URL | You run an HTTPS reverse proxy in front of the host | See "Your own HTTPS reverse proxy" below |
-| Codync relay | Anywhere with internet | Nothing (on by default) |
+| Codync relay | Anywhere with internet | The computer in your account, and the phone signed in to that account |
| Your own relay | Anywhere with internet | **Relay address** on the computer |
The host lists its Tailscale and private network addresses, plus any URL you set yourself. It never advertises a public IP address on its own.
+A computer in no account has no relay to tell a phone its new address, so it advertises its private network addresses on the local network. Phones nearby try them, and the connection still checks the computer's key.
+
## Pairing
Pairing introduces your phone and your computer to each other. The computer shows a one-time code as a QR code; the phone scans it and learns the computer's public keys and addresses. The computer in turn remembers your phone's key. From then on, each side can check that it's talking to the other, on any route.
@@ -26,24 +28,33 @@ Show the code on the computer:
- **Terminal:** run `codync-host pair`. It prints the QR code in the terminal, and waits to answer when the computer asks about a phone (see below). `codync-host pair --json` prints the link instead and doesn't wait.
- **Terminal UI:** press `^k` and choose **Pair a phone…**.
-Then, on the iPhone, scan it during first-time setup (tap **Continue** on the install page, after **Pair a new computer** if your account already has a computer), 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, or type the short code `codync-host pair` prints, like `QRTX-4821`.
+Then, on the iPhone, scan it during first-time setup (tap **Continue** on the install page, after **Pair a new computer** if your account already has a computer), 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 or, signed in, type the short code `codync-host pair` prints, like `QRTX-4821`.
-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.
+A code works once and expires after 10 minutes. If it has expired, show a new one on the computer. A signed-out phone pairs only directly; a signed-in phone can also pair through the relay, if the computer joins its account.
-Pairing checks your account, so a phone and a computer pair only when they're in the same Codync account:
+What happens next depends on whose computer it is:
- **The computer is in your account:** the phone is let in right away.
-- **The computer is in someone else's account:** the phone says whose (for example *k•••@example.com*). Move the computer to your account on that computer, or sign in to that account.
-- **The computer isn't in an account yet:** the computer asks first, for 90 seconds. The desktop app asks whether to let the phone in, and the terminal UI and `codync-host pair` ask you to answer `y`. Without any of them (`codync-host pair --json`, a script, SSH with no terminal), run `codync-host access approve <code>` with the 6 digits the phone shows. Check that the phone shows the same 6-digit code, then let it in. The computer joins your account. While its cloud is off or it uses a private relay, the phone gets in and the computer stays out of any account.
-- **The computer let the phone in but didn't join your account** (the phone couldn't reach the Codync cloud while pairing, or the computer's cloud was off or on a private relay): the next time the phone connects while the computer is on the Codync cloud, the computer joins your account on its own, as long as no phone of another account is paired with it. If it still isn't in your account after that, pair it again. A computer taken out of your account isn't brought back this way.
+- **The computer is in someone else's account:** the phone says whose (for example *k•••@example.com*). Move the computer to your account on that computer, or sign in to that account. A signed-out phone is told to sign in.
+- **The computer isn't in an account:** the computer asks first, for 90 seconds. Check that the phone shows the same 6-digit code, then answer:
+ - **Add to account:** the phone gets in and the computer joins the phone's account, so the phone reaches it from anywhere. Offered for a signed-in phone while the computer's cloud is on.
+ - **Wi-Fi or Tailscale only:** the phone gets in and the computer stays out of any account. Not offered for a phone that came through the relay, which it couldn't use afterwards.
+ - **Let in:** for a signed-out phone. It connects only over Wi-Fi or Tailscale.
+ - **Don't allow:** the phone stays out.
+
+Answer in the desktop app's dialog, in the terminal UI (`y` adds to the account or lets in, `w` is Wi-Fi or Tailscale only, `n` is don't allow), or in `codync-host pair`, which asks in the terminal. Without any of them (`codync-host pair --json`, a script, SSH with no terminal), run `codync-host access approve <code>` with the 6 digits the phone shows. Add `--phone-only` for **Wi-Fi or Tailscale only**, or use `codync-host access deny <code>`.
-Changing the account a computer belongs to (moving it, or **Remove from account**) takes away access from every device of the old account. A computer joining its first account keeps the phones that were already paired.
+**Adding a computer later:** on a signed-in phone connected to a computer in no account, tap **Add to account** on its card in **Manage computers**. The computer asks the same way and shows the code, in the desktop app or the terminal UI; on a server, run `codync-host access approve <code>`. If the computer doesn't answer, it stays out of the account and the phone keeps connecting over Wi-Fi or Tailscale.
+
+Changing the account a computer belongs to (moving it, or **Remove from account**) takes away access from every device of the old account. A computer joining its first account warns first, and removes phones with no account or of another account: they pair again, signed in to that account. Phones paired before version 2.36 stay.
## Signing in
-The iPhone, Android and desktop apps ask you to sign in with Apple, Google or GitHub 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:
+You can use the iPhone, Android and desktop apps without an account: choose **Continue without an account** (on the computer, **Continue on this Mac** or **this computer**). Then phones pair by scanning the computer's code, only with a computer that isn't in an account, and connect only over Wi-Fi or Tailscale. The relay, **Ask for access**, custom icons, cloud assistants and public webhook addresses need a computer in an account and a phone signed in to it.
+
+Signing in with Apple, Google or GitHub doesn't give any device access by itself. It lets your phone find the computers in your account without scanning a code, and reach them from anywhere:
-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**.
+1. On the computer, sign in to the desktop app and choose **Add to account** when it asks. For an SSH computer, choose **Add to account** on its card in **Settings → Computers**.
2. On the iPhone, sign in with the same account. The first time, the first page lists your account's computers; after that, they're in **Manage computers**. Tap **Ask for access**. The phone shows a 6-digit code. (Setting up another computer, like a VPS? Tap **Pair a new computer** on that first page.)
3. On the computer, an **Access request** opens with a code. Choose **Approve** only if it matches the code on your phone exactly. If it doesn't, choose **Deny**: someone may be trying to get in.
@@ -51,12 +62,11 @@ 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**. Every device of the old account loses access, phones paired with a QR code included. 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):
+When the computer is in another account than the desktop app's, an amber notice at the bottom of the sidebar says so (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 stops its notifications from your computers, and it keeps them: sign back in with the same account and it connects again, with no scan. To take the phone off your computers, for example before giving it away, use **Start over** on the **Settings** tab instead of signing out. Computers a phone paired before sign-in was required come along: the first sign-in moves them into the account, with no new scan.
+Signing out of a phone stops its notifications from your computers, and it keeps them: sign back in with the same account and it connects again, with no scan. To take the phone off your computers, for example before giving it away, use **Start over** on the **Settings** tab instead of signing out. Computers a phone paired without an account stay on it when it signs in: with no new scan if that account is new on the phone, or after scanning each computer's code again if the account has been on this phone before, since it has its own key there. Either way a computer joins your account only when you choose **Add to account**.
## Deleting your account
@@ -154,7 +164,7 @@ The SSH tunnel serves only the desktop app. To use that computer from your phone
A routine can start when another service (GitHub, a monitoring tool, a script) sends it a webhook. Each webhook routine has a key and two addresses:
-- A **public URL** on the Codync relay. Services anywhere can reach it without you opening a port. If your computer is offline, the relay keeps deliveries for up to 72 hours and hands them over when it's back.
+- A **public URL** on the Codync relay, for a computer in your account. Services anywhere can reach it without you opening a port. If your computer is offline, the relay keeps deliveries for up to 72 hours and hands them over when it's back.
- A **local URL** on the computer itself (`http://127.0.0.1:19222/...`).
Webhook deliveries are **not** end-to-end encrypted. The relay receives them over HTTPS, can read their content, and stores the routine's key to check signatures. Your computer checks the key again before anything runs. Turning the relay off doesn't take the public URL down (see [Turning the relay off](#turning-the-relay-off)). Setting up webhook routines: [Routines](/docs/routines).
diff --git a/web/content/docs/routines.mdx b/web/content/docs/routines.mdx
index 6d15138d..180183ab 100644
--- a/web/content/docs/routines.mdx
+++ b/web/content/docs/routines.mdx
@@ -109,7 +109,7 @@ The run's prompt tells the bot that the delivery's contents are untrusted data t
### What the Codync cloud sees
-A routine's public URL goes through the Codync cloud, so services can reach your computer without an open port or fixed address. A computer that uses [your own relay](/docs/remote-access#your-own-relay) has no public URL: only the local one works.
+A routine's public URL goes through the Codync cloud, so services can reach your computer without an open port or fixed address. A computer that isn't in an account, or that uses [your own relay](/docs/remote-access#your-own-relay), has no public URL: only the local one works.
- Deliveries to the public URL are **not end-to-end encrypted**. The cloud handles the HTTPS connection, can read each delivery, and stores the key to check it. Your computer checks the key again before anything runs.
- If your computer is off or offline, the cloud keeps deliveries for up to 72 hours and hands them over once the host is back.
diff --git a/web/public/llms.txt b/web/public/llms.txt
index 2f58a2a0..d848e268 100644
--- a/web/public/llms.txt
+++ b/web/public/llms.txt
@@ -8,7 +8,7 @@ Key facts:
- Where it runs: `codync-host`, one Rust binary, on macOS, Windows (x64, bundled in the desktop app) or Linux (desktop or headless server, static binary for x86_64 and arm64). Bots, chats and memory stay on that computer.
- Clients: native SwiftUI iPhone app (iOS 26+), one Electron desktop app for macOS, Windows and Linux, and a terminal UI (`codync-host tui`) that works over SSH.
- Features: persistent bots with their own agent, project folder and instructions; group chats where bots answer in turn; quote replies; bots asking each other for help; approval cards (allow once, always allow, deny) on the phone; per-bot memory; routines on a schedule or webhook; connectors from the MCP registry, apps through Composio, and skills; agent fallbacks (when a bot's agent runs out of usage, is rate limited, signed out or won't start, the next agent in its list carries on in the same chat); SSH computers in the Mac and Linux desktop app, their bots in the same sidebar; remote screen over WebRTC; voice calls; "needs you" and "done" push notifications.
-- Remote access: a free Cloudflare relay, end-to-end encrypted between phone and computer, or a direct connection on the same network or Tailscale. No account required; pairing is a QR code.
+- Remote access: a direct connection on the same network or Tailscale, with no account; pairing is a QR code. From anywhere else, a free Cloudflare relay, end-to-end encrypted between phone and computer, needs the computer and the phone in the same free account.
- Not affiliated with Grok Bot, Muse, Dots, Anthropic, OpenAI or any agent vendor.
## Get it