Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: add a private relay a computer can use (#209)
ForwardXuea35fadf0359
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex b2aa3964..0964e05b 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -58,8 +58,8 @@ if touches '^web/'; then(cd "$snapshot/web" && npm run check:docs)fi-for dir in cloud relay discord; do- if touches "^(cloud/|relay/|discord/|docs/reference/fixtures/remote-relay-vectors\\.json)"; then+for dir in cloud relay discord private-relay; do+ if touches "^(cloud/|relay/|discord/|private-relay/|docs/reference/fixtures/remote-relay-vectors\\.json)"; thenstaged_copyecho "Checking $dir (typecheck, test)..."ln -s "$repo/$dir/node_modules" "$snapshot/$dir/node_modules"diff --git a/.github/workflows/cloud.yml b/.github/workflows/cloud.ymlindex d209b29d..45d0f2ba 100644--- a/.github/workflows/cloud.yml+++ b/.github/workflows/cloud.yml@@ -2,7 +2,7 @@ name: codync-cloudon:pull_request:- paths: ["cloud/**", "relay/**", "discord/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/cloud.yml"]+ paths: ["cloud/**", "relay/**", "private-relay/**", "discord/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/cloud.yml"]# A newer push to the same PR supersedes the run in progress; tag runs always finish.concurrency:@@ -42,6 +42,22 @@ jobs:- run: npm run typecheck- run: npm test+ private-relay:+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: private-relay+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ cache: npm+ cache-dependency-path: private-relay/package-lock.json+ - run: npm ci+ - run: npm run typecheck+ - run: npm test+discord:runs-on: ubuntu-latestdefaults:diff --git a/AGENTS.md b/AGENTS.mdindex 25ad8a92..bf422715 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -7,7 +7,7 @@- `apps/desktop/`: desktop app for macOS, Linux and Windows (Electron, React, TypeScript): [docs/architecture/desktop-app.md](docs/architecture/desktop-app.md); how its views are styled: [docs/guides/desktop-styles.md](docs/guides/desktop-styles.md).- `apps/android/`: Android phone app (Kotlin, Jetpack Compose), ported from the iPhone app: `core` (models, crypto, transport), `design` (Codync's components), `app` (screens, store, widgets): [apps/android/README.md](apps/android/README.md).- `apps/screen-macos` and `apps/screen-linux`: Remote screen helpers.-- `cloud/`: Cloudflare accounts, encrypted relay, Durable Objects and D1; tests live in `cloud/test/`.+- `cloud/`: Cloudflare accounts, encrypted relay, Durable Objects and D1; tests live in `cloud/test/`. `private-relay/`: a single-process subset of that relay a person runs for their own computers (Node, `node:sqlite`), tests in `private-relay/test/`.- `relay/`: Cloudflare push worker and `test/`; `web/`: website (Next.js); `packaging/`: distribution templates; `docs/`: architecture and naming guidance.## Host owns the logicdiff --git a/README.md b/README.mdindex 73b963d5..d296997a 100644--- a/README.md+++ b/README.md@@ -201,6 +201,7 @@ Data lives in `~/.codync`. The local bearer token authorizes loopback helpers an| `apps/screen-macos/`, `apps/screen-linux/` | Platform screen capture/input helpers || `docs/` | [Documentation index](docs/README.md) and [file structure](docs/architecture/file-structure.md) || `relay/` | Cloudflare Worker APNs relay with encrypted per-device tickets |+| `private-relay/` | Single-process Node relay a person runs for their own computers: the cloud relay's WebSocket subset, without accounts || `web/` | Website (Next.js static export, deployed on Vercel) || `packaging/` | Homebrew cask and formula templates (published to `leepokai/homebrew-codync` on release) and `install.sh` (the curl installer) |diff --git a/SECURITY.md b/SECURITY.mdindex e0bf6c0f..3be9fa74 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -26,7 +26,7 @@ We close these without a reply:- **"A paired device can run commands on the host."** This covers it through bot launch commands, agent prompts, permission modes, working folders, the screen, or any other route. See the trust model.- Attacks that require a compromised computer, a compromised paired device, or physical access to an unlocked one.- What a coding agent does when you prompt it, including prompt injection into an agent you chose to run. Report those to the agent's vendor.-- Self-hosted or third-party relay deployments you configured yourself.+- Self-hosted or third-party relay deployments you configured yourself: how you set up and run the server. Vulnerabilities in the code itself, including the [private relay](private-relay/README.md) in this repository, are in scope.- Missing hardening with no exploit: headers, rate limits beyond those documented, dependency versions with no reachable vulnerable path, and so on.- Findings from scanners or AI tools that you did not reproduce yourself.diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex c1195e88..c8caf019 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -14,12 +14,14 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動翻頁,每頁可選 6、10、20 或 50 筆。- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自列表上方。+- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.-- Extensions shows Agents, Connectors or Skills one at a time, in pages: tap the round buttons beside the list or swipe, with 6, 10, 20 or 50 per page.+- Extensions shows Agents, Connectors or Skills in pages: tap the round buttons or swipe, 6 to 50 per page.- Credentials sits beside the computer's name; Custom connector and Your own skill top their lists.+- A private relay shows its address in Settings and status.## 2.26.0diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.ktindex a3e557ea..90ec82cc 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@@ -2,8 +2,10 @@ package com.codync.androidimport com.codync.android.core.CloudComputerimport com.codync.android.core.Computer+import com.codync.android.core.ConnectionRouteimport com.codync.android.core.HostRouteimport com.codync.android.core.LinkState+import com.codync.android.core.Pairing// What the roster header, Computers & settings and the chat header say about the computer's link// (iOS `ComputerStatus`, `ConnectionSummary`, `BotStore.connectionLabel`).@@ -39,11 +41,53 @@ internal fun connectionDescription(state: AppState): String {link == LinkState.Connecting -> "Connecting"link !is LinkState.Ready -> connectionLabel(state)state.mismatch != null -> "Needs update"- link.route == HostRoute.Relay -> "Connected through Cloudflare"+ link.route == HostRoute.Relay -> connectedThrough(state.computers.firstOrNull()?.cloud)else -> "Connected over Wi-Fi or Tailscale"}}+/** Host of a private relay, or null when this is an official Codync cloud (those stay "Cloudflare"). */+internal fun relayHost(cloud: String?): String? {+ if (cloud.isNullOrBlank()) return null+ val uri = runCatching { java.net.URI(cloud.trim()) }.getOrNull() ?: return null+ // `URI.host` keeps an IPv6 address's brackets.+ val name = uri.host?.lowercase() ?: return null+ if ((name == "api.codync.dev" || name == "dev-api.codync.dev") && uri.port == -1) return null+ return if (uri.port > 0) "$name:${uri.port}" else name+}++/** The route after a bot count in Computers & settings (iOS `RelayCopy.detailSuffix`). */+internal fun routeLabel(route: HostRoute, cloud: String?): String =+ if (route == HostRoute.Direct) "Wi-Fi/Tailscale" else relayHost(cloud)?.let { "Private relay ($it)" } ?: "Cloudflare"++internal fun connectedThrough(cloud: String?): String {+ val host = relayHost(cloud)+ return if (host == null) "Connected through Cloudflare" else "Connected through Private relay ($host)"+}++internal fun routeTitle(route: ConnectionRoute, cloud: String?): String {+ val host = relayHost(cloud) ?: return when (route) {+ ConnectionRoute.Automatic -> "Auto: Wi-Fi or Tailscale, then Cloudflare"+ ConnectionRoute.CloudflareFirst -> "Cloudflare, then Wi-Fi or Tailscale"+ ConnectionRoute.DirectOnly -> "Wi-Fi or Tailscale only, never Cloudflare"+ }+ return when (route) {+ ConnectionRoute.Automatic -> "Auto: Wi-Fi or Tailscale, then Private relay ($host)"+ ConnectionRoute.CloudflareFirst -> "Private relay ($host), then Wi-Fi or Tailscale"+ ConnectionRoute.DirectOnly -> "Wi-Fi or Tailscale only, never Private relay ($host)"+ }+}++internal fun pairingLine(cloud: String?): String {+ val host = relayHost(cloud)+ return if (host == null) "Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted."+ else "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ($host), on its own. End-to-end encrypted."+}++/** 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())+/** "1 connected", "Connecting…", "No access": the roster header's summary of its computers. */internal fun connectionSummary(state: AppState): String = when {state.computers.isEmpty() -> "Computers"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.ktindex a3e530cd..1cc11800 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@@ -247,7 +247,7 @@ private enum class ComputerOS { Mac, Linux }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("Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted.", "lock.fill")+ IconLabel(pairingLine(pasted, BuildConfig.URL_SCHEME), "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/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.ktindex a99ff5a2..69bd9aef 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt@@ -47,7 +47,6 @@ import androidx.compose.ui.unit.dpimport com.codync.android.core.Botimport com.codync.android.core.CloudComputerimport com.codync.android.core.ConnectionRoute-import com.codync.android.core.HostRouteimport com.codync.android.core.LinkStateimport com.codync.android.design.*import com.kyant.shapes.Capsule@@ -202,7 +201,7 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unitval viewable = online && state.screen != nullval detail = if (link is LinkState.Ready) {val count = state.bots.count { !it.deleted && it.kind != "group" }- "$count bot${if (count == 1) "" else "s"} · ${if (link.route == HostRoute.Direct) "Wi-Fi/Tailscale" else "Cloudflare"}"+ "$count bot${if (count == 1) "" else "s"} · ${routeLabel(link.route, computer.cloud)}"} else computerStatusText(state)Column(Modifier.fillMaxWidth().contextActions(items = {listOfNotNull(@@ -246,7 +245,7 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> UnitIconButton("Extensions", "square.grid.2x2", action = actions.extensions)if (state.screen != null) IconButton("Screen", "display", action = actions.screen)}- DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },+ DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(routeTitle(route, computer.cloud), icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },Modifier.size(36.dp), label = "Connection") {Symbol(computer.route.icon, size = 21.dp, tint = Palette.secondary)}@@ -346,12 +345,6 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit}}-private val ConnectionRoute.title get() = when (this) {- ConnectionRoute.Automatic -> "Auto: Wi-Fi or Tailscale, then Cloudflare"- ConnectionRoute.CloudflareFirst -> "Cloudflare, then Wi-Fi or Tailscale"- ConnectionRoute.DirectOnly -> "Wi-Fi or Tailscale only, never Cloudflare"-}-private val ConnectionRoute.icon get() = when (this) {ConnectionRoute.Automatic -> "arrow.triangle.branch"ConnectionRoute.CloudflareFirst -> "cloud"diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.ktindex f98dc618..67219a80 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt@@ -32,6 +32,16 @@ class ConnectionPresentationTest {assertEquals("Not paired", statusText(unpaired))assertEquals("Not paired", connectionLabel(unpaired))assertEquals("Not paired", connectionDescription(unpaired))+ val custom = computer.copy(cloud = "https://relay.example.com")+ assertEquals("Connected through Private relay (relay.example.com)", connectionDescription(state(LinkState.Ready(HostRoute.Relay), computers = listOf(custom))))+ assertEquals("Connected through Cloudflare", connectionDescription(state(LinkState.Ready(HostRoute.Relay), computers = listOf(computer.copy(cloud = "https://api.codync.dev")))))+ assertEquals("relay.example.com", relayHost("https://relay.example.com/"))+ assertEquals(null, relayHost("https://dev-api.codync.dev"))+ assertEquals("[2001:db8::1]:8443", relayHost("https://[2001:db8::1]:8443"))+ assertEquals("[2001:db8::1]", relayHost("https://[2001:db8::1]"))+ assertEquals("Private relay (relay.example.com)", routeLabel(HostRoute.Relay, "https://relay.example.com"))+ assertEquals("Cloudflare", routeLabel(HostRoute.Relay, "https://api.codync.dev"))+ assertEquals("Wi-Fi/Tailscale", routeLabel(HostRoute.Direct, "https://relay.example.com"))}@Test fun anOfflineComputerSaysWhenItWasLastSeen() {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.ktnew file mode 100644index 00000000..e0948671--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt@@ -0,0 +1,22 @@+package com.codync.android++import java.net.URLEncoder+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+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"))+ val link = "codync://pair?" + mapOf(+ "v" to "3",+ "id" to "NHUPmL1Z_PyUbaRaqr6TOw",+ "sk" to "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w",+ "bk" to "zo060cy2M-x7cMF4FKXHbs0CloUFDTRHRboFhw5YfVk",+ "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)"))+ }+}diff --git a/apps/desktop/src/renderer/lib/auto-claim.test.ts b/apps/desktop/src/renderer/lib/auto-claim.test.tsindex 9abdfc2f..53ab1559 100644--- a/apps/desktop/src/renderer/lib/auto-claim.test.ts+++ b/apps/desktop/src/renderer/lib/auto-claim.test.ts@@ -19,3 +19,8 @@ test('no auto-claim when kept out, owned, offline, or the cloud is off or unknowassert.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)+})diff --git a/apps/desktop/src/renderer/lib/auto-claim.ts b/apps/desktop/src/renderer/lib/auto-claim.tsindex 56077f8c..6f7d63d7 100644--- a/apps/desktop/src/renderer/lib/auto-claim.ts+++ b/apps/desktop/src/renderer/lib/auto-claim.ts@@ -2,15 +2,17 @@export interface ClaimCandidate {id: stringonline: boolean- cloud: { enabled: boolean; owner?: unknown } | null+ cloud: { enabled: boolean; owner?: unknown; relay?: string | null } | null}/**- * Whether this computer joins the signed-in account on its own. Only with the cloud on: joining needs- * it, and turning it back on is never done silently. Never an identity the user took out here- * (`keptOut`), nor one 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.+ * Whether this computer joins the signed-in account on its own. 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`), nor one 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 host.online && !!host.cloud?.enabled && !host.cloud.owner && !keptOut.includes(host.id) && !seen.includes(host.id)+ const cloud = host.cloud+ return host.online && !!cloud?.enabled && cloud.relay !== 'private' && !cloud.owner && !keptOut.includes(host.id) && !seen.includes(host.id)}diff --git a/apps/desktop/src/renderer/lib/l10n.test.ts b/apps/desktop/src/renderer/lib/l10n.test.tsindex f4ab9bec..09ef8444 100644--- a/apps/desktop/src/renderer/lib/l10n.test.ts+++ b/apps/desktop/src/renderer/lib/l10n.test.ts@@ -124,6 +124,10 @@ test('known chrome becomes Chinese and everything else stays', () => {assert.equal(translate('Usage', 'zh', false), '用量')assert.equal(translate('Computers & devices', 'zh', false), '电脑和设备')assert.equal(translate('Reachable from anywhere through Cloudflare (encrypted).', 'zh', false), '通过 Cloudflare 随时随地连接(已加密)。')+ assert.equal(+ translate('Reachable from anywhere through Private relay (relay.example.com) (encrypted).', 'zh', false),+ '通过私人中继(relay.example.com)随时随地连接(已加密)。',+ )assert.equal(translate('Use Anthropic Console (API usage billing)', 'zh', false), '使用 Anthropic 控制台(按 API 用量计费)')assert.equal(translate('12 pt (Default)', 'zh', false), '12 pt(默认)')assert.equal(diff --git a/apps/desktop/src/renderer/lib/relay-address.test.ts b/apps/desktop/src/renderer/lib/relay-address.test.tsnew file mode 100644index 00000000..2a8ff99c--- /dev/null+++ b/apps/desktop/src/renderer/lib/relay-address.test.ts@@ -0,0 +1,11 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { relayAddressToSave } from './relay-address.ts'++test('a typed relay address is stored only when it changes', () => {+ assert.equal(relayAddressToSave(' https://relay.example.com/ ', 'https://relay.example.com'), null)+ assert.equal(relayAddressToSave('https://relay.example.com///', 'https://relay.example.com'), null)+ assert.equal(relayAddressToSave(' ', null), null)+ assert.equal(relayAddressToSave('https://other.example', 'https://relay.example.com'), 'https://other.example')+ assert.equal(relayAddressToSave(' ', 'https://relay.example.com'), '')+})diff --git a/apps/desktop/src/renderer/lib/relay-address.ts b/apps/desktop/src/renderer/lib/relay-address.tsnew file mode 100644index 00000000..a2ba66e8--- /dev/null+++ b/apps/desktop/src/renderer/lib/relay-address.ts@@ -0,0 +1,6 @@+/** The relay address to store, or null when the typed text already matches the saved one. */+export function relayAddressToSave(typed: string, saved: string | null | undefined): string | null {+ const next = typed.trim().replace(/\/+$/, '')+ const current = (saved ?? '').trim().replace(/\/+$/, '')+ return next === current ? null : next+}diff --git a/apps/desktop/src/renderer/lib/relay-copy.test.ts b/apps/desktop/src/renderer/lib/relay-copy.test.tsnew file mode 100644index 00000000..7979a06d--- /dev/null+++ b/apps/desktop/src/renderer/lib/relay-copy.test.ts@@ -0,0 +1,23 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { cloudStatusLine, connectedThrough, relayHost } from './relay-copy.ts'++test('official clouds stay Cloudflare and any other host is named', () => {+ assert.equal(relayHost('https://api.codync.dev'), null)+ assert.equal(relayHost('https://dev-api.codync.dev/'), null)+ assert.equal(relayHost(null), null)+ assert.equal(relayHost('https://relay.example.com'), 'relay.example.com')+ assert.equal(relayHost('http://127.0.0.1:8788'), '127.0.0.1:8788')+ assert.equal(relayHost('https://[2001:db8::1]:8443'), '[2001:db8::1]:8443')+ assert.equal(relayHost('https://[2001:db8::1]'), '[2001:db8::1]')+ assert.equal(connectedThrough('https://api.codync.dev'), 'Connected through Cloudflare')+ assert.equal(connectedThrough('https://relay.example.com'), 'Connected through Private relay (relay.example.com)')+ assert.equal(+ cloudStatusLine({ enabled: true, url: 'https://relay.example.com', connected: true }),+ 'Reachable from anywhere through Private relay (relay.example.com) (encrypted).',+ )+ 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.tsnew file mode 100644index 00000000..c543708d--- /dev/null+++ b/apps/desktop/src/renderer/lib/relay-copy.ts@@ -0,0 +1,33 @@+/** What the interface calls the computer's relay. Official clouds stay "Cloudflare". */++const OFFICIAL = new Set(['api.codync.dev', 'dev-api.codync.dev'])++/** Host, with a non-default port. Null for the official Codync clouds or when there is no URL. */+export function relayHost(cloud: string | null | undefined): string | null {+ if (!cloud) return null+ let url: URL+ try {+ url = new URL(cloud)+ } catch {+ return null+ }+ const hostname = url.hostname.toLowerCase()+ if (OFFICIAL.has(hostname) && url.port === '') return null+ // `URL.hostname` already brackets an IPv6 address.+ return url.port ? `${hostname}:${url.port}` : hostname+}++export function connectedThrough(cloud: string | null | undefined): string {+ const host = relayHost(cloud)+ return host ? `Connected through Private relay (${host})` : 'Connected through Cloudflare'+}++/** 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 {+ if (!cloud.enabled) return 'Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare.'+ const host = relayHost(cloud.url)+ if (!host) return cloud.connected ? 'Reachable from anywhere through Cloudflare (encrypted).' : 'Connecting to Cloudflare…'+ return cloud.connected+ ? `Reachable from anywhere through Private relay (${host}) (encrypted).`+ : `Connecting to Private relay (${host})…`+}diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.tsindex d1dbed01..938c4300 100644--- a/apps/desktop/src/renderer/store/cloud.ts+++ b/apps/desktop/src/renderer/store/cloud.ts@@ -2,6 +2,7 @@ import type { CloudStatus, ClaimSignature } from '@shared/models'import { mayAutoClaim } from '../lib/auto-claim'import { Observable } from '../lib/observable'import { isOlderCopy } from '../lib/older-copy'+import { relayAddressToSave } from '../lib/relay-address'import { pref, type Pref } from '../lib/prefs'import { account } from './account'import type { AppModel } from './app-model'@@ -268,6 +269,29 @@ export class CloudModel extends Observable {}}+ /** Points this computer's relay at `raw`, or clears it when `raw` is blank. False when the host refuses. */+ async setCloudUrl(store: BotStore, raw: string): Promise<boolean> {+ const next = relayAddressToSave(raw, store.cloud?.url)+ return next === null || (await this.saveRelay(store, { url: next }))+ }++ /** Saves the private relay's registration token for the address in use. Blank leaves it as it is. */+ async setRelayToken(store: BotStore, token: string): Promise<void> {+ const url = store.cloud?.url+ if (url && token.trim()) await this.saveRelay(store, { url, token: token.trim() })+ }++ /** The host's `setCloudUrl`. The relay restarts, same as turning the cloud on or off. */+ private async saveRelay(store: BotStore, body: { url: string; token?: string }): Promise<boolean> {+ try {+ await (await store.ready()).call('setCloudUrl', body, 30_000)+ return true+ } catch (error) {+ this.fail(error)+ return false+ }+ }+async setCloud(store: BotStore, enabled: boolean) {include(cloudDefaultApplied, store.computer.id)try {diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsxindex c3376a76..3efc082f 100644--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx@@ -14,8 +14,10 @@ import { StoreContext, useApp } from '../../store/context'import { ComputerBadge } from '../ComputerBadge'import { PairingCode } from '../PairingCode'import { AuthorizedDevicesSection } from './AuthorizedDevicesSection'+import { cloudStatusLine } from '../../lib/relay-copy'import { useTr } from '../../lib/use-language'import { errorText, liveClient, relativeDay, SectionHeader, statusText, thisMac } from './parts'+import { RelayAddressRow, RelayTokenRow } from './RelayFields'import { useSSH } from './ssh-model'import { SSHConfigSuggestions } from './SSHConfigSuggestions'import { SSHRow } from './SSHRow'@@ -113,9 +115,9 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: boconst manageable = online && !store.mismatchconst name = store.hostName- const run = (work: () => Promise<void>) => {+ const run = <T,>(work: () => Promise<T>): Promise<T> => {setBusy(true)- void work().finally(() => setBusy(false))+ return work().finally(() => setBusy(false))}const setApproval = (approval: AccountApproval) =>@@ -127,9 +129,10 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo}})- const cloudLine = !cloud?.enabled- ? tr('Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare.')- : (cloud.lastError ?? tr(cloud.connected ? 'Reachable from anywhere through Cloudflare (encrypted).' : 'Connecting to Cloudflare…'))+ // A private relay has no accounts: no claim, no access requests.+ const privateRelay = cloud?.relay === 'private'+ // The host's error is shown as it wrote it.+ const cloudLine = cloud?.enabled && cloud.lastError ? cloud.lastError : cloud ? tr(cloudStatusLine(cloud)) : ''const accountLine = (<HStack key="account" gap={8} className="settings-row settings-appear">@@ -182,7 +185,19 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo<Text size="caption" tone={cloud.lastError ? 'attention' : 'secondary'}>{cloudLine}</Text></span></Switch>,- accountLine,+ // The relay's address shows only while it's on: off, the host reports no address, so the+ // field couldn't tell a saved private relay from none.+ ...(cloud.enabled+ ? [<RelayAddressRow key="relay" url={cloud.url} disabled={busy || !manageable} save={(typed) => run(() => app.cloud.setCloudUrl(store, typed))} />]+ : []),+ // Only a private relay asks for a token; the Codync cloud never does.+ privateRelay ? (+ cloud.enabled ? (+ <RelayTokenRow key="relay-token" tokenSet={cloud.tokenSet === true} disabled={busy || !manageable} save={(token) => void run(() => app.cloud.setRelayToken(store, token))} />+ ) : null+ ) : (+ accountLine+ ),]: []),...(ownerdiff --git a/apps/desktop/src/renderer/views/settings/RelayFields.tsx b/apps/desktop/src/renderer/views/settings/RelayFields.tsxnew file mode 100644index 00000000..f969ba67--- /dev/null+++ b/apps/desktop/src/renderer/views/settings/RelayFields.tsx@@ -0,0 +1,67 @@+import { Text } from '../../components/Text'+import { useTr } from '../../lib/use-language'++/**+ * A settings row whose field saves when it loses focus; Enter blurs it. Uncontrolled, so a host+ * status event never overwrites what is being typed.+ */+function CommitField(props: { label: string; placeholder: string; defaultValue: string; password?: boolean; disabled: boolean; commit: (input: HTMLInputElement) => void }) {+ const tr = useTr()+ return (+ <div className="settings-row settings-appear">+ <Text tone="text">{tr(props.label)}</Text>+ <input+ className="settings-field"+ aria-label={tr(props.label)}+ type={props.password ? 'password' : undefined}+ autoComplete={props.password ? 'off' : undefined}+ placeholder={props.placeholder}+ defaultValue={props.defaultValue}+ spellCheck={false}+ disabled={props.disabled}+ onBlur={(e) => props.commit(e.currentTarget)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') e.currentTarget.blur()+ }}+ />+ </div>+ )+}++/** The computer's relay address. A new saved address resets the field; a refused one puts the saved one back. */+export function RelayAddressRow({ url, disabled, save }: { url: string | null | undefined; disabled: boolean; save: (typed: string) => Promise<boolean> }) {+ const saved = url ?? ''+ return (+ <CommitField+ key={saved}+ label="Relay address"+ placeholder="https://"+ defaultValue={saved}+ disabled={disabled}+ commit={(input) =>+ void save(input.value).then((kept) => {+ if (!kept) input.value = saved+ })+ }+ />+ )+}++/** A private relay's registration token. Write-only: the field only says whether one is saved. */+export function RelayTokenRow({ tokenSet, disabled, save }: { tokenSet: boolean; disabled: boolean; save: (token: string) => void }) {+ const tr = useTr()+ return (+ <CommitField+ label="Relay token"+ password+ placeholder={tokenSet ? tr('Saved. Type a new one to replace it.') : tr("The token from the relay's setup")}+ defaultValue=""+ disabled={disabled}+ commit={(input) => {+ const typed = input.value+ input.value = ''+ save(typed)+ }}+ />+ )+}diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex 94dd5f5e..24e86612 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -7,6 +7,7 @@ import { Sheet, usePresence } from '../../components/Overlay'import { HStack, IconSlot, Spacer } from '../../components/Stack'import { Text } from '../../components/Text'import { prefs, usePref } from '../../lib/prefs'+import { connectedThrough } from '../../lib/relay-copy'import { useTr } from '../../lib/use-language'import { useScreenViewed } from '../../store/analytics'import { useStore } from '../../store/context'@@ -247,6 +248,7 @@ function TopFade() {function ConnectionSubtitle() {const store = useStore()+ const tr = useTr()const connecting = store.shownConnection.kind === 'connecting'const symbol = store.connection.kind !== 'online' ? 'wifi.slash' : store.hostRoute === 'relay' ? 'cloud' : store.hostRoute === 'direct' ? 'wifi' : store.hostRoute === 'loopback' ? 'desktopcomputer' : 'network'const description = (() => {@@ -262,10 +264,11 @@ function ConnectionSubtitle() {return 'Not paired'}if (store.mismatch) return 'Needs update'- return store.hostRoute === 'relay' ? 'Connected through Cloudflare' : store.hostRoute === 'direct' ? 'Connected over Wi-Fi or Tailscale' : store.hostRoute === 'loopback' ? 'Connected locally' : 'Connected'+ return store.hostRoute === 'relay' ? connectedThrough(store.computer.cloud) : store.hostRoute === 'direct' ? 'Connected over Wi-Fi or Tailscale' : store.hostRoute === 'loopback' ? 'Connected locally' : 'Connected'})()+ const spoken = tr(description)return (- <HStack as="span" gap={6} className="title-pill-subtitle" title={`${store.hostName} · ${description}`} aria-label={`${store.hostName}, ${description}`}>+ <HStack as="span" gap={6} className="title-pill-subtitle" title={`${store.hostName} · ${spoken}`} aria-label={`${store.hostName}, ${spoken}`}><IconSlot width={12}>{connecting ? <Spinner size={8} /> : <Icon name={symbol} size={8} weight="medium" />}</IconSlot><Text size="caption" weight="medium" truncate>{store.connectionLabel}</Text></HStack>diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 5f6d4117..cdc5b592 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -527,11 +527,15 @@ export type AccountApproval = 'code' | 'auto'export interface CloudStatus {enabled: booleanurl?: string | null+ /** A private relay's registration token is saved (the token itself never leaves the host). */+ tokenSet?: boolean | nullregistered?: boolean | nullconnected?: boolean | nullowner?: CloudOwner | nulllastError?: string | nullapproval?: AccountApproval | null+ /** Whose relay: a `private` one has no account, access requests or relayed screen. Absent from older hosts (always Codync's). */+ relay?: 'codync' | 'private' | null}export interface ClaimSignature {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift b/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swiftnew file mode 100644index 00000000..e4510de6--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/RelayCopy.swift@@ -0,0 +1,61 @@+import Foundation++/// What the interface calls the computer's relay. The official clouds stay "Cloudflare".+/// Any other cloud URL is that person's private relay, named by its host.+public enum RelayCopy {+ private static let official = ["api.codync.dev", "dev-api.codync.dev"]++ /// Host (and a non-default port) when `cloud` is a private relay. Nil for the official clouds.+ public static func host(of cloud: URL?) -> String? {+ guard let cloud, let name = cloud.host?.lowercased() else { return nil }+ if official.contains(name), cloud.port == nil { return nil }+ // `URL.host` drops an IPv6 address's brackets; the other clients keep them.+ let shown = name.contains(":") ? "[\(name)]" : name+ if let port = cloud.port { return "\(shown):\(port)" }+ return shown+ }++ /// The connection menu sentence. Official clouds keep the existing Cloudflare phrases.+ public static func routeTitle(_ route: ConnectionRoute, cloud: URL?) -> String {+ guard let host = host(of: cloud) else {+ return switch route {+ case .automatic: "Auto: Wi-Fi or Tailscale, then Cloudflare"+ case .cloudflareFirst: "Cloudflare, then Wi-Fi or Tailscale"+ case .directOnly: "Wi-Fi or Tailscale only, never Cloudflare"+ }+ }+ return switch route {+ case .automatic: "Auto: Wi-Fi or Tailscale, then Private relay (\(host))"+ case .cloudflareFirst: "Private relay (\(host)), then Wi-Fi or Tailscale"+ case .directOnly: "Wi-Fi or Tailscale only, never Private relay (\(host))"+ }+ }++ /// The short suffix after a bot count: ` · Cloudflare` or ` · Private relay (host)`.+ public static func detailSuffix(route: HostRoute?, cloud: URL?) -> String {+ switch route {+ case .direct: " · Wi-Fi/Tailscale"+ case .relay: host(of: cloud).map { " · Private relay (\($0))" } ?? " · Cloudflare"+ case nil: ""+ }+ }++ public static func connected(cloud: URL?) -> String {+ host(of: cloud).map { "Connected through Private relay (\($0))" } ?? "Connected through Cloudflare"+ }++ public static func through(cloud: URL?) -> String {+ host(of: cloud).map { "Through Private relay (\($0))" } ?? "Through Cloudflare"+ }++ public static func pairing(cloud: URL?) -> String {+ host(of: cloud).map {+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay (\($0)), on its own. End-to-end encrypted."+ } ?? "Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted."+ }++ /// 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)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex dc3361d8..bc043669 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -263,6 +263,18 @@"This computer": "Dieser Computer","This iPhone forgets the account's computers. Your bots stay on them.": "Dieses iPhone vergisst die Computer des Kontos. Deine Bots bleiben auf ihnen erhalten.","Through Cloudflare": "Über Cloudflare",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Auto: Wi-Fi oder Tailscale, dann privates Relay ({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "Privates Relay ({host}), dann Wi-Fi oder Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "Nur WLAN oder Tailscale, niemals privates Relay ({host})",+ "Connected through Private relay ({host})": "Über privates Relay ({host}) verbunden",+ "Through Private relay ({host})": "Über privates Relay ({host})",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "Verbindet sich allein über WLAN, über Tailscale oder von überall über privates Relay ({host}). Ende-zu-Ende verschlüsselt.",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "Von überall über privates Relay ({host}) erreichbar (verschlüsselt).",+ "Connecting to Private relay ({host})…": "Verbindung mit privatem Relay ({host}) wird hergestellt…",+ "Relay address": "Relay-Adresse",+ "Relay token": "Relay-Token",+ "Saved. Type a new one to replace it.": "Gespeichert. Gib ein neues ein, um es zu ersetzen.",+ "The token from the relay's setup": "Der Token aus der Einrichtung des Relays","Try again": "Erneut versuchen","Turn on": "Aktivieren","Turn on notifications": "Mitteilungen aktivieren",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 699ed4d7..757bb03c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -263,6 +263,18 @@"This computer": "Esta computadora","This iPhone forgets the account's computers. Your bots stay on them.": "Este iPhone se olvida de los ordenadores de la cuenta. Tus robots permanecen en ellos.","Through Cloudflare": "A través de Cloudflare",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Automático: Wi-Fi o Tailscale, luego relé privado ({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "Relé privado ({host}), luego Wi-Fi o Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "Solo Wi-Fi o Tailscale, nunca el relé privado ({host})",+ "Connected through Private relay ({host})": "Conectado mediante relé privado ({host})",+ "Through Private relay ({host})": "A través del relé privado ({host})",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "Se conecta por Wi-Fi, a través de Tailscale o desde cualquier lugar a través del relé privado ({host}), por sí solo. Cifrado de extremo a extremo.",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "Accesible desde cualquier lugar mediante relé privado ({host}) (cifrado).",+ "Connecting to Private relay ({host})…": "Conectando con el relé privado ({host})…",+ "Relay address": "Dirección del relé",+ "Relay token": "Token del relé",+ "Saved. Type a new one to replace it.": "Guardado. Escribe uno nuevo para reemplazarlo.",+ "The token from the relay's setup": "El token de la configuración del relé","Try again": "Intentar otra vez","Turn on": "Encender","Turn on notifications": "Activar notificaciones",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 06a42a9f..468e531f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -263,6 +263,18 @@"This computer": "Cet ordinateur","This iPhone forgets the account's computers. Your bots stay on them.": "Cet iPhone oublie les ordinateurs du compte. Vos bots restent sur ces ordinateurs.","Through Cloudflare": "Via Cloudflare",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "Auto : Wi-Fi ou Tailscale, puis relais privé ({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "Relais privé ({host}), puis Wi-Fi ou Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "Wi-Fi ou Tailscale uniquement, jamais le relais privé ({host})",+ "Connected through Private relay ({host})": "Connecté via le relais privé ({host})",+ "Through Private relay ({host})": "Via le relais privé ({host})",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "Se connecte seul en Wi-Fi, via Tailscale ou depuis n'importe où via le relais privé ({host}). Chiffré de bout en bout.",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "Accessible de partout via le relais privé ({host}) (chiffré).",+ "Connecting to Private relay ({host})…": "Connexion au relais privé ({host})…",+ "Relay address": "Adresse du relais",+ "Relay token": "Jeton du relais",+ "Saved. Type a new one to replace it.": "Enregistré. Saisissez-en un nouveau pour le remplacer.",+ "The token from the relay's setup": "Le jeton défini lors de l'installation du relais","Try again": "Réessayer","Turn on": "Activer","Turn on notifications": "Activer les notifications",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 4d451ab2..07dbcf5a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -263,6 +263,18 @@"This computer": "このコンピュータ","This iPhone forgets the account's computers. Your bots stay on them.": "この iPhone はアカウントのコンピュータを忘れます。ボットはそこに留まります。","Through Cloudflare": "Cloudflareを通じて",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自動: Wi-Fi または Tailscale、次にプライベートリレー({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "プライベートリレー({host})、次に Wi-Fi または Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "Wi-Fi または Tailscale のみ、プライベートリレー({host})は不可",+ "Connected through Private relay ({host})": "プライベートリレー({host})経由で接続",+ "Through Private relay ({host})": "プライベートリレー({host})を通じて",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "Wi-Fi、Tailscale経由、またはプライベートリレー({host})経由でどこからでも単独で接続します。エンドツーエンドで暗号化されます。",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "プライベートリレー({host})(暗号化)を介してどこからでもアクセス可能。",+ "Connecting to Private relay ({host})…": "プライベートリレー({host})に接続中…",+ "Relay address": "リレーのアドレス",+ "Relay token": "リレーのトークン",+ "Saved. Type a new one to replace it.": "保存済み。新しいものを入力すると置き換えます。",+ "The token from the relay's setup": "リレーの設定で発行したトークン","Try again": "再試行","Turn on": "オンにする","Turn on notifications": "通知をオンにする",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex f5eb3265..3ebb9780 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -263,6 +263,18 @@"This computer": "이 컴퓨터","This iPhone forgets the account's computers. Your bots stay on them.": "이 iPhone는 계정의 컴퓨터를 잊어버립니다. 당신의 봇은 그 위에 머물러 있습니다.","Through Cloudflare": "Cloudflare를 통해",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "자동: Wi-Fi 또는 Tailscale, 프라이빗 릴레이({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "프라이빗 릴레이({host}), 그 다음 Wi-Fi 또는 Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "Wi-Fi 또는 Tailscale만 가능, 프라이빗 릴레이({host}) 불가",+ "Connected through Private relay ({host})": "프라이빗 릴레이({host})를 통해 연결됨",+ "Through Private relay ({host})": "프라이빗 릴레이({host})를 통해",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "Wi-Fi, Tailscale 또는 프라이빗 릴레이({host})를 통해 어디서나 자체적으로 연결됩니다. 엔드투엔드 암호화.",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "프라이빗 릴레이({host})를 통해 어디서나 접근할 수 있습니다(암호화됨).",+ "Connecting to Private relay ({host})…": "프라이빗 릴레이({host}) 연결 중…",+ "Relay address": "릴레이 주소",+ "Relay token": "릴레이 토큰",+ "Saved. Type a new one to replace it.": "저장됨. 새 토큰을 입력하면 바뀝니다.",+ "The token from the relay's setup": "릴레이 설정에서 만든 토큰","Try again": "다시 시도","Turn on": "켜기","Turn on notifications": "알림 켜기",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 6bbb62b1..8bbea4fe 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -263,6 +263,18 @@"This computer": "这台电脑","This iPhone forgets the account's computers. Your bots stay on them.": "这台 iPhone 会忘掉账户里的电脑。Bot 仍留在那些电脑上。","Through Cloudflare": "经 Cloudflare",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自动:先 Wi-Fi 或 Tailscale,再私人中继({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "先私人中继({host}),再 Wi-Fi 或 Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "只用 Wi-Fi 或 Tailscale,不走私人中继({host})",+ "Connected through Private relay ({host})": "经私人中继({host})连接",+ "Through Private relay ({host})": "经私人中继({host})",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "会自己走 Wi-Fi、Tailscale,或经私人中继({host})从任何地方连接。端到端加密。",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "通过私人中继({host})随时随地连接(已加密)。",+ "Connecting to Private relay ({host})…": "正在连接私人中继({host})…",+ "Relay address": "中继地址",+ "Relay token": "中继令牌",+ "Saved. Type a new one to replace it.": "已保存。输入新的即可替换。",+ "The token from the relay's setup": "中继设置时生成的令牌","Try again": "再试一次","Turn on": "打开","Turn on notifications": "打开通知",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 50716047..748c7891 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -263,6 +263,18 @@"This computer": "這臺電腦","This iPhone forgets the account's computers. Your bots stay on them.": "這臺 iPhone 會忘掉賬戶裡的電腦。Bot 仍留在那些電腦上。","Through Cloudflare": "經 Cloudflare",+ "Auto: Wi-Fi or Tailscale, then Private relay ({host})": "自動:先 Wi-Fi 或 Tailscale,再私人中繼({host})",+ "Private relay ({host}), then Wi-Fi or Tailscale": "先私人中繼({host}),再 Wi-Fi 或 Tailscale",+ "Wi-Fi or Tailscale only, never Private relay ({host})": "只用 Wi-Fi 或 Tailscale,不走私人中繼({host})",+ "Connected through Private relay ({host})": "經私人中繼({host})連線",+ "Through Private relay ({host})": "經私人中繼({host})",+ "Connects on Wi-Fi, over Tailscale, or from anywhere through Private relay ({host}), on its own. End-to-end encrypted.": "會自己走 Wi-Fi、Tailscale,或經私人中繼({host})從任何地方連線。端到端加密。",+ "Reachable from anywhere through Private relay ({host}) (encrypted).": "透過私人中繼({host})隨時隨地連線(已加密)。",+ "Connecting to Private relay ({host})…": "正在連線私人中繼({host})…",+ "Relay address": "中繼位址",+ "Relay token": "中繼權杖",+ "Saved. Type a new one to replace it.": "已儲存。輸入新的即可替換。",+ "The token from the relay's setup": "中繼設定時產生的權杖","Try again": "再試一次","Turn on": "開啟","Turn on notifications": "開啟通知",diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex 8ce7f0c3..f77d74a7 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -169,7 +169,7 @@ public struct ThreadView: View {}if model.mismatch != nil { return "Needs update" }switch model.hostRoute {- case .relay: return "Connected through Cloudflare"+ case .relay: return RelayCopy.connected(cloud: model.computer.cloud)case .direct: return "Connected over Wi-Fi or Tailscale"case nil: return "Connected"}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swiftnew file mode 100644index 00000000..b9c17ba9--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/RelayCopyTests.swift@@ -0,0 +1,41 @@+import Foundation+import Testing+@testable import CodyncKit++struct RelayCopyTests {+ @Test func officialCloudsKeepTheCloudflareName() {+ #expect(RelayCopy.host(of: URL(string: "https://api.codync.dev")) == nil)+ #expect(RelayCopy.host(of: URL(string: "https://dev-api.codync.dev/")) == nil)+ #expect(RelayCopy.host(of: nil) == nil)+ #expect(RelayCopy.connected(cloud: URL(string: "https://api.codync.dev")) == "Connected through Cloudflare")+ #expect(RelayCopy.routeTitle(.automatic, cloud: nil) == "Auto: Wi-Fi or Tailscale, then Cloudflare")+ }++ @Test func anotherHostIsNamedInTheSentence() {+ let cloud = URL(string: "https://relay.example.com")+ #expect(RelayCopy.host(of: cloud) == "relay.example.com")+ #expect(RelayCopy.host(of: URL(string: "http://127.0.0.1:8788")) == "127.0.0.1:8788")+ #expect(RelayCopy.host(of: URL(string: "https://[2001:db8::1]:8443")) == "[2001:db8::1]:8443")+ #expect(RelayCopy.host(of: URL(string: "https://[2001:db8::1]")) == "[2001:db8::1]")+ #expect(RelayCopy.connected(cloud: cloud) == "Connected through Private relay (relay.example.com)")+ #expect(RelayCopy.through(cloud: cloud) == "Through Private relay (relay.example.com)")+ #expect(RelayCopy.routeTitle(.cloudflareFirst, cloud: cloud) == "Private relay (relay.example.com), then Wi-Fi or Tailscale")+ #expect(RelayCopy.detailSuffix(route: .relay, cloud: cloud) == " · Private relay (relay.example.com)")+ #expect(RelayCopy.pairing(cloud: cloud).contains("Private relay (relay.example.com)"))+ }++ @Test func aPastedLinkNamesItsRelay() {+ let v = Vectors.shared+ var comps = URLComponents(string: "codync://pair")!+ comps.queryItems = [+ URLQueryItem(name: "v", value: "3"),+ URLQueryItem(name: "id", value: v.str("keys", "computerId")),+ URLQueryItem(name: "sk", value: v.str("keys", "hostSignPub")),+ URLQueryItem(name: "bk", value: v.str("keys", "hostBoxPub")),+ 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"))+ }+}diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swiftindex 9ce56c9f..d09f5d34 100644--- a/apps/ios/Views/BotListView.swift+++ b/apps/ios/Views/BotListView.swift@@ -395,7 +395,7 @@ private struct ComputerSection: View {.lineLimit(1).contentTransition(.opacity)if store.connection == .online {- RouteIcon(route: store.hostRoute).font(.caption2).foregroundStyle(Palette.tertiary)+ RouteIcon(route: store.hostRoute, cloud: store.computer.cloud).font(.caption2).foregroundStyle(Palette.tertiary)}Image(systemName: "chevron.down").font(.caption.weight(.semibold))diff --git a/apps/ios/Views/ComputerStatus.swift b/apps/ios/Views/ComputerStatus.swiftindex 6972f78e..e9842ba7 100644--- a/apps/ios/Views/ComputerStatus.swift+++ b/apps/ios/Views/ComputerStatus.swift@@ -28,13 +28,14 @@ extension AccountStore {/// How the phone reaches a computer right now: a subtle icon, direct Wi-Fi/LAN or the encrypted relay.struct RouteIcon: View {let route: HostRoute?+ var cloud: URL?var body: some View {switch route {case .direct:Image(systemName: "wifi").accessibilityLabel("Wi-Fi or Tailscale")case .relay:- Image(systemName: "cloud").accessibilityLabel("Through Cloudflare")+ Image(systemName: "cloud").accessibilityLabel(L10n.tr(RelayCopy.through(cloud: cloud)))case nil:EmptyView()}diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swiftindex 31fec926..183f4f9d 100644--- a/apps/ios/Views/PairingView.swift+++ b/apps/ios/Views/PairingView.swift@@ -265,8 +265,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("Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted."),- systemImage: "lock.fill")+ Label(L10n.tr(RelayCopy.pairing(pasted: pasted)), 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/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex 9d329a01..0e088501 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -345,7 +345,7 @@ private struct ComputerRow: View {}DropdownMenu {ConnectionRoute.allCases.map { route in- MenuItem(route.title, icon: route.icon, selected: route == preference) {+ MenuItem(RelayCopy.routeTitle(route, cloud: store.computer.cloud), icon: route.icon, selected: route == preference) {accounts.setRoute(store.computer.id, route)}}@@ -368,11 +368,7 @@ private struct ComputerRow: View {private var detail: String {guard store.connection == .online else { return accounts.statusText(store) }let count = store.roster.count- let route = switch store.hostRoute {- case .direct: " · Wi-Fi/Tailscale"- case .relay: " · Cloudflare"- default: ""- }+ let route = RelayCopy.detailSuffix(route: store.hostRoute, cloud: store.computer.cloud)return "\(count) bot\(count == 1 ? "" : "s")\(route)"}}@@ -479,14 +475,6 @@ private struct SwatchPanel: View {}private extension ConnectionRoute {- var title: String {- switch self {- case .automatic: "Auto: Wi-Fi or Tailscale, then Cloudflare"- case .cloudflareFirst: "Cloudflare, then Wi-Fi or Tailscale"- case .directOnly: "Wi-Fi or Tailscale only, never Cloudflare"- }- }-var icon: String {switch self {case .automatic: "arrow.triangle.branch"diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex b5b98c5b..b585a3ba 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -14,6 +14,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動就能翻頁,下方可選每頁 6、10、20 或 50 筆,並顯示目前在第幾頁。- 聯結器翻到還沒載入的頁面時,會從 MCP Registry 接著載入。- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自分類的列表上方。+- 電腦使用自建中繼時,設定和連線狀態會顯示該中繼的地址,不再一律寫成 Cloudflare。### en-US- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.@@ -21,6 +22,7 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- Extensions shows one section at a time: Agents, Connectors or Skills, each in pages. Tap the round buttons beside the list or swipe left or right to turn the page; under it, pick 6, 10, 20 or 50 per page and see which page you're on.- Connectors keep loading from the MCP Registry as you page past what's loaded.- Credentials sits beside the computer's name at the top, and Custom connector and Your own skill sit above their lists.+- When a computer uses a private relay, Settings and connection status show that relay's address instead of always saying Cloudflare.## 2.26.1diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex f76befea..7b30b0ae 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -59,6 +59,7 @@ Codync/│ ├── src/│ ├── migrations/ # D1 migrations│ └── test/ # workerd tests; e2e/ runs against a real test host+├── private-relay/ # Single-process relay (the cloud WebSocket subset) for a person's own computers├── relay/ # Separate APNs push Worker; src/ and test/├── discord/ # Discord GitHub-role Worker (discord.codync.dev)├── docs/ # Architecture, features, design, guides, reference, plans, investigations, archive@@ -95,7 +96,7 @@ Codync/| Team management (bots creating and changing bots) | `host/src/chat/manage.rs`, its approval card (`Cmd::Approve`) in `agent/bot/updates.rs` || Prompt snapshots and memory | `host/src/chat/context.rs`, `memory/` (`api.rs` the apps' read-only view, `tools.rs` and `file_tools.rs` the MCP tools, `files.rs` the folders and scan, `turns.rs` which bot's turn a found change is credited to, `file_api.rs`, `dream.rs`, `import.rs`); the rules in `host/crates/memory` (`codync-mem`: files and facts in `files/`, dreaming in `dream/`, tombstones in `store.rs`, the old entries in `legacy.rs`); harnesses' own memory turned off in `host/src/agent/own_memory.rs` || Identity, encryption and direct channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` |-| Host cloud state and relay connection | `host/src/remote/cloud.rs`, `relay.rs` |+| Host cloud state and relay connection | `host/src/remote/cloud.rs`, `cloud_url.rs`, `relay.rs` || Agent discovery, sign-in, setup terminal, Node.js for npm agents | `host/src/agent/backends.rs` (+ `backends/sign_in.rs`, `backends/search_path.rs`), `registry.rs`, `auth.rs`, `term.rs`, `node.rs` || Fast mode (session config option) | `host/src/agent/config.rs`, `agent/bot/fast_mode.rs` || Marketplace, Composio, connector OAuth | `host/src/market/` |@@ -125,7 +126,7 @@ Codync/- Each `BotStore` (Swift, and its TypeScript port in the desktop app) talks to one computer. `AccountStore` aggregates stores and routes by `BotReference`; bare bot IDs are not globally unique.- The host owns routing, reply quotes, permissions and group turn scheduling. Clients render these results; they do not reimplement host policy.- Android: `core` is plain JVM (no Android or Compose imports) and `design` holds no I/O; `app` uses both. Like the other clients it renders host state and sends intents, never product logic.-- `cloud/` transports encrypted chat traffic and manages account metadata. `relay/` delivers APNs pushes. The two Workers have separate configuration and tests.+- `cloud/` transports encrypted chat traffic and manages account metadata. `relay/` delivers APNs pushes. The two Workers have separate configuration and tests. `private-relay/` is a single-process subset of the cloud relay protocol for a person's own computers. It is not the APNs worker.## Namesdiff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.mdindex a3953e5f..c22947fd 100644--- a/docs/guides/accounts-and-ssh.md+++ b/docs/guides/accounts-and-ssh.md@@ -211,7 +211,9 @@ first). See [desktop app](../architecture/desktop-app.md).**Computers & devices** (Settings) shows, for this computer and each SSH computer:*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud),-*Add to account* (claim: `POST /v1/claims` → loopback `claimSign` → complete) and+*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*Remove from account* (`unclaim`), a pairing QR, and the authorized devices with revoke.Signed in, this computer joins the account on its own once per host identity; an identitythat was already in the account and was removed (here or from a phone) is never re-addeddiff --git a/docs/guides/development.md b/docs/guides/development.mdindex d7e7129b..c11480a9 100644--- a/docs/guides/development.md+++ b/docs/guides/development.md@@ -117,8 +117,8 @@ git config core.hooksPath .githooks```It runs CI's checks for each part a commit touches, so a failure shows up before the push:-host and the memory crate (`cargo fmt --all --check`, clippy and `cargo test` for the workspace), desktop, cloud-and relay (`npm run typecheck`, `npm test`), the Android app (core and app unit tests, and a Kotlin compile of+host and the memory crate (`cargo fmt --all --check`, clippy and `cargo test` for the workspace), desktop, cloud,+relay, discord and private-relay (`npm run typecheck`, `npm test`), the Android app (core and app unit tests, and a Kotlin compile ofthe app and its instrumentation tests, with JDK 21), Linux screen helper formatting, a parse of the macOSscreen helper's Swift sources (on macOS), and the website's user manual (`npm run check:docs` in `web/`: pagescompile, links and anchors resolve). It checks the staged files only, in a copy under `.git/precommit-snapshot`,diff --git a/docs/guides/environments-and-deployment.md b/docs/guides/environments-and-deployment.mdindex 4f58bed7..89283213 100644--- a/docs/guides/environments-and-deployment.md+++ b/docs/guides/environments-and-deployment.md@@ -10,11 +10,11 @@ See [side-by-side Dev and production apps](dev-app.md) for schemes, identifiers,| --- | --- | --- || Apple app | `apps/shared/Config/dev.plist`, `main.plist` | `project.yml` copies the selected file to bundled `AccountConfig.plist`; `iOS Dev` uses dev; `iOS` uses main || Account SDK | `apps/ios/App/AccountSession.swift` | Public Clerk configuration; development environment overrides are supported |-| Host | `host/src/remote/cloud.rs` | `CODYNC_CLOUD=off` or stored disable wins; then `CODYNC_CLOUD_URL`, then the build's cloud (`CODYNC_ENV` at compile time) |+| Host | `host/src/remote/cloud_url.rs` | `CODYNC_CLOUD=off` or stored disable wins; then `CODYNC_CLOUD_URL`, then a saved relay address (`cloud_url`), then the build's cloud (`CODYNC_ENV` at compile time) || Cloud Worker / D1 / DO | `cloud/wrangler.toml` | Root production, `dev`, or `local` environment || APNs Worker | `relay/wrangler.toml` | Separate deployment and secrets; see [relay README](../../relay/README.md) |-The environment is chosen when building, never stored: the host compiles in its cloud from `CODYNC_ENV` (`main` → `https://api.codync.dev`, unset or anything else → `https://dev-api.codync.dev`, debug or release alike), and the only cloud setting a host saves is on/off (**Reach from anywhere**, `codync-host cloud --enable|--disable`). `CODYNC_CLOUD_URL` points a host at a cloud you're developing (https, or http to this computer). `npm run dist:<platform>:dev` / `dist:<platform>:main` build the bundled host for the app's environment, so the script name picks the environment of a whole desktop build ([desktop app](../architecture/desktop-app.md#development)); the release workflows set `CODYNC_ENV=main`.+The environment is chosen when building, never stored: the host compiles in its cloud from `CODYNC_ENV` (`main` → `https://api.codync.dev`, unset or anything else → `https://dev-api.codync.dev`, debug or release alike), and the host saves only two cloud settings: on/off (**Reach from anywhere**, `codync-host cloud --enable|--disable`) and an optional [private relay](../../private-relay/README.md) (kv `cloud_url` and its registration token `cloud_relay_token`, set with **Relay address** and **Relay token** in Settings → Computers or `codync-host cloud --url … --token`). `CODYNC_CLOUD_URL` points a host at a Codync cloud you're developing or run yourself (https, or http to this computer); `CODYNC_CLOUD_TOKEN` beside it gives that URL a private relay's token and marks it as one (the saved token is never sent to an env URL). A private relay has no accounts: the host skips the state pull there, so account devices are kept but stay out until the Codync cloud renews them, and claims, approval, access requests, public webhooks and relayed screen are refused (`cloud_url.rs` `RelayKind`). `npm run dist:<platform>:dev` / `dist:<platform>:main` build the bundled host for the app's environment, so the script name picks the environment of a whole desktop build ([desktop app](../architecture/desktop-app.md#development)); the release workflows set `CODYNC_ENV=main`.## Checked-in readinessdiff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.mdindex 9074da25..af1df883 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 tThe 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_CLOUD_URL=https://…` points the host at a cloud you run yourself (see [environments](environments-and-deployment.md)).+- **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)).- **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 or Linux) 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/reference/analytics-events.md b/docs/reference/analytics-events.mdindex 1b3cc62a..6a63aeb5 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -96,7 +96,7 @@ host answers and sends it once the host is up.| `credential_saved` | host | A key, login or vault is saved (clearing one isn't) | `kind` (`login`/`onepassword`/`connector`/`composio`/`voice`/`agent_env`) || `agent_setup_started` | host | `agentSetup` (an agent's install or sign-in terminal) | `agent` || `agent_signed_in` | host | `agentAuthenticate` | `agent` |-| `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`; phones: `push`/`live_activities`), `on` |+| `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`remote_access_url` (`on`: a relay address is saved, never the address)/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`; phones: `push`/`live_activities`), `on` || `host_update_installed` | host | `installHostUpdate` | — |## Screensdiff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex 73320346..cd009656 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -312,7 +312,7 @@ blob = epk(32) ‖ sig(64) ‖ ct| 類別 | 方法 | 允許的 caller ||---|---|---|-| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `cloudStatus`, `setCloud` | `Caller::Local`(loopback + token) |+| loopback 專用 | `setScreenEnabled`, `pairing`, `computerCall`, `computerTools`, `chatCall`, `teamCall`, `manageCall`, `memoryCall`, `routineCall`, `composioCall`, `claimSign`, `unclaim`, `devices`, `revokeDevice`, `accessRequests`, `decideAccessRequest`, `cloudStatus`, `setCloud`, `setCloudUrl` | `Caller::Local`(loopback + token) || 配對中 | `pair` | 只在 pairing 狀態的 channel;配對完成後不可再呼叫 || screen scope | `screenPrepare`, `screenOffer`, `screenClose`, `screenTakeover` | Local,或 scopes 含 `screen` 的裝置 || control scope | 其餘所有既有方法(`hello`, `history`, `createBot`, `updateBot`, `deleteBot`, `markRead`, `send`, `stop`, `newSession`, `respondPermission`, `registerDevice`, `unregisterDevice`, `registerActivity`, `refreshBackends`, `usage`, `listDirs`, market/skills/connectors、`agentSetup`, `agentAuth`, `agentAuthenticate`, `setAgentEnv`, `termInput`, `termResize`, `termClose`, `screenStatus`) | Local,或 scopes 含 `control` 的裝置 |@@ -489,7 +489,7 @@ The route table below summarizes the contract. Executable schema and validation- `DELETE /v1/computers/{id}/grants/{grantId}` → `{}`(`owner`)+ DO block + changed**Sig(host)(不需要帳號)**-- `POST /v1/host/register` `{"boxKey","name","platform":"macos"|"linux"|"windows","device","version"}` → `{"computerId","owned":bool}`。以 kid 推導 id;upsert(`name`/`device`/`version`/`box_pub`/`updated_at`)。同 IP 每分鐘最多 10 次新建(Workers Rate Limiting binding;平台不支援時先略過並在 README 註記)。+- `POST /v1/host/register` `{"boxKey","name","platform":"macos"|"linux"|"windows","device","version"}` → `{"computerId","owned":bool}`。以 kid 推導 id;upsert(`name`/`device`/`version`/`box_pub`/`updated_at`)。同 IP 每分鐘最多 10 次新建(Workers Rate Limiting binding;平台不支援時先略過並在 README 註記)。Host 指向 [private relay](../../private-relay/README.md) 時只在這個請求帶 `Codync-Relay-Token`(官方 cloud 忽略它):私人中繼收新電腦必須 token 相符,不符回 `403 forbidden`("This relay needs its relay token to add a new computer."),最多 32 台;已註冊的 key 不需要 token 就能 refresh。私人中繼的 `GET /v1/host/state` 永遠是空的,host 不拉它(不套用 grants、不處理 requests)。- `GET /v1/host/state` →```json{"owner":{"userId":"user_…","email":"[email protected]"} | null,diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex c1d19dc6..7b5f48ea 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -55,6 +55,13 @@ pub fn observe(caller: &Caller, method: &str, b: &Value) -> Option<(Event, Map<S/// The rest of `observe`: one arm per method.fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Event> {Some(match method {+ "setCloudUrl" => {+ // The address itself stays off the event. `on` is only whether a custom URL was saved.+ let on = b["url"].as_str().is_some_and(|url| !url.trim().is_empty());+ p.insert("setting".into(), "remote_access_url".into());+ p.insert("on".into(), on.into());+ Event::SettingChanged+ }"createBot" => {let group = b["kind"] == "group";p.insert("kind".into(), (if group { "group" } else { "bot" }).into());@@ -313,6 +320,13 @@ mod tests {Some(json!("automatic_updates")));assert_eq!(setting("setScreenEnabled", json!({"enabled": true})).map(|s| s.1), Some(json!("remote_screen")));+ let saved = props("setCloudUrl", &json!({"url": "https://relay.example.com"}));+ assert_eq!(+ saved.as_ref().map(|(e, p)| (*e, p["setting"].clone(), p["on"].clone())),+ Some((Event::SettingChanged, json!("remote_access_url"), json!(true)))+ );+ assert!(!saved.unwrap().1.to_string().contains("relay.example.com"), "the URL is not a property");+ assert_eq!(setting("setCloudUrl", json!({"url": " "})).map(|s| s.2), Some(json!(false)));assert_eq!(props("setRoutineEnabled", &json!({"botId": "b", "id": "r", "enabled": false})),diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 50e56b3a..822958d1 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -61,6 +61,7 @@ const LOCAL_ONLY: &[&str] = &["decideAccessRequest","cloudStatus","setCloud",+ "setCloudUrl","setApproval",];const SCREEN: &[&str] = &["screenPrepare", "screenOffer", "screenClose", "screenTakeover"];diff --git a/host/src/api/remote.rs b/host/src/api/remote.rsindex fcaaf5b5..9560db78 100644--- a/host/src/api/remote.rs+++ b/host/src/api/remote.rs@@ -4,6 +4,7 @@ use super::devices::Caller;use super::str_arg;use crate::LockExt;use crate::hub::{BotStatus, Hub};+use crate::remote::cloud::TokenChange;use crate::remote::crypto;use crate::store::DeviceSource;use anyhow::{Context, Result, anyhow, bail};@@ -103,6 +104,15 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuelet enabled = b["enabled"].as_bool().ok_or_else(|| anyhow!("`enabled` is required"))?;serde_json::to_value(crate::remote::cloud::set_cloud(hub, enabled)?)?}+ "setCloudUrl" => {+ let url = match &b["url"] {+ Value::Null => None,+ Value::String(url) => Some(url.as_str()),+ _ => bail!("`url` must be a string"),+ };+ let token = TokenChange::from_json(b.get("token"))?;+ serde_json::to_value(crate::remote::cloud::set_cloud_url(hub, url, token)?)?+ }"setApproval" => {let approval = serde_json::from_value(b["approval"].clone()).context("`approval` is code or auto")?;serde_json::to_value(crate::remote::cloud::set_approval(hub, approval)?)?@@ -137,6 +147,7 @@ async fn pairing(hub: &Arc<Hub>) -> Result<Value> {/// Signs this computer into an account claim (§4.2 A) for the signed-in desktop app to complete.async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {+ crate::remote::cloud::require_accounts(&hub.store)?;let field = |k: &str| -> Result<&str> {let v = str_arg(b, k)?;// Fields are newline-separated in the signed string: a newline would forge another field.diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rsnew file mode 100644index 00000000..ba02bd03--- /dev/null+++ b/host/src/cloud_cli.rs@@ -0,0 +1,75 @@+//! `codync-host cloud`: the relay this computer uses, its registration token and account approval.++use crate::local_call;+use anyhow::Result;+use serde_json::json;++#[derive(clap::Args)]+#[allow(clippy::struct_excessive_bools, reason = "independent command-line flags")]+pub struct CloudArgs {+ #[arg(long, default_value_t = crate::service::DEFAULT_PORT)]+ port: u16,+ #[arg(long, conflicts_with = "disable")]+ enable: bool,+ #[arg(long)]+ disable: bool,+ /// How devices on this computer's account get in: `code` (compare the 6-digit code,+ /// the default) or `auto` (no check: anyone who gets into the account, or controls+ /// the cloud, can then add a device).+ #[arg(long, value_parser = ["code", "auto"])]+ approval: Option<String>,+ /// Cloud base URL for this computer. `https://…`, or `http://127.0.0.1` / `localhost` for a relay on this machine.+ #[arg(long, conflicts_with = "clear_url")]+ url: Option<String>,+ /// Forget the saved URL and use this build's Codync cloud again.+ #[arg(long)]+ clear_url: bool,+ /// Ask for the private relay's registration token (typed without echo, or piped on stdin),+ /// so it stays out of the URL and shell history.+ #[arg(long, requires = "url")]+ token: bool,+}++/// `codync-host cloud`: shows or changes the cloud this computer uses.+pub async fn run(args: CloudArgs) -> Result<()> {+ let CloudArgs { port, enable, disable, approval, url, clear_url, token } = args;+ let mut status = None;+ if clear_url {+ status = Some(local_call(port, "setCloudUrl", json!({ "url": "" })).await?);+ } else if let Some(url) = url {+ let mut body = json!({ "url": url });+ if token {+ let token = crate::secret_prompt::read("Relay token: ")?;+ // An empty answer would clear the saved token; `--clear-url` is the way to forget it.+ if token.is_empty() {+ anyhow::bail!("No relay token was given.");+ }+ body["token"] = token.into();+ }+ status = Some(local_call(port, "setCloudUrl", body).await?);+ }+ if let Some(approval) = approval {+ status = Some(local_call(port, "setApproval", json!({ "approval": approval })).await?);+ }+ if enable || disable {+ status = Some(local_call(port, "setCloud", json!({"enabled": !disable})).await?);+ }+ let status = match status {+ Some(status) => status,+ None => local_call(port, "cloudStatus", json!({})).await?,+ };+ let text = |k: &str| status[k].as_str().unwrap_or("-").to_owned();+ let owner = status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str()).unwrap_or("none");+ println!(+ "enabled: {}\nurl: {}\nrelay: {}\ntoken: {}\nregistered: {}\nconnected: {}\naccount: {owner}\napproval: {}\nlast error: {}",+ status["enabled"],+ text("url"),+ text("relay"),+ if status["tokenSet"] == true { "saved" } else { "none" },+ status["registered"],+ status["connected"],+ text("approval"),+ text("lastError"),+ );+ Ok(())+}diff --git a/host/src/main.rs b/host/src/main.rsindex e3e518f9..cdba01f1 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -5,6 +5,7 @@ mod analytics;mod api;mod background;mod chat;+mod cloud_cli;mod compat;mod environment;mod hub;@@ -13,6 +14,7 @@ mod mcp;mod remote;mod routines;mod screen;+mod secret_prompt;mod service;mod shell;mod store;@@ -106,19 +108,7 @@ enum Sub {action: Option<AccessAction>,},/// Show or change the Codync cloud (reach this computer from anywhere).- Cloud {- #[arg(long, default_value_t = service::DEFAULT_PORT)]- port: u16,- #[arg(long, conflicts_with = "disable")]- enable: bool,- #[arg(long)]- disable: bool,- /// How devices on this computer's account get in: `code` (compare the 6-digit code,- /// the default) or `auto` (no check: anyone who gets into the account, or controls- /// the cloud, can then add a device).- #[arg(long, value_parser = ["code", "auto"])]- approval: Option<String>,- },+ Cloud(cloud_cli::CloudArgs),/// Install and start the host as a background service (launchd / systemd --user).Install {#[arg(long, default_value_t = service::DEFAULT_PORT)]@@ -360,28 +350,7 @@ async fn main() -> Result<()> {}},Sub::Access { port, action } => access(port, action.unwrap_or(AccessAction::List)).await,- Sub::Cloud { port, enable, disable, approval } => {- if let Some(approval) = approval {- local_call(port, "setApproval", json!({ "approval": approval })).await?;- }- let status = if enable || disable {- local_call(port, "setCloud", json!({"enabled": !disable})).await?- } else {- local_call(port, "cloudStatus", json!({})).await?- };- let text = |k: &str| status[k].as_str().unwrap_or("-").to_owned();- let owner = status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str()).unwrap_or("none");- println!(- "enabled: {}\nurl: {}\nregistered: {}\nconnected: {}\naccount: {owner}\napproval: {}\nlast error: {}",- status["enabled"],- text("url"),- status["registered"],- status["connected"],- text("approval"),- text("lastError"),- );- Ok(())- }+ Sub::Cloud(args) => cloud_cli::run(args).await,Sub::Install { port } => {open_store()?;// Windows: the shell Claude Code runs status lines in varies (Git Bash, PowerShell), sodiff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rsindex 49a2f021..0df65101 100644--- a/host/src/remote/channel.rs+++ b/host/src/remote/channel.rs@@ -401,6 +401,9 @@ impl Channel {writer: &mut tokio::task::JoinHandle<()>,) -> CloseWith {let mut auth = self.hub.auth.subscribe();+ // 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 rekey_at = Instant::now() + MAX_AGE;loop {let lease = self.lease;@@ -434,6 +437,7 @@ impl Channel {}}() = sleep_until(rekey_at) => return (close::REKEY, "rekey"),+ _ = cloud.changed() => return (close::REKEY, "relay"),_ = &mut *writer => return (close::NORMAL, ""),}}@@ -867,6 +871,23 @@ mod tests {assert!(hub.connected.locked().is_empty());}+ #[tokio::test]+ async fn a_new_relay_address_makes_phones_reconnect_and_read_it() {+ let hub = temp_hub();+ let key = paired_phone(&hub).await;+ let mut p = Phone::direct(&hub, key);+ p.hello(&hub, false).await;+ assert!(p.call(1, "hello", json!({})).await["ok"].is_object());+ hub.store.kv_set("test_cloud_url", "https://relay.example.com").unwrap();+ hub.cloud.config.send_modify(|g| *g += 1);+ let (code, _) = p.recv().await.unwrap_err();+ assert_eq!(code, close::REKEY, "a rekey close reconnects at once on every client");+ let key = paired_phone(&hub).await;+ let mut again = Phone::direct(&hub, key);+ again.hello(&hub, false).await;+ assert_eq!(again.call(1, "hello", json!({})).await["ok"]["cloud"], "https://relay.example.com");+ }+#[tokio::test]async fn account_devices_need_a_synced_live_lease() {let hub = temp_hub();diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rsindex b0854d09..6da7ac54 100644--- a/host/src/remote/cloud.rs+++ b/host/src/remote/cloud.rs@@ -1,7 +1,7 @@-//! The Codync cloud (Cloudflare relay + accounts, spec §4.2, §4.3, §8.4, §9.6): which one-//! this host uses, its `/v1/host/*` API (signed with `Codync-Sig`), the state pull that may-//! only renew or remove account devices, never add one, and account access requests with-//! the commit-then-reveal SAS. The relay socket itself lives in `relay`.+//! The Codync cloud (Cloudflare relay + accounts, spec §4.2, §4.3, §8.4, §9.6): its+//! `/v1/host/*` API (signed with `Codync-Sig`), the state pull that may only renew or remove+//! account devices, never add one, and account access requests with the commit-then-reveal+//! SAS. Which cloud this host uses lives in `cloud_url`, the relay socket in `relay`.use crate::LockExt;use crate::hub::Hub;@@ -16,12 +16,7 @@ use std::sync::Mutex;use std::time::Duration;use tokio::sync::watch;-/// The cloud this build belongs to: main only for builds made with `CODYNC_ENV=main` (the-/// release workflows), dev for every local build, debug or release, like the apps built next-/// to it.-fn build_cloud_url() -> &'static str {- crate::environment::Environment::current().cloud_url()-}+pub use super::cloud_url::{Address, RelayKind, TokenChange, current, set_cloud, set_cloud_url, show, url};/// How long one successful state pull keeps an account device allowed.pub const LEASE_MS: i64 = 15 * 60 * 1000;@@ -42,35 +37,6 @@ const SAS_NONCES: &str = "sas_nonces";const SAS_NONCES_PER_HOUR: usize = 5;const HOUR_MS: i64 = 60 * 60 * 1000;-/// The cloud base URL in use, or `None` when the cloud is off.-/// `CODYNC_CLOUD=off` > turned off here > `CODYNC_CLOUD_URL` (a cloud you're developing) > the-/// build's cloud. Which cloud is never saved here: on/off is the only stored cloud setting.-/// Unit tests point at a fake cloud through kv `test_cloud_url`, so they never reach a real one.-pub fn url(store: &Store) -> Option<String> {- if std::env::var("CODYNC_CLOUD").is_ok_and(|v| v == "off")- || store.kv_get("cloud_enabled").as_deref() == Some("false")- {- return None;- }- if cfg!(test) {- return store.kv_get("test_cloud_url");- }- let custom = std::env::var("CODYNC_CLOUD_URL")- .ok()- .map(|u| u.trim().trim_end_matches('/').to_owned())- .filter(|u| valid_url(&format!("{u}/")));- Some(custom.unwrap_or_else(|| build_cloud_url().to_owned()))-}--/// A cloud URL this host may be pointed at: https, or plain http to this computer (local dev).-fn valid_url(u: &str) -> bool {- let Ok(parsed) = reqwest::Url::parse(u) else { return false };- let local = matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"));- parsed.path() == "/"- && parsed.query().is_none()- && (parsed.scheme() == "https" || (parsed.scheme() == "http" && local))-}-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub struct Owner {@@ -82,14 +48,19 @@ pub struct Owner {/// `cloudStatus` and the `cloud` event.#[derive(Serialize, Clone, Debug, Default, PartialEq, Eq)]#[serde(rename_all = "camelCase")]+#[allow(clippy::struct_excessive_bools, reason = "independent facts the apps show, sent as JSON")]pub struct CloudStatus {pub enabled: bool,pub url: Option<String>,+ /// The relay in use has a registration token. The token itself is never sent.+ pub token_set: bool,pub registered: bool,pub connected: bool,pub owner: Option<Owner>,pub last_error: Option<String>,pub approval: Approval,+ /// Whose relay: on a private one there is no account, access request or relayed screen.+ pub relay: RelayKind,}/// How account devices get in (`setApproval`, local only).@@ -224,18 +195,41 @@ pub fn authority(base: &str) -> Result<String> {.to_ascii_lowercase())}-fn base(hub: &Hub) -> Result<String> {- url(&hub.store).ok_or_else(|| anyhow!("The Codync cloud is off on this computer."))+const NO_ACCOUNTS: &str = "This computer uses a private relay, which has no Codync accounts or remote screen.";++/// The Codync cloud's base URL. Accounts, access requests, grants, public webhooks and the+/// screen's TURN live only there: refused while the cloud is off or a private relay is in use.+pub fn codync_url(hub: &Hub) -> Result<String> {+ match current(&hub.store) {+ None => bail!("The Codync cloud is off on this computer."),+ Some(address) if address.kind == RelayKind::Private => bail!(NO_ACCOUNTS),+ Some(address) => Ok(address.url),+ }}-/// One signed `/v1/host/*` call.-async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {+/// Refuses an account change (claim, approval) while this computer uses a private relay.+pub fn require_accounts(store: &Store) -> Result<()> {+ if current(store).is_some_and(|address| address.kind == RelayKind::Private) {+ bail!(NO_ACCOUNTS);+ }+ Ok(())+}++/// A `/v1/host/*` request signed with `Codync-Sig`.+fn signed(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<reqwest::RequestBuilder> {let bytes = body.map(serde_json::to_vec).transpose()?.unwrap_or_default();let sig = hub.identity.sign_request(method.as_str(), &authority(base)?, path, &bytes);- let mut req = crate::http().request(method, format!("{base}{path}")).header("Codync-Sig", sig).timeout(TIMEOUT);- if body.is_some() {- req = req.header("content-type", "application/json").body(bytes);- }+ let req = crate::http().request(method, format!("{base}{path}")).header("Codync-Sig", sig).timeout(TIMEOUT);+ Ok(if body.is_some() { req.header("content-type", "application/json").body(bytes) } else { req })+}++/// One signed `/v1/host/*` call.+async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&Value>) -> Result<Value> {+ answer(signed(hub, base, method, path, body)?).await+}++/// Sends `req`; a refusal becomes a `CloudError`.+async fn answer(req: reqwest::RequestBuilder) -> Result<Value> {let res = req.send().await.context("the Codync cloud is unreachable")?;let status = res.status();let v: Value = res.json().await.unwrap_or(Value::Null);@@ -252,7 +246,7 @@ async fn call(hub: &Hub, base: &str, method: Method, path: &str, body: Option<&V}/// `POST /v1/host/register`: makes this computer known to the cloud (no account needed).-pub async fn register(hub: &Hub, base: &str) -> Result<()> {+pub async fn register(hub: &Hub, cloud: &Address) -> Result<()> {let body = json!({"boxKey": hub.identity.box_pub_b64(),"name": crate::service::host_name(),@@ -260,7 +254,13 @@ pub async fn register(hub: &Hub, base: &str) -> Result<()> {"device": tokio::task::spawn_blocking(crate::service::device).await?,"version": env!("CARGO_PKG_VERSION"),});- let v = call(hub, base, Method::POST, "/v1/host/register", Some(&body)).await?;+ let mut req = signed(hub, &cloud.url, Method::POST, "/v1/host/register", Some(&body))?;+ // A private relay requires it to enroll a new computer. It stays out of the URL `hello`+ // publishes, so phones never see it, and no other request carries it.+ if let Some(token) = &cloud.token {+ req = req.header("Codync-Relay-Token", token);+ }+ let v = answer(req).await?;if v["computerId"].as_str() != Some(hub.identity.computer_id().as_str()) {bail!("the cloud registered a different computer id");}@@ -272,7 +272,8 @@ pub async fn register(hub: &Hub, base: &str) -> Result<()> {/// Short-lived media credentials, issued only after the host checks screen authorization.pub async fn screen_ice(hub: &Hub, device_key: &str) -> Result<crate::screen::IceConfig> {let value =- call(hub, &base(hub)?, Method::POST, "/v1/host/screen-ice", Some(&json!({"deviceKey": device_key}))).await?;+ call(hub, &codync_url(hub)?, Method::POST, "/v1/host/screen-ice", Some(&json!({"deviceKey": device_key})))+ .await?;let config: crate::screen::IceConfig =serde_json::from_value(value).context("invalid screen relay configuration")?;if config.ice_servers.is_empty() || config.expires_at <= now_ms() + 60_000 {@@ -522,7 +523,7 @@ async fn deny(hub: &Hub, base: &str, id: &str) {/// compared) with the grant the cloud returns; nothing else can add an account device./// `how`: the user compared the code, or the computer approves on its own (`Approval::Auto`).pub async fn decide(hub: &Hub, id: &str, approve: bool, how: Approval) -> Result<()> {- let base = base(hub)?;+ let base = codync_url(hub)?;let r =hub.cloud.requests.locked().iter().find(|r| r.id == id).cloned().ok_or_else(|| anyhow!("unknown request"))?;if approve && r.code.is_none() {@@ -578,7 +579,8 @@ pub async fn revoke_grant(hub: Arc<Hub>, grant_id: String) {pending.push(grant_id);set_pending_revokes(&hub.store, &pending);}- if let Ok(base) = base(&hub) {+ // On a private relay it waits for the next pull from the Codync cloud.+ if let Ok(base) = codync_url(&hub) {retry_revokes(&hub, &base).await;}}@@ -606,26 +608,15 @@ async fn retry_revokes(hub: &Hub, base: &str) {/// `unclaim`: takes this computer out of its account.pub async fn unclaim(hub: &Hub) -> Result<()> {- let base = base(hub)?;+ let base = codync_url(hub)?;call(hub, &base, Method::POST, "/v1/host/unclaim", Some(&json!({}))).await?;tracing::info!("left the account");pull(hub, &base).await}-/// `setCloud`: turns the cloud on or off; the relay restarts.-pub fn set_cloud(hub: &Hub, enabled: bool) -> Result<CloudStatus> {- hub.store.kv_set("cloud_enabled", if enabled { "true" } else { "false" })?;- let now = url(&hub.store);- update_status(hub, |s| {- s.enabled = now.is_some();- s.url.clone_from(&now);- });- hub.cloud.config.send_modify(|g| *g += 1);- Ok(hub.cloud.status())-}-/// `setApproval`: whether account devices need the 6-digit check. Local only.pub fn set_approval(hub: &Hub, approval: Approval) -> Result<CloudStatus> {+ require_accounts(&hub.store)?;hub.store.kv_set(APPROVAL, if approval == Approval::Auto { "auto" } else { "code" })?;tracing::info!(?approval, "account approval changed");update_status(hub, |s| s.approval = approval);@@ -678,12 +669,7 @@ mod tests {}#[test]- fn only_safe_cloud_urls() {- assert!(valid_url("https://codync-cloud.example.workers.dev/"));- assert!(valid_url("http://127.0.0.1:8787/"));- assert!(!valid_url("http://example.com/"));- assert!(!valid_url("https://example.com/path/"));- assert!(!valid_url("ftp://example.com/"));+ fn signed_authority_omits_the_default_port() {assert_eq!(authority("https://Codync.Example.dev").unwrap(), "codync.example.dev");assert_eq!(authority("http://127.0.0.1:8787").unwrap(), "127.0.0.1:8787");assert_eq!(authority("https://x.dev:443").unwrap(), "x.dev", "default port is left out");@@ -822,4 +808,23 @@ mod tests {assert_eq!(fake.posts.lock().unwrap().len(), SAS_NONCES_PER_HOUR);assert!(hub.cloud.status().last_error.is_some(), "the Mac hears about it, though the pull worked");}++ #[tokio::test]+ async fn a_private_relay_takes_no_account_change() {+ let hub = temp_hub();+ hub.store.kv_set("test_cloud_url", "http://127.0.0.1:9").unwrap();+ hub.store.kv_set("test_cloud_token", "s3cret-token-value").unwrap();+ assert!(set_approval(&hub, Approval::Auto).unwrap_err().to_string().contains("private relay"));+ assert_eq!(approval(&hub.store), Approval::Code);+ assert!(unclaim(&hub).await.unwrap_err().to_string().contains("private relay"));+ let screen = screen_ice(&hub, "dk").await.err().expect("no TURN on a private relay");+ assert!(screen.to_string().contains("private relay"), "{screen}");+ let claim = json!({"claimId": "clm_1", "nonce": "n", "userId": "user_1"});+ let local = crate::api::devices::Caller::Local;+ let refused = crate::api::dispatch(&hub, &local, "claimSign", claim.clone()).await.unwrap_err();+ assert!(refused.to_string().contains("private relay"), "{refused}");+ hub.store.kv_delete("test_cloud_token").unwrap();+ assert!(crate::api::dispatch(&hub, &local, "claimSign", claim).await.is_ok(), "a Codync cloud signs claims");+ assert!(require_accounts(&hub.store).is_ok(), "a Codync cloud has accounts");+ }}diff --git a/host/src/remote/cloud_url.rs b/host/src/remote/cloud_url.rsnew file mode 100644index 00000000..1e4687fb--- /dev/null+++ b/host/src/remote/cloud_url.rs@@ -0,0 +1,366 @@+//! Which cloud this computer uses, the address a person saves, and turning the cloud on or off.+//!+//! `CODYNC_CLOUD=off` wins, then the switch in settings, then `CODYNC_CLOUD_URL`, then the+//! saved `cloud_url`, then the build's cloud. Unit tests point at a fake cloud through kv+//! `test_cloud_url` (and `test_cloud_token` for a private relay), so they never reach a real one.+//!+//! A private relay's registration token is kept apart from its address (kv `cloud_relay_token`,+//! or `CODYNC_CLOUD_TOKEN` beside `CODYNC_CLOUD_URL`), so it never sits in a URL, shell history+//! or the address `hello` publishes.++use super::cloud::{self, CloudStatus};+use crate::environment::Environment;+use crate::hub::Hub;+use crate::store::Store;+use anyhow::{Result, bail};+use serde::Serialize;+use serde_json::Value;++/// kv: `false` while Reach from anywhere is off here.+const ENABLED: &str = "cloud_enabled";+/// kv: the relay address a person saved, and that relay's registration token.+const SAVED_URL: &str = "cloud_url";+const SAVED_TOKEN: &str = "cloud_relay_token";++/// Whose relay this is. Accounts, access requests, public webhooks and the screen's TURN exist+/// only in the Codync cloud, so the host never takes them from a private relay.+#[derive(Serialize, Clone, Copy, Debug, Default, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum RelayKind {+ /// A Codync cloud: this build's, a saved official address, or one `CODYNC_CLOUD_URL` names+ /// without a token (a Codync cloud you develop or run yourself).+ #[default]+ Codync,+ /// An owner-run `private-relay/`: a saved address, or `CODYNC_CLOUD_URL` with `CODYNC_CLOUD_TOKEN`.+ Private,+}++/// The cloud in use.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Address {+ pub url: String,+ /// The private relay's registration token, sent only when enrolling (`Codync-Relay-Token`).+ pub token: Option<String>,+ pub kind: RelayKind,+}++/// Where an address can come from, with the token kept beside it.+#[derive(Clone, Copy, Default)]+struct Candidate<'a> {+ url: Option<&'a str>,+ token: Option<&'a str>,+}++/// The cloud in use: its public address, its kind, and the registration token when it has one.+pub fn current(store: &Store) -> Option<Address> {+ let off =+ std::env::var("CODYNC_CLOUD").is_ok_and(|v| v == "off") || store.kv_get(ENABLED).as_deref() == Some("false");+ if cfg!(test) {+ // No fake cloud, no cloud: a test never reaches a real one.+ let url = store.kv_get("test_cloud_url")?;+ let token = store.kv_get("test_cloud_token");+ return resolve(off, Candidate { url: Some(&url), token: token.as_deref() }, Candidate::default(), &url);+ }+ let (env_url, env_token) = (std::env::var("CODYNC_CLOUD_URL").ok(), std::env::var("CODYNC_CLOUD_TOKEN").ok());+ let (saved_url, saved_token) = (store.kv_get(SAVED_URL), store.kv_get(SAVED_TOKEN));+ resolve(+ off,+ Candidate { url: env_url.as_deref(), token: env_token.as_deref() },+ Candidate { url: saved_url.as_deref(), token: saved_token.as_deref() },+ Environment::current().cloud_url(),+ )+}++/// The cloud base URL in use, or `None` when the cloud is off.+pub fn url(store: &Store) -> Option<String> {+ current(store).map(|address| address.url)+}++/// `off` wins. Otherwise the first valid candidate, then `builtin`. An illegal candidate is skipped.+/// Each address carries only its own token: the saved token is never sent to an env URL.+fn resolve(off: bool, env: Candidate, saved: Candidate, builtin: &str) -> Option<Address> {+ if off {+ return None;+ }+ let token = |c: Candidate| c.token.filter(|token| valid_token(token)).map(str::to_owned);+ if let Some(url) = env.url.and_then(parse_url) {+ // A relay token marks a private relay: the Codync cloud never asks for one.+ let kind = if env.token.is_some_and(|t| !t.trim().is_empty()) { RelayKind::Private } else { RelayKind::Codync };+ return Some(Address { url, token: token(env), kind });+ }+ if let Some(url) = saved.url.and_then(parse_url) {+ let official = [Environment::Main, Environment::Dev].iter().any(|e| e.cloud_url() == url);+ let kind = if official { RelayKind::Codync } else { RelayKind::Private };+ return Some(Address { url, token: token(saved), kind });+ }+ let url = parse_url(builtin).unwrap_or_else(|| builtin.to_owned());+ Some(Address { url, token: None, kind: RelayKind::Codync })+}++/// https, or plain http to this computer (local dev). No user name, password, path, query or fragment.+fn parse_url(raw: &str) -> Option<String> {+ let trimmed = raw.trim().trim_end_matches('/');+ if trimmed.is_empty() {+ return None;+ }+ let parsed = reqwest::Url::parse(&format!("{trimmed}/")).ok()?;+ let local = matches!(parsed.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"));+ if parsed.path() != "/"+ || parsed.query().is_some()+ || parsed.fragment().is_some()+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || !(parsed.scheme() == "https" || (parsed.scheme() == "http" && local))+ {+ return None;+ }+ let host = parsed.host_str()?;+ let port = parsed.port().map_or(String::new(), |port| format!(":{port}"));+ Some(format!("{}://{host}{port}", parsed.scheme()))+}++/// What the private relay accepts (`CODYNC_PRIVATE_RELAY_TOKEN`): 16 to 256 visible ASCII characters.+fn valid_token(token: &str) -> bool {+ (16..=256).contains(&token.len()) && token.bytes().all(|byte| (0x21..=0x7e).contains(&byte))+}++/// What `setCloudUrl` does with the saved registration token.+#[derive(Debug, PartialEq, Eq)]+pub enum TokenChange {+ /// Keep it while the address stays the same; a new address drops it, since a token belongs to one relay.+ Keep,+ Clear,+ Set(String),+}++impl TokenChange {+ /// `setCloudUrl`'s `token`: absent keeps the saved token for the same address; null or blank clears it.+ pub fn from_json(token: Option<&Value>) -> Result<Self> {+ Ok(match token {+ None => Self::Keep,+ Some(Value::Null) => Self::Clear,+ Some(Value::String(token)) if token.trim().is_empty() => Self::Clear,+ Some(Value::String(token)) => Self::Set(token.trim().to_owned()),+ Some(_) => bail!("`token` must be a string"),+ })+ }+}++/// Writes which cloud is in use into the status. Only the Codync cloud has an account owner.+pub fn show(s: &mut CloudStatus, address: Option<&Address>) {+ s.enabled = address.is_some();+ s.url = address.map(|a| a.url.clone());+ s.token_set = address.is_some_and(|a| a.token.is_some());+ s.relay = address.map(|a| a.kind).unwrap_or_default();+ if s.relay == RelayKind::Private {+ s.owner = None;+ }+}++/// `setCloud`: turns the cloud on or off; the relay restarts.+pub fn set_cloud(hub: &Hub, enabled: bool) -> Result<CloudStatus> {+ hub.store.kv_set(ENABLED, if enabled { "true" } else { "false" })?;+ Ok(restart(hub))+}++/// `setCloudUrl`: points this computer at a cloud, or clears the saved URL (and its token) so the+/// build's cloud is used again. Empty and null clear it. An illegal URL or token is refused and+/// changes nothing. The relay restarts either way. Local only.+pub fn set_cloud_url(hub: &Hub, raw: Option<&str>, token: TokenChange) -> Result<CloudStatus> {+ match raw.map(str::trim).filter(|u| !u.is_empty()) {+ None => {+ hub.store.kv_delete(SAVED_URL)?;+ hub.store.kv_delete(SAVED_TOKEN)?;+ }+ Some(raw) => {+ if raw.contains('@') {+ bail!("Enter the relay token in its own field, not in the address.");+ }+ let Some(url) = parse_url(raw) else {+ bail!("That relay address isn't a usable cloud URL.");+ };+ let same = hub.store.kv_get(SAVED_URL).as_deref() == Some(url.as_str());+ match token {+ TokenChange::Set(token) if !valid_token(&token) => {+ bail!("A relay token is 16 to 256 visible characters, with no spaces.");+ }+ TokenChange::Set(token) => hub.store.kv_set(SAVED_TOKEN, &token)?,+ TokenChange::Keep if same => {}+ TokenChange::Keep | TokenChange::Clear => hub.store.kv_delete(SAVED_TOKEN)?,+ }+ hub.store.kv_set(SAVED_URL, &url)?;+ }+ }+ Ok(restart(hub))+}++/// Shows the new choice and restarts the relay on it.+fn restart(hub: &Hub) -> CloudStatus {+ let address = current(&hub.store);+ cloud::update_status(hub, |s| show(s, address.as_ref()));+ hub.cloud.config.send_modify(|g| *g += 1);+ hub.cloud.status()+}++#[cfg(test)]+mod tests {+ #![allow(clippy::unwrap_used, clippy::expect_used)]+ use super::*;+ use crate::remote::identity::Identity;+ use serde_json::json;+ use std::sync::Arc;++ fn temp_hub() -> Arc<Hub> {+ let dir = std::env::temp_dir().join(format!("codync-cloud-url-{}", 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)+ }++ fn at(url: &'static str) -> Candidate<'static> {+ Candidate { url: Some(url), token: None }+ }++ fn with_token(url: &'static str, token: &'static str) -> Candidate<'static> {+ Candidate { url: Some(url), token: Some(token) }+ }++ #[test]+ fn only_safe_cloud_urls() {+ assert_eq!(+ parse_url("https://codync-cloud.example.workers.dev/").as_deref(),+ Some("https://codync-cloud.example.workers.dev")+ );+ assert_eq!(parse_url("http://127.0.0.1:8787/").as_deref(), Some("http://127.0.0.1:8787"));+ assert_eq!(parse_url("https://[2001:db8::1]:8443").as_deref(), Some("https://[2001:db8::1]:8443"));+ assert!(parse_url("https://[email protected]/").is_none(), "a token never rides in the address");+ assert!(parse_url("https://user:[email protected]").is_none());+ assert!(parse_url("http://example.com/").is_none());+ assert!(parse_url("https://example.com/path/").is_none());+ assert!(parse_url("ftp://example.com/").is_none());+ assert!(parse_url("https://relay.example.com/#setup").is_none());+ assert!(parse_url("https://relay.example.com/?a=1").is_none());+ }++ #[test]+ fn tokens_are_header_safe() {+ assert!(valid_token("a-long-random-secret"));+ assert!(valid_token("abcdefghijklmnop@"));+ assert!(!valid_token("too-short"));+ assert!(!valid_token("has a space in the middle"));+ assert!(!valid_token("line\nbreak-0123456789"));+ assert!(!valid_token(&"x".repeat(257)));+ }++ #[test]+ fn a_saved_cloud_url_is_used_only_when_nothing_in_front_of_it_is() {+ let none = Candidate::default();+ let url = |a: Option<Address>| a.map(|a| a.url);+ assert_eq!(+ url(resolve(false, none, at("https://relay.example.com/"), "https://builtin")).as_deref(),+ Some("https://relay.example.com")+ );+ assert_eq!(+ url(resolve(false, at("https://from.env"), at("https://saved.example"), "https://builtin")).as_deref(),+ Some("https://from.env")+ );+ assert_eq!(+ url(resolve(false, at("http://example.com"), none, "https://builtin")).as_deref(),+ Some("https://builtin"),+ "an illegal candidate is skipped"+ );+ assert_eq!(resolve(true, at("https://relay.example.com"), none, "https://builtin"), None);++ let saved =+ resolve(false, none, with_token("https://relay.example.com", "s3cret-token-value"), "https://builtin")+ .unwrap();+ assert_eq!((saved.token.as_deref(), saved.kind), (Some("s3cret-token-value"), RelayKind::Private));+ let from_env = resolve(+ false,+ at("https://from.env"),+ with_token("https://saved.example", "saved-token-value"),+ "https://builtin",+ )+ .unwrap();+ assert_eq!(from_env.token, None, "the env address does not inherit the saved token");+ let env_token =+ resolve(false, with_token("https://from.env", "env-token-value-123"), none, "https://builtin").unwrap();+ assert_eq!(env_token.token.as_deref(), Some("env-token-value-123"));+ }++ #[test]+ fn only_a_codync_cloud_has_accounts() {+ let none = Candidate::default();+ let kind = |env, saved| resolve(false, env, saved, "https://dev-api.codync.dev").unwrap().kind;+ assert_eq!(kind(none, none), RelayKind::Codync, "the build's cloud");+ assert_eq!(kind(at("http://127.0.0.1:8787"), none), RelayKind::Codync, "a Codync cloud you run yourself");+ assert_eq!(kind(with_token("https://relay.example.com", "env-token-value-123"), none), RelayKind::Private);+ assert_eq!(kind(none, at("https://relay.example.com")), RelayKind::Private, "even before its token is typed");+ assert_eq!(kind(none, at("https://api.codync.dev/")), RelayKind::Codync, "a saved official address");+ }++ #[test]+ fn token_changes_follow_the_json() {+ assert_eq!(TokenChange::from_json(None).unwrap(), TokenChange::Keep);+ assert_eq!(TokenChange::from_json(Some(&Value::Null)).unwrap(), TokenChange::Clear);+ assert_eq!(TokenChange::from_json(Some(&json!(" "))).unwrap(), TokenChange::Clear);+ assert_eq!(TokenChange::from_json(Some(&json!(" t "))).unwrap(), TokenChange::Set("t".into()));+ assert!(TokenChange::from_json(Some(&json!(1))).is_err());+ }++ #[test]+ fn set_cloud_url_stores_the_address_and_its_token_apart() {+ let hub = temp_hub();+ set_cloud_url(&hub, Some("https://relay.example.com/"), TokenChange::Keep).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_URL).as_deref(), Some("https://relay.example.com"));+ let bad = set_cloud_url(&hub, Some("http://example.com"), TokenChange::Keep).unwrap_err();+ assert!(bad.to_string().contains("relay address"), "{bad}");+ assert_eq!(hub.store.kv_get(SAVED_URL).as_deref(), Some("https://relay.example.com"));++ set_cloud_url(&hub, Some("https://relay.example.com"), TokenChange::Set("s3cret-token-value".into())).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_TOKEN).as_deref(), Some("s3cret-token-value"));+ let short =+ set_cloud_url(&hub, Some("https://relay.example.com"), TokenChange::Set("short".into())).unwrap_err();+ assert!(short.to_string().contains("relay token"), "{short}");+ assert_eq!(+ hub.store.kv_get(SAVED_TOKEN).as_deref(),+ Some("s3cret-token-value"),+ "a refused token changes nothing"+ );+ let inline =+ set_cloud_url(&hub, Some("https://[email protected]"), TokenChange::Keep).unwrap_err();+ assert!(inline.to_string().contains("its own field"), "{inline}");+ let fragment = set_cloud_url(&hub, Some("https://relay.example.com/#setup"), TokenChange::Keep).unwrap_err();+ assert!(fragment.to_string().contains("relay address"), "{fragment}");++ set_cloud_url(&hub, Some("https://relay.example.com/"), TokenChange::Keep).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_TOKEN).as_deref(), Some("s3cret-token-value"), "same address keeps it");+ set_cloud_url(&hub, Some("https://another.example.com"), TokenChange::Keep).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_TOKEN), None, "a new address drops the old relay's token");++ set_cloud_url(&hub, Some("https://another.example.com"), TokenChange::Set("another-token-value".into()))+ .unwrap();+ set_cloud_url(&hub, Some("https://another.example.com"), TokenChange::Clear).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_TOKEN), None);+ set_cloud_url(&hub, Some("https://another.example.com"), TokenChange::Set("another-token-value".into()))+ .unwrap();+ set_cloud_url(&hub, None, TokenChange::Keep).unwrap();+ assert_eq!(hub.store.kv_get(SAVED_URL), None);+ assert_eq!(hub.store.kv_get(SAVED_TOKEN), None);+ }++ #[test]+ fn the_status_shows_the_token_of_the_address_in_use() {+ let hub = temp_hub();+ hub.store.kv_set("test_cloud_url", "https://relay.example.com").unwrap();+ hub.store.kv_set("test_cloud_token", "s3cret-token-value").unwrap();+ cloud::update_status(&hub, |s| s.owner = Some(cloud::Owner { user_id: "user_1".into(), email: None }));+ let status = set_cloud(&hub, true).unwrap();+ assert_eq!((status.token_set, status.relay), (true, RelayKind::Private));+ assert_eq!(status.owner, None, "a private relay has no account owner");+ hub.store.kv_delete("test_cloud_token").unwrap();+ let status = set_cloud(&hub, true).unwrap();+ assert_eq!((status.token_set, status.relay), (false, RelayKind::Codync));+ assert!(!set_cloud(&hub, false).unwrap().enabled);+ }+}diff --git a/host/src/remote/mod.rs b/host/src/remote/mod.rsindex c8518eec..23ea3b7e 100644--- a/host/src/remote/mod.rs+++ b/host/src/remote/mod.rs@@ -3,6 +3,7 @@pub mod channel;pub mod cloud;+mod cloud_url;pub mod crypto;pub mod identity;pub mod push;diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rsindex 526e4406..e0059db0 100644--- a/host/src/remote/relay.rs+++ b/host/src/remote/relay.rs@@ -1,12 +1,13 @@//! The outbound WebSocket to this computer's relay in the Codync cloud (spec §7, §9.6).//!//! Every connection runs the same order: register (once per URL) → connect with-//! `Codync-Sig` → pull the cloud state (≤ 10 s; account devices wait for it) → publish the-//! signed ACL → `acl.ok` → `ready`. Then device links are multiplexed onto `channel::run`-//! (the relay only ever sees ciphertext), queued mailbox sends are delivered in order and-//! acknowledged, and every change to the device table republishes the ACL. Once ready, the-//! routine webhooks are registered (and again whenever they change) and public webhook-//! deliveries arrive one at a time for an ack (§7.8). A reconnect drops all link state.+//! `Codync-Sig` → pull the cloud state (≤ 10 s; account devices wait for it; a private relay+//! has none) → publish the signed ACL → `acl.ok` → `ready`. Then device links are multiplexed+//! onto `channel::run` (the relay only ever sees ciphertext), queued mailbox sends are+//! delivered in order and acknowledged, and every change to the device table republishes the+//! ACL. Once ready, the routine webhooks are registered (and again whenever they change) and+//! public webhook deliveries arrive one at a time for an ack (§7.8). A reconnect drops all link+//! state.use crate::LockExt;use crate::api;@@ -30,6 +31,7 @@ use tokio::time::{Instant, sleep, timeout};use tokio_stream::StreamMap;use tokio_stream::wrappers::ReceiverStream;use tokio_tungstenite::tungstenite::{self, Message, client::IntoClientRequest as _};+use tracing::Instrument as _;const PATH: &str = "/v1/relay/host?v=1";/// Must be exactly this string: the relay answers it without waking up.@@ -49,27 +51,38 @@ const MAILBOX_MAX_AGE_MS: i64 = 25 * 60 * 60 * 1000;const REPLACED: u16 = 4009;const RATE_LIMITED: u16 = 4008;+/// How long the old relay stays up after the cloud is reconfigured, so phones that reach this+/// computer through it can reconnect once and learn the new address.+const MOVE_GRACE: Duration = Duration::from_secs(10);+/// Keeps this computer on the relay while the cloud is on; restarts when it's reconfigured.pub async fn run(hub: Arc<Hub>) {let mut config = hub.cloud.config.subscribe();loop {config.mark_unchanged();- let url = cloud::url(&hub.store);+ let address = cloud::current(&hub.store);cloud::update_status(&hub, |s| {- s.enabled = url.is_some();- s.url.clone_from(&url);+ cloud::show(s, address.as_ref());s.approval = cloud::approval(&hub.store);s.registered = false;s.connected = false;- if url.is_none() {+ if address.is_none() {s.owner = None;s.last_error = None;}});- let restart = if let Some(url) = url {+ let restart = if let Some(address) = address {+ let cloud_host = cloud::authority(&address.url).unwrap_or_else(|_| "unknown".into());+ let session = supervise(&hub, &address).instrument(tracing::info_span!("relay", cloud_host));+ tokio::pin!(session);tokio::select! {- () = supervise(&hub, &url) => Ok(()),- r = config.changed() => r,+ () = &mut session => Ok(()),+ r = config.changed() => {+ // Every channel reconnects on this change (`channel::serve`) and reads the new+ // address from `hello`. Phones on this relay need it to stay up while they do.+ let _ = timeout(MOVE_GRACE, &mut session).await;+ r+ }}} else {// No cloud: account devices can't be renewed, so they aren't honored either.@@ -107,13 +120,13 @@ impl Backoff {}}-async fn supervise(hub: &Arc<Hub>, url: &str) {+async fn supervise(hub: &Arc<Hub>, address: &cloud::Address) {let mut register_wait = Backoff::new(Duration::from_secs(30 * 60));let mut wait = Backoff::new(Duration::from_secs(60));let mut registered = false;loop {if !registered {- if let Err(e) = cloud::register(hub, url).await {+ if let Err(e) = cloud::register(hub, address).await {tracing::warn!(error = format!("{e:#}"), "couldn't register with the Codync cloud");cloud::update_status(hub, |s| s.last_error = Some(format!("{e:#}")));sleep(register_wait.wait()).await;@@ -123,7 +136,7 @@ async fn supervise(hub: &Arc<Hub>, url: &str) {register_wait.reset();}let started = Instant::now();- let outcome = session(hub, url).await;+ let outcome = session(hub, address).await;cloud::update_status(hub, |s| s.connected = false);match outcome {Ok(Some(REPLACED)) => {@@ -168,9 +181,9 @@ type Sink = futures::stream::SplitSink<>;/// One relay connection; returns the close code the relay sent, if any.-async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {- let mut req = relay_url(base)?.into_client_request()?;- let sig = hub.identity.sign_request("GET", &cloud::authority(base)?, PATH, b"");+async fn session(hub: &Arc<Hub>, address: &cloud::Address) -> Result<Option<u16>> {+ let mut req = relay_url(&address.url)?.into_client_request()?;+ let sig = hub.identity.sign_request("GET", &cloud::authority(&address.url)?, PATH, b"");req.headers_mut().insert("Codync-Sig", sig.parse()?);let (ws, _) = timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(req)).await@@ -185,7 +198,7 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {let (sink, mut stream) = ws.split();let mut s = Session {hub: hub.clone(),- base: base.to_owned(),+ address: address.clone(),sink,links: HashMap::new(),outs: StreamMap::new(),@@ -194,7 +207,7 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {ready: false,retried: false,};- if timeout(STATE_WAIT, pull_state(hub.clone(), base.to_owned())).await.is_err() {+ if timeout(STATE_WAIT, pull_state(hub.clone(), address.clone())).await.is_err() {tracing::warn!("the cloud state didn't arrive in time; account devices wait for it");}let mut auth = hub.auth.subscribe();@@ -253,9 +266,14 @@ async fn session(hub: &Arc<Hub>, base: &str) -> Result<Option<u16>> {}}-/// A state pull on the current connection; success lets account devices in.-async fn pull_state(hub: Arc<Hub>, base: String) {- match cloud::pull(&hub, &base).await {+/// A state pull on the current connection; success lets account devices in. A private relay+/// has no accounts: nothing is pulled, so its empty grant list never removes an account device,+/// and those devices stay out, as with the cloud off, until the Codync cloud renews them.+async fn pull_state(hub: Arc<Hub>, address: cloud::Address) {+ if address.kind == cloud::RelayKind::Private {+ return;+ }+ 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");@@ -266,7 +284,7 @@ async fn pull_state(hub: Arc<Hub>, base: String) {struct Session {hub: Arc<Hub>,- base: String,+ address: cloud::Address,sink: Sink,/// Device messages into each link's channel.links: HashMap<String, mpsc::Sender<Value>>,@@ -288,7 +306,7 @@ impl Session {}fn pull(&mut self) {- self.pulls.spawn(pull_state(self.hub.clone(), self.base.clone()));+ self.pulls.spawn(pull_state(self.hub.clone(), self.address.clone()));}/// Delivers the held mailbox item once a state pull has succeeded.@@ -371,9 +389,11 @@ impl Session {"mbox.item" => {let from = v["from"].as_str().unwrap_or_default();let account = self.hub.store.device(from).is_some_and(|d| d.source == DeviceSource::Account);- if account && !self.hub.cloud_synced.load(Ordering::Acquire) {+ let pulls = self.address.kind == cloud::RelayKind::Codync;+ if account && pulls && !self.hub.cloud_synced.load(Ordering::Acquire) {// Refusing it would drop it for good; unacknowledged, it waits for the pull- // (or goes back to the queue if this connection ends).+ // (or goes back to the queue if this connection ends). A private relay never+ // pulls, so there it is refused instead of holding up the mailbox.self.held = Some(v);if self.pulls.is_empty() {self.pull();@@ -553,6 +573,13 @@ mod tests {/// 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 {@@ -576,6 +603,7 @@ mod tests {.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}))@@ -584,6 +612,7 @@ mod tests {.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 {@@ -596,7 +625,7 @@ mod tests {.route("/v1/relay/host",any(move |State(f): State<Arc<Fake>>, ws: WebSocketUpgrade, req: Request| async move {- let _ = req;+ note_token(&f, &req);ws.on_upgrade(move |socket| fake_do(f, socket))}),)@@ -846,4 +875,73 @@ mod tests {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,+ })+ .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.rsindex b36ce288..00395ea2 100644--- a/host/src/routines/mod.rs+++ b/host/src/routines/mod.rs@@ -362,8 +362,9 @@ impl Routines {})}- /// The routine's webhook: the public URL through the Codync cloud (when it's on), the- /// local one, and the key. `rotate` replaces the key first, cutting off the old one.+ /// The routine's webhook: the public URL through the Codync cloud (when it's on; a private+ /// relay doesn't deliver them), the local one, and the key. `rotate` replaces the key first,+ /// cutting off the old one.pub fn credentials(&self, hub: &Hub, bot: &str, id: &str, rotate: bool) -> Result<Value> {if rotate {self.change(&hub.store, |s| {@@ -387,7 +388,8 @@ impl Routines {.clone()};let cloud = hub.cloud.status();- let url = crate::remote::cloud::url(&hub.store)+ let url = crate::remote::cloud::codync_url(hub)+ .ok().map(|base| format!("{}/v1/hooks/{}/{id}", base.trim_end_matches('/'), hub.identity.computer_id()));Ok(json!({"url": url,diff --git a/host/src/secret_prompt.rs b/host/src/secret_prompt.rsnew file mode 100644index 00000000..49aee496--- /dev/null+++ b/host/src/secret_prompt.rs@@ -0,0 +1,42 @@+//! Reads a secret for a CLI command: typed without echo on a terminal, or one line of piped stdin.++use anyhow::{Result, bail};+use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};+use crossterm::terminal;+use std::io::{BufRead, IsTerminal, Write};++/// One line of secret input, trimmed. Typed keys are never shown.+pub fn read(prompt: &str) -> Result<String> {+ if !std::io::stdin().is_terminal() {+ let mut line = String::new();+ std::io::stdin().lock().read_line(&mut line)?;+ return Ok(line.trim().to_owned());+ }+ eprint!("{prompt}");+ std::io::stderr().flush()?;+ terminal::enable_raw_mode()?;+ let typed = read_keys();+ terminal::disable_raw_mode()?;+ eprintln!();+ typed+}++fn read_keys() -> Result<String> {+ let mut secret = String::new();+ loop {+ let Event::Key(key) = event::read()? else { continue };+ if key.kind != KeyEventKind::Press {+ continue;+ }+ match key.code {+ KeyCode::Enter => return Ok(secret.trim().to_owned()),+ KeyCode::Backspace => {+ secret.pop();+ }+ KeyCode::Esc => bail!("cancelled"),+ KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => bail!("cancelled"),+ KeyCode::Char(c) => secret.push(c),+ _ => {}+ }+ }+}diff --git a/private-relay/.gitignore b/private-relay/.gitignorenew file mode 100644index 00000000..db9eb316--- /dev/null+++ b/private-relay/.gitignore@@ -0,0 +1,4 @@+node_modules/+data/+*.sqlite+*.sqlite-*diff --git a/private-relay/README.md b/private-relay/README.mdnew file mode 100644index 00000000..311123bb--- /dev/null+++ b/private-relay/README.md@@ -0,0 +1,115 @@+# Codync private relay++A single-process relay for one person's computers. It speaks the same WebSocket subset the Codync host and phones already use (`docs/reference/remote-relay.md`). It does not decrypt chat. One process can hold several computers; each `computerId` is its own room.++It does not do accounts, routine webhooks, TURN, or push. Push stays on the existing APNs worker. Remote screen over the relay needs TURN, which this service does not issue (`POST /v1/host/screen-ice` is 404). Direct Wi-Fi and Tailscale screen still work. It does bounce a connector sign-in on the phone back to the app (`/v1/oauth/callback`), as the Codync cloud does.++## Run++Node.js 22.13 or newer (built-in `node:sqlite` and `--experimental-strip-types`). The process listens on `127.0.0.1` only. Put TLS and the public hostname on a reverse proxy.++```bash+cd private-relay+npm ci+export CODYNC_PRIVATE_RELAY_DATA=/var/lib/codync-private-relay+export CODYNC_PRIVATE_RELAY_TOKEN='a-long-random-secret'+export CODYNC_PRIVATE_RELAY_PUBLIC_URL=https://relay.example.com+export PORT=8788+npm start+```++`CODYNC_PRIVATE_RELAY_PUBLIC_URL` is the address computers put in their Relay address (`https://relay.example.com`, or `https://relay.example.com:8443`). Every `Codync-Sig` must be signed for it, so a signature made for another relay is refused here. The request's `Host` header is not used. Unset, only the loopback address itself verifies (`http://127.0.0.1:8788`), which suits a relay on the same machine and refuses everything that arrives through a proxy.++`CODYNC_PRIVATE_RELAY_TOKEN` is required: 16 to 256 visible ASCII characters (no spaces). A computer this relay does not already know can register only by presenting that token. Without it, anyone who can reach the relay could create a computer and hold a room. The process refuses to start without such a token. At most 32 computers are stored. One that is already registered can refresh its row and reconnect with its own key, without the token.++The database is `$CODYNC_PRIVATE_RELAY_DATA/relay.sqlite` (mode `0600` on Unix). When `CODYNC_PRIVATE_RELAY_DATA` is unset it uses `/var/lib/codync-private-relay`.++`GET /health` returns `{"ok":true}`.++## systemd++Run it as its own user, not root.++```ini+[Unit]+Description=Codync private relay+After=network-online.target++[Service]+Type=simple+User=codync-relay+Group=codync-relay+Environment=PORT=8788+Environment=CODYNC_PRIVATE_RELAY_DATA=/var/lib/codync-private-relay+Environment=CODYNC_PRIVATE_RELAY_TOKEN=a-long-random-secret+Environment=CODYNC_PRIVATE_RELAY_PUBLIC_URL=https://relay.example.com+ExecStart=/usr/bin/node --experimental-strip-types /opt/codync-private-relay/src/index.ts+Restart=always+RestartSec=2+NoNewPrivileges=true+PrivateTmp=true++[Install]+WantedBy=multi-user.target+```++Create `/var/lib/codync-private-relay` owned by that user (`0700`) before starting.++## Nginx++TLS terminates here. Do not enable `http2` on this server: the relay is a WebSocket upgrade.++```nginx+map $http_upgrade $connection_upgrade {+ default upgrade;+ '' close;+}++server {+ listen 443 ssl;+ server_name relay.example.com;++ ssl_certificate /etc/letsencrypt/live/relay.example.com/fullchain.pem;+ ssl_certificate_key /etc/letsencrypt/live/relay.example.com/privkey.pem;++ location / {+ proxy_pass http://127.0.0.1:8788;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_read_timeout 3600s;+ proxy_send_timeout 3600s;+ }+}+```++Open TCP 443 to the internet. Leave 8788 on loopback.++## Point a computer at it++On the computer (not on the VPS), in Codync's Computers settings, turn on Reach from anywhere, set Relay address to `https://relay.example.com`, and paste the same value as `CODYNC_PRIVATE_RELAY_TOKEN` into Relay token. The token stays on that computer: it is sent only in the `Codync-Relay-Token` header when the computer enrolls, never in a URL, and phones never see it. Or:++```bash+codync-host cloud --url https://relay.example.com --token+```++`--token` reads the token without echo (or one line from stdin when piped), so it does not land in shell history. `--clear-url` forgets the saved address and the token, and uses this build's Codync cloud again. Clearing the Relay address field does the same, and moving to another address drops the old token. Each computer keeps its own `identity.json`. Do not copy that file to a second machine; register the second machine on its own, with the token. Both can use this same relay. They are separate rooms.++Accounts, public routine webhooks and remote screen through the relay are not served (`404`). Direct Wi-Fi and Tailscale screen still work. Push stays on the existing notification worker. Devices approved through a Codync account stay on the computer but can't connect while it uses this relay; they can again once it goes back to the Codync relay. Devices paired with a QR code are not affected.++Phones learn the address from the pairing code and from the next `hello`. They do not have their own address field.++## Manage computers++The relay keeps each computer in `relay.sqlite`. Changing `CODYNC_PRIVATE_RELAY_TOKEN` only stops new enrollments: computers already registered keep refreshing and connecting with their own keys. To take one out (a lost machine, or a leaked token used to fill the 32 places), use `sqlite3` on the relay, then restart it so a live connection drops:++```bash+cd /var/lib/codync-private-relay+sqlite3 relay.sqlite "SELECT id, name, platform, status, datetime(updated_at / 1000, 'unixepoch') FROM computers"+# Keep it out: it can no longer register, connect, or be reached by its devices.+sqlite3 relay.sqlite "UPDATE computers SET status = 'disabled' WHERE id = '<computerId>'"+# Or forget it and free its place; it can enroll again only with the token.+sqlite3 relay.sqlite "DELETE FROM computers WHERE id = '<computerId>'; DELETE FROM acl WHERE computer_id = '<computerId>'; DELETE FROM mailbox WHERE computer_id = '<computerId>'"+sudo systemctl restart codync-private-relay+```diff --git a/private-relay/package-lock.json b/private-relay/package-lock.jsonnew file mode 100644index 00000000..e6822e2a--- /dev/null+++ b/private-relay/package-lock.json@@ -0,0 +1,109 @@+{+ "name": "codync-private-relay",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "codync-private-relay",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@hono/node-server": "^1.19.6",+ "hono": "^4.10.3",+ "ws": "^8.18.3"+ },+ "devDependencies": {+ "@types/node": "^24.10.0",+ "@types/ws": "^8.18.1",+ "typescript": "^5.9.3"+ },+ "engines": {+ "node": ">=22.13"+ }+ },+ "node_modules/@hono/node-server": {+ "version": "1.19.17",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",+ "integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },+ "node_modules/@types/node": {+ "version": "24.19.2",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",+ "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": ">=7.24.0 <7.24.7"+ }+ },+ "node_modules/@types/ws": {+ "version": "8.18.2",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",+ "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/hono": {+ "version": "4.13.13",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",+ "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "7.24.6",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ }+ }+}diff --git a/private-relay/package.json b/private-relay/package.jsonnew file mode 100644index 00000000..5461f65f--- /dev/null+++ b/private-relay/package.json@@ -0,0 +1,26 @@+{+ "name": "codync-private-relay",+ "version": "0.1.0",+ "description": "Single-process Codync relay for one person's computers. A subset of the cloud WebSocket protocol.",+ "private": true,+ "license": "Apache-2.0",+ "type": "module",+ "engines": {+ "node": ">=22.13"+ },+ "scripts": {+ "start": "node --experimental-strip-types src/index.ts",+ "test": "node --experimental-strip-types --test test/*.test.ts",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@hono/node-server": "^1.19.6",+ "hono": "^4.10.3",+ "ws": "^8.18.3"+ },+ "devDependencies": {+ "@types/node": "^24.10.0",+ "@types/ws": "^8.18.1",+ "typescript": "^5.9.3"+ }+}diff --git a/private-relay/src/acl.ts b/private-relay/src/acl.tsnew file mode 100644index 00000000..7034f2b7--- /dev/null+++ b/private-relay/src/acl.ts@@ -0,0 +1,37 @@+/** A host-signed ACL. The bytes of `d` are verified before this parses them. */++import { fromB64url } from './codec.ts'++export interface Acl {+ v: 1+ computerId: string+ ver: number+ devices: { dk: string; grant: string | null }[]+ offers: { id: string; exp: number }[]+}++/** Parses and shape-checks a signed ACL's JSON. `null` when malformed. */+export function parseAcl(bytes: Uint8Array): Acl | null {+ let acl: unknown+ try {+ acl = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes))+ } catch {+ return null+ }+ if (!acl || typeof acl !== 'object') return null+ const a = acl as Partial<Acl>+ const devices = a.devices+ const offers = a.offers+ const ok =+ a.v === 1 &&+ typeof a.computerId === 'string' &&+ Number.isSafeInteger(a.ver) &&+ (a.ver ?? 0) >= 1 &&+ Array.isArray(devices) &&+ devices.every(+ (d) => !!d && fromB64url(d.dk, 32) !== null && (d.grant === null || (typeof d.grant === 'string' && d.grant.length <= 64)),+ ) &&+ Array.isArray(offers) &&+ offers.every((o) => !!o && fromB64url(o.id, 16) !== null && Number.isSafeInteger(o.exp))+ return ok ? (a as Acl) : null+}diff --git a/private-relay/src/codec.ts b/private-relay/src/codec.tsnew file mode 100644index 00000000..21677731--- /dev/null+++ b/private-relay/src/codec.ts@@ -0,0 +1,43 @@+/** Base64url and the computer id. Same rules as `cloud/src/auth.ts`. */++export const b64url = (bytes: Uint8Array): string => {+ let s = ''+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+}++/** Strict base64url (no padding). `null` when malformed or not `len` bytes. */+export function fromB64url(s: unknown, len?: number): Uint8Array | null {+ if (typeof s !== 'string' || !/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) return null+ const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4))+ let bytes: Uint8Array+ try {+ bytes = Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + pad), (c) => c.charCodeAt(0))+ } catch {+ return null+ }+ if (len !== undefined && bytes.length !== len) return null+ return b64url(bytes) === s ? bytes : null+}++export const utf8 = (s: string): Uint8Array => new TextEncoder().encode(s)++export const sha256 = async (bytes: Uint8Array): Promise<Uint8Array> =>+ new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))++export const randomId = (n = 16): string => b64url(crypto.getRandomValues(new Uint8Array(n)))++/** `computerId = b64url(SHA-256(hostSignPub)[0..16])`. */+export const computerIdFor = async (signPub: Uint8Array): Promise<string> => b64url((await sha256(signPub)).subarray(0, 16))++export const COMPUTER_ID = /^[A-Za-z0-9_-]{22}$/++export async function verifyEd25519(pub: Uint8Array, sig: Uint8Array, msg: Uint8Array): Promise<boolean> {+ if (pub.length !== 32 || sig.length !== 64) return false+ try {+ const key = await crypto.subtle.importKey('raw', pub, { name: 'Ed25519' }, false, ['verify'])+ return await crypto.subtle.verify({ name: 'Ed25519' }, key, sig, msg)+ } catch {+ return false+ }+}diff --git a/private-relay/src/http.ts b/private-relay/src/http.tsnew file mode 100644index 00000000..bcdb89e4--- /dev/null+++ b/private-relay/src/http.ts@@ -0,0 +1,297 @@+/** HTTP registration and the WebSocket upgrade. The upgrade is accepted only after admission. */++import { timingSafeEqual } from 'node:crypto'+import { createServer, STATUS_CODES, type IncomingMessage, type Server } from 'node:http'+import type { Duplex } from 'node:stream'+import { Hono } from 'hono'+import { getRequestListener } from '@hono/node-server'+import { HTTPException } from 'hono/http-exception'+import { WebSocketServer } from 'ws'+import { COMPUTER_ID, computerIdFor, fromB64url } from './codec.ts'+import { publicAuthority, verifyCodyncSig } from './sig.ts'+import type { RelayStore } from './store.ts'+import { Rooms } from './room.ts'++const MAX_BODY = 64 * 1024+const MAX_COMPUTERS = 32+const REGISTER_WINDOW_MS = 60_000+const REGISTER_LIMIT = 10+const REJECT_LIMIT = 30+const PLATFORMS = ['macos', 'linux', 'windows'] as const++/** Equal-length compare. A length mismatch is a miss; the token is not a secret length. */+function sameToken(given: string, expected: string): boolean {+ const left = Buffer.from(given)+ const right = Buffer.from(expected)+ return left.length === right.length && timingSafeEqual(left, right)+}++/** At most `limit` attempts in any `REGISTER_WINDOW_MS`. */+class Window {+ private readonly attempts: number[] = []+ private readonly limit: number++ constructor(limit: number) {+ this.limit = limit+ }++ /** Counts one attempt at `at`, or `false` when the window is already full. */+ take(at: number): boolean {+ while (this.attempts.length && at - (this.attempts[0] ?? at) >= REGISTER_WINDOW_MS) this.attempts.shift()+ if (this.attempts.length >= this.limit) return false+ this.attempts.push(at)+ return true+ }+}++function jsonError(status: number, code: string, message?: string): Response {+ return Response.json({ error: { code, ...(message ? { message } : {}) } }, { status })+}++/**+ * Ends the request with `jsonError`. Thrown rather than returned: `@hono/node-server` swaps the+ * global `Response`, so `instanceof Response` is false for what `Response.json` makes.+ */+function refuse(status: 400 | 401 | 403 | 404 | 429, code: string, message?: string): never {+ throw new HTTPException(status, { res: jsonError(status, code, message) })+}++function reject(socket: Duplex, status: number, code: string): void {+ const body = JSON.stringify({ error: { code } })+ socket.write(+ `HTTP/1.1 ${status} ${STATUS_CODES[status] ?? 'Error'}\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`,+ )+ socket.destroy()+}++function objectBody(raw: Uint8Array): Record<string, unknown> {+ if (!raw.length) return {}+ let value: unknown+ try {+ value = JSON.parse(new TextDecoder().decode(raw))+ } catch {+ refuse(400, 'badRequest', 'Body is not JSON')+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) refuse(400, 'badRequest', 'Body must be an object')+ return value as Record<string, unknown>+}++interface Registration {+ boxPub: string+ name: string+ platform: string+ device: string | null+ version: string+}++/** The register body's fields, checked. */+function parseRegister(body: Record<string, unknown>): Registration {+ const { boxKey, name, version, platform, device } = body+ if (!fromB64url(boxKey, 32) || typeof name !== 'string' || !name.trim() || name.length > 100) refuse(400, 'badRequest', 'Invalid register')+ if (typeof version !== 'string' || !version.trim() || version.length > 32) refuse(400, 'badRequest', 'Invalid register')+ if (typeof platform !== 'string' || !PLATFORMS.includes(platform as (typeof PLATFORMS)[number])) refuse(400, 'badRequest', 'Invalid platform')+ if (device != null && (typeof device !== 'string' || device.length > 32)) refuse(400, 'badRequest', 'Invalid device')+ return { boxPub: boxKey as string, name, platform, device: typeof device === 'string' ? device : null, version }+}++/** Reads at most `MAX_BODY` bytes, including a request with no `Content-Length`. */+async function limitedBody(request: Request): Promise<Uint8Array> {+ const declared = request.headers.get('content-length')+ if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > MAX_BODY)) {+ await request.body?.cancel().catch(() => {+ // The client may already be gone. The size refusal still stands.+ })+ refuse(400, 'badRequest', 'Body too large')+ }+ const reader = request.body?.getReader()+ if (!reader) return new Uint8Array()+ const chunks: Uint8Array[] = []+ let total = 0+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ if (!value?.byteLength) continue+ total += value.byteLength+ if (total > MAX_BODY) {+ await reader.cancel().catch(() => {+ // The client may already be gone. The size refusal still stands.+ })+ break+ }+ chunks.push(value)+ }+ } catch {+ refuse(400, 'badRequest', 'Body is not JSON')+ }+ if (total > MAX_BODY) refuse(400, 'badRequest', 'Body too large')+ return Buffer.concat(chunks)+}++/** A valid `Codync-Sig` and the computer its key derives. */+interface Signed {+ kid: string+ nonce: string+ computerId: string+}++export interface RelayServer {+ server: Server+ url: string+ store: RelayStore+ rooms: Rooms+ close: () => Promise<void>+}++export async function startRelay(options: {+ store: RelayStore+ host?: string+ port?: number+ now?: () => number+ /**+ * The host (and non-default port) computers put in their Relay address, which `Codync-Sig`+ * signs. Defaults to the listening address. Never taken from the request's `Host` header, so a+ * signature made for another relay does not verify here.+ */+ publicUrl?: string+ /** Required to enroll a computer this relay does not already know. */+ token?: string+ maxComputers?: number+ /** New enrollments allowed per minute. A known computer refreshing its row does not count. */+ newRegisterLimit?: number+ /** Wrong-token attempts allowed per minute. They do not consume `newRegisterLimit`. */+ rejectedRegisterLimit?: number+}): Promise<RelayServer> {+ const now = options.now ?? Date.now+ const rooms = new Rooms(options.store, now)+ const store = options.store+ const token = options.token ?? ''+ const maxComputers = options.maxComputers ?? MAX_COMPUTERS+ const enrollments = new Window(options.newRegisterLimit ?? REGISTER_LIMIT)+ const rejections = new Window(options.rejectedRegisterLimit ?? REJECT_LIMIT)+ // Set once the port is bound, before the first request can arrive.+ let authority = ''++ /** Any key can sign, so callers spend the nonce (`rememberNonce`) only once the request is+ * otherwise allowed: unknown keys never add rows. */+ async function verify(header: string | undefined, method: string, url: URL, body: Uint8Array): Promise<Signed | null> {+ const signed = await verifyCodyncSig(header, method, authority, url.pathname + url.search, body, now())+ if (!signed) return null+ // `verifyCodyncSig` already checked `kid` is a 32-byte key.+ const pub = fromB64url(signed.kid, 32) as Uint8Array+ return { kid: signed.kid, nonce: signed.nonce, computerId: await computerIdFor(pub) }+ }++ const app = new Hono()++ app.get('/health', (c) => c.json({ ok: true }))++ // A connector's sign-in on the phone returns here; the query goes on to the app (cloud/src/api.ts).+ // The code in it is useless without the PKCE verifier only the host holds.+ const bounce = (scheme: string) => (c: { req: { url: string } }) =>+ new Response(null, { status: 302, headers: { Location: `${scheme}://oauth${new URL(c.req.url).search}`, 'Cache-Control': 'no-store' } })+ app.get('/v1/oauth/callback', bounce('codync'))+ app.get('/v1/oauth/callback/dev', bounce('codync-dev'))++ app.post('/v1/host/register', async (c) => {+ const raw = await limitedBody(c.req.raw)+ const body = objectBody(raw)+ const signed = await verify(c.req.header('codync-sig'), 'POST', new URL(c.req.url), raw)+ if (!signed) return jsonError(401, 'badSignature')+ const fields = parseRegister(body)+ const existing = store.computer(signed.computerId)+ if (existing && existing.status !== 'active') return jsonError(403, 'forbidden')+ // A key this relay already accepted can refresh. Any other key needs the operator's token,+ // and the table stops growing once it is full.+ if (!existing) {+ const at = now()+ // A wrong token must not use up the allowance a real computer needs to enroll.+ if (!token || !sameToken(c.req.header('codync-relay-token') ?? '', token)) {+ if (!rejections.take(at)) return jsonError(429, 'rateLimited')+ return jsonError(403, 'forbidden', 'This relay needs its relay token to add a new computer.')+ }+ if (!enrollments.take(at)) return jsonError(429, 'rateLimited')+ if (store.countComputers() >= maxComputers) return jsonError(403, 'forbidden', 'This relay already has as many computers as it keeps.')+ }+ if (!store.rememberNonce(signed.kid, signed.nonce, now())) return jsonError(401, 'badSignature')+ store.register({ id: signed.computerId, signPub: signed.kid, ...fields, now: now() })+ return c.json({ computerId: signed.computerId, owned: false })+ })++ app.get('/v1/host/state', async (c) => {+ const signed = await verify(c.req.header('codync-sig'), 'GET', new URL(c.req.url), new Uint8Array())+ if (!signed) return jsonError(401, 'badSignature')+ const computer = store.computer(signed.computerId)+ if (!computer || computer.status !== 'active') return jsonError(404, 'unknownComputer')+ if (!store.rememberNonce(signed.kid, signed.nonce, now())) return jsonError(401, 'badSignature')+ return c.json({ owner: null, grants: [], requests: [] })+ })++ // Accounts, screen TURN and public webhooks are not served here.+ app.notFound(() => jsonError(404, 'notFound'))++ const listener = getRequestListener(app.fetch)+ const server = createServer((req, res) => {+ listener(req, res)+ })+ const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 })+ const sweep = setInterval(() => rooms.sweep(), 30_000)+ sweep.unref?.()++ /** Admits the socket to a room, or refuses it with an HTTP answer. */+ async function upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {+ const url = new URL(req.url ?? '/', 'http://relay.local')+ if (url.searchParams.get('v') !== '1') return reject(socket, 426, 'upgradeRequired')+ if (req.method !== 'GET') return reject(socket, 400, 'badRequest')+ const header = req.headers['codync-sig']+ const signed = Array.isArray(header) ? null : await verify(header, 'GET', url, new Uint8Array())+ if (!signed) return reject(socket, 401, 'badSignature')++ if (url.pathname === '/v1/relay/host') {+ const admitted = rooms.admitHost(signed.computerId, signed.kid)+ if (!admitted.ok) return reject(socket, admitted.status, admitted.code)+ if (!store.rememberNonce(signed.kid, signed.nonce, now())) return reject(socket, 401, 'badSignature')+ wss.handleUpgrade(req, socket, head, (ws) => rooms.attachHost(signed.computerId, signed.kid, ws))+ return+ }++ const computerId = url.pathname.match(/^\/v1\/relay\/device\/([^/]+)$/)?.[1]+ if (!computerId) return reject(socket, 404, 'notFound')+ if (!COMPUTER_ID.test(computerId)) return reject(socket, 400, 'badRequest')+ const pair = url.searchParams.get('pair') ?? ''+ if (pair && !fromB64url(pair, 16)) return reject(socket, 400, 'badRequest')+ const admitted = rooms.admitDevice(computerId, signed.kid, pair)+ if (!admitted.ok) return reject(socket, admitted.status, admitted.code)+ if (!store.rememberNonce(signed.kid, signed.nonce, now())) return reject(socket, 401, 'badSignature')+ wss.handleUpgrade(req, socket, head, (ws) => rooms.attachDevice(computerId, signed.kid, admitted, ws))+ }++ server.on('upgrade', (req, socket, head) => {+ // Node hands over the raw socket. Until `ws` takes it, an unhandled 'error' (a reset during+ // the signature check) would throw out of the event loop and stop the whole relay.+ socket.on('error', () => socket.destroy())+ void upgrade(req, socket, head).catch((error: unknown) => {+ console.error('upgrade failed', error)+ socket.destroy()+ })+ })++ const host = options.host ?? '127.0.0.1'+ await new Promise<void>((resolve) => server.listen(options.port ?? 0, host, resolve))+ const address = server.address()+ const bound = typeof address === 'object' && address ? address.port : (options.port ?? 0)+ authority = publicAuthority(options.publicUrl ?? `http://${host}:${bound}`)+ return {+ server,+ url: `http://${host}:${bound}`,+ store,+ rooms,+ close: () =>+ new Promise((resolve, reject) => {+ clearInterval(sweep)+ for (const client of wss.clients) client.terminate()+ wss.close()+ server.close((error) => (error ? reject(error) : resolve()))+ }),+ }+}diff --git a/private-relay/src/index.ts b/private-relay/src/index.tsnew file mode 100644index 00000000..af501b24--- /dev/null+++ b/private-relay/src/index.ts@@ -0,0 +1,20 @@+/** Codync private relay. Listens on loopback; a reverse proxy terminates TLS in front of it. */++import { resolve } from 'node:path'+import { RelayStore } from './store.ts'+import { startRelay } from './http.ts'++const dataDir = process.env.CODYNC_PRIVATE_RELAY_DATA ?? '/var/lib/codync-private-relay'+const port = Number(process.env.PORT ?? 8788)+const host = '127.0.0.1'+const token = process.env.CODYNC_PRIVATE_RELAY_TOKEN ?? ''+if (token.length < 16 || token.length > 256 || !/^[\x21-\x7E]+$/.test(token)) {+ console.error('CODYNC_PRIVATE_RELAY_TOKEN must be 16 to 256 visible ASCII characters.')+ process.exit(1)+}+// What computers put in their Relay address. Unset, only this loopback address verifies.+const publicUrl = process.env.CODYNC_PRIVATE_RELAY_PUBLIC_URL?.trim() || undefined++const store = new RelayStore(resolve(dataDir, 'relay.sqlite'))+const relay = await startRelay({ store, host, port, token, publicUrl })+console.log(`codync private relay listening on ${relay.url} for ${publicUrl ?? relay.url}`)diff --git a/private-relay/src/mailbox.ts b/private-relay/src/mailbox.tsnew file mode 100644index 00000000..1285ebc1--- /dev/null+++ b/private-relay/src/mailbox.ts@@ -0,0 +1,83 @@+/** Offline mailbox (§7.7). The blob stays ciphertext. One item is in flight per computer. */++import { b64url, fromB64url } from './codec.ts'+import type { RelayStore } from './store.ts'++const MBOX_MAX_BLOB = 64 * 1024+const MBOX_PER_DEVICE = 50+const MBOX_PER_COMPUTER = 500+const MBOX_MAX_BYTES = 8 * 1024 * 1024+const MBOX_TTL_MS = 24 * 3600_000+const MBOX_MIN_BLOB = 32 + 64 + 16+const FAIL_CODES = new Set(['unauthorized', 'unknownBot', 'invalid'])++export interface MailboxNote {+ dk: string+ text: string+}++type Msg = Record<string, unknown>++const err = (nonce: unknown, code: string): string => JSON.stringify({ t: 'mbox.err', nonce: typeof nonce === 'string' ? nonce : null, code })++export function putMailbox(store: RelayStore, computerId: string, dk: string, msg: Msg, hostReady: boolean, now: number): string {+ const nonce = msg.nonce+ if (typeof nonce !== 'string' || !nonce || nonce.length > 128) return err(nonce, 'invalid')+ const existing = store.mailboxByNonce(computerId, dk, nonce)+ if (existing) return JSON.stringify({ t: 'mbox.ok', nonce, state: existing.state })+ if (hostReady) return err(nonce, 'hostOnline')+ if (typeof msg.d === 'string' && msg.d.length > Math.ceil((MBOX_MAX_BLOB * 4) / 3) + 8) return err(nonce, 'tooLarge')+ const blob = fromB64url(msg.d)+ if (!blob || blob.length < MBOX_MIN_BLOB) return err(nonce, 'invalid')+ if (blob.length > MBOX_MAX_BLOB) return err(nonce, 'tooLarge')+ const exp = msg.exp === undefined ? now + MBOX_TTL_MS : msg.exp+ if (typeof exp !== 'number' || !Number.isSafeInteger(exp) || exp <= now || exp > now + MBOX_TTL_MS) return err(nonce, 'invalid')+ const counts = store.mailboxCounts(computerId, dk)+ if (counts.mine >= MBOX_PER_DEVICE || counts.all >= MBOX_PER_COMPUTER || counts.bytes + blob.length > MBOX_MAX_BYTES) return err(nonce, 'full')+ store.insertMailbox(computerId, dk, nonce, blob, exp)+ return JSON.stringify({ t: 'mbox.ok', nonce, state: 'queued' })+}++export function cancelMailbox(store: RelayStore, computerId: string, dk: string, msg: Msg): string {+ const nonce = typeof msg.nonce === 'string' ? msg.nonce : ''+ if (store.cancelQueued(computerId, dk, nonce)) return JSON.stringify({ t: 'mbox.cancelled', nonce })+ const state = store.mailboxByNonce(computerId, dk, nonce)?.state+ return JSON.stringify({ t: 'mbox.gone', nonce, state: state === 'delivering' ? 'delivering' : 'unknown' })+}++export function listMailbox(store: RelayStore, computerId: string, dk: string): string {+ return JSON.stringify({ t: 'mbox.items', items: store.listMailbox(computerId, dk) })+}++/** The next queued item, marked delivering. `null` when one is already in flight or the queue is empty. */+export function deliverNext(store: RelayStore, computerId: string, now: number): string | null {+ if (store.delivering(computerId)) return null+ const row = store.nextQueued(computerId, now)+ if (!row) return null+ store.markDelivering(row.seq)+ return JSON.stringify({+ t: 'mbox.item',+ seq: row.seq,+ from: row.dk,+ nonce: row.nonce,+ d: b64url(row.blob),+ exp: row.exp,+ })+}++/** Applies the host's ack and returns the note for that device, if the seq was in flight. */+export function ackMailbox(store: RelayStore, computerId: string, msg: Msg): MailboxNote | null {+ const seq = typeof msg.seq === 'number' ? msg.seq : Number(msg.seq)+ if (!Number.isSafeInteger(seq)) return null+ const row = store.takeDelivering(computerId, seq)+ if (!row) return null+ const note =+ msg.ok === true+ ? { t: 'mbox.delivered', nonce: row.nonce }+ : { t: 'mbox.failed', nonce: row.nonce, code: FAIL_CODES.has(msg.code as string) ? msg.code : 'invalid' }+ return { dk: row.dk, text: JSON.stringify(note) }+}++export function expireMailbox(store: RelayStore, computerId: string, now: number): MailboxNote[] {+ return store.takeExpired(computerId, now).map((row) => ({ dk: row.dk, text: JSON.stringify({ t: 'mbox.expired', nonce: row.nonce }) }))+}diff --git a/private-relay/src/room.ts b/private-relay/src/room.tsnew file mode 100644index 00000000..e9293ec1--- /dev/null+++ b/private-relay/src/room.ts@@ -0,0 +1,409 @@+/**+ * One in-memory room per computer: the host socket, device sockets, presence and forwarding.+ * ACL and mailbox live in SQLite so they survive a restart. This process never decrypts a frame.+ */++import type { WebSocket } from 'ws'+import { fromB64url, randomId, utf8, verifyEd25519 } from './codec.ts'+import { parseAcl, type Acl } from './acl.ts'+import { ackMailbox, cancelMailbox, deliverNext, expireMailbox, listMailbox, putMailbox, type MailboxNote } from './mailbox.ts'+import type { RelayStore } from './store.ts'++const MAX_DEVICE_SOCKETS = 16+const MAX_PAIRING_SOCKETS = 2+const PAIRING_TTL_MS = 120_000+const PAIRING_MAX_MESSAGES = 16+const RATE_WINDOW_MS = 10_000+const RATE_MAX_MESSAGES = 200+const RATE_MAX_BYTES = 8 * 1024 * 1024+const SILENT_TIMEOUT_MS = 90_000++export const PING = '{"t":"ping"}'+export const PONG = '{"t":"pong"}'++interface HostConn {+ ws: WebSocket+ kid: string+ ready: boolean+ heard: number+ left: boolean+}++interface DeviceConn {+ ws: WebSocket+ dk: string+ link: string+ pair: boolean+ offer?: string+ /** Pairing sockets close when `now` reaches this (offer expiry or the 120s window). */+ until: number+ heard: number+ msgs: number+ /** Traffic in the current `RATE_WINDOW_MS`. */+ rate: { start: number; msgs: number; bytes: number }+ left: boolean+}++interface Room {+ id: string+ host: HostConn | null+ devices: DeviceConn[]+ lastSeenAt: number | null+}++export interface Admit {+ ok: true+ pair: boolean+ offer?: string+}++export interface Refuse {+ ok: false+ status: number+ code: string+}++type Msg = Record<string, unknown> & { t?: unknown }++/** A JSON object. `null` and other non-objects are refused before any field is read. */+function readMessage(raw: string): Msg | null {+ try {+ const value: unknown = JSON.parse(raw)+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null+ return value as Msg+ } catch {+ return null+ }+}++function send(ws: WebSocket | undefined, text: string): void {+ if (!ws || ws.readyState !== ws.OPEN) return+ try {+ ws.send(text)+ } catch {+ // Closed underneath us. The close handler does the bookkeeping.+ }+}++const validClose = (c: unknown): c is number => typeof c === 'number' && Number.isInteger(c) && (c === 1000 || (c >= 3000 && c <= 4999))++export class Rooms {+ private readonly rooms = new Map<string, Room>()+ private readonly store: RelayStore+ private readonly now: () => number++ constructor(store: RelayStore, now: () => number) {+ this.store = store+ this.now = now+ }++ /** Device admission before the socket is accepted. A bad id or pair never creates a computer. */+ admitDevice(computerId: string, dk: string, pair: string): Admit | Refuse {+ const computer = this.store.computer(computerId)+ if (!computer || computer.status !== 'active') return { ok: false, status: 404, code: 'unknownComputer' }+ const acl = this.readAcl(computerId)+ if (!acl) return { ok: false, status: 404, code: 'unknownComputer' }+ const now = this.now()+ const room = this.rooms.get(computerId)+ const devices = room?.devices ?? []+ if (devices.length >= MAX_DEVICE_SOCKETS) return { ok: false, status: 429, code: 'rateLimited' }+ if (pair) {+ const offer = acl.offers.find((o) => o.id === pair && o.exp > now)+ if (!offer) return { ok: false, status: 403, code: 'forbidden' }+ if (devices.filter((d) => d.pair).length >= MAX_PAIRING_SOCKETS) return { ok: false, status: 429, code: 'rateLimited' }+ return { ok: true, pair: true, offer: pair }+ }+ if (!acl.devices.some((d) => d.dk === dk)) return { ok: false, status: 403, code: 'forbidden' }+ return { ok: true, pair: false }+ }++ admitHost(computerId: string, kid: string): { ok: true } | Refuse {+ const computer = this.store.computer(computerId)+ if (!computer) return { ok: false, status: 404, code: 'unknownComputer' }+ if (computer.status !== 'active' || computer.signPub !== kid) return { ok: false, status: 403, code: 'forbidden' }+ return { ok: true }+ }++ attachHost(computerId: string, kid: string, ws: WebSocket): void {+ const room = this.room(computerId)+ const previous = room.host+ if (previous && !previous.left) this.dropHost(room, previous, 4009, 'replaced', true)+ const host: HostConn = { ws, kid, ready: false, heard: this.now(), left: false }+ room.host = host+ ws.on('message', (data, isBinary) => {+ host.heard = this.now()+ if (isBinary) return+ const raw = data.toString()+ if (raw === PING) return send(ws, PONG)+ void this.onHost(room, host, raw).catch(() => {+ // A thrown frame must not reject outside this socket.+ this.dropHost(room, host, 4002, 'protocolError')+ })+ })+ ws.on('close', () => this.dropHost(room, host, 1000, ''))+ ws.on('error', () => this.dropHost(room, host, 1000, ''))+ }++ attachDevice(computerId: string, dk: string, admitted: Admit, ws: WebSocket): void {+ const room = this.room(computerId)+ if (room.devices.length >= MAX_DEVICE_SOCKETS) {+ ws.close(4008, 'rateLimited')+ return+ }+ const now = this.now()+ const device: DeviceConn = {+ ws,+ dk,+ link: randomId(12),+ pair: admitted.pair,+ offer: admitted.offer,+ until: admitted.pair ? this.pairingDeadline(computerId, admitted.offer, now) : Number.POSITIVE_INFINITY,+ heard: now,+ msgs: 0,+ rate: { start: now, msgs: 0, bytes: 0 },+ left: false,+ }+ room.devices.push(device)+ send(ws, JSON.stringify(this.presence(room)))+ const host = room.host+ if (host?.ready) send(host.ws, JSON.stringify({ t: 'open', link: device.link, dk, pair: device.pair }))+ ws.on('message', (data, isBinary) => {+ try {+ device.heard = this.now()+ if (isBinary) return this.dropDevice(room, device, 4002, 'protocolError')+ this.onDevice(room, device, data.toString())+ } catch {+ // One bad frame stays on this socket. The room and every other computer keep running.+ this.dropDevice(room, device, 4002, 'protocolError')+ }+ })+ ws.on('close', () => this.dropDevice(room, device))+ ws.on('error', () => this.dropDevice(room, device))+ }++ /** In-memory rooms. An empty one is dropped, so a disconnect does not keep it. */+ retained(): number {+ return this.rooms.size+ }++ /** Closes silent sockets and drops expired mailbox items, including rows whose room is gone. */+ sweep(): void {+ const now = this.now()+ for (const room of [...this.rooms.values()]) {+ if (room.host && now - room.host.heard > SILENT_TIMEOUT_MS) this.dropHost(room, room.host, 1011, 'timeout')+ for (const device of [...room.devices]) {+ if (device.pair && now >= device.until) this.dropDevice(room, device, 4410, 'pairingExpired')+ else if (now - device.heard > SILENT_TIMEOUT_MS) this.dropDevice(room, device, 1011, 'timeout')+ }+ this.note(room, expireMailbox(this.store, room.id, now))+ }+ // A phone can queue mail and leave while the host is offline. That room is no longer in memory.+ this.store.deleteExpiredAnywhere(now)+ }++ private room(id: string): Room {+ let room = this.rooms.get(id)+ if (!room) {+ room = { id, host: null, devices: [], lastSeenAt: null }+ this.rooms.set(id, room)+ }+ return room+ }++ private readAcl(computerId: string): Acl | null {+ const row = this.store.acl(computerId)+ if (!row) return null+ const bytes = fromB64url(row.body)+ return bytes ? parseAcl(bytes) : null+ }++ private presence(room: Room): { t: 'presence'; online: boolean; lastSeenAt: number | null } {+ return { t: 'presence', online: room.host?.ready === true, lastSeenAt: room.lastSeenAt }+ }++ private pairingDeadline(computerId: string, offer: string | undefined, now: number): number {+ const acl = this.readAcl(computerId)+ const exp = acl?.offers.find((o) => o.id === offer)?.exp ?? now+ return Math.min(now + PAIRING_TTL_MS, exp)+ }++ private async onHost(room: Room, host: HostConn, raw: string): Promise<void> {+ if (host.left || room.host !== host) return+ const msg = readMessage(raw)+ if (!msg) return+ if (msg.t === 'ping') return send(host.ws, PONG)+ if (msg.t === 'acl') return this.onAcl(room, host, msg)+ if (msg.t === 'ready') return this.onReady(room, host)+ if (msg.t === 'data') return this.onData(room, host, msg)+ if (msg.t === 'close') return this.onCloseDevice(room, host, msg)+ if (msg.t === 'mbox.ack') return this.onAck(room, host, msg)+ if (msg.t === 'hooks') return send(host.ws, JSON.stringify({ t: 'hooks.ok' }))+ }++ private async onAcl(room: Room, host: HostConn, msg: Msg): Promise<void> {+ const d = fromB64url(msg.d)+ const sig = fromB64url(msg.sig, 64)+ const pub = fromB64url(host.kid, 32)+ const acl = d && sig && pub && (await verifyEd25519(pub, sig, d)) ? parseAcl(d) : null+ const current = this.store.acl(room.id)?.ver ?? 0+ if (!acl || acl.computerId !== room.id || typeof msg.d !== 'string') {+ send(host.ws, JSON.stringify({ t: 'error', code: 'badAcl', ver: current }))+ return+ }+ if (acl.ver <= current) {+ send(host.ws, JSON.stringify({ t: 'error', code: 'staleVersion', ver: current }))+ return+ }+ this.store.saveAcl(room.id, acl.ver, msg.d)+ const now = this.now()+ for (const device of [...room.devices]) {+ if (device.pair) {+ if (!acl.offers.some((o) => o.id === device.offer && o.exp > now)) this.dropDevice(room, device, 4410, 'pairingExpired')+ } else if (!acl.devices.some((x) => x.dk === device.dk)) {+ this.dropDevice(room, device, 4003, 'revoked')+ }+ }+ send(host.ws, JSON.stringify({ t: 'acl.ok', ver: acl.ver }))+ }++ private onReady(room: Room, host: HostConn): void {+ if (host.left || room.host !== host || host.ready) return+ if (!this.readAcl(room.id)) {+ send(host.ws, JSON.stringify({ t: 'error', code: 'badAcl', ver: 0 }))+ return+ }+ host.ready = true+ room.lastSeenAt = this.now()+ const presence = JSON.stringify(this.presence(room))+ for (const device of room.devices) {+ send(device.ws, presence)+ send(host.ws, JSON.stringify({ t: 'open', link: device.link, dk: device.dk, pair: device.pair }))+ }+ this.deliver(room, host)+ }++ private onData(room: Room, host: HostConn, msg: Msg): void {+ if (!host.ready || room.host !== host || !msg.m || typeof msg.m !== 'object') return+ const device = room.devices.find((d) => d.link === msg.link)+ send(device?.ws, JSON.stringify(msg.m))+ }++ private onCloseDevice(room: Room, host: HostConn, msg: Msg): void {+ if (!host.ready || room.host !== host) return+ const device = room.devices.find((d) => d.link === msg.link)+ if (!device) return+ const code = validClose(msg.code) ? msg.code : 1000+ const reason = typeof msg.reason === 'string' ? msg.reason.slice(0, 120) : ''+ this.dropDevice(room, device, code, reason)+ }++ private onAck(room: Room, host: HostConn, msg: Msg): void {+ if (room.host !== host) return+ const note = ackMailbox(this.store, room.id, msg)+ if (note) this.note(room, [note])+ this.deliver(room, host)+ }++ private onDevice(room: Room, device: DeviceConn, raw: string): void {+ if (device.left) return+ const now = this.now()+ if (device.pair && now >= device.until) {+ this.dropDevice(room, device, 4410, 'pairingExpired')+ return+ }+ if (!this.charge(device, utf8(raw).length, now)) {+ this.dropDevice(room, device, 4008, 'rateLimited')+ return+ }+ if (device.pair) {+ device.msgs += 1+ if (device.msgs > PAIRING_MAX_MESSAGES) {+ this.dropDevice(room, device, 4008, 'rateLimited')+ return+ }+ }+ const msg = readMessage(raw)+ if (!msg) {+ this.dropDevice(room, device, 4002, 'protocolError')+ return+ }+ if (msg.t === 'ping') return send(device.ws, PONG)+ if (msg.t === 'hello' || msg.t === 'f') {+ const host = room.host+ if (host?.ready) send(host.ws, JSON.stringify({ t: 'data', link: device.link, m: msg }))+ else send(device.ws, JSON.stringify(this.presence(room)))+ return+ }+ if (msg.t === 'mbox.put' || msg.t === 'mbox.cancel' || msg.t === 'mbox.list') {+ if (device.pair) return send(device.ws, JSON.stringify({ t: 'mbox.err', nonce: msg.nonce ?? null, code: 'pairing' }))+ if (msg.t === 'mbox.put') return send(device.ws, putMailbox(this.store, room.id, device.dk, msg, room.host?.ready === true, now))+ if (msg.t === 'mbox.cancel') return send(device.ws, cancelMailbox(this.store, room.id, device.dk, msg))+ return send(device.ws, listMailbox(this.store, room.id, device.dk))+ }+ this.dropDevice(room, device, 4002, 'protocolError')+ }++ private charge(device: DeviceConn, bytes: number, now: number): boolean {+ if (now - device.rate.start >= RATE_WINDOW_MS) device.rate = { start: now, msgs: 0, bytes: 0 }+ const rate = device.rate+ rate.msgs += 1+ rate.bytes += bytes+ return rate.msgs <= RATE_MAX_MESSAGES && rate.bytes <= RATE_MAX_BYTES+ }++ private deliver(room: Room, host: HostConn): void {+ if (!host.ready || host.left || room.host !== host) return+ const text = deliverNext(this.store, room.id, this.now())+ if (text) send(host.ws, text)+ }++ private note(room: Room, notes: MailboxNote[]): void {+ for (const note of notes) {+ for (const device of room.devices) {+ if (device.dk === note.dk && !device.pair) send(device.ws, note.text)+ }+ }+ }++ private dropHost(room: Room, host: HostConn, code: number, reason: string, keepRoom = false): void {+ if (host.left) return+ host.left = true+ const wasReady = host.ready+ host.ready = false+ if (room.host === host) {+ room.host = null+ if (wasReady) {+ room.lastSeenAt = this.now()+ this.store.requeueDelivering(room.id)+ const presence = JSON.stringify(this.presence(room))+ for (const device of room.devices) send(device.ws, presence)+ }+ }+ this.close(host.ws, code, reason)+ // Replacing the host assigns the next socket on this same room. Dropping it first would leave+ // that host, and every later device, on different rooms.+ if (!keepRoom) this.release(room)+ }++ private dropDevice(room: Room, device: DeviceConn, code = 1000, reason = ''): void {+ if (device.left) return+ device.left = true+ room.devices = room.devices.filter((d) => d !== device)+ const host = room.host+ if (host?.ready) send(host.ws, JSON.stringify({ t: 'close', link: device.link }))+ this.close(device.ws, code, reason)+ this.release(room)+ }++ private release(room: Room): void {+ if (!room.host && room.devices.length === 0) this.rooms.delete(room.id)+ }++ private close(ws: WebSocket, code: number, reason: string): void {+ try {+ ws.close(code, reason)+ } catch {+ // Already gone.+ }+ }+}diff --git a/private-relay/src/sig.ts b/private-relay/src/sig.tsnew file mode 100644index 00000000..04f230a4--- /dev/null+++ b/private-relay/src/sig.ts@@ -0,0 +1,68 @@+/** Codync-Sig (§5). The signed authority is the public Host header, not the socket's own URL. */++import { b64url, fromB64url, sha256, utf8, verifyEd25519 } from './codec.ts'++export const SIG_WINDOW_MS = 300_000+export const NONCE_TTL_MS = 600_000++export interface SignedRequest {+ kid: string+ ts: number+ nonce: string+}++/**+ * The authority computers sign for this relay: the host of its public URL, with the port only when+ * it isn't the scheme's default, as the host derives it from the same address.+ * `https://Relay.Example.com:443` → `relay.example.com`, `http://127.0.0.1:443` → `127.0.0.1:443`.+ */+export function publicAuthority(publicUrl: string): string {+ const url = new URL(publicUrl)+ if (!['http:', 'https:'].includes(url.protocol) || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {+ throw new Error('CODYNC_PRIVATE_RELAY_PUBLIC_URL must be an http(s) address with no path, such as https://relay.example.com.')+ }+ return url.host.toLowerCase()+}++export async function sigCanonical(+ method: string,+ authority: string,+ pathAndQuery: string,+ ts: number,+ nonce: string,+ body: Uint8Array,+): Promise<string> {+ return ['codync-sig-v1', method.toUpperCase(), authority.toLowerCase(), pathAndQuery, String(ts), nonce, b64url(await sha256(body))].join('\n')+}++/**+ * Checks the header's signature and time window. Replay of `(kid, nonce)` is the caller's job.+ * `authority` is this relay's `publicAuthority`.+ */+export async function verifyCodyncSig(+ header: string | undefined,+ method: string,+ authority: string,+ pathAndQuery: string,+ body: Uint8Array,+ now: number,+): Promise<SignedRequest | null> {+ if (!header) return null+ const fields = new Map<string, string>()+ for (const part of header.split(',')) {+ const i = part.indexOf('=')+ if (i <= 0) return null+ fields.set(part.slice(0, i).trim(), part.slice(i + 1).trim())+ }+ const kid = fields.get('kid')+ const pub = fromB64url(kid, 32)+ const sig = fromB64url(fields.get('sig'), 64)+ const nonce = fields.get('nonce') ?? ''+ const tsText = fields.get('ts') ?? ''+ if (fields.get('v') !== '1' || !pub || !sig || !kid || !fromB64url(nonce, 16) || !/^\d{1,16}$/.test(tsText)) return null+ const ts = Number(tsText)+ if (Math.abs(now - ts) > SIG_WINDOW_MS) return null+ const canonical = await sigCanonical(method, authority, pathAndQuery, ts, nonce, body)+ if (!(await verifyEd25519(pub, sig, utf8(canonical)))) return null+ return { kid, ts, nonce }+}diff --git a/private-relay/src/store.ts b/private-relay/src/store.tsnew file mode 100644index 00000000..a26f3b7f--- /dev/null+++ b/private-relay/src/store.ts@@ -0,0 +1,218 @@+/** SQLite for computers, ACL, signature nonces and the offline mailbox. Sockets stay in memory. */++import { chmodSync, mkdirSync } from 'node:fs'+import { DatabaseSync, type StatementSync } from 'node:sqlite'+import { NONCE_TTL_MS } from './sig.ts'++export interface ComputerRow {+ id: string+ signPub: string+ status: string+}++export interface MailboxRow {+ seq: number+ dk: string+ nonce: string+ blob: Uint8Array+ exp: number+ state: string+}++export class RelayStore {+ readonly db: DatabaseSync+ /** Run on every signed request, so prepared once. */+ private readonly hot: { computer: StatementSync; dropNonces: StatementSync; addNonce: StatementSync }++ constructor(file: string) {+ const dir = file.slice(0, file.lastIndexOf('/')) || '.'+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ try {+ chmodSync(dir, 0o700)+ } catch {+ // Windows has no Unix mode bits.+ }+ this.db = new DatabaseSync(file)+ this.db.exec(`+ PRAGMA journal_mode = WAL;+ PRAGMA busy_timeout = 5000;+ CREATE TABLE IF NOT EXISTS computers(+ id TEXT PRIMARY KEY,+ sign_pub TEXT NOT NULL,+ box_pub TEXT NOT NULL,+ name TEXT NOT NULL,+ platform TEXT NOT NULL,+ device TEXT,+ version TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'active',+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE IF NOT EXISTS acl(+ computer_id TEXT PRIMARY KEY,+ ver INTEGER NOT NULL,+ body TEXT NOT NULL+ );+ CREATE TABLE IF NOT EXISTS nonces(+ kid TEXT NOT NULL,+ nonce TEXT NOT NULL,+ exp INTEGER NOT NULL,+ PRIMARY KEY(kid, nonce)+ );+ CREATE INDEX IF NOT EXISTS nonces_exp ON nonces(exp);+ CREATE TABLE IF NOT EXISTS mailbox(+ seq INTEGER PRIMARY KEY AUTOINCREMENT,+ computer_id TEXT NOT NULL,+ dk TEXT NOT NULL,+ nonce TEXT NOT NULL,+ blob BLOB NOT NULL,+ size INTEGER NOT NULL,+ exp INTEGER NOT NULL,+ state TEXT NOT NULL,+ UNIQUE(computer_id, dk, nonce)+ );+ `)+ // A crash leaves the in-flight row marked delivering, and the new process has no host to ack it.+ this.db.exec("UPDATE mailbox SET state = 'queued' WHERE state = 'delivering'")+ this.hot = {+ computer: this.db.prepare('SELECT id, sign_pub, status FROM computers WHERE id = ?'),+ dropNonces: this.db.prepare('DELETE FROM nonces WHERE exp <= ?'),+ addNonce: this.db.prepare('INSERT OR IGNORE INTO nonces(kid, nonce, exp) VALUES (?, ?, ?)'),+ }+ try {+ chmodSync(file, 0o600)+ } catch {+ // Windows has no Unix mode bits. The directory is still the operator's.+ }+ }++ close(): void {+ this.db.close()+ }++ computer(id: string): ComputerRow | null {+ const row = this.hot.computer.get(id) as+ | { id: string; sign_pub: string; status: string }+ | undefined+ return row ? { id: row.id, signPub: row.sign_pub, status: row.status } : null+ }++ countComputers(): number {+ const row = this.db.prepare('SELECT COUNT(*) AS n FROM computers').get() as { n: number }+ return row.n+ }++ /** Insert or refresh a computer. The id is derived from `signPub`, so the key does not change. */+ register(row: {+ id: string+ signPub: string+ boxPub: string+ name: string+ platform: string+ device: string | null+ version: string+ now: number+ }): void {+ this.db+ .prepare(+ `INSERT INTO computers(id, sign_pub, box_pub, name, platform, device, version, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)+ ON CONFLICT(id) DO UPDATE SET name = excluded.name, device = excluded.device, version = excluded.version,+ box_pub = excluded.box_pub, updated_at = excluded.updated_at`,+ )+ .run(row.id, row.signPub, row.boxPub, row.name, row.platform, row.device, row.version, row.now, row.now)+ }++ /** `false` when this nonce was already seen and is still inside its 10-minute window. */+ rememberNonce(kid: string, nonce: string, now: number): boolean {+ this.hot.dropNonces.run(now)+ return this.hot.addNonce.run(kid, nonce, now + NONCE_TTL_MS).changes === 1+ }++ acl(computerId: string): { ver: number; body: string } | null {+ const row = this.db.prepare('SELECT ver, body FROM acl WHERE computer_id = ?').get(computerId) as+ | { ver: number; body: string }+ | undefined+ return row ?? null+ }++ saveAcl(computerId: string, ver: number, body: string): void {+ this.db.prepare('INSERT INTO acl(computer_id, ver, body) VALUES (?, ?, ?) ON CONFLICT(computer_id) DO UPDATE SET ver = excluded.ver, body = excluded.body').run(computerId, ver, body)+ }++ mailboxByNonce(computerId: string, dk: string, nonce: string): { state: string } | null {+ const row = this.db.prepare('SELECT state FROM mailbox WHERE computer_id = ? AND dk = ? AND nonce = ?').get(computerId, dk, nonce) as+ | { state: string }+ | undefined+ return row ?? null+ }++ mailboxCounts(computerId: string, dk: string): { mine: number; all: number; bytes: number } {+ const mine = this.db.prepare('SELECT COUNT(*) AS n FROM mailbox WHERE computer_id = ? AND dk = ?').get(computerId, dk) as { n: number }+ const all = this.db.prepare('SELECT COUNT(*) AS n, COALESCE(SUM(size), 0) AS b FROM mailbox WHERE computer_id = ?').get(computerId) as { n: number; b: number }+ return { mine: mine.n, all: all.n, bytes: all.b }+ }++ insertMailbox(computerId: string, dk: string, nonce: string, blob: Uint8Array, exp: number): void {+ this.db+ .prepare("INSERT INTO mailbox(computer_id, dk, nonce, blob, size, exp, state) VALUES (?, ?, ?, ?, ?, ?, 'queued')")+ .run(computerId, dk, nonce, Buffer.from(blob), blob.length, exp)+ }++ cancelQueued(computerId: string, dk: string, nonce: string): boolean {+ const result = this.db+ .prepare("DELETE FROM mailbox WHERE computer_id = ? AND dk = ? AND nonce = ? AND state = 'queued'")+ .run(computerId, dk, nonce)+ return result.changes === 1+ }++ listMailbox(computerId: string, dk: string): { nonce: string; exp: number; state: string }[] {+ return this.db+ .prepare('SELECT nonce, exp, state FROM mailbox WHERE computer_id = ? AND dk = ? ORDER BY seq')+ .all(computerId, dk) as { nonce: string; exp: number; state: string }[]+ }++ delivering(computerId: string): boolean {+ const row = this.db.prepare("SELECT 1 AS n FROM mailbox WHERE computer_id = ? AND state = 'delivering'").get(computerId) as { n: number } | undefined+ return row != null+ }++ nextQueued(computerId: string, now: number): MailboxRow | null {+ const row = this.db+ .prepare(+ `SELECT seq, dk, nonce, blob, exp, state FROM mailbox+ WHERE computer_id = ? AND state = 'queued' AND exp > ? ORDER BY seq LIMIT 1`,+ )+ .get(computerId, now) as { seq: number; dk: string; nonce: string; blob: Uint8Array; exp: number; state: string } | undefined+ return row ?? null+ }++ markDelivering(seq: number): void {+ this.db.prepare("UPDATE mailbox SET state = 'delivering' WHERE seq = ?").run(seq)+ }++ /** Removes the item the host is acknowledging, if it is the one in flight. */+ takeDelivering(computerId: string, seq: number): { dk: string; nonce: string } | null {+ const row = this.db+ .prepare("DELETE FROM mailbox WHERE seq = ? AND computer_id = ? AND state = 'delivering' RETURNING dk, nonce")+ .get(seq, computerId) as { dk: string; nonce: string } | undefined+ return row ?? null+ }++ requeueDelivering(computerId: string): void {+ this.db.prepare("UPDATE mailbox SET state = 'queued' WHERE computer_id = ? AND state = 'delivering'").run(computerId)+ }++ /** Removes this computer's expired items and says whose they were. */+ takeExpired(computerId: string, now: number): { dk: string; nonce: string }[] {+ return this.db.prepare('DELETE FROM mailbox WHERE computer_id = ? AND exp <= ? RETURNING dk, nonce').all(computerId, now) as {+ dk: string+ nonce: string+ }[]+ }++ /** Expired mail for every computer, whether or not a room is still open. */+ deleteExpiredAnywhere(now: number): void {+ this.db.prepare('DELETE FROM mailbox WHERE exp <= ?').run(now)+ }+}diff --git a/private-relay/test/hardening.test.ts b/private-relay/test/hardening.test.tsnew file mode 100644index 00000000..04e6e747--- /dev/null+++ b/private-relay/test/hardening.test.ts@@ -0,0 +1,234 @@+import assert from 'node:assert/strict'+import { join } from 'node:path'+import { DatabaseSync } from 'node:sqlite'+import { PassThrough } from 'node:stream'+import test from 'node:test'+import type { WebSocket } from 'ws'+import { b64url } from '../src/codec.ts'+import type { RelayServer } from '../src/http.ts'+import { PING } from '../src/room.ts'+import {+ TOKEN,+ authorityOf,+ deviceSocket,+ hostSocket,+ nextClose,+ nextMessage,+ openSocket,+ refusedWith,+ register,+ registerAs,+ relay,+ signedAcl,+ vectors,+} from './harness.ts'+import { freshKey, sigHeader } from './sign.ts'++function nonceRows(dir: string): number {+ const db = new DatabaseSync(join(dir, 'relay.sqlite'))+ try {+ return (db.prepare('SELECT COUNT(*) AS n FROM nonces').get() as { n: number }).n+ } finally {+ db.close()+ }+}++test('a connection reset during the signature check closes only that socket', async () => {+ const { server } = await relay()+ try {+ const socket = new PassThrough()+ const req = {+ url: '/v1/relay/host?v=1',+ method: 'GET',+ headers: { host: authorityOf(server.url), 'codync-sig': 'v=1,kid=a,ts=1,nonce=b,sig=c' },+ }+ // The upgrade is now awaiting the signature check; a reset there used to throw out of the event loop.+ server.server.emit('upgrade', req, socket, Buffer.alloc(0))+ assert.doesNotThrow(() => socket.emit('error', Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' })))+ assert.equal((await fetch(`${server.url}/health`)).status, 200)+ } finally {+ await server.close()+ }+})++test('an unknown key is refused without storing its nonces, and an allowed request cannot be replayed', async () => {+ const { server, dir } = await relay()+ try {+ const outsider = freshKey()+ const authority = authorityOf(server.url)+ for (let i = 0; i < 3; i++) {+ const state = '/v1/host/state'+ const header = await sigHeader(outsider.seed, outsider.pub, 'GET', authority, state, new Uint8Array())+ assert.equal((await fetch(`${server.url}${state}`, { headers: { 'Codync-Sig': header } })).status, 404)+ assert.equal((await registerAs(server, outsider.seed, outsider.pub)).status, 403)+ const host = '/v1/relay/host?v=1'+ const hostHeader = await sigHeader(outsider.seed, outsider.pub, 'GET', authority, host, new Uint8Array())+ await assert.rejects(openSocket(`${server.url.replace('http', 'ws')}${host}`, hostHeader), refusedWith(404))+ }+ assert.equal(nonceRows(dir), 0)++ await register(server)+ const state = '/v1/host/state'+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'GET', authority, state, new Uint8Array())+ assert.equal((await fetch(`${server.url}${state}`, { headers: { 'Codync-Sig': header } })).status, 200)+ assert.equal((await fetch(`${server.url}${state}`, { headers: { 'Codync-Sig': header } })).status, 401)+ } finally {+ await server.close()+ }+})++/** A registered computer whose host published an ACL with the fixture device and `offers`, then went ready. */+async function readyHost(server: RelayServer, offers: { id: string; exp: number }[] = []): Promise<WebSocket> {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], offers))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ host.send(JSON.stringify({ t: 'ready' }))+ return host+}++test('a device outside the ACL is refused, and so is every device before the first ACL', async () => {+ const { server } = await relay()+ try {+ await register(server)+ await assert.rejects(deviceSocket(server), refusedWith(404))+ const host = await hostSocket(server)+ host.send(signedAcl(1, [], []))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ await assert.rejects(deviceSocket(server), refusedWith(403))+ host.close()+ } finally {+ await server.close()+ }+})++test('a new ACL closes a removed device and a pairing whose offer is gone', async () => {+ const { server } = await relay()+ try {+ const host = await readyHost(server, [{ id: vectors.pairing.offerId, exp: Date.now() + 60_000 }])+ const device = await deviceSocket(server)+ const pairing = await deviceSocket(server, vectors.pairing.offerId)+ const revoked = nextClose(device)+ const expired = nextClose(pairing)+ host.send(signedAcl(2, [], []))+ assert.equal(await revoked, 4003)+ assert.equal(await expired, 4410)+ host.close()+ } finally {+ await server.close()+ }+})++test('pairing sockets are capped, short-lived, limited in messages and kept off the mailbox', async () => {+ let now = Date.now()+ const { server } = await relay({ now: () => now })+ try {+ const host = await readyHost(server, [{ id: vectors.pairing.offerId, exp: now + 60_000 }])+ const first = await deviceSocket(server, vectors.pairing.offerId)+ const second = await deviceSocket(server, vectors.pairing.offerId)+ await assert.rejects(deviceSocket(server, vectors.pairing.offerId), refusedWith(429))+ await nextMessage(first)+ first.send(JSON.stringify({ t: 'mbox.list' }))+ assert.deepEqual(JSON.parse(await nextMessage(first)), { t: 'mbox.err', nonce: null, code: 'pairing' })+ const chatty = nextClose(first)+ for (let i = 0; i < 16; i++) first.send(PING)+ assert.equal(await chatty, 4008)+ const timedOut = nextClose(second)+ now += 60_000+ server.rooms.sweep()+ assert.equal(await timedOut, 4410)+ host.close()+ } finally {+ await server.close()+ }+})++test('a device sending more than 200 messages in 10 seconds is closed', async () => {+ const { server } = await relay()+ try {+ const host = await readyHost(server)+ const device = await deviceSocket(server)+ const closed = nextClose(device)+ for (let i = 0; i < 201; i++) device.send(PING)+ assert.equal(await closed, 4008)+ host.close()+ } finally {+ await server.close()+ }+})++test('a replayed WebSocket upgrade is refused', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const path = '/v1/relay/host?v=1'+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ const url = `${server.url.replace('http', 'ws')}${path}`+ const host = await openSocket(url, header)+ await assert.rejects(openSocket(url, header), refusedWith(401))+ host.close()+ } finally {+ await server.close()+ }+})++test('an ACL for another computer is refused, even with this host signature', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [], [], 'A'.repeat(22)))+ assert.deepEqual(JSON.parse(await nextMessage(host)), { t: 'error', code: 'badAcl', ver: 0 })+ host.close()+ } finally {+ await server.close()+ }+})++test('the mailbox refuses an oversized blob and a device past its count', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], []))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ const device = await deviceSocket(server)+ await nextMessage(device)+ const put = async (nonce: string, d = vectors.mailbox.blob) => {+ device.send(JSON.stringify({ t: 'mbox.put', nonce, d }))+ return JSON.parse(await nextMessage(device)) as { state?: string; code?: string }+ }+ assert.equal((await put('big', b64url(new Uint8Array(64 * 1024 + 1)))).code, 'tooLarge')+ for (let i = 0; i < 50; i++) assert.equal((await put(`n${i}`)).state, 'queued')+ assert.equal((await put('one-more')).code, 'full')+ host.close()+ device.close()+ } finally {+ await server.close()+ }+})++test('a signature made for another relay address does not verify here', async () => {+ const { server } = await relay({ publicUrl: 'https://Relay.Example.com:443' })+ try {+ const key = freshKey()+ assert.equal((await registerAs(server, key.seed, key.pub, TOKEN)).status, 401, 'signed for the address it was reached on')+ assert.equal((await registerAs(server, key.seed, key.pub, TOKEN, 'relay.example.com')).status, 200)+ } finally {+ await server.close()+ }+})++test('a connector sign-in returns to the app with its query', async () => {+ const { server } = await relay()+ try {+ for (const [path, scheme] of [['/v1/oauth/callback', 'codync'], ['/v1/oauth/callback/dev', 'codync-dev']]) {+ const res = await fetch(`${server.url}${path}?code=c&state=s`, { redirect: 'manual' })+ assert.equal(res.status, 302)+ assert.equal(res.headers.get('location'), `${scheme}://oauth?code=c&state=s`)+ assert.equal(res.headers.get('cache-control'), 'no-store')+ }+ } finally {+ await server.close()+ }+})diff --git a/private-relay/test/harness.ts b/private-relay/test/harness.tsnew file mode 100644index 00000000..d7e292aa--- /dev/null+++ b/private-relay/test/harness.ts@@ -0,0 +1,141 @@+/** Shared setup for the relay tests: a relay on a temp store, the fixture keys, and signed sockets. */++import assert from 'node:assert/strict'+import { mkdtempSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { WebSocket } from 'ws'+import { b64url } from '../src/codec.ts'+import { startRelay, type RelayServer } from '../src/http.ts'+import { RelayStore } from '../src/store.ts'+import { sigHeader, signBytes } from './sign.ts'++export const TOKEN = 'test-relay-token-1'++export const vectors = JSON.parse(readFileSync(new URL('../../docs/reference/fixtures/remote-relay-vectors.json', import.meta.url), 'utf8')) as {+ keys: { hostSignSeed: string; hostSignPub: string; hostBoxPub: string; deviceSignSeed: string; deviceSignPub: string; computerId: string }+ acl: { d: string; sig: string }+ mailbox: { blob: string; clientNonce: string }+ pairing: { offerId: string }+}++export async function relay(options: { now?: () => number; publicUrl?: string } = {}): Promise<{ server: RelayServer; dir: string }> {+ const dir = mkdtempSync(join(tmpdir(), 'codync-private-relay-'))+ const store = new RelayStore(join(dir, 'relay.sqlite'))+ const server = await startRelay({ store, port: 0, token: TOKEN, ...options })+ return { server, dir }+}++/** For `assert.rejects`: the upgrade was answered with this HTTP status. */+export const refusedWith = (status: number) => (error: { status?: number }) => error.status === status++export function authorityOf(url: string): string {+ return new URL(url).host+}++export async function register(server: RelayServer): Promise<void> {+ const body = JSON.stringify({+ boxKey: vectors.keys.hostBoxPub,+ name: 'Studio',+ platform: 'macos',+ device: 'macstudio',+ version: '2.24.0',+ })+ const bytes = new TextEncoder().encode(body)+ const path = '/v1/host/register'+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'POST', authorityOf(server.url), path, bytes)+ const res = await fetch(`${server.url}${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'Codync-Sig': header, 'Codync-Relay-Token': TOKEN },+ body,+ })+ assert.equal(res.status, 200)+ const json = (await res.json()) as { computerId: string; owned: boolean }+ assert.equal(json.computerId, vectors.keys.computerId)+ assert.equal(json.owned, false)+}++/** Messages that arrive before the test asks for them stay queued. */+export function openSocket(url: string, header: string): Promise<WebSocket> {+ const ws = new WebSocket(url, { headers: { 'Codync-Sig': header } })+ const queued: string[] = []+ const waiters: ((text: string) => void)[] = []+ ws.on('message', (data) => {+ const text = data.toString()+ const waiter = waiters.shift()+ if (waiter) waiter(text)+ else queued.push(text)+ })+ let socketError: Error | null = null+ ws.once('error', (error) => {+ socketError = error instanceof Error ? error : new Error(String(error))+ })+ ;(ws as WebSocket & { take(): Promise<string> }).take = () =>+ new Promise((resolve, reject) => {+ if (socketError) return reject(socketError)+ const text = queued.shift()+ if (text !== undefined) resolve(text)+ else waiters.push(resolve)+ })+ return new Promise((resolve, reject) => {+ let settled = false+ const fail = (error: unknown) => {+ if (settled) return+ settled = true+ reject(error)+ }+ ws.once('open', () => {+ if (settled) return+ settled = true+ resolve(ws)+ })+ ws.once('unexpected-response', (_req, res) => {+ const chunks: Buffer[] = []+ res.on('data', (c: Buffer) => chunks.push(c))+ res.on('end', () => fail(Object.assign(new Error(`HTTP ${res.statusCode} ${Buffer.concat(chunks).toString()}`), { status: res.statusCode, body: Buffer.concat(chunks).toString() })))+ })+ ws.once('error', fail)+ })+}++export function nextMessage(ws: WebSocket): Promise<string> {+ return (ws as WebSocket & { take(): Promise<string> }).take()+}++export function nextClose(ws: WebSocket): Promise<number> {+ return new Promise((resolve) => ws.once('close', (code) => resolve(code)))+}++export async function hostSocket(server: RelayServer): Promise<WebSocket> {+ const path = '/v1/relay/host?v=1'+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ return openSocket(`${server.url.replace('http', 'ws')}${path}`, header)+}++export async function deviceSocket(server: RelayServer, pair = ''): Promise<WebSocket> {+ const path = `/v1/relay/device/${vectors.keys.computerId}?v=1${pair ? `&pair=${pair}` : ''}`+ const header = await sigHeader(vectors.keys.deviceSignSeed, vectors.keys.deviceSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ return openSocket(`${server.url.replace('http', 'ws')}${path}`, header)+}++export function signedAcl(+ ver: number,+ devices: { dk: string; grant: null }[],+ offers: { id: string; exp: number }[],+ computerId = vectors.keys.computerId,+): string {+ const json = JSON.stringify({ v: 1, computerId, ver, devices, offers })+ const d = b64url(new TextEncoder().encode(json))+ const sig = signBytes(vectors.keys.hostSignSeed, new TextEncoder().encode(json))+ return JSON.stringify({ t: 'acl', d, sig })+}++export async function registerAs(server: RelayServer, seed: string, pub: string, token?: string, authority = authorityOf(server.url)): Promise<Response> {+ const body = JSON.stringify({ boxKey: vectors.keys.hostBoxPub, name: 'Other', platform: 'linux', version: '2.24.0' })+ const bytes = new TextEncoder().encode(body)+ const path = '/v1/host/register'+ const header = await sigHeader(seed, pub, 'POST', authority, path, bytes)+ const headers: Record<string, string> = { 'content-type': 'application/json', 'Codync-Sig': header }+ if (token !== undefined) headers['Codync-Relay-Token'] = token+ return fetch(`${server.url}${path}`, { method: 'POST', headers, body })+}diff --git a/private-relay/test/relay.test.ts b/private-relay/test/relay.test.tsnew file mode 100644index 00000000..7d718a67--- /dev/null+++ b/private-relay/test/relay.test.ts@@ -0,0 +1,391 @@+import assert from 'node:assert/strict'+import { copyFileSync, mkdtempSync } from 'node:fs'+import { request as httpRequest } from 'node:http'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import test from 'node:test'+import { b64url, fromB64url } from '../src/codec.ts'+import { startRelay } from '../src/http.ts'+import { PONG } from '../src/room.ts'+import { RelayStore } from '../src/store.ts'+import {+ TOKEN,+ vectors,+ relay,+ authorityOf,+ register,+ openSocket,+ nextMessage,+ nextClose,+ hostSocket,+ deviceSocket,+ signedAcl,+ registerAs,+} from './harness.ts'+import { freshKey, sigHeader } from './sign.ts'++test('register, an empty state pull, and the cloud routes this relay does not serve', async () => {+ const { server } = await relay()+ try {+ assert.equal((await fetch(`${server.url}/health`)).status, 200)+ await register(server)+ const path = '/v1/host/state'+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ const state = await fetch(`${server.url}${path}`, { headers: { 'Codync-Sig': header } })+ assert.deepEqual(await state.json(), { owner: null, grants: [], requests: [] })+ const old = '/v1/relay/host?v=2'+ const oldHeader = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'GET', authorityOf(server.url), old, new Uint8Array())+ await assert.rejects(openSocket(`${server.url.replace('http', 'ws')}${old}`, oldHeader), (error: { status?: number }) => error.status === 426)+ for (const route of ['/v1/host/screen-ice', '/v1/host/unclaim', '/v1/host/grants/g/revoke', `/v1/hooks/${vectors.keys.computerId}/h`]) {+ const res = await fetch(`${server.url}${route}`, { method: 'POST', body: '{}' })+ assert.equal(res.status, 404, route)+ assert.equal(((await res.json()) as { error: { code: string } }).error.code, 'notFound')+ }+ } finally {+ await server.close()+ }+})++test('a pair that is not 16 bytes is refused and creates no computer', async () => {+ const { server } = await relay()+ try {+ const path = `/v1/relay/device/${vectors.keys.computerId}?v=1&pair=abc`+ const header = await sigHeader(vectors.keys.deviceSignSeed, vectors.keys.deviceSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ await assert.rejects(openSocket(`${server.url.replace('http', 'ws')}${path}`, header), (error: { status?: number }) => error.status === 400)+ assert.equal(server.store.countComputers(), 0)+ } finally {+ await server.close()+ }+})++test('the host publishes an ACL, devices are capped, and pong bytes are exact', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ const acl = signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], [{ id: vectors.pairing.offerId, exp: Date.now() + 60_000 }])+ const ok = nextMessage(host)+ host.send(acl)+ assert.deepEqual(JSON.parse(await ok), { t: 'acl.ok', ver: 1 })++ const stale = nextMessage(host)+ host.send(acl)+ const staleMsg = JSON.parse(await stale) as { t: string; code: string; ver: number }+ assert.deepEqual(staleMsg, { t: 'error', code: 'staleVersion', ver: 1 })++ const bad = nextMessage(host)+ host.send(JSON.stringify({ t: 'acl', d: b64url(new TextEncoder().encode('{}')), sig: vectors.acl.sig }))+ const badMsg = JSON.parse(await bad) as { code: string; ver: number }+ assert.equal(badMsg.code, 'badAcl')+ assert.equal(badMsg.ver, 1)++ host.send(JSON.stringify({ t: 'ready' }))+ const device = await deviceSocket(server)+ const presence = JSON.parse(await nextMessage(device)) as { t: string; online: boolean }+ assert.equal(presence.t, 'presence')+ assert.equal(presence.online, true)+ const pong = nextMessage(device)+ device.send('{"t":"ping"}')+ assert.equal(await pong, PONG)+ const spaced = nextMessage(device)+ device.send('{"t":"ping","x":1}')+ assert.equal(await spaced, PONG)++ const sockets = [device]+ for (let i = 1; i < 16; i++) sockets.push(await deviceSocket(server))+ await assert.rejects(deviceSocket(server), (error: { status?: number }) => error.status === 429)+ for (const socket of sockets) socket.close()+ host.close()+ } finally {+ await server.close()+ }+})++test('mailbox put is idempotent, refused while the host is ready, and delivered one at a time', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], []))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ const device = await deviceSocket(server)+ await nextMessage(device)+ const blob = vectors.mailbox.blob+ assert.ok((fromB64url(blob)?.length ?? 0) >= 112)+ const put = (nonce: string) => JSON.stringify({ t: 'mbox.put', nonce, d: blob })+ device.send(put(vectors.mailbox.clientNonce))+ assert.deepEqual(JSON.parse(await nextMessage(device)), { t: 'mbox.ok', nonce: vectors.mailbox.clientNonce, state: 'queued' })+ device.send(put(vectors.mailbox.clientNonce))+ assert.deepEqual(JSON.parse(await nextMessage(device)), { t: 'mbox.ok', nonce: vectors.mailbox.clientNonce, state: 'queued' })+ device.send(JSON.stringify({ t: 'mbox.put', nonce: 'short', d: b64url(new Uint8Array(16)) }))+ assert.equal(JSON.parse(await nextMessage(device)).code, 'invalid')+ device.send(JSON.stringify({ t: 'mbox.list' }))+ const listed = JSON.parse(await nextMessage(device)) as { items: { nonce: string }[] }+ assert.equal(listed.items.length, 1)++ const second = 'second-nonce'+ device.send(put(second))+ assert.equal(JSON.parse(await nextMessage(device)).state, 'queued')+ host.send(JSON.stringify({ t: 'ready' }))+ const open = JSON.parse(await nextMessage(host)) as { t: string }+ const firstItem = JSON.parse(await nextMessage(host)) as { t: string; seq: number; nonce: string }+ assert.equal(open.t, 'open')+ assert.equal(firstItem.t, 'mbox.item')+ assert.equal((JSON.parse(await nextMessage(device)) as { online: boolean }).online, true)+ device.send(put('while-online'))+ assert.equal(JSON.parse(await nextMessage(device)).code, 'hostOnline')+ host.send(JSON.stringify({ t: 'mbox.ack', seq: firstItem.seq, ok: true }))+ assert.equal(JSON.parse(await nextMessage(device)).t, 'mbox.delivered')+ const next = JSON.parse(await nextMessage(host)) as { t: string; nonce: string; seq: number }+ assert.equal(next.t, 'mbox.item')+ assert.equal(next.nonce, second)+ host.send(JSON.stringify({ t: 'mbox.ack', seq: next.seq, ok: false, code: 'nope' }))+ const failed = JSON.parse(await nextMessage(device)) as { t: string; code: string }+ assert.equal(failed.t, 'mbox.failed')+ assert.equal(failed.code, 'invalid')+ device.send(JSON.stringify({ t: 'mbox.cancel', nonce: 'missing' }))+ assert.equal(JSON.parse(await nextMessage(device)).t, 'mbox.gone')+ host.close()+ device.close()+ } finally {+ await server.close()+ }+})++test('a null message closes only the socket that sent it', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], []))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ const device = await deviceSocket(server)+ await nextMessage(device)+ const other = await deviceSocket(server)+ await nextMessage(other)++ const closed = nextClose(device)+ device.send('null')+ assert.equal(await closed, 4002)++ host.send('null')+ host.send('true')+ host.send('[]')+ const hostPong = nextMessage(host)+ host.send('{"t":"ping","n":1}')+ assert.equal(await hostPong, PONG)+ const devicePong = nextMessage(other)+ other.send('{"t":"ping","n":1}')+ assert.equal(await devicePong, PONG)+ assert.equal((await fetch(`${server.url}/health`)).status, 200)+ host.close()+ other.close()+ } finally {+ await server.close()+ }+})++test('a body over the limit is refused before it is trusted', async () => {+ const { server } = await relay()+ try {+ const over = Buffer.alloc(64 * 1024 + 1, 0x61)+ const declared = await fetch(`${server.url}/v1/host/register`, { method: 'POST', body: over })+ assert.equal(declared.status, 400)+ // The size refusal itself, not a later field check.+ assert.deepEqual(await declared.json(), { error: { code: 'badRequest', message: 'Body too large' } })+ const chunked = await new Promise<{ status: number; body: string }>((resolve, reject) => {+ const url = new URL(`${server.url}/v1/host/register`)+ const req = httpRequest(+ { hostname: url.hostname, port: url.port, path: url.pathname, method: 'POST', headers: { 'content-type': 'application/json' } },+ (res) => {+ let body = ''+ res.on('data', (chunk: Buffer) => (body += chunk.toString()))+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body }))+ },+ )+ req.on('error', reject)+ req.write(over)+ req.end()+ })+ assert.equal(chunked.status, 400)+ assert.match(chunked.body, /Body too large/)+ } finally {+ await server.close()+ }+})++test('a restart between delivery and acknowledgment sends the item again', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'codync-private-relay-'))+ const file = join(dir, 'relay.sqlite')+ const store = new RelayStore(file)+ const server = await startRelay({ store, port: 0, token: TOKEN })+ const nonce = vectors.mailbox.clientNonce+ try {+ await register(server)+ const host = await hostSocket(server)+ host.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], []))+ assert.equal(JSON.parse(await nextMessage(host)).t, 'acl.ok')+ const device = await deviceSocket(server)+ await nextMessage(device)+ device.send(JSON.stringify({ t: 'mbox.put', nonce, d: vectors.mailbox.blob }))+ assert.equal(JSON.parse(await nextMessage(device)).state, 'queued')+ host.send(JSON.stringify({ t: 'ready' }))+ assert.equal((JSON.parse(await nextMessage(host)) as { t: string }).t, 'open')+ const item = JSON.parse(await nextMessage(host)) as { t: string; nonce: string }+ assert.equal(item.t, 'mbox.item')+ assert.equal(item.nonce, nonce)+ assert.equal(store.mailboxByNonce(vectors.keys.computerId, vectors.keys.deviceSignPub, nonce)?.state, 'delivering')+ store.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')+ copyFileSync(file, join(dir, 'crash.sqlite'))+ host.close()+ device.close()+ } finally {+ await server.close()+ }++ const recovered = new RelayStore(join(dir, 'crash.sqlite'))+ const again = await startRelay({ store: recovered, port: 0, token: TOKEN })+ try {+ assert.equal(recovered.mailboxByNonce(vectors.keys.computerId, vectors.keys.deviceSignPub, nonce)?.state, 'queued')+ const host = await hostSocket(again)+ host.send(JSON.stringify({ t: 'ready' }))+ const item = JSON.parse(await nextMessage(host)) as { t: string; nonce: string }+ assert.equal(item.t, 'mbox.item')+ assert.equal(item.nonce, nonce)+ host.close()+ } finally {+ await again.close()+ }+})++test('a second host replaces the first, and an expired offer is forbidden', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const first = await hostSocket(server)+ const replaced = nextClose(first)+ const second = await hostSocket(server)+ assert.equal(await replaced, 4009)+ assert.equal(server.rooms.retained(), 1)+ second.send(signedAcl(1, [{ dk: vectors.keys.deviceSignPub, grant: null }], []))+ assert.equal(JSON.parse(await nextMessage(second)).t, 'acl.ok')+ second.send(JSON.stringify({ t: 'ready' }))+ const device = await deviceSocket(server)+ assert.equal(JSON.parse(await nextMessage(device)).online, true)+ assert.equal((JSON.parse(await nextMessage(second)) as { t: string }).t, 'open')+ device.close()+ assert.equal((JSON.parse(await nextMessage(second)) as { t: string }).t, 'close')+ second.send(signedAcl(2, [], [{ id: vectors.pairing.offerId, exp: Date.now() - 1000 }]))+ assert.equal(JSON.parse(await nextMessage(second)).t, 'acl.ok')+ const path = `/v1/relay/device/${vectors.keys.computerId}?v=1&pair=${vectors.pairing.offerId}`+ const header = await sigHeader(vectors.keys.deviceSignSeed, vectors.keys.deviceSignPub, 'GET', authorityOf(server.url), path, new Uint8Array())+ await assert.rejects(openSocket(`${server.url.replace('http', 'ws')}${path}`, header), (error: { status?: number }) => error.status === 403)+ second.close()+ } finally {+ await server.close()+ }+})++test('a new computer needs the registration token, and a known one can refresh without it', async () => {+ const { server } = await relay()+ try {+ const outsider = freshKey()+ const refused = await registerAs(server, outsider.seed, outsider.pub)+ assert.equal(refused.status, 403)+ assert.equal(server.store.countComputers(), 0)+ const wrong = await registerAs(server, outsider.seed, outsider.pub, 'not-the-token')+ assert.equal(wrong.status, 403)+ assert.equal(server.store.countComputers(), 0)++ await register(server)+ const path = '/v1/host/register'+ const body = JSON.stringify({ boxKey: vectors.keys.hostBoxPub, name: 'Studio', platform: 'macos', version: '2.24.0' })+ const bytes = new TextEncoder().encode(body)+ const header = await sigHeader(vectors.keys.hostSignSeed, vectors.keys.hostSignPub, 'POST', authorityOf(server.url), path, bytes)+ const refresh = await fetch(`${server.url}${path}`, { method: 'POST', headers: { 'content-type': 'application/json', 'Codync-Sig': header }, body })+ assert.equal(refresh.status, 200)+ assert.equal(server.store.countComputers(), 1)+ } finally {+ await server.close()+ }+})++test('new enrollments stop at the cap and at the per-minute limit', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'codync-private-relay-'))+ const store = new RelayStore(join(dir, 'relay.sqlite'))+ const server = await startRelay({ store, port: 0, token: TOKEN, maxComputers: 1, newRegisterLimit: 2 })+ try {+ await register(server)+ const extra = freshKey()+ const full = await registerAs(server, extra.seed, extra.pub, TOKEN)+ assert.equal(full.status, 403)+ assert.equal(server.store.countComputers(), 1)++ const limited = await startRelay({ store: new RelayStore(join(dir, 'limit.sqlite')), port: 0, token: TOKEN, newRegisterLimit: 1 })+ try {+ const first = freshKey()+ const second = freshKey()+ assert.equal((await registerAs(limited, first.seed, first.pub, 'nope')).status, 403)+ const enrolled = await registerAs(limited, second.seed, second.pub, TOKEN)+ assert.equal(enrolled.status, 200)+ assert.equal(limited.store.countComputers(), 1)++ const blocked = await startRelay({+ store: new RelayStore(join(dir, 'reject.sqlite')),+ port: 0,+ token: TOKEN,+ rejectedRegisterLimit: 1,+ })+ try {+ const wrong = freshKey()+ const right = freshKey()+ const again = freshKey()+ assert.equal((await registerAs(blocked, wrong.seed, wrong.pub, 'nope')).status, 403)+ assert.equal((await registerAs(blocked, again.seed, again.pub, 'nope')).status, 429)+ assert.equal((await registerAs(blocked, right.seed, right.pub, TOKEN)).status, 200)+ } finally {+ await blocked.close()+ }+ } finally {+ await limited.close()+ }+ } finally {+ await server.close()+ }+})++test('a host that disconnects does not leave its room behind', async () => {+ const { server } = await relay()+ try {+ await register(server)+ const host = await hostSocket(server)+ assert.equal(server.rooms.retained(), 1)+ const closed = nextClose(host)+ host.close()+ await closed+ for (let i = 0; i < 20 && server.rooms.retained() !== 0; i++) {+ await new Promise((resolve) => setTimeout(resolve, 10))+ }+ assert.equal(server.rooms.retained(), 0)+ } finally {+ await server.close()+ }+})++test('expired mailbox rows are deleted when no room is open', async () => {+ let now = 1_000_000+ const dir = mkdtempSync(join(tmpdir(), 'codync-private-relay-'))+ const store = new RelayStore(join(dir, 'relay.sqlite'))+ const server = await startRelay({ store, port: 0, token: TOKEN, now: () => now })+ try {+ store.insertMailbox(vectors.keys.computerId, vectors.keys.deviceSignPub, 'gone', new Uint8Array(128), now + 1_000)+ store.insertMailbox(vectors.keys.computerId, vectors.keys.deviceSignPub, 'kept', new Uint8Array(128), now + 10_000)+ assert.equal(server.rooms.retained(), 0)+ now += 1_000+ server.rooms.sweep()+ assert.equal(store.mailboxByNonce(vectors.keys.computerId, vectors.keys.deviceSignPub, 'gone'), null)+ assert.equal(store.mailboxByNonce(vectors.keys.computerId, vectors.keys.deviceSignPub, 'kept')?.state, 'queued')+ } finally {+ await server.close()+ }+})diff --git a/private-relay/test/sign.ts b/private-relay/test/sign.tsnew file mode 100644index 00000000..923a5fd5--- /dev/null+++ b/private-relay/test/sign.ts@@ -0,0 +1,41 @@+/** Ed25519 request signing for tests. Node has no seed import, so the PKCS#8 prefix wraps the 32-byte seed. */++import { createPrivateKey, createPublicKey, sign, type KeyObject } from 'node:crypto'+import { b64url, fromB64url, sha256 } from '../src/codec.ts'+import { sigCanonical } from '../src/sig.ts'++const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex')++function privateKeyFromSeed(seed: Uint8Array): KeyObject {+ return createPrivateKey({ key: Buffer.concat([PKCS8_PREFIX, Buffer.from(seed)]), format: 'der', type: 'pkcs8' })+}++export function signBytes(seedB64: string, message: Uint8Array): string {+ const seed = fromB64url(seedB64, 32)+ if (!seed) throw new Error('bad seed')+ return b64url(sign(null, message, privateKeyFromSeed(seed)))+}++/** A new Ed25519 key as base64url seed and public key. */+export function freshKey(): { seed: string; pub: string } {+ const seed = crypto.getRandomValues(new Uint8Array(32))+ const der = createPublicKey(privateKeyFromSeed(seed)).export({ format: 'der', type: 'spki' })+ return { seed: b64url(seed), pub: b64url(der.subarray(der.length - 32)) }+}++export async function sigHeader(+ seedB64: string,+ kid: string,+ method: string,+ authority: string,+ pathAndQuery: string,+ body: Uint8Array,+ ts = Date.now(),+): Promise<string> {+ const nonce = b64url(crypto.getRandomValues(new Uint8Array(16)))+ const canonical = await sigCanonical(method, authority, pathAndQuery, ts, nonce, body)+ const sig = signBytes(seedB64, new TextEncoder().encode(canonical))+ return `v=1,kid=${kid},ts=${ts},nonce=${nonce},sig=${sig}`+}++export const emptySha = async (): Promise<string> => b64url(await sha256(new Uint8Array()))diff --git a/private-relay/test/vectors.test.ts b/private-relay/test/vectors.test.tsnew file mode 100644index 00000000..aa0afce9--- /dev/null+++ b/private-relay/test/vectors.test.ts@@ -0,0 +1,56 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import { computerIdFor, fromB64url, verifyEd25519 } from '../src/codec.ts'+import { parseAcl } from '../src/acl.ts'+import { publicAuthority, verifyCodyncSig } from '../src/sig.ts'+import { RelayStore } from '../src/store.ts'+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++const vectors = JSON.parse(readFileSync(new URL('../../docs/reference/fixtures/remote-relay-vectors.json', import.meta.url), 'utf8')) as {+ keys: { hostSignPub: string; deviceSignPub: string; computerId: string }+ requestSig: { header: string; ts: number; authority: string }+ acl: { d: string; sig: string; json: string }+}++test('the vector computer id, request signature and ACL bytes verify', async () => {+ const pub = fromB64url(vectors.keys.hostSignPub, 32)!+ assert.equal(await computerIdFor(pub), vectors.keys.computerId)+ const header = vectors.requestSig.header.replace(/^Codync-Sig:\s*/, '')+ const signed = await verifyCodyncSig(+ header,+ 'GET',+ vectors.requestSig.authority,+ '/v1/relay/device/NHUPmL1Z_PyUbaRaqr6TOw?v=1',+ new Uint8Array(),+ vectors.requestSig.ts,+ )+ assert.equal(signed?.kid, vectors.keys.deviceSignPub)+ assert.equal(await verifyCodyncSig(header, 'GET', vectors.requestSig.authority, '/v1/relay/device/NHUPmL1Z_PyUbaRaqr6TOw?v=1', new Uint8Array(), vectors.requestSig.ts + 300_001), null)++ const dir = mkdtempSync(join(tmpdir(), 'codync-relay-nonce-'))+ const store = new RelayStore(join(dir, 'relay.sqlite'))+ assert.equal(store.rememberNonce(signed!.kid, signed!.nonce, vectors.requestSig.ts), true)+ assert.equal(store.rememberNonce(signed!.kid, signed!.nonce, vectors.requestSig.ts), false)+ store.close()++ const d = fromB64url(vectors.acl.d)!+ const sig = fromB64url(vectors.acl.sig, 64)!+ assert.equal(await verifyEd25519(pub, sig, d), true)+ const acl = parseAcl(d)+ assert.equal(acl?.computerId, vectors.keys.computerId)+ assert.equal(acl?.ver, 1)+ assert.equal(acl?.devices[0]?.dk, vectors.keys.deviceSignPub)+})++test('the signed authority keeps a real port and drops the defaults', () => {+ assert.equal(publicAuthority('https://Example.COM:8443'), 'example.com:8443')+ assert.equal(publicAuthority('https://relay.example.com:443/'), 'relay.example.com')+ assert.equal(publicAuthority('http://127.0.0.1:80'), '127.0.0.1')+ assert.equal(publicAuthority('http://127.0.0.1:443'), '127.0.0.1:443', 'only the scheme default drops')+ assert.equal(publicAuthority('https://relay.example.com:80'), 'relay.example.com:80')+ assert.equal(publicAuthority('http://[::1]:8788'), '[::1]:8788')+ assert.throws(() => publicAuthority('https://relay.example.com/path'))+})diff --git a/private-relay/tsconfig.json b/private-relay/tsconfig.jsonnew file mode 100644index 00000000..cc6dae05--- /dev/null+++ b/private-relay/tsconfig.json@@ -0,0 +1,16 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "nodenext",+ "moduleResolution": "nodenext",+ "lib": ["ES2022"],+ "types": ["node"],+ "strict": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "noUncheckedIndexedAccess": true,+ "skipLibCheck": true+ },+ "include": ["src", "test"]+}diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsxindex 8de27430..6e1e070d 100644--- a/web/app/privacy/page.tsx+++ b/web/app/privacy/page.tsx@@ -18,7 +18,7 @@ export default function Privacy() {<Section title="What stays on your devices"><ul className="list-disc pl-5 space-y-2"><li><strong>Bots and conversations</strong> are stored by the Codync host on your computer (in <code>~/.codync</code>). Your phone keeps a cache so the app opens instantly.</li>- <li><strong>Your phone talks to your computer</strong> directly over your local network or Tailscale, or, away from home, through our relay, which only forwards end-to-end encrypted data it can't read. A message you send while your computer is offline waits in the relay, still encrypted for your computer, for up to 24 hours, and is deleted once delivered.</li>+ <li><strong>Your phone talks to your computer</strong> directly over your local network or Tailscale, or, away from home, through our relay, which only forwards end-to-end encrypted data it can't read. A message you send while your computer is offline waits in the relay, still encrypted for your computer, for up to 24 hours, and is deleted once delivered. If you point a computer at a relay you run yourself, its traffic goes through that relay instead of ours and we receive none of it; its notifications still go through our push relay.</li><li><strong>Agents run with your own logins</strong> (Claude Code, Codex, Cursor and others). Codync never sees or stores their credentials.</li><li><strong>Usage limits</strong> are read locally from the agents installed on your computer. Only percentages reach your phone.</li></ul>diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdxindex 92615103..908d14fd 100644--- a/web/content/docs/privacy.mdx+++ b/web/content/docs/privacy.mdx@@ -11,6 +11,8 @@ Codync keeps your work on your computer. The phone and desktop apps are windowsWhen your phone isn't on the same network as your computer, the connection goes through the Codync relay on Cloudflare. Everything inside it is end-to-end encrypted between your phone and your computer. See [Remote access](/docs/remote-access) for how that works and how to turn the relay off.+If you point a computer at [a relay you run yourself](/docs/remote-access#your-own-relay), that relay takes the Codync relay's place for it: whoever runs that server sees what's listed below, and Codync's relay sees none of it. It can't read the encrypted connection either. Sign-in, public routine webhooks and remote screen through the relay aren't available there, and push notifications still go through Codync's push service.+**The relay can't read** your messages, files, bot output, approvals, terminals or anything else you send through the encrypted connection.**The relay does see:**diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdxindex ab3cb2f8..c8cfdfa8 100644--- a/web/content/docs/remote-access.mdx+++ b/web/content/docs/remote-access.mdx@@ -1,4 +1,4 @@-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 the **Codync relay**, a service on Cloudflare that passes encrypted traffic between your phone and your computer when they can't see each other. 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. 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.@@ -12,6 +12,7 @@ Each time it connects, the phone first tries the computer's direct addresses. If| 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) |+| 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.@@ -63,6 +64,31 @@ With the relay off:- Devices approved through your account can't connect. Devices paired with a QR code still can.- Deliveries to public routine webhooks no longer reach the computer. Local ones keep working. The relay still accepts deliveries at the old public URLs and keeps them, readable, for up to 72 hours; they run if you turn the relay back on within that time. To stop them, remove the URL from the sender, or delete the routine or replace its key while the relay is on.+## Your own relay++You can run a relay yourself and point a computer at it, instead of the Codync relay on Cloudflare. Chat stays end-to-end encrypted either way. The relay still cannot read it. How to set one up on a server is in the [private relay README](https://github.com/leepokai/Codync/blob/main/private-relay/README.md).++On the computer, open **Settings → Computers**, turn on **Reach from anywhere**, and set **Relay address** to your relay, such as `https://relay.example.com`. A **Relay token** field then appears: paste the token the relay was started with. The field never shows the token again; it says it's saved, and typing a new one replaces it. On a computer without the desktop app:++```sh+codync-host cloud --url https://relay.example.com --token+```++`--token` asks for the token without showing it, so it stays out of your shell history. You can also pipe it in: `codync-host cloud --url https://relay.example.com --token < token.txt`.++The relay must be started with the same token (`CODYNC_PRIVATE_RELAY_TOKEN`). It accepts a new computer only when the token matches, and it keeps at most 32 computers. A computer it already knows can reconnect with its own key.++To use the Codync relay again, clear **Relay address**, or run `codync-host cloud --clear-url`. That forgets the saved address and the token. Changing the address to another relay forgets the token too, since a token belongs to one relay.++A private relay does not do everything the Codync relay does:++- Signing in, **Add to account** and the 6-digit access check are not available. Devices approved through your account stay on the computer but can't connect until it goes back to the Codync relay. Devices paired with a QR code aren't affected.+- Public routine webhooks are not delivered. A local webhook on the computer still works.+- Remote screen through the relay is not available. Screen over Wi-Fi or Tailscale still works.+- Notifications still go through Codync's push service.++The iPhone learns the address from the pairing code and the next connection. It has no address field of its own, and it never receives the token.+## Your own HTTPS reverse proxyIf you already run a web server with a domain and TLS certificate, you can give the phone its own direct address, such as `https://codync.example.com`.diff --git a/web/content/docs/routines.mdx b/web/content/docs/routines.mdxindex 8a08f181..600d48c6 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 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.- 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.