Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): end-to-end encrypted connections between your machines, an opt-in beta (CUA-1505) (#5094)

ddupontae2c117cd966
diff --git a/LICENSING.md b/LICENSING.md
index c274054477..96ea0cc4ae 100644
--- a/LICENSING.md
+++ b/LICENSING.md
@@ -100,6 +100,13 @@ targets and preferences). The SDK's `MediaSession` (open a stream, receive
its encoded frames and audio packets) and `@trycua/cua/spaces/pip` (a
picture-in-picture wrapper around a canvas you paint) stay MIT.
+The WireGuard®-based mesh node (`cua-mesh`: userspace tunnels, NAT
+traversal, the encrypted relay client, QUIC streams and the coordinator
+protocol) is MIT and depends only on MIT, Apache-2.0 and BSD code (the
+WireGuard protocol through Cloudflare's BSD-3-Clause `boringtun`). A hosted
+machine's side of it is part of cua-spacesd (FSL). No GPL or AGPL code is
+linked: not the WireGuard kernel module or `wireguard-tools`.
+
## Commercial use and trademarks
Offering Cua Spaces, or a product built on it, to others as a hosted or
diff --git a/apps/cua-spaces-desktop/src/mesh-channel.ts b/apps/cua-spaces-desktop/src/mesh-channel.ts
new file mode 100644
index 0000000000..43c3befce4
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/mesh-channel.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The update channel, recorded where the app's cua daemon and this
+// machine's host read it (`<cua home>/app-update-channel`, cua_mesh::policy):
+// the WireGuard-based mesh follows it once it is turned on for Beta. In this
+// release the mesh is off on every channel unless CUA_MESH asks for it, so
+// the file changes nothing yet.
+import { mkdirSync, renameSync, writeFileSync } from "node:fs";
+import * as path from "node:path";
+import { cuaHome } from "./model/daemon";
+
+/** cua_mesh::policy::CHANNEL_FILE. */
+export const CHANNEL_FILE = "app-update-channel";
+
+/** Writes `channel` to `<home>/app-update-channel` (atomically; a failure is only logged). */
+export function recordUpdateChannel(channel: "stable" | "beta", home: string = cuaHome()): void {
+ try {
+ mkdirSync(home, { recursive: true });
+ const file = path.join(home, CHANNEL_FILE);
+ const tmp = `${file}.tmp`;
+ writeFileSync(tmp, `${channel}\n`);
+ renameSync(tmp, file);
+ } catch (error) {
+ console.warn("[cua-spaces] could not record the update channel:", error);
+ }
+}
diff --git a/apps/cua-spaces-desktop/src/updater.ts b/apps/cua-spaces-desktop/src/updater.ts
index 362e1f8769..93fb01d04f 100644
--- a/apps/cua-spaces-desktop/src/updater.ts
+++ b/apps/cua-spaces-desktop/src/updater.ts
@@ -22,6 +22,7 @@ import { app, BrowserWindow, dialog } from "electron";
import { existsSync } from "node:fs";
import * as path from "node:path";
import { electronUpdater } from "./electron-updater";
+import { recordUpdateChannel } from "./mesh-channel";
import type { UpdaterDriving } from "./model/updates";
import { readSettings, writeSettings } from "./settings";
@@ -75,6 +76,8 @@ export class ElectronUpdater implements UpdaterDriving {
/** The updater for this build; null in a development run (no feed). */
static start(): ElectronUpdater | null {
+ // Where the cua daemon and this machine's host read it (mesh-channel.ts).
+ if (app.isPackaged) recordUpdateChannel(updateChannel());
if (!hasFeed()) return null;
const u = new ElectronUpdater();
u.schedule();
@@ -113,6 +116,7 @@ export class ElectronUpdater implements UpdaterDriving {
set channel(channel: UpdateChannel) {
if (readSettings().updateChannel === channel) return;
writeSettings({ updateChannel: channel });
+ recordUpdateChannel(channel);
this.loaded = null;
this.schedule();
}
diff --git a/apps/cua-spaces-desktop/test/mesh-channel.test.ts b/apps/cua-spaces-desktop/test/mesh-channel.test.ts
new file mode 100644
index 0000000000..97fced26f2
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/mesh-channel.test.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The update channel the app records for its daemon and this machine's host
+// (cua_mesh::policy reads `<cua home>/app-update-channel`).
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import * as path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+import { CHANNEL_FILE, recordUpdateChannel } from "../src/mesh-channel";
+
+const scratch = mkdtempSync(path.join(tmpdir(), "cua-mesh-channel-test-"));
+afterAll(() => rmSync(scratch, { recursive: true, force: true }));
+
+describe("recordUpdateChannel", () => {
+ it("writes the channel into the cua home, and follows a switch", () => {
+ const home = path.join(scratch, "home", ".cua");
+ recordUpdateChannel("beta", home);
+ expect(readFileSync(path.join(home, CHANNEL_FILE), "utf8")).toBe("beta\n");
+ recordUpdateChannel("stable", home);
+ expect(readFileSync(path.join(home, CHANNEL_FILE), "utf8")).toBe("stable\n");
+ });
+
+ it("never throws when the home cannot be written", () => {
+ expect(() => recordUpdateChannel("beta", "/dev/null/not-a-dir")).not.toThrow();
+ });
+});
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 4c49ecac5d..4f17a939fb 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -653,6 +653,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "brotli"
version = "8.0.4"
@@ -862,6 +887,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -874,6 +910,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -881,9 +930,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
]
[[package]]
@@ -908,6 +957,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -1474,13 +1524,13 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
"sha2 0.10.9",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
@@ -1513,6 +1563,36 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1575,6 +1655,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -1862,6 +1943,21 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -1871,7 +1967,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -2456,6 +2552,12 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -3474,6 +3576,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -3580,6 +3692,28 @@ version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -4199,6 +4333,18 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -4981,6 +5127,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -5313,7 +5470,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -8784,13 +8941,25 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index 6a28937652..25af504860 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -34,6 +34,7 @@ More of this crate: [client](/cua-sdk/reference/rust/cua-spaces-client), [agents
- `hotspot`: Hotspot: a Space borrows this machine's network.
- `id`: Space ids: the unified sandbox ref scheme (a Space is a ...
- `install_cache`: Pinned install archives, fetched once on this machine ...
+- `mesh`: Relay Spaces over the WireGuard®-based mesh ...
- `operator`: Presenting a Space to the human: picture-in-picture ...
- `presence`: Presence: who is looking at a Space and where their ...
- `presence::art`: The shared presence cursor art (ass ...
@@ -1648,6 +1649,8 @@ impl Spaces {
fn set_share_consent(&self, consent: Option<Arc<dyn ShareConsent>>);
fn has_share_consent(&self) -> bool;
fn set_relay(&self, relay: Option<RelayAccount>);
+ async fn explain_mesh_cut(&self, space: &str, e: Error) -> Error;
+ async fn mesh_status(&self) -> Vec<(String, Status)>;
async fn relay_machines(&self) -> Result<Vec<RelayMachine>>;
async fn find(&self, space: &str) -> Result<SpaceInfo>;
fn resolve(&self, space: &str) -> Result<SpaceId>;
@@ -2199,6 +2202,10 @@ pub async fn fetch(dir: &Path, a: &StagedArchive, progress: &mut dyn FnMut(u64,
/// Whether to stage through the host for a ...
pub fn wanted(url: &Url) -> bool
+// mod mesh
+/// The policy for this process now ...
+pub fn policy() -> MeshPolicy
+
// mod presence
/// The stable presence color of an agent ...
pub fn color_for(id: &str) -> &'static str
@@ -2465,4 +2472,4 @@ pub type DatagramChannel = (Arc<dyn CursorUplink>, Receiver<PresenceEvent>);
## Re-exports
-`cua_sandbox_core::byoc::CloudCheck`, `cua_sandbox_core::byoc::CloudConnected`, `cua_sandbox_core::byoc::CloudCredentials`, `cua_sandbox_core::byoc::CloudDisconnected`, `cua_sandbox_core::byoc::CloudKind`, `cua_sandbox_core::byoc::CloudProvider`, `cua_sandbox_core::byoc::CloudResource`, `cua_sandbox_core::byoc::CloudStatusReport`, `cua_sandbox_core::byoc::CloudSweepItem`, `cua_sandbox_core::byoc::CloudSweepReport`, `cua_sandbox_core::byoc::CloudTarget`, `cua_sandbox_core::byoc::CloudTestReport`, `cua_spaces_contract`, `spaces::CreatePhase`, `spaces::CreateProgress`, `cua_spacesd_client`, `cua_host::relay::AccountTokens`, `cua_host::ConnectedClient`, `cua_host::DEFAULT_RELAY_URL`, `cua_host::DeviceAuth`, `cua_host::Identity`, `cua_host::relay::NoAccount`, `cua_host::relay_url_from_env`, `cua_host::relay::StaticToken`.
+`cua_sandbox_core::byoc::CloudCheck`, `cua_sandbox_core::byoc::CloudConnected`, `cua_sandbox_core::byoc::CloudCredentials`, `cua_sandbox_core::byoc::CloudDisconnected`, `cua_sandbox_core::byoc::CloudKind`, `cua_sandbox_core::byoc::CloudProvider`, `cua_sandbox_core::byoc::CloudResource`, `cua_sandbox_core::byoc::CloudStatusReport`, `cua_sandbox_core::byoc::CloudSweepItem`, `cua_sandbox_core::byoc::CloudSweepReport`, `cua_sandbox_core::byoc::CloudTarget`, `cua_sandbox_core::byoc::CloudTestReport`, `cua_spaces_contract`, `spaces::CreatePhase`, `spaces::CreateProgress`, `cua_spacesd_client`, `cua_mesh::policy::Policy`, `cua_host::relay::AccountTokens`, `cua_host::ConnectedClient`, `cua_host::DEFAULT_RELAY_URL`, `cua_host::DeviceAuth`, `cua_host::Identity`, `cua_host::relay::NoAccount`, `cua_host::relay_url_from_env`, `cua_host::relay::StaticToken`.
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spacesd-client.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spacesd-client.mdx
index 96800cc356..e4cd7855de 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spacesd-client.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spacesd-client.mdx
@@ -96,6 +96,7 @@ pub struct ConnectOptions {
pub keepalive: Keepalive,
pub retry: RetryPolicy,
pub probe: bool,
+ pub headers: Vec<(String, String)>,
}
impl ConnectOptions {
fn new(endpoint: Endpoint) -> Self;
@@ -107,6 +108,7 @@ impl ConnectOptions {
fn retry(self, retry: RetryPolicy) -> Self;
fn keepalive(self, keepalive: Keepalive) -> Self;
fn probe_timeout(self, timeout: Duration) -> Self;
+ fn header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
fn probe(self, probe: bool) -> Self;
}
```
diff --git a/docs/content/docs/spaces/guides/mesh.mdx b/docs/content/docs/spaces/guides/mesh.mdx
new file mode 100644
index 0000000000..09163344c9
--- /dev/null
+++ b/docs/content/docs/spaces/guides/mesh.mdx
@@ -0,0 +1,103 @@
+---
+title: End-to-end encrypted connections (beta)
+description: 'An opt-in beta: your devices reach your machines over a WireGuard®-based mesh inside Cua, end to end encrypted, with the relay forwarding only ciphertext.'
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+<Callout type="info">
+ **Beta, off by default.** Nothing changes unless you turn the mesh on with
+ `CUA_MESH` (below). It is meant for the Beta channel of the Cua Spaces app
+ and will be on by default there in a later beta; stable releases keep the
+ relay's HTTPS path.
+</Callout>
+
+With the mesh on, a device that opens a Space on one of your machines
+(`relay:<machine>`) connects to it over a WireGuard®-based mesh that runs
+inside Cua itself, instead of through the relay's HTTPS path. The relay
+coordinates the mesh but never holds a session key: shell, files, input,
+screen and Keyvault deliveries cross it only as ciphertext.
+
+- **End to end.** Each device and machine makes its own key pair on first
+ use; the private half never leaves it. Traffic between two of them is
+ encrypted with WireGuard between those two keys.
+- **Direct when possible.** Two ends on the same network connect directly.
+ Otherwise packets go through the relay, still encrypted between the two
+ ends: the relay forwards them without being able to read or change them.
+- **Inside Cua only.** There is no network interface, no VPN profile, no
+ system extension and nothing that needs administrator rights. Mesh
+ addresses (`fd5c:a000::/32`) exist only inside Cua, so the mesh never
+ conflicts with Tailscale or another VPN you already run, and it carries
+ Spaces traffic only.
+
+## Turn it on
+
+Both ends opt in: the device you connect from and the machine you host.
+
+| `CUA_MESH` | Behavior |
+|---|---|
+| unset or `off` (default) | The relay's HTTPS path only, as before. |
+| `prefer` | The mesh when both ends and the relay support it; the relay's HTTPS path otherwise, with a log line saying why. |
+| `require` | The mesh or nothing: a relay that could read the session is never used. |
+
+- **On the device:** set `CUA_MESH` where `cua` runs (your shell, or the
+ environment of the cua daemon; restart the daemon with `cua daemon stop`
+ after changing it).
+- **On a hosted machine:** run `cua host setup` with `CUA_MESH=prefer` set.
+ The setting is kept for the host's service until you run setup again
+ without it.
+
+`cua spaces ls` lists the same machines either way. With `prefer`, a machine
+or relay that does not speak the mesh yet is used over HTTPS, so mixing
+updated and older machines works.
+
+## Who can connect
+
+The relay applies the rules you already manage:
+
+- A device enrolled for your account reaches the machines your account owns
+ and those shared with it, while their sharing is on.
+- The machine sees each device with the same identity as before (account,
+ verified email, owner, editor or viewer), and its own host policy still
+ decides what that caller may do.
+- Stopping sharing, removing someone from a share list, or revoking a device
+ takes it off the mesh within seconds and cuts its open connections. The
+ next call says why.
+
+## Your relay allowance
+
+A desktop view, terminal or agent session over the mesh counts toward your
+plan's live sessions, the same as one over the relay's HTTPS path, and one
+machine reached both ways at once counts once. Relay hours count only the
+time a session's traffic goes through the relay: a direct connection uses
+none. `cua usage` and the app's Settings show both.
+
+## When the network changes
+
+Connections belong to the two ends, not to a network path. When a laptop
+moves from Wi-Fi to Ethernet or its public address changes, traffic moves to
+the relay for a moment and back to a direct path as soon as one answers. A
+relay restart does not interrupt direct connections; a connection that was
+going through the relay resumes when the relay is back.
+
+## What still goes through the relay's HTTPS path
+
+- The **browser viewer** and **web or Cloudflare-hosted agents** that cannot
+ run Cua: they reach `https://<relay>/m/<machine>/…` as before. See
+ [what the relay can see](/spaces/guides/relay-security).
+- Machines and devices without the mesh turned on, or on a version of Cua
+ from before it.
+- Relays that do not coordinate a mesh, such as a self-hosted `cua-relay`:
+ `prefer` uses their HTTPS path quietly.
+
+## Firewalls
+
+Direct paths use UDP. Each end picks a UDP port on its own; outbound UDP is
+all it needs. On networks that block UDP, the mesh still works through the
+relay, over HTTPS to the same relay address as the rest of Cua.
+
+<Callout type="info">
+ WireGuard is a registered trademark of Jason A. Donenfeld. Cua's mesh uses
+ the WireGuard protocol through Cloudflare's BSD-licensed boringtun; it is
+ not affiliated with or endorsed by the WireGuard project.
+</Callout>
diff --git a/docs/content/docs/spaces/guides/meta.json b/docs/content/docs/spaces/guides/meta.json
index 4efd0c4135..10f6ea3550 100644
--- a/docs/content/docs/spaces/guides/meta.json
+++ b/docs/content/docs/spaces/guides/meta.json
@@ -12,6 +12,7 @@
"keyvault",
"site-login",
"relay-security",
+ "mesh",
"cua-volume",
"use-from-an-agent",
"updates"
diff --git a/docs/content/docs/spaces/guides/relay-security.mdx b/docs/content/docs/spaces/guides/relay-security.mdx
index 7fb1529246..afcab0b620 100644
--- a/docs/content/docs/spaces/guides/relay-security.mdx
+++ b/docs/content/docs/spaces/guides/relay-security.mdx
@@ -29,6 +29,19 @@ bug in this page: tell us.
through it: it can mint assertions the machines still trust, and read
whatever crosses it meanwhile.
+## The mesh (beta, opt-in)
+
+With [end-to-end encrypted connections](/spaces/guides/mesh) turned on
+(`CUA_MESH=prefer` or `require` on both the device and the machine), a
+`relay:` Space no longer goes through the HTTPS path below: the device and
+the machine talk WireGuard to each other, directly when they can, and the
+relay forwards only ciphertext it cannot read or change. It still decides
+who may connect, from the same accounts, devices and share lists. The mesh
+is off by default; everything on this page describes the HTTPS path, which
+stays in use for everything else (the browser viewer, web-hosted agents,
+machines and devices without the mesh, and `prefer` when the mesh is not
+available). With `CUA_MESH=require`, a device never falls back to it.
+
## What crosses the relay
| | Path | Relay sees plaintext? |
diff --git a/examples/streaming/rust/Cargo.lock b/examples/streaming/rust/Cargo.lock
index a6b750f506..172ed5c347 100644
--- a/examples/streaming/rust/Cargo.lock
+++ b/examples/streaming/rust/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -83,6 +93,45 @@ dependencies = [
"winnow 0.7.15",
]
+[[package]]
+name = "asn1-rs"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
+dependencies = [
+ "asn1-rs-derive",
+ "asn1-rs-impl",
+ "displaydoc",
+ "nom",
+ "num-traits",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
+[[package]]
+name = "asn1-rs-derive"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure 0.13.2",
+]
+
+[[package]]
+name = "asn1-rs-impl"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "async-compat"
version = "0.2.6"
@@ -673,6 +722,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -685,6 +743,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -746,6 +813,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek",
+]
+
[[package]]
name = "bstr"
version = "1.13.1"
@@ -852,6 +944,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -863,6 +966,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead",
+ "chacha20 0.9.1",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -877,6 +993,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common 0.1.7",
+ "inout",
+ "zeroize",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -1061,6 +1188,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1335,6 +1463,36 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305",
+ "futures-util",
+ "hex",
+ "hkdf",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1439,6 +1597,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -1558,6 +1717,32 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "cyclops-sdk"
version = "0.1.0"
@@ -1718,6 +1903,20 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "der-parser"
+version = "10.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+dependencies = [
+ "asn1-rs",
+ "displaydoc",
+ "nom",
+ "num-bigint",
+ "num-traits",
+ "rusticata-macros",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1913,6 +2112,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "filetime"
version = "0.2.29"
@@ -2236,6 +2441,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac 0.12.1",
+]
+
[[package]]
name = "hmac"
version = "0.12.1"
@@ -2562,6 +2776,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -2622,6 +2846,37 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -2843,6 +3098,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "lazy_static"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
+
[[package]]
name = "libc"
version = "0.2.189"
@@ -2959,6 +3220,18 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -2969,6 +3242,16 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -3036,6 +3319,15 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "oid-registry"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+dependencies = [
+ "asn1-rs",
+]
+
[[package]]
name = "olpc-cjson"
version = "0.1.4"
@@ -3053,6 +3345,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -3146,6 +3444,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "pem"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
+dependencies = [
+ "base64 0.23.1",
+ "serde_core",
+]
+
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -3252,6 +3560,17 @@ dependencies = [
"miniz_oxide 0.8.9",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -3503,7 +3822,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -3561,6 +3880,20 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "rcgen"
+version = "0.14.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
+dependencies = [
+ "pem",
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "x509-parser",
+ "yasna",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -3768,6 +4101,15 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rusticata-macros"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "rustix"
version = "1.1.5"
@@ -4343,6 +4685,17 @@ dependencies = [
"futures-core",
]
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -4997,6 +5350,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -5381,6 +5744,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -5558,6 +5930,36 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
+[[package]]
+name = "x509-parser"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
+dependencies = [
+ "asn1-rs",
+ "data-encoding",
+ "der-parser",
+ "lazy_static",
+ "nom",
+ "oid-registry",
+ "ring",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -5574,6 +5976,16 @@ version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
+[[package]]
+name = "yasna"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
+dependencies = [
+ "bit-vec",
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5594,7 +6006,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -5635,7 +6047,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -5643,6 +6055,20 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
[[package]]
name = "zerotrie"
diff --git a/libs/cua-spacesd/Cargo.lock b/libs/cua-spacesd/Cargo.lock
index a59b40eaba..a5411e596f 100644
--- a/libs/cua-spacesd/Cargo.lock
+++ b/libs/cua-spacesd/Cargo.lock
@@ -703,6 +703,15 @@ dependencies = [
"wyz",
]
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -770,6 +779,31 @@ dependencies = [
"piper",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix 0.31.3",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "borrow-or-share"
version = "0.2.4"
@@ -902,6 +936,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -915,6 +960,19 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -922,9 +980,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
"zeroize",
]
@@ -986,6 +1044,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -1375,7 +1434,7 @@ dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"ciborium",
"coset",
"cua-driver-contract",
@@ -1458,13 +1517,13 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
"sha2 0.10.9",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
@@ -1505,6 +1564,36 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite 0.29.0",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1745,6 +1834,7 @@ dependencies = [
"cua-driver-core",
"cua-driver-sdk",
"cua-machine-seal",
+ "cua-mesh",
"cua-proto",
"cua-relay",
"cua-spacesd-client",
@@ -1770,6 +1860,7 @@ dependencies = [
"prost",
"prost-types",
"rand 0.8.8",
+ "reqwest",
"rustls",
"serde",
"serde_json",
@@ -1920,6 +2011,21 @@ dependencies = [
"zstd",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -1929,7 +2035,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -2265,6 +2371,12 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -3065,6 +3177,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -3155,6 +3277,28 @@ version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -4573,6 +4717,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -4595,6 +4750,12 @@ dependencies = [
"universal-hash 0.5.1",
]
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
[[package]]
name = "portable-pty"
version = "0.9.0"
@@ -4885,7 +5046,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -7279,6 +7440,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -7595,13 +7765,25 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/Cargo.toml b/libs/cua-spacesd/crates/cua-spacesd-server/Cargo.toml
index 9b1f89f1d4..f37e560e8c 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/Cargo.toml
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/Cargo.toml
@@ -9,6 +9,8 @@ repository.workspace = true
publish = false
[dependencies]
+# The machine's node on the WireGuard®-based mesh (mesh_host).
+cua-mesh = { path = "../../../cua/crates/cua-mesh" }
cua-proto = { path = "../../../cua/crates/cua-proto" }
# Sealed delivery to a pinned machine key (S1): this guest's own keypair
# and the replay guard for unsealing.
@@ -45,6 +47,8 @@ notify = "8"
percent-encoding = "2"
prost.workspace = true
rand.workspace = true
+# mesh_host: is the relay coordinating a mesh (`/v1/info`)?
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde.workspace = true
# `join` account mode: relay assertion verification (relay_account).
cua-relay = { path = "../cua-relay" }
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
index 69740207d8..a06c77fd5b 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/context.rs
@@ -485,10 +485,62 @@ impl ServerContext {
p.stop.cancel();
}
tracing::info!(machine = %machine_id, "attached to relay");
+ let mesh = self.mesh_host_config(
+ relay_url,
+ machine_token,
+ None,
+ machine_id,
+ join.account.clone(),
+ local,
+ );
+ tokio::spawn(crate::mesh_host::run(mesh, stop.clone()));
tokio::spawn(cua_relay::client::run(join, stop));
Ok(())
}
+ /// The machine's mesh settings next to a relay join: its node lives in
+ /// `<data dir>/mesh`, peers reach this listener and the QUIC media
+ /// port, and static-mode pairing proofs are checked against the env
+ /// token. The node runs only while [`cua_mesh::policy`] allows it:
+ /// `CUA_MESH`, else the channel the Cua Spaces app recorded in this
+ /// machine's Cua home (the data dir's parent).
+ pub fn mesh_host_config(
+ &self,
+ relay_url: &str,
+ relay_token: &str,
+ relay_token_file: Option<std::path::PathBuf>,
+ machine_id: &str,
+ account: Arc<cua_relay::client::AccountLink>,
+ local: std::net::SocketAddr,
+ ) -> crate::mesh_host::MeshHostConfig {
+ let ip = if local.ip().is_unspecified() {
+ std::net::IpAddr::from([127, 0, 0, 1])
+ } else {
+ local.ip()
+ };
+ let quic_port = self.config().media_quic_port;
+ let auth = self.inner.auth.clone();
+ let home = self
+ .config()
+ .data_dir
+ .parent()
+ .map(std::path::Path::to_path_buf);
+ crate::mesh_host::MeshHostConfig {
+ relay_url: relay_url.to_owned(),
+ relay_token: relay_token.to_owned(),
+ relay_token_file,
+ machine_id: machine_id.to_owned(),
+ dir: self.config().data_dir.join("mesh"),
+ local: std::net::SocketAddr::new(ip, local.port()),
+ quic: (quic_port != 0).then(|| std::net::SocketAddr::new(ip, quic_port)),
+ account,
+ env_token: Arc::new(move || auth.token().map(|t| t.to_string())),
+ name: cua_mesh::node::hostname(),
+ policy: Arc::new(move || cua_mesh::Policy::current(home.as_deref())),
+ recheck: crate::mesh_host::GATE_RECHECK,
+ }
+ }
+
/// Leaves the relay attached with [`Self::attach_relay`]. Returns
/// false when none was attached.
pub fn detach_relay(&self) -> bool {
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/lib.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/lib.rs
index d0f8c61f5a..2a40b5e419 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/lib.rs
@@ -18,6 +18,7 @@ pub mod error;
pub mod filesystem;
pub mod host_spaces;
pub mod http;
+pub mod mesh_host;
pub mod peer;
pub mod process;
pub mod provider;
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs
new file mode 100644
index 0000000000..2609cee218
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/mesh_host.rs
@@ -0,0 +1,679 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The machine side of the mesh (`cua-spacesd join`).
+//!
+//! Next to its relay connection, a hosted machine runs a mesh node (MIT
+//! `cua-mesh`) when the relay coordinates one. Peers reach the machine's
+//! spacesd over WireGuard end to end, so the relay only ever relays
+//! ciphertext for them:
+//!
+//! - **Account machines.** Every stream comes from a peer the relay's map
+//! vouched for (its account, email and role, the same facts a relay
+//! assertion carries). A small local proxy strips any client credential
+//! and adds an assertion this process signs with an in-process key the
+//! machine trusts next to the relay's, so spacesd's own host policy
+//! (owner, local allow list, sharing switch, view-only shares) decides
+//! exactly as it does for relayed calls. The assertion is only added when
+//! the request carries the per-forward session key its dialer chose, so
+//! another local user on the client machine cannot borrow the session.
+//! - **Static machines.** Clients pair by proving they hold the machine's
+//! env token (checked here, never sent); the machine approves and
+//! remembers them, and filters the relay's map to its own approvals.
+//! Streams are spliced to spacesd unchanged: the env token still travels
+//! in each request, now inside WireGuard.
+//! - **QUIC media.** Mesh UDP [`cua_mesh::MEDIA_UDP_PORT`] reaches the
+//! local QUIC media port, so QUIC streaming works over the mesh.
+//! - **Metering (account machines).** The relay meters sessions on its
+//! HTTPS path itself; mesh traffic never passes it in the clear, so this
+//! node tells it which peers hold streams open (requests in flight,
+//! WebSockets, media flows), as a small snapshot sent when it changes and
+//! only to a relay that asks for it. The relay checks each peer against
+//! this machine's map and meters it as that peer's own account.
+//!
+//! A relay without a mesh (an older one) is simply not used: the machine
+//! keeps serving over its relay connection and checks again later.
+//!
+//! The node runs only while [`cua_mesh::policy`] allows it: `CUA_MESH` in
+//! the service's environment, else the update channel the Cua Spaces app
+//! recorded in this machine's Cua home (off on every channel in this
+//! release). Until then nothing is asked of the relay, and the machine
+//! serves over its relay connection exactly as before.
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::{Arc, LazyLock, Mutex};
+use std::time::Duration;
+
+use cua_mesh::{Grant, IncomingStream, Mesh, MeshConfig, NodeKind, PeerUsage, Policy, PublicKey};
+use http::{HeaderValue, Request, Response, StatusCode, Version};
+use http_body_util::BodyExt as _;
+use hyper::body::Incoming;
+use hyper_util::rt::{TokioExecutor, TokioIo};
+use tokio_util::sync::CancellationToken;
+
+use cua_relay::assertion::{AssertionClaims, RelayKey, TrustedKeys, ASSERTION_HEADER};
+use cua_relay::client::AccountLink;
+
+/// The service name spacesd streams use.
+pub const SPACESD_SERVICE: &str = "spacesd";
+/// The request header carrying the dialer's per-forward session key.
+pub const SESSION_HEADER: &str = "x-cua-mesh-session";
+
+/// Client credential headers a mesh request never forwards in account mode
+/// (the same set the relay strips).
+const CLIENT_CREDENTIAL_HEADERS: &[&str] = &[
+ "authorization",
+ "x-cua-relay-authorization",
+ "x-cua-env-authorization",
+ "x-cua-device-session",
+ ASSERTION_HEADER,
+];
+
+/// How often the streams peers hold open are checked and, when they
+/// changed, reported to the relay.
+pub const USAGE_EVERY: Duration = Duration::from_secs(1);
+/// A media flow counts as open while its peer sent within this.
+pub const MEDIA_ACTIVE: Duration = Duration::from_secs(10);
+
+/// The streams each account peer holds open on this machine, for the
+/// relay's allowance meter.
+#[derive(Default)]
+pub struct PeerStreams {
+ peers: Mutex<HashMap<PublicKey, PeerOpen>>,
+}
+
+#[derive(Default)]
+struct PeerOpen {
+ user: String,
+ open: u32,
+ /// A WebSocket upgraded since the last snapshot.
+ upgraded: bool,
+}
+
+/// One open stream of a peer; closes on drop.
+pub struct StreamUse {
+ streams: Arc<PeerStreams>,
+ peer: PublicKey,
+}
+
+impl PeerStreams {
+ /// A stream of `peer` (whose grant names `user`) opens.
+ pub fn open(self: &Arc<Self>, peer: PublicKey, user: &str) -> StreamUse {
+ let mut peers = self.peers.lock().expect("peer streams");
+ let p = peers.entry(peer).or_default();
+ p.user = user.to_owned();
+ p.open += 1;
+ StreamUse {
+ streams: self.clone(),
+ peer,
+ }
+ }
+
+ /// `peer` upgraded a stream (a WebSocket): a session at once.
+ pub fn upgraded(&self, peer: &PublicKey) {
+ if let Some(p) = self.peers.lock().expect("peer streams").get_mut(peer) {
+ p.upgraded = true;
+ }
+ }
+
+ /// What to report now: every peer with a stream open or just upgraded,
+ /// plus `media` peers (with their grants), sorted by key.
+ pub fn snapshot(&self, media: &[(PublicKey, String)]) -> Vec<PeerUsage> {
+ let mut out: HashMap<PublicKey, PeerUsage> = HashMap::new();
+ {
+ let mut peers = self.peers.lock().expect("peer streams");
+ for (k, p) in peers.iter_mut() {
+ if p.open > 0 || p.upgraded {
+ out.insert(
+ *k,
+ PeerUsage {
+ peer: *k,
+ user: p.user.clone(),
+ open: p.open,
+ live: std::mem::take(&mut p.upgraded),
+ },
+ );
+ }
+ }
+ peers.retain(|_, p| p.open > 0);
+ }
+ for (k, user) in media {
+ let e = out.entry(*k).or_insert_with(|| PeerUsage {
+ peer: *k,
+ user: user.clone(),
+ open: 0,
+ live: false,
+ });
+ // An active media flow is a held stream (a desktop view).
+ e.open += 1;
+ e.live = true;
+ }
+ let mut out: Vec<_> = out.into_values().filter(|p| p.open > 0).collect();
+ out.sort_by_key(|p| p.peer);
+ out
+ }
+}
+
+impl Drop for StreamUse {
+ fn drop(&mut self) {
+ let mut peers = self.streams.peers.lock().expect("peer streams");
+ if let Some(p) = peers.get_mut(&self.peer) {
+ p.open = p.open.saturating_sub(1);
+ }
+ }
+}
+
+/// The machine's env token, read when a pairing proof arrives.
+pub type EnvToken = Arc<dyn Fn() -> Option<String> + Send + Sync>;
+
+/// The mesh policy now (re-read while the machine runs).
+pub type PolicySource = Arc<dyn Fn() -> Policy + Send + Sync>;
+
+/// How often a machine whose mesh is off checks whether it was turned on
+/// (and a running node whether it was turned off). Local reads only.
+pub const GATE_RECHECK: Duration = Duration::from_secs(30);
+
+/// The in-process keys this process's mesh endpoints sign assertions with
+/// (never leave the process). [`verify_local`] trusts them next to the
+/// relay's keys.
+static LOCAL_KEYS: LazyLock<Mutex<Vec<serde_json::Value>>> = LazyLock::new(Mutex::default);
+static LOCAL_TRUSTED: LazyLock<TrustedKeys> = LazyLock::new(TrustedKeys::default);
+
+fn trust_local(key: &RelayKey) -> Result<(), String> {
+ let mut keys = LOCAL_KEYS.lock().expect("local keys");
+ let jwks = key.jwks();
+ keys.extend(jwks["keys"].as_array().cloned().unwrap_or_default());
+ LOCAL_TRUSTED
+ .set_jwks_json(&serde_json::json!({ "keys": *keys }).to_string())
+ .map(|_| ())
+}
+
+/// Verifies an assertion this process's mesh endpoint signed (for an
+/// account peer the relay's network map identified). `None` when no mesh
+/// endpoint ever ran here.
+pub fn verify_local(token: &str, machine_id: &str) -> Option<Result<AssertionClaims, String>> {
+ if LOCAL_TRUSTED.is_empty() {
+ return None;
+ }
+ Some(LOCAL_TRUSTED.verify(token, machine_id))
+}
+
+/// `bytes` bytes from the OS RNG, lowercase hex (assertion ids).
+fn os_random_hex(bytes: usize) -> String {
+ use rand::RngCore as _;
+ let mut buf = vec![0u8; bytes];
+ rand::rngs::OsRng.fill_bytes(&mut buf);
+ hex::encode(buf)
+}
+
+/// How the machine joins the mesh.
+#[derive(Clone)]
+pub struct MeshHostConfig {
+ /// Relay base URL.
+ pub relay_url: String,
+ /// The machine token (account) or static registration token.
+ pub relay_token: String,
+ /// Re-read before every connect when set (token rotation).
+ pub relay_token_file: Option<PathBuf>,
+ /// The machine id.
+ pub machine_id: String,
+ /// Where the node identity and approvals live.
+ pub dir: PathBuf,
+ /// The local spacesd listener.
+ pub local: SocketAddr,
+ /// The local QUIC media port, if QUIC runs.
+ pub quic: Option<SocketAddr>,
+ /// Account details learned on the relay handshake.
+ pub account: Arc<AccountLink>,
+ /// The env token, for static-mode pairing proofs.
+ pub env_token: EnvToken,
+ /// Display name.
+ pub name: String,
+ /// Whether the mesh may run ([`cua_mesh::policy`]).
+ pub policy: PolicySource,
+ /// How often [`Self::policy`] is checked again ([`GATE_RECHECK`]).
+ pub recheck: Duration,
+}
+
+impl std::fmt::Debug for MeshHostConfig {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("MeshHostConfig")
+ .field("relay_url", &self.relay_url)
+ .field("machine_id", &self.machine_id)
+ .finish()
+ }
+}
+
+/// Whether the relay at `url` coordinates a mesh this build speaks.
+pub async fn relay_has_mesh(url: &str) -> Result<bool, String> {
+ let info = format!("{}/v1/info", url.trim_end_matches('/'));
+ let info = info
+ .replacen("wss://", "https://", 1)
+ .replacen("ws://", "http://", 1);
+ let resp = reqwest::Client::builder()
+ .timeout(Duration::from_secs(10))
+ .build()
+ .map_err(|e| e.to_string())?
+ .get(&info)
+ .send()
+ .await
+ .map_err(|e| e.to_string())?;
+ if !resp.status().is_success() {
+ return Ok(false);
+ }
+ let v: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
+ Ok(v.get("mesh")
+ .and_then(|m| m.get("version"))
+ .and_then(|v| v.as_u64())
+ == Some(u64::from(cua_mesh::VERSION)))
+}
+
+/// Runs the machine's mesh node until `shutdown`: while the policy allows
+/// it and the relay coordinates a mesh (re-checking every 10 minutes while
+/// it does not), stopping it again when the policy turns it off.
+pub async fn run(cfg: MeshHostConfig, shutdown: CancellationToken) {
+ let ctx_key = Arc::new(RelayKey::generate());
+ let mut trusted = false;
+ loop {
+ if !wait_until_allowed(&cfg, &shutdown).await {
+ return;
+ }
+ let mesh = match start(&cfg).await {
+ Ok(m) => m,
+ Err(e) => {
+ tracing::warn!(error = %e, "mesh unavailable; serving over the relay only");
+ tokio::select! {
+ _ = tokio::time::sleep(Duration::from_secs(600)) => continue,
+ _ = shutdown.cancelled() => return,
+ }
+ }
+ };
+ tracing::info!(addr = %mesh.addr(), "machine joined the mesh");
+ if !trusted {
+ match trust_local(&ctx_key) {
+ Ok(()) => trusted = true,
+ Err(e) => tracing::warn!(
+ error = %e,
+ "cannot trust the mesh key; account peers cannot authenticate"
+ ),
+ }
+ }
+ let streams = Arc::new(PeerStreams::default());
+ let reporter = tokio::spawn(report_usage(
+ mesh.clone(),
+ streams.clone(),
+ cfg.account.clone(),
+ ));
+ let ctx = Arc::new(Ctx {
+ cfg: cfg.clone(),
+ key: ctx_key.clone(),
+ streams,
+ });
+ let mut gate = tokio::time::interval(cfg.recheck);
+ gate.tick().await;
+ let stopped = loop {
+ let incoming = tokio::select! {
+ i = mesh.accept() => i,
+ _ = gate.tick() => {
+ if (cfg.policy)().uses_mesh() {
+ continue;
+ }
+ tracing::info!("the mesh was turned off; serving over the relay only");
+ break false;
+ }
+ _ = shutdown.cancelled() => break true,
+ };
+ let Some(incoming) = incoming else {
+ break false;
+ };
+ let ctx = ctx.clone();
+ tokio::spawn(async move { handle(ctx, incoming).await });
+ };
+ reporter.abort();
+ mesh.shutdown();
+ if stopped {
+ return;
+ }
+ }
+}
+
+/// Waits until the policy allows the mesh and the relay coordinates one
+/// this build speaks. False when `shutdown` came first. While the policy
+/// is off, nothing is asked of the relay.
+async fn wait_until_allowed(cfg: &MeshHostConfig, shutdown: &CancellationToken) -> bool {
+ let mut said = false;
+ loop {
+ let wait = if !(cfg.policy)().uses_mesh() {
+ cfg.recheck
+ } else {
+ match relay_has_mesh(&cfg.relay_url).await {
+ Ok(true) => return true,
+ Ok(false) => {
+ if !said {
+ tracing::info!(
+ "the relay has no mesh coordinator; serving over the relay only"
+ );
+ said = true;
+ }
+ }
+ Err(e) => tracing::debug!(error = %e, "relay info"),
+ }
+ Duration::from_secs(600)
+ };
+ tokio::select! {
+ _ = tokio::time::sleep(wait) => {}
+ _ = shutdown.cancelled() => return false,
+ }
+ }
+}
+
+/// Reports the streams account peers hold open to the relay, whenever
+/// they change ([`Mesh::report_usage`] sends nothing unchanged, and
+/// nothing to a relay that does not meter).
+async fn report_usage(mesh: Mesh, streams: Arc<PeerStreams>, account: Arc<AccountLink>) {
+ let mut tick = tokio::time::interval(USAGE_EVERY);
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ tick.tick().await;
+ if account.owner().is_none() {
+ continue;
+ }
+ let active = mesh.udp_active_peers(MEDIA_ACTIVE);
+ let media: Vec<(PublicKey, String)> = if active.is_empty() {
+ Vec::new()
+ } else {
+ mesh.peers()
+ .into_iter()
+ .filter(|p| active.contains(&p.node_key))
+ .filter_map(|p| p.grant.map(|g| (p.node_key, g.user)))
+ .collect()
+ };
+ mesh.report_usage(streams.snapshot(&media));
+ }
+}
+
+async fn start(cfg: &MeshHostConfig) -> cua_mesh::Result<Mesh> {
+ let token = cfg.relay_token.clone();
+ let token_file = cfg.relay_token_file.clone();
+ let machine_id = cfg.machine_id.clone();
+ let auth: cua_mesh::AuthProvider = Arc::new(move || {
+ let token = token_file
+ .as_deref()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .map(|t| t.trim().to_owned())
+ .filter(|t| !t.is_empty())
+ .unwrap_or_else(|| token.clone());
+ let id = machine_id.clone();
+ Box::pin(async move {
+ Ok(vec![
+ ("authorization".to_owned(), format!("Bearer {token}")),
+ (cua_mesh::proto::MACHINE_ID_HEADER.to_owned(), id),
+ ])
+ })
+ });
+ let mut mc = MeshConfig::new(
+ cfg.relay_url.clone(),
+ NodeKind::Machine,
+ Some(cfg.dir.join("identity.json")),
+ auth,
+ );
+ mc.name = cfg.name.clone();
+ mc.approved_path = Some(cfg.dir.join("approved.json"));
+ let env = cfg.env_token.clone();
+ let id = cfg.machine_id.clone();
+ mc.pair_verifier = Some(Arc::new(move |client, ts, proof| {
+ env().is_some_and(|token| {
+ cua_mesh::proto::verify_pair_proof(
+ &token,
+ &id,
+ client,
+ ts,
+ proof,
+ cua_mesh::proto::now_secs(),
+ )
+ })
+ }));
+ let mesh = Mesh::start(mc).await?;
+ if let Some(quic) = cfg.quic {
+ mesh.serve_udp(cua_mesh::MEDIA_UDP_PORT, quic)?;
+ }
+ Ok(mesh)
+}
+
+struct Ctx {
+ cfg: MeshHostConfig,
+ key: Arc<RelayKey>,
+ streams: Arc<PeerStreams>,
+}
+
+async fn handle(ctx: Arc<Ctx>, incoming: IncomingStream) {
+ if incoming.header.service != SPACESD_SERVICE {
+ return;
+ }
+ let account_machine = ctx.cfg.account.owner().is_some();
+ match (incoming.peer.grant.clone(), account_machine) {
+ (Some(grant), true) => {
+ let peer = incoming.peer.node_key;
+ serve_with_identity(ctx, incoming.stream, peer, grant, incoming.header.session).await
+ }
+ (None, false) => splice(incoming.stream, ctx.cfg.local).await,
+ // A peer without an identity on an account machine (or the other
+ // way round) has nothing to do here.
+ _ => tracing::warn!(peer = %incoming.peer.node_key.short(), "mesh stream refused"),
+ }
+}
+
+async fn splice(mut stream: cua_mesh::MeshStream, local: SocketAddr) {
+ match tokio::net::TcpStream::connect(local).await {
+ Ok(mut tcp) => {
+ let _ = tcp.set_nodelay(true);
+ let _ = tokio::io::copy_bidirectional(&mut stream, &mut tcp).await;
+ }
+ Err(e) => tracing::warn!(error = %e, %local, "cannot reach the local spacesd"),
+ }
+}
+
+type BoxBody = http_body_util::combinators::BoxBody<bytes::Bytes, hyper::Error>;
+
+fn plain(status: StatusCode, msg: &str) -> Response<BoxBody> {
+ let mut r = Response::new(
+ http_body_util::Full::new(bytes::Bytes::from(msg.to_owned()))
+ .map_err(|never| match never {})
+ .boxed(),
+ );
+ *r.status_mut() = status;
+ r
+}
+
+/// Serves HTTP/1.1 and HTTP/2 (gRPC, WebSockets, files) on one mesh
+/// stream, adding the peer's identity, and forwards to the local spacesd.
+async fn serve_with_identity(
+ ctx: Arc<Ctx>,
+ stream: cua_mesh::MeshStream,
+ peer: PublicKey,
+ grant: Grant,
+ session: Option<String>,
+) {
+ let h2: Arc<tokio::sync::OnceCell<hyper::client::conn::http2::SendRequest<Incoming>>> =
+ Arc::default();
+ let grant = Arc::new(grant);
+ let service = hyper::service::service_fn(move |req: Request<Incoming>| {
+ let ctx = ctx.clone();
+ let grant = grant.clone();
+ let session = session.clone();
+ let h2 = h2.clone();
+ async move {
+ // Held until the response body ends (or the upgraded socket
+ // closes), as the relay's HTTPS path meters its streams.
+ let held = ctx.streams.open(peer, &grant.user);
+ let streams = ctx.streams.clone();
+ let resp = forward(ctx, grant, session, h2, req, held).await;
+ if resp.status() == StatusCode::SWITCHING_PROTOCOLS {
+ streams.upgraded(&peer);
+ }
+ Ok::<_, std::convert::Infallible>(resp)
+ }
+ });
+ let builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
+ if let Err(e) = builder
+ .serve_connection_with_upgrades(TokioIo::new(stream), service)
+ .await
+ {
+ tracing::debug!(error = %e, "mesh stream ended");
+ }
+}
+
+fn mint(ctx: &Ctx, grant: &Grant) -> String {
+ let now = cua_relay::assertion::now_secs();
+ ctx.key.sign(&AssertionClaims {
+ iss: "cua-mesh".into(),
+ aud: ctx.cfg.machine_id.clone(),
+ sub: grant.user.clone(),
+ acct: grant.account.clone(),
+ email: grant.email.clone(),
+ name: grant.name.clone(),
+ mid: ctx.cfg.machine_id.clone(),
+ role: grant.role.clone(),
+ scope: "env".into(),
+ iat: now,
+ exp: now + cua_relay::assertion::MAX_ASSERTION_TTL_SECS,
+ jti: os_random_hex(16),
+ })
+}
+
+async fn forward(
+ ctx: Arc<Ctx>,
+ grant: Arc<Grant>,
+ session: Option<String>,
+ h2: Arc<tokio::sync::OnceCell<hyper::client::conn::http2::SendRequest<Incoming>>>,
+ mut req: Request<Incoming>,
+ held: StreamUse,
+) -> Response<BoxBody> {
+ let presented = req
+ .headers()
+ .get(SESSION_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ let headers = req.headers_mut();
+ for name in CLIENT_CREDENTIAL_HEADERS {
+ headers.remove(*name);
+ }
+ headers.remove(SESSION_HEADER);
+ let authentic = match (&session, &presented) {
+ (Some(want), Some(got)) => {
+ use subtle::ConstantTimeEq as _;
+ want.len() == got.len() && bool::from(want.as_bytes().ct_eq(got.as_bytes()))
+ }
+ _ => false,
+ };
+ if authentic {
+ if let Ok(v) = HeaderValue::from_str(&mint(&ctx, &grant)) {
+ headers.insert(ASSERTION_HEADER, v);
+ }
+ }
+ let local = ctx.cfg.local;
+ if req.version() == Version::HTTP_2 {
+ let sender = h2
+ .get_or_try_init(|| async {
+ let tcp = tokio::net::TcpStream::connect(local)
+ .await
+ .map_err(|e| e.to_string())?;
+ let _ = tcp.set_nodelay(true);
+ let (sender, conn) =
+ hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(tcp))
+ .await
+ .map_err(|e| e.to_string())?;
+ tokio::spawn(async move {
+ let _ = conn.await;
+ });
+ Ok::<_, String>(sender)
+ })
+ .await;
+ let mut sender = match sender {
+ Ok(s) => s.clone(),
+ Err(e) => return plain(StatusCode::BAD_GATEWAY, &format!("local spacesd: {e}")),
+ };
+ return match sender.send_request(req).await {
+ Ok(resp) => resp.map(|b| holding(b, held)),
+ Err(e) => plain(StatusCode::BAD_GATEWAY, &format!("local spacesd: {e}")),
+ };
+ }
+ // HTTP/1.1 (WebSockets, files, the viewer): one local connection per
+ // request, upgrades spliced through.
+ let tcp = match tokio::net::TcpStream::connect(local).await {
+ Ok(t) => t,
+ Err(e) => return plain(StatusCode::BAD_GATEWAY, &format!("local spacesd: {e}")),
+ };
+ let _ = tcp.set_nodelay(true);
+ let (mut sender, conn) = match hyper::client::conn::http1::handshake(TokioIo::new(tcp)).await {
+ Ok(p) => p,
+ Err(e) => return plain(StatusCode::BAD_GATEWAY, &format!("local spacesd: {e}")),
+ };
+ tokio::spawn(async move {
+ let _ = conn.with_upgrades().await;
+ });
+ let is_upgrade = req.headers().contains_key(http::header::UPGRADE);
+ let client_upgrade = is_upgrade.then(|| hyper::upgrade::on(&mut req));
+ let mut resp = match sender.send_request(req).await {
+ Ok(r) => r,
+ Err(e) => return plain(StatusCode::BAD_GATEWAY, &format!("local spacesd: {e}")),
+ };
+ if resp.status() == StatusCode::SWITCHING_PROTOCOLS {
+ if let Some(client_upgrade) = client_upgrade {
+ let local_upgrade = hyper::upgrade::on(&mut resp);
+ tokio::spawn(async move {
+ // The upgraded socket is the stream now.
+ let _held = held;
+ if let Ok((a, b)) = tokio::try_join!(client_upgrade, local_upgrade) {
+ let mut a = TokioIo::new(a);
+ let mut b = TokioIo::new(b);
+ let _ = tokio::io::copy_bidirectional(&mut a, &mut b).await;
+ }
+ });
+ return resp.map(|b| b.boxed());
+ }
+ }
+ resp.map(|b| holding(b, held))
+}
+
+/// `body`, keeping `held` open until it ends or is dropped.
+fn holding(body: Incoming, held: StreamUse) -> BoxBody {
+ body.map_frame(move |frame| {
+ let _ = &held;
+ frame
+ })
+ .boxed()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn snapshots_count_open_streams_upgrades_and_media_per_peer() {
+ let streams = Arc::new(PeerStreams::default());
+ let (a, b) = (
+ cua_mesh::SecretKey::generate().public(),
+ cua_mesh::SecretKey::generate().public(),
+ );
+ assert!(streams.snapshot(&[]).is_empty());
+ let s1 = streams.open(a, "ada");
+ let s2 = streams.open(a, "ada");
+ streams.upgraded(&a);
+ let snap = streams.snapshot(&[(b, "bob".into())]);
+ let ada = snap.iter().find(|p| p.peer == a).unwrap();
+ assert_eq!((ada.user.as_str(), ada.open, ada.live), ("ada", 2, true));
+ let bob = snap.iter().find(|p| p.peer == b).unwrap();
+ assert_eq!((bob.user.as_str(), bob.open, bob.live), ("bob", 1, true));
+ // The upgrade is reported once; closed streams leave.
+ drop(s1);
+ let snap = streams.snapshot(&[]);
+ assert_eq!(snap.len(), 1);
+ assert_eq!((snap[0].open, snap[0].live), (1, false));
+ drop(s2);
+ assert!(streams.snapshot(&[]).is_empty());
+ assert!(streams.peers.lock().unwrap().is_empty());
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/relay_account.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/relay_account.rs
index c62dd888f2..601de00b3b 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/relay_account.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/relay_account.rs
@@ -245,7 +245,15 @@ impl ExternalAuthenticator for RelayAssertionAuth {
fn authenticate(&self, headers: &http::HeaderMap) -> Option<Result<ExternalGrant, String>> {
let token = headers.get(ASSERTION_HEADER)?.to_str().ok()?;
Some((|| {
- let claims = self.link.keys.verify(token, &self.machine_id)?;
+ // The relay's keys, or the in-process key this machine's own
+ // mesh endpoint signs with for peers the relay's map vouched for.
+ let claims = match self.link.keys.verify(token, &self.machine_id) {
+ Ok(claims) => claims,
+ Err(e) => match crate::mesh_host::verify_local(token, &self.machine_id) {
+ Some(Ok(claims)) => claims,
+ _ => return Err(e),
+ },
+ };
let policy = self.policy()?;
let access = policy.authorize(&claims, self.link.owner().as_deref())?;
let client = crate::auth::principal_from_headers(headers);
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs
new file mode 100644
index 0000000000..464b7fc099
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/mesh_gate.rs
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The machine side of the mesh is off unless allowed (`CUA_MESH`, or the
+//! app's channel with the Beta switch on): while it is off the machine
+//! never asks its relay about the mesh, and it starts asking once the
+//! policy allows it, without a restart.
+
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use cua_mesh::Policy;
+use cua_spacesd_server::mesh_host::{run, MeshHostConfig};
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+use tokio_util::sync::CancellationToken;
+
+/// A relay without a mesh that counts `/v1/info` requests.
+async fn counting_relay() -> (String, Arc<AtomicUsize>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let count = Arc::new(AtomicUsize::new(0));
+ let seen = count.clone();
+ tokio::spawn(async move {
+ loop {
+ let Ok((mut tcp, _)) = listener.accept().await else {
+ continue;
+ };
+ let seen = seen.clone();
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 4096];
+ let n = tcp.read(&mut buf).await.unwrap_or(0);
+ if String::from_utf8_lossy(&buf[..n]).starts_with("GET /v1/info") {
+ seen.fetch_add(1, Ordering::SeqCst);
+ }
+ let body = r#"{"account_auth":true,"static_tokens":false}"#;
+ let reply = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = tcp.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ (url, count)
+}
+
+fn config(relay: &str, dir: &std::path::Path, on: Arc<AtomicBool>) -> MeshHostConfig {
+ MeshHostConfig {
+ relay_url: relay.to_owned(),
+ relay_token: "machine-token".into(),
+ relay_token_file: None,
+ machine_id: "mesh-gate-test-0001".into(),
+ dir: dir.join("mesh"),
+ local: "127.0.0.1:9".parse().unwrap(),
+ quic: None,
+ account: Arc::default(),
+ env_token: Arc::new(|| None),
+ name: "test".into(),
+ policy: Arc::new(move || {
+ if on.load(Ordering::SeqCst) {
+ Policy::Prefer
+ } else {
+ Policy::Off
+ }
+ }),
+ recheck: Duration::from_millis(50),
+ }
+}
+
+async fn wait_for(count: &AtomicUsize, at_least: usize) -> bool {
+ for _ in 0..100 {
+ if count.load(Ordering::SeqCst) >= at_least {
+ return true;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ false
+}
+
+#[tokio::test]
+async fn an_off_machine_never_asks_its_relay_about_the_mesh() {
+ let (relay, count) = counting_relay().await;
+ let dir = tempfile::tempdir().unwrap();
+ let on = Arc::new(AtomicBool::new(false));
+ let stop = CancellationToken::new();
+ let task = tokio::spawn(run(config(&relay, dir.path(), on.clone()), stop.clone()));
+
+ // Off: 20 rechecks later, still nothing asked and no node state written.
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 0,
+ "an off machine asked the relay"
+ );
+ assert!(
+ !dir.path().join("mesh").exists(),
+ "an off machine made a node"
+ );
+
+ // Allowed (CUA_MESH=prefer, or the Beta switch): the next recheck asks,
+ // with no restart. This relay has no mesh, so it asks once and waits.
+ on.store(true, Ordering::SeqCst);
+ assert!(wait_for(&count, 1).await, "an allowed machine never asked");
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 1,
+ "a relay without a mesh is asked again later, not hammered"
+ );
+
+ stop.cancel();
+ tokio::time::timeout(Duration::from_secs(5), task)
+ .await
+ .expect("stops on shutdown")
+ .unwrap();
+}
+
+#[tokio::test]
+async fn the_default_policy_is_off() {
+ // No CUA_MESH and no app channel: the machine stays on the relay path.
+ let dir = tempfile::tempdir().unwrap();
+ if std::env::var(cua_mesh::policy::ENV).is_err() {
+ assert_eq!(Policy::current(Some(dir.path())), Policy::Off);
+ std::fs::write(dir.path().join(cua_mesh::policy::CHANNEL_FILE), "beta").unwrap();
+ // The Beta switch is off in this release.
+ assert_eq!(Policy::current(Some(dir.path())), Policy::Off);
+ }
+}
diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
index 81fcbb2df5..82a0524d4e 100644
--- a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
@@ -778,6 +778,19 @@ async fn serve(args: ServeArgs, join: Option<JoinArgs>) -> Result<Exit, BoxError
));
ctx.mark_joined_at_start();
tracing::info!(relay = %join.relay, machine = %machine_id, "joining relay; clients connect to <relay>/m/{machine_id}");
+ // The WireGuard®-based mesh next to the relay connection, when
+ // allowed (`CUA_MESH`, see cua_mesh::policy) and the relay
+ // coordinates one: end-to-end encrypted, direct when possible. The
+ // relay path stays for clients that lack it.
+ let mesh = ctx.mesh_host_config(
+ &join.relay,
+ join.relay_token.as_deref().unwrap_or_default(),
+ join.relay_token_file.clone(),
+ &machine_id,
+ join_config.account.clone(),
+ addr,
+ );
+ tokio::spawn(cua_spacesd_server::mesh_host::run(mesh, shutdown.clone()));
tokio::spawn(cua_relay::client::run(join_config, shutdown.clone()));
}
server.serve(listener).await?;
diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
index 826b13a954..0780ec00c5 100644
--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock
@@ -1255,6 +1255,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix 0.31.3",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "borrow-or-share"
version = "0.2.4"
@@ -1397,6 +1422,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -1410,6 +1446,19 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -1417,9 +1466,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
"zeroize",
]
@@ -1482,6 +1531,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -2100,7 +2150,7 @@ dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"ciborium",
"coset",
"cua-driver-contract",
@@ -2285,13 +2335,13 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
"sha2 0.10.9",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
@@ -2324,6 +2374,36 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite 0.29.0",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -2460,6 +2540,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -2626,6 +2707,7 @@ dependencies = [
"cua-driver-core",
"cua-driver-sdk",
"cua-machine-seal",
+ "cua-mesh",
"cua-proto",
"cua-relay",
"cua-spacesd-html5",
@@ -2648,6 +2730,7 @@ dependencies = [
"portable-pty",
"prost",
"rand 0.8.8",
+ "reqwest 0.12.28",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -2828,6 +2911,21 @@ dependencies = [
"zstd",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -2837,7 +2935,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -3416,6 +3514,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -4294,6 +4398,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -4403,6 +4517,28 @@ version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -5006,6 +5142,18 @@ dependencies = [
"libc",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases 0.2.2",
+ "libc",
+]
+
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -6057,6 +6205,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -6403,7 +6562,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -9053,6 +9212,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -9368,13 +9536,25 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
diff --git a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
index 3ac1793576..e5d6a3c146 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
+++ b/libs/cua-spacesd/tests/teleport-e2e/Cargo.lock
@@ -256,6 +256,45 @@ dependencies = [
"winnow 0.7.15",
]
+[[package]]
+name = "asn1-rs"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
+dependencies = [
+ "asn1-rs-derive",
+ "asn1-rs-impl",
+ "displaydoc",
+ "nom 7.1.3",
+ "num-traits",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
+[[package]]
+name = "asn1-rs-derive"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure",
+]
+
+[[package]]
+name = "asn1-rs-impl"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -553,7 +592,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
- "bit-vec",
+ "bit-vec 0.8.0",
]
[[package]]
@@ -562,6 +601,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -586,6 +634,15 @@ dependencies = [
"wyz",
]
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -653,6 +710,31 @@ dependencies = [
"piper",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix 0.31.3",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "borrow-or-share"
version = "0.2.4"
@@ -785,6 +867,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -798,6 +891,19 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -805,9 +911,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
"zeroize",
]
@@ -869,6 +975,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -1294,7 +1401,7 @@ dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"ciborium",
"coset",
"cua-driver-contract",
@@ -1380,16 +1487,46 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
"sha2 0.10.9",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite 0.29.0",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1492,6 +1629,7 @@ dependencies = [
"cua-driver-core",
"cua-driver-sdk",
"cua-machine-seal",
+ "cua-mesh",
"cua-proto",
"cua-relay",
"cua-spacesd-html5",
@@ -1514,6 +1652,7 @@ dependencies = [
"portable-pty",
"prost",
"rand 0.8.8",
+ "reqwest",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -1665,6 +1804,21 @@ dependencies = [
"zstd",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -1674,7 +1828,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -1697,6 +1851,20 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+[[package]]
+name = "der-parser"
+version = "10.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+dependencies = [
+ "asn1-rs",
+ "displaydoc",
+ "nom 7.1.3",
+ "num-bigint",
+ "num-traits",
+ "rusticata-macros",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1982,6 +2150,12 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -2762,6 +2936,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -2871,6 +3055,28 @@ version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -2972,7 +3178,7 @@ checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
dependencies = [
"base64 0.22.1",
"js-sys",
- "pem",
+ "pem 3.0.6",
"ring",
"serde",
"serde_json",
@@ -3288,6 +3494,18 @@ dependencies = [
"libc",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cfg_aliases 0.2.2",
+ "libc",
+]
+
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -3756,6 +3974,15 @@ dependencies = [
"objc2-foundation 0.3.2",
]
+[[package]]
+name = "oid-registry"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+dependencies = [
+ "asn1-rs",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -3945,6 +4172,16 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "pem"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
+dependencies = [
+ "base64 0.23.1",
+ "serde_core",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -4185,6 +4422,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -4207,6 +4455,12 @@ dependencies = [
"universal-hash 0.5.1",
]
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
[[package]]
name = "portable-pty"
version = "0.9.0"
@@ -4506,7 +4760,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -4564,6 +4818,20 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "rcgen"
+version = "0.14.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
+dependencies = [
+ "pem 4.0.0",
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "x509-parser",
+ "yasna",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -4801,6 +5069,15 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rusticata-macros"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+dependencies = [
+ "nom 7.1.3",
+]
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -6760,6 +7037,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -7066,17 +7352,47 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
+[[package]]
+name = "x509-parser"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
+dependencies = [
+ "asn1-rs",
+ "data-encoding",
+ "der-parser",
+ "lazy_static",
+ "nom 7.1.3",
+ "oid-registry",
+ "ring",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -7103,6 +7419,16 @@ dependencies = [
"web-time",
]
+[[package]]
+name = "yasna"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
+dependencies = [
+ "bit-vec 0.9.1",
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 24de7d6368..65d0437fed 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -1455,6 +1455,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix 0.31.3",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "borrow-or-share"
version = "0.2.4"
@@ -1671,6 +1696,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -1683,6 +1719,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -1690,9 +1739,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
]
[[package]]
@@ -1744,6 +1793,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -2610,7 +2660,7 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
@@ -2618,7 +2668,7 @@ dependencies = [
"sha2 0.10.9",
"tempfile",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
@@ -2674,6 +2724,41 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "cua-mesh",
+ "cua-proto",
+ "cua-spacesd-client",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "tempfile",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite 0.29.0",
+ "tracing",
+ "tracing-subscriber",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-mock-llm"
version = "0.1.0"
@@ -2804,6 +2889,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -3204,6 +3290,21 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -3213,7 +3314,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -3797,6 +3898,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -4728,6 +4835,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -4827,6 +4944,28 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -6436,6 +6575,17 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -6816,7 +6966,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -9932,6 +10082,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -10321,13 +10480,25 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.toml
index bf428e22fd..c470eb0bdf 100644
--- a/libs/cua/Cargo.toml
+++ b/libs/cua/Cargo.toml
@@ -48,6 +48,9 @@ members = [
"crates/cua-machine-seal",
# Host setup (unattended access) and the cua-relay directory client.
"crates/cua-host",
+ # The WireGuard®-based in-app mesh: userspace tunnels, NAT traversal,
+ # the encrypted relay client and QUIC streams between peers.
+ "crates/cua-mesh",
# Media plane shared with cua-spacesd (wire format, transport, codecs)
# and the media clients. The driver depends on these, never the reverse.
"crates/cua-media-protocol",
@@ -158,6 +161,7 @@ cua-disk = { path = "crates/cua-disk", version = "0.1.0" }
cua-sandbox-core = { path = "crates/cua-sandbox-core", version = "0.1.0" }
cua-contrib = { path = "crates/cua-contrib", version = "0.1.0", default-features = false }
cua-host = { path = "crates/cua-host", version = "0.1.0" }
+cua-mesh = { path = "crates/cua-mesh", version = "0.1.0" }
cua-daemon = { path = "crates/cua-daemon", version = "0.1.0", default-features = false }
cua-auth = { path = "crates/cua-auth", version = "0.1.0" }
cua-agent-setup = { path = "crates/cua-agent-setup", version = "0.1.0" }
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rs
index f42cff33db..130e6c9fbe 100644
--- a/libs/cua/crates/cua-host/src/host.rs
+++ b/libs/cua/crates/cua-host/src/host.rs
@@ -292,6 +292,20 @@ pub struct HostConfig {
/// [`Host::resume_signed_in`] can bring it back.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub paused_signed_out: bool,
+ /// `CUA_MESH` as it was set where `cua host setup` ran (an explicit
+ /// opt-in to the WireGuard®-based mesh, or out of it): passed on to the
+ /// service. Unset, the service follows its own default (off unless the
+ /// Cua Spaces app's channel turns it on).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mesh: Option<String>,
+}
+
+/// `CUA_MESH` where setup runs, when set.
+fn mesh_env() -> Option<String> {
+ std::env::var("CUA_MESH")
+ .ok()
+ .map(|v| v.trim().to_owned())
+ .filter(|v| !v.is_empty())
}
/// A macOS privacy pane the user must grant the driver in.
@@ -903,10 +917,14 @@ impl Host {
"--no-mcp".into(),
]);
}
+ let mut env = vec![("CUA_ENV_LOG".into(), "info".into())];
+ if let Some(mesh) = &config.mesh {
+ env.push(("CUA_MESH".into(), mesh.clone()));
+ }
ServiceSpec {
program: config.driver_bin.clone(),
args,
- env: vec![("CUA_ENV_LOG".into(), "info".into())],
+ env,
log_path: p.log(),
working_dir: user_home(&self.home),
}
@@ -988,6 +1006,7 @@ impl Host {
sharing: true,
share_desktop: opts.share_desktop,
provide_spaces: opts.provide_spaces,
+ mesh: mesh_env(),
..Default::default()
};
if opts.download_first {
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 2117a7fea6..20e4f4dc84 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -243,8 +243,9 @@ pub struct RelayInfo {
/// Public base URL.
#[serde(default)]
pub public_url: String,
- /// Assertion issuer.
- #[serde(default)]
+ /// Assertion issuer (empty on a static-token relay, which sends
+ /// `null`).
+ #[serde(default, deserialize_with = "null_as_empty")]
pub issuer: String,
/// Accepts account tokens.
#[serde(default)]
@@ -252,6 +253,23 @@ pub struct RelayInfo {
/// Accepts static relay tokens.
#[serde(default)]
pub static_tokens: bool,
+ /// The WireGuard®-based mesh this relay coordinates, if any.
+ #[serde(default)]
+ pub mesh: Option<RelayMeshInfo>,
+}
+
+fn null_as_empty<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
+ Ok(Option::<String>::deserialize(d)?.unwrap_or_default())
+}
+
+/// What a relay says about its mesh (`/v1/info` `mesh`).
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RelayMeshInfo {
+ /// Mesh protocol version.
+ pub version: u32,
+ /// STUN servers it advertises.
+ #[serde(default)]
+ pub stun: Vec<String>,
}
#[derive(Deserialize)]
@@ -898,6 +916,19 @@ fn sharing_default() -> bool {
#[cfg(test)]
mod tests {
+ #[test]
+ fn a_static_relays_info_parses() {
+ // A static-token relay has no OIDC issuer: `null`. Rejecting it
+ // kept self-hosted relays' clients off their mesh (CUA-1426).
+ let info: RelayInfo = serde_json::from_str(
+ r#"{"account_auth":false,"issuer":null,"mesh":{"stun":[],"version":1},"public_url":"http://relay","state_writable":true,"static_tokens":true}"#,
+ )
+ .unwrap();
+ assert_eq!(info.issuer, "");
+ assert!(info.static_tokens);
+ assert_eq!(info.mesh.map(|m| m.version), Some(1));
+ }
+
use super::*;
#[test]
diff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rs
index 8161e7270d..4071234a35 100644
--- a/libs/cua/crates/cua-host/src/tests.rs
+++ b/libs/cua/crates/cua-host/src/tests.rs
@@ -1613,3 +1613,38 @@ async fn a_pause_keeps_the_owners_choice_and_skips_direct_mode() {
assert!(!s.paused_signed_out);
assert!(g.manager.calls.lock().unwrap().is_empty());
}
+
+/// The mesh stays off on a hosted machine unless asked for: a setup without
+/// `CUA_MESH` installs the same service as before, and an explicit
+/// `CUA_MESH` at setup reaches the service.
+#[test]
+fn the_service_gets_cua_mesh_only_when_setup_was_given_it() {
+ let home = tempfile::tempdir().unwrap();
+ let host = Host::new(home.path());
+ let config = crate::HostConfig {
+ mode: "relay".into(),
+ relay_url: Some("https://relay.example".into()),
+ machine_id: Some("machine-0001".into()),
+ ..Default::default()
+ };
+ let spec = host.service_spec(&config);
+ assert_eq!(
+ spec.env,
+ vec![("CUA_ENV_LOG".to_string(), "info".to_string())]
+ );
+ let json = serde_json::to_string(&config).unwrap();
+ assert!(!json.contains("mesh"), "{json}");
+
+ let config = crate::HostConfig {
+ mesh: Some("prefer".into()),
+ ..config
+ };
+ let spec = host.service_spec(&config);
+ assert!(
+ spec.env
+ .contains(&("CUA_MESH".to_string(), "prefer".to_string()))
+ );
+ let back: crate::HostConfig =
+ serde_json::from_str(&serde_json::to_string(&config).unwrap()).unwrap();
+ assert_eq!(back.mesh.as_deref(), Some("prefer"));
+}
diff --git a/libs/cua/crates/cua-mesh/Cargo.toml b/libs/cua/crates/cua-mesh/Cargo.toml
new file mode 100644
index 0000000000..c3423b9411
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/Cargo.toml
@@ -0,0 +1,53 @@
+[package]
+name = "cua-mesh"
+description = "WireGuard®-based in-app mesh for Cua Spaces: userspace tunnels, NAT traversal, an encrypted fallback relay client and QUIC streams between peers"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+license.workspace = true
+repository.workspace = true
+publish = false
+
+[features]
+default = []
+# An in-process coordinator and relay for tests (MIT, never the real one).
+testing = []
+
+[dependencies]
+# WireGuard (BSD-3-Clause): only the Noise/WireGuard protocol state machine
+# (`boringtun::noise`); no TUN device, no root, no kernel module.
+boringtun = { version = "0.7.1", default-features = false }
+quinn = { workspace = true }
+rustls = { workspace = true }
+# The coordinator connection's TLS roots (explicit, see coord.rs).
+webpki-roots = "1"
+rcgen = { version = "0.14", default-features = false, features = ["crypto", "ring", "pem"] }
+tokio = { workspace = true, features = ["io-util", "macros", "net", "rt", "sync", "time"] }
+tokio-tungstenite = { workspace = true }
+futures-util = { workspace = true, features = ["sink"] }
+http = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+base64 = { workspace = true }
+hex = { workspace = true }
+sha2 = { workspace = true }
+hmac = "0.12"
+hkdf = "0.12"
+chacha20poly1305 = "0.10"
+rand = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+url = { workspace = true }
+if-addrs = "0.13"
+socket2 = { version = "0.6", features = ["all"] }
+bytes = { workspace = true }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util"] }
+tempfile = { workspace = true }
+tracing-subscriber = { workspace = true }
+cua-mesh = { path = ".", features = ["testing"] }
+# examples/mesh-bench.rs
+cua-spacesd-client.workspace = true
+cua-proto = { workspace = true, features = ["client"] }
diff --git a/libs/cua/crates/cua-mesh/examples/mesh-bench.rs b/libs/cua/crates/cua-mesh/examples/mesh-bench.rs
new file mode 100644
index 0000000000..a229a47467
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/examples/mesh-bench.rs
@@ -0,0 +1,386 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Measures a machine's spacesd over the mesh against the relay's HTTPS
+//! path: connect time, call round trips, download throughput, and how
+//! often (and how fast) the mesh finds a direct path.
+//!
+//! ```text
+//! mesh-bench --relay https://relay.example --machine <id> --env-token <t> \
+//! [--path mesh|relay|both] [--rtt 200] [--mib 256] [--direct-trials 10]
+//! ```
+//!
+//! Static-token relays only (the env token is the credential on both
+//! paths). Prints one JSON object per measurement.
+
+use std::time::{Duration, Instant};
+
+use cua_mesh::dialer::{Dialer, SESSION_HEADER};
+use cua_proto::env::v1 as pb;
+use cua_spacesd_client::{ConnectOptions, SpacesdClient, TransportPreference};
+
+struct Args {
+ relay: String,
+ machine: String,
+ token: String,
+ path: String,
+ rtt: usize,
+ mib: u64,
+ direct_trials: usize,
+ hold_secs: u64,
+ rebind_at: Vec<u64>,
+ relay_only: bool,
+ serve_secs: u64,
+ tunnel_port: u16,
+}
+
+fn args() -> Args {
+ let mut a = Args {
+ relay: String::new(),
+ machine: String::new(),
+ token: std::env::var("CUA_ENV_TOKEN").unwrap_or_default(),
+ path: "both".into(),
+ rtt: 200,
+ mib: 256,
+ direct_trials: 0,
+ hold_secs: 0,
+ rebind_at: Vec::new(),
+ relay_only: false,
+ serve_secs: 0,
+ tunnel_port: 0,
+ };
+ let mut it = std::env::args().skip(1);
+ while let Some(k) = it.next() {
+ let mut v = || it.next().expect("value");
+ match k.as_str() {
+ "--relay" => a.relay = v(),
+ "--machine" => a.machine = v(),
+ "--env-token" => a.token = v(),
+ "--path" => a.path = v(),
+ "--rtt" => a.rtt = v().parse().expect("number"),
+ "--mib" => a.mib = v().parse().expect("number"),
+ "--direct-trials" => a.direct_trials = v().parse().expect("number"),
+ "--hold" => a.hold_secs = v().parse().expect("number"),
+ // Move to new UDP ports at these seconds of --hold (a NAT
+ // rebinding, as after a network change).
+ "--rebind-at" => a.rebind_at.push(v().parse().expect("number")),
+ "--relay-only" => a.relay_only = true,
+ // Keep a loopback route to the machine open for other tools
+ // (the streaming bench): prints its addresses, then waits.
+ "--serve" => a.serve_secs = v().parse().expect("number"),
+ // With --serve: also forward this guest TCP port (spacesd's
+ // ticketed tunnel, over the same path).
+ "--tunnel-port" => a.tunnel_port = v().parse().expect("number"),
+ other => panic!("unknown argument {other}"),
+ }
+ }
+ assert!(!a.relay.is_empty() && !a.machine.is_empty() && !a.token.is_empty());
+ a
+}
+
+fn pct(v: &mut [f64], p: f64) -> f64 {
+ if v.is_empty() {
+ return f64::NAN;
+ }
+ v.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ v[((v.len() as f64 - 1.0) * p).round() as usize]
+}
+
+async fn connect(options: ConnectOptions) -> SpacesdClient {
+ SpacesdClient::connect(options.transport(TransportPreference::Native))
+ .await
+ .expect("connect")
+}
+
+async fn measure(label: &str, client: &SpacesdClient, a: &Args, extra: serde_json::Value) {
+ let mut rtts = Vec::with_capacity(a.rtt);
+ for _ in 0..a.rtt {
+ let t = Instant::now();
+ client
+ .system()
+ .health(pb::HealthRequest {})
+ .await
+ .expect("health");
+ rtts.push(t.elapsed().as_secs_f64() * 1000.0);
+ }
+ // Download and upload a file of `mib` MiB of random bytes through the
+ // files API (chunked, SHA-256 verified): a lossless transfer.
+ let bytes = a.mib << 20;
+ let remote = format!("/tmp/wgm-bench-{}.bin", std::process::id());
+ let mut stream = client
+ .process()
+ .start_process(pb::StartProcessRequest {
+ config: Some(pb::ProcessConfig {
+ command: "/bin/sh".into(),
+ args: vec![
+ "-c".into(),
+ format!("head -c {bytes} /dev/urandom > {remote}"),
+ ],
+ ..Default::default()
+ }),
+ ..Default::default()
+ })
+ .await
+ .expect("start")
+ .into_inner();
+ while let Some(m) = stream.message().await.expect("stream") {
+ if matches!(
+ m.event.and_then(|e| e.event),
+ Some(pb::process_event::Event::End(_))
+ ) {
+ break;
+ }
+ }
+ // The file is complete once it has every byte (bounded wait).
+ for _ in 0..600 {
+ if client.stat(&remote).await.map(|e| e.size).unwrap_or(0) >= bytes {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let t = Instant::now();
+ let data = client.download(&remote).await.expect("download");
+ let down_secs = t.elapsed().as_secs_f64();
+ let got = data.len() as u64;
+ let t = Instant::now();
+ client
+ .upload(
+ &format!("{remote}.up"),
+ data,
+ cua_spacesd_client::UploadOptions::default(),
+ )
+ .await
+ .expect("upload");
+ let up_secs = t.elapsed().as_secs_f64();
+ let _ = client.remove(&remote, false).await;
+ let _ = client.remove(&format!("{remote}.up"), false).await;
+ let secs = down_secs;
+ let out = serde_json::json!({
+ "path": label,
+ "rtt_ms_p50": pct(&mut rtts.clone(), 0.5),
+ "rtt_ms_p95": pct(&mut rtts.clone(), 0.95),
+ "rtt_ms_min": pct(&mut rtts.clone(), 0.0),
+ "download_bytes": got,
+ "download_mbit_s": got as f64 * 8.0 / secs / 1e6,
+ "upload_mbit_s": got as f64 * 8.0 / up_secs / 1e6,
+ "extra": extra,
+ });
+ println!("{out}");
+}
+
+#[tokio::main]
+async fn main() {
+ let _ = tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .with_writer(std::io::stderr)
+ .try_init();
+ let a = args();
+ if a.serve_secs > 0 {
+ serve(&a).await;
+ return;
+ }
+ if a.path == "relay" || a.path == "both" {
+ let t = Instant::now();
+ let url = format!("{}/m/{}", a.relay.trim_end_matches('/'), a.machine);
+ let c = connect(ConnectOptions::parse(&url).unwrap().token(a.token.clone())).await;
+ c.health().await.expect("health");
+ let connect_ms = t.elapsed().as_secs_f64() * 1000.0;
+ measure(
+ "relay-https",
+ &c,
+ &a,
+ serde_json::json!({"connect_ms": connect_ms}),
+ )
+ .await;
+ }
+ if a.path == "mesh" || a.path == "both" {
+ let t = Instant::now();
+ let dialer = Dialer::start(
+ &a.relay,
+ cua_mesh::static_auth(Vec::new()),
+ None,
+ Duration::from_secs(15),
+ )
+ .await
+ .expect("mesh");
+ let route = dialer
+ .route(&a.machine, Some(&a.token), Duration::from_secs(10))
+ .await
+ .expect("route");
+ let mut o = ConnectOptions::parse(&format!("http://{}", route.local))
+ .unwrap()
+ .token(a.token.clone());
+ if let Some(s) = &route.session {
+ o = o.header(SESSION_HEADER, s.clone());
+ }
+ let c = connect(o).await;
+ c.health().await.expect("health");
+ let connect_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let path_at_connect = dialer.mesh().path(&route.peer).map(|p| p.to_string());
+ // Time to a direct path, with traffic flowing.
+ let mut direct_ms = None;
+ for _ in 0..150 {
+ if matches!(
+ dialer.mesh().path(&route.peer),
+ Some(cua_mesh::Path::Direct(_))
+ ) {
+ direct_ms = Some(t.elapsed().as_secs_f64() * 1000.0);
+ break;
+ }
+ let _ = c.system().health(pb::HealthRequest {}).await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let path = dialer.mesh().path(&route.peer).map(|p| p.to_string());
+ let label = match dialer.mesh().path(&route.peer) {
+ Some(cua_mesh::Path::Direct(_)) => "mesh-direct",
+ _ => "mesh-relayed",
+ };
+ measure(
+ label,
+ &c,
+ &a,
+ serde_json::json!({
+ "connect_ms": connect_ms,
+ "path_at_connect": path_at_connect,
+ "time_to_direct_ms": direct_ms,
+ "path": path,
+ }),
+ )
+ .await;
+ let st = dialer.mesh().status();
+ println!("{}", serde_json::json!({"status": st}));
+ if a.hold_secs > 0 {
+ // Keep a call going every second (outage tests watch this).
+ if a.relay_only {
+ dialer.mesh().set_relay_only(true);
+ }
+ for i in 0..a.hold_secs {
+ if a.rebind_at.contains(&i) {
+ dialer.mesh().rebind().await.expect("rebind");
+ println!("{}", serde_json::json!({"t": i, "event": "rebind"}));
+ }
+ let t = Instant::now();
+ let ok = tokio::time::timeout(
+ Duration::from_secs(5),
+ c.system().health(pb::HealthRequest {}),
+ )
+ .await
+ .map(|r| r.is_ok())
+ .unwrap_or(false);
+ println!(
+ "{}",
+ serde_json::json!({
+ "t": i,
+ "ok": ok,
+ "ms": t.elapsed().as_secs_f64() * 1000.0,
+ "path": dialer.mesh().path(&route.peer).map(|p| p.to_string()),
+ "coordinator": dialer.mesh().control_state().connected,
+ })
+ );
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ }
+ }
+ // Direct-path rate: fresh nodes, each paired anew.
+ for trial in 0..a.direct_trials {
+ let t = Instant::now();
+ let dialer = Dialer::start(
+ &a.relay,
+ cua_mesh::static_auth(Vec::new()),
+ None,
+ Duration::from_secs(15),
+ )
+ .await
+ .expect("mesh");
+ let ready_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let route = dialer
+ .route(&a.machine, Some(&a.token), Duration::from_secs(10))
+ .await
+ .expect("route");
+ let routed_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let c = connect(
+ ConnectOptions::parse(&format!("http://{}", route.local))
+ .unwrap()
+ .token(a.token.clone()),
+ )
+ .await;
+ let connected_ms = t.elapsed().as_secs_f64() * 1000.0;
+ let mut direct_ms = None;
+ for _ in 0..150 {
+ let _ = c.system().health(pb::HealthRequest {}).await;
+ if matches!(
+ dialer.mesh().path(&route.peer),
+ Some(cua_mesh::Path::Direct(_))
+ ) {
+ direct_ms = Some(t.elapsed().as_secs_f64() * 1000.0);
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ println!(
+ "{}",
+ serde_json::json!({"trial": trial, "direct": direct_ms.is_some(), "time_to_direct_ms": direct_ms,
+ "ready_ms": ready_ms, "paired_and_forwarded_ms": routed_ms, "connected_ms": connected_ms,
+ "path": dialer.mesh().path(&route.peer).map(|p| p.to_string())})
+ );
+ }
+}
+
+/// `--serve`: a route to the machine (the mesh, or the relay's HTTPS path
+/// with `--path relay`) for another tool, plus a tunnel to a guest port.
+async fn serve(a: &Args) {
+ let mut dialer = None;
+ let (url, session) = if a.path == "relay" {
+ (
+ format!("{}/m/{}", a.relay.trim_end_matches('/'), a.machine),
+ None,
+ )
+ } else {
+ let d = Dialer::start(
+ &a.relay,
+ cua_mesh::static_auth(Vec::new()),
+ None,
+ Duration::from_secs(15),
+ )
+ .await
+ .expect("mesh");
+ let route = d
+ .route(&a.machine, Some(&a.token), Duration::from_secs(10))
+ .await
+ .expect("route");
+ let url = format!("http://{}", route.local);
+ dialer = Some(d);
+ (url, route.session)
+ };
+ let mut o = ConnectOptions::parse(&url).unwrap().token(a.token.clone());
+ if let Some(s) = &session {
+ o = o.header(SESSION_HEADER, s.clone());
+ }
+ let c = connect(o).await;
+ c.health().await.expect("health");
+ let tunnel = if a.tunnel_port > 0 {
+ Some(
+ c.forward_tcp(cua_spacesd_client::ForwardOptions::new(a.tunnel_port))
+ .await
+ .expect("tunnel"),
+ )
+ } else {
+ None
+ };
+ println!(
+ "{}",
+ serde_json::json!({
+ "url": url,
+ "tunnel": tunnel.as_ref().map(|t| t.local_addr().to_string()),
+ "path": dialer.as_ref().and_then(|d| {
+ d.mesh().machine(&a.machine).and_then(|p| d.mesh().path(&p.node_key)).map(|p| p.to_string())
+ }),
+ })
+ );
+ for _ in 0..a.serve_secs {
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ if let Some(d) = &dialer {
+ println!("{}", serde_json::json!({"status": d.mesh().status()}));
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/coord.rs b/libs/cua/crates/cua-mesh/src/coord.rs
new file mode 100644
index 0000000000..6d2b3eadfe
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/coord.rs
@@ -0,0 +1,644 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The node's connection to the coordinator: control messages and the
+//! encrypted relay, over one WebSocket that reconnects on its own.
+//!
+//! The coordinator going away does not end sessions: peers keep their
+//! WireGuard sessions and their last network map, so direct paths carry on
+//! untouched and relayed traffic resumes when the connection comes back.
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use futures_util::{SinkExt as _, StreamExt as _};
+use tokio::sync::{mpsc, oneshot, watch};
+use tokio_tungstenite::tungstenite::Message as WsMessage;
+use tokio_tungstenite::tungstenite::client::IntoClientRequest as _;
+
+use crate::engine::Engine;
+use crate::key::{NodeIdentity, PublicKey};
+use crate::proto::{self, ClientMsg, Mode, NodeKind, PeerUsage, ServerMsg};
+use crate::{Error, Result};
+
+/// Credentials for the coordinator connection, fetched before every
+/// (re)connect: header name and value pairs.
+pub type AuthFuture =
+ Pin<Box<dyn Future<Output = std::result::Result<Vec<(String, String)>, String>> + Send>>;
+/// Produces [`AuthFuture`]s.
+pub type AuthProvider = Arc<dyn Fn() -> AuthFuture + Send + Sync>;
+
+/// A static-mode pairing request a machine decides on: `(client key, ts,
+/// proof)`; true accepts.
+pub type PairVerifier = Arc<dyn Fn(&PublicKey, u64, &str) -> bool + Send + Sync>;
+
+/// The control connection's state, for status and waiting.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct ControlState {
+ /// Connected and welcomed.
+ pub connected: bool,
+ /// Received at least one network map since start.
+ pub has_netmap: bool,
+ /// Account or static (once welcomed).
+ pub mode: Option<Mode>,
+ /// The coordinator's protocol version.
+ pub version: Option<u32>,
+ /// STUN servers it advertised.
+ pub stun: Vec<String>,
+ /// The last error, if the connection is down.
+ pub last_error: Option<String>,
+ /// Why the coordinator turned this node away (HTTP 401 or 403: its
+ /// device was revoked or its account may no longer use the mesh),
+ /// until it is welcomed again. Streams then fail at once with this
+ /// reason instead of waiting on peers that dropped this node.
+ pub denied: Option<String>,
+ /// The relay answered that it has no mesh coordinator (it was turned
+ /// off), until it is welcomed again.
+ pub unsupported: bool,
+ /// Connections made since start.
+ pub connects: u64,
+ /// The [`ClientMsg::Usage`] version the coordinator meters (0: none).
+ pub usage: u32,
+}
+
+/// A machine's stream usage: the snapshot to report, and the one this
+/// connection last sent.
+#[derive(Default)]
+struct UsageOut {
+ current: Vec<PeerUsage>,
+ sent: Option<Vec<PeerUsage>>,
+}
+
+type PairWaiter = oneshot::Sender<std::result::Result<(), String>>;
+
+pub(crate) struct Control {
+ pub(crate) state: watch::Sender<ControlState>,
+ out: Mutex<Option<mpsc::Sender<ClientMsg>>>,
+ pair_waiters: Mutex<HashMap<String, Vec<PairWaiter>>>,
+ endpoints: Mutex<Vec<std::net::SocketAddr>>,
+ usage: Mutex<UsageOut>,
+}
+
+pub(crate) struct ControlConfig {
+ pub url: String,
+ pub kind: NodeKind,
+ pub name: String,
+ pub auth: AuthProvider,
+ pub pair_verifier: Option<PairVerifier>,
+ /// Static mode, machines: peers this machine approved (filters netmaps).
+ pub approved: Option<Arc<crate::node::Approved>>,
+ /// Forgotten by the coordinator on disconnect.
+ pub ephemeral: bool,
+}
+
+impl Control {
+ pub(crate) fn new() -> Arc<Self> {
+ Arc::new(Self {
+ state: watch::channel(ControlState::default()).0,
+ out: Mutex::new(None),
+ pair_waiters: Mutex::new(HashMap::new()),
+ endpoints: Mutex::new(Vec::new()),
+ usage: Mutex::new(UsageOut::default()),
+ })
+ }
+
+ /// Sets the stream usage to report, and sends it when the coordinator
+ /// meters it and it differs from what this connection last sent. A
+ /// coordinator that does not meter is sent nothing.
+ pub(crate) fn set_usage(&self, mut peers: Vec<PeerUsage>) {
+ peers.truncate(proto::MAX_USAGE_PEERS);
+ let mut usage = self.usage.lock().expect("usage");
+ usage.current = peers;
+ self.flush_usage(&mut usage);
+ }
+
+ /// A new connection was welcomed: what it last sent is gone.
+ fn usage_reconnected(&self) {
+ let mut usage = self.usage.lock().expect("usage");
+ usage.sent = None;
+ self.flush_usage(&mut usage);
+ }
+
+ fn flush_usage(&self, usage: &mut UsageOut) {
+ let (connected, version) = {
+ let s = self.state.borrow();
+ (s.connected, s.usage)
+ };
+ if !connected || version < proto::USAGE_VERSION {
+ return;
+ }
+ let unchanged = match &usage.sent {
+ Some(sent) => *sent == usage.current,
+ // A fresh connection starts with nothing open.
+ None => usage.current.is_empty(),
+ };
+ if unchanged {
+ return;
+ }
+ let msg = ClientMsg::Usage {
+ v: proto::USAGE_VERSION,
+ peers: usage.current.clone(),
+ };
+ // A full queue: tried again on the next change or snapshot.
+ if self.send(msg) {
+ usage.sent = Some(usage.current.clone());
+ }
+ }
+
+ pub(crate) fn send(&self, msg: ClientMsg) -> bool {
+ match self.out.lock().expect("out").as_ref() {
+ Some(tx) => tx.try_send(msg).is_ok(),
+ None => false,
+ }
+ }
+
+ pub(crate) fn set_endpoints(&self, endpoints: Vec<std::net::SocketAddr>) {
+ let changed = {
+ let mut e = self.endpoints.lock().expect("endpoints");
+ let changed = *e != endpoints;
+ *e = endpoints.clone();
+ changed
+ };
+ if changed {
+ self.send(ClientMsg::Endpoints { endpoints });
+ }
+ }
+
+ pub(crate) async fn pair(
+ &self,
+ machine_id: &str,
+ ts: u64,
+ proof: String,
+ timeout: Duration,
+ ) -> Result<()> {
+ let (tx, rx) = oneshot::channel();
+ self.pair_waiters
+ .lock()
+ .expect("pair")
+ .entry(machine_id.to_owned())
+ .or_default()
+ .push(tx);
+ if !self.send(ClientMsg::Pair {
+ machine_id: machine_id.to_owned(),
+ ts,
+ proof,
+ }) {
+ return Err(Error::Unreachable(
+ "not connected to the coordinator".into(),
+ ));
+ }
+ match tokio::time::timeout(timeout, rx).await {
+ Ok(Ok(Ok(()))) => Ok(()),
+ Ok(Ok(Err(reason))) => Err(Error::Refused(reason)),
+ _ => Err(Error::Unreachable(format!(
+ "no pairing answer from {machine_id} within {timeout:?}"
+ ))),
+ }
+ }
+
+ fn finish_pair(&self, machine_id: &str, result: std::result::Result<(), String>) {
+ if let Some(waiters) = self.pair_waiters.lock().expect("pair").remove(machine_id) {
+ for w in waiters {
+ let _ = w.send(result.clone());
+ }
+ }
+ }
+}
+
+/// The coordinator's connect URL (`ws(s)://<base>/v1/mesh/connect`).
+pub fn connect_url(base: &str) -> Result<String> {
+ let mut url = url::Url::parse(base).map_err(|e| Error::Protocol(format!("{base:?}: {e}")))?;
+ let scheme = match url.scheme() {
+ "https" | "wss" => "wss",
+ "http" | "ws" => "ws",
+ other => return Err(Error::Protocol(format!("unsupported scheme {other:?}"))),
+ };
+ url.set_scheme(scheme)
+ .map_err(|_| Error::Protocol("cannot set scheme".into()))?;
+ let path = url.path().trim_end_matches('/').to_owned();
+ url.set_path(&format!("{path}{}", proto::CONNECT_PATH));
+ Ok(url.to_string())
+}
+
+fn tls_connector() -> tokio_tungstenite::Connector {
+ let mut roots = rustls::RootCertStore::empty();
+ roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+ let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
+ rustls::crypto::ring::default_provider(),
+ ))
+ .with_protocol_versions(rustls::DEFAULT_VERSIONS)
+ .expect("the ring provider supports the default TLS versions")
+ .with_root_certificates(roots)
+ .with_no_client_auth();
+ tokio_tungstenite::Connector::Rustls(Arc::new(cfg))
+}
+
+/// The reason, when `e` is the coordinator refusing this node's
+/// credentials (HTTP 401 or 403) rather than a transient failure (a
+/// restarting relay answers 502 or 503 and is retried as before).
+fn denial(e: &Error) -> Option<String> {
+ match e {
+ Error::Refused(m) if m.starts_with("HTTP 401") || m.starts_with("HTTP 403") => {
+ Some(m.clone())
+ }
+ _ => None,
+ }
+}
+
+fn backoff(attempt: u32) -> Duration {
+ let base = Duration::from_millis(250)
+ .saturating_mul(1 << attempt.min(6))
+ .min(Duration::from_secs(10));
+ base.mul_f64(rand::random_range(0.5..=1.0))
+}
+
+pub(crate) async fn run(
+ cfg: ControlConfig,
+ control: Arc<Control>,
+ engine: Arc<Engine>,
+ identity: NodeIdentity,
+ shutdown: tokio_util_cancel::Token,
+) {
+ let mut attempt = 0u32;
+ loop {
+ if shutdown.is_cancelled() {
+ return;
+ }
+ let started = std::time::Instant::now();
+ let result = session(&cfg, &control, &engine, &identity, &shutdown).await;
+ engine.set_relay(None);
+ *control.out.lock().expect("out") = None;
+ control.state.send_modify(|s| {
+ s.connected = false;
+ s.last_error = result.as_ref().err().map(ToString::to_string);
+ if let Some(reason) = result.as_ref().err().and_then(denial) {
+ s.denied = Some(reason);
+ }
+ if matches!(result, Err(Error::Unsupported(_))) {
+ s.unsupported = true;
+ }
+ });
+ if let Err(e) = &result {
+ tracing::info!(error = %e, "mesh coordinator connection ended");
+ if matches!(e, Error::Refused(_)) {
+ attempt = attempt.max(5);
+ }
+ }
+ if started.elapsed() > Duration::from_secs(30) {
+ attempt = 0;
+ }
+ let delay = backoff(attempt);
+ attempt = attempt.saturating_add(1);
+ tokio::select! {
+ _ = tokio::time::sleep(delay) => {}
+ _ = shutdown.cancelled() => return,
+ }
+ }
+}
+
+async fn session(
+ cfg: &ControlConfig,
+ control: &Arc<Control>,
+ engine: &Arc<Engine>,
+ identity: &NodeIdentity,
+ shutdown: &tokio_util_cancel::Token,
+) -> Result<()> {
+ let url = connect_url(&cfg.url)?;
+ let mut request = url
+ .as_str()
+ .into_client_request()
+ .map_err(|e| Error::Protocol(e.to_string()))?;
+ let headers = (cfg.auth)().await.map_err(Error::Refused)?;
+ for (k, v) in headers {
+ let name = http::HeaderName::from_bytes(k.as_bytes())
+ .map_err(|e| Error::Protocol(e.to_string()))?;
+ let mut value =
+ http::HeaderValue::from_str(&v).map_err(|e| Error::Protocol(e.to_string()))?;
+ value.set_sensitive(true);
+ request.headers_mut().insert(name, value);
+ }
+ // An explicit TLS setup (ring, the web PKI roots): never the
+ // process-wide default provider, which a host process may leave
+ // ambiguous. No Nagle: relayed packets and control frames are small.
+ let connect = tokio_tungstenite::connect_async_tls_with_config(
+ request,
+ None,
+ true,
+ Some(tls_connector()),
+ );
+ let (ws, _) = match tokio::time::timeout(Duration::from_secs(15), connect).await {
+ Ok(Ok(v)) => v,
+ Ok(Err(tokio_tungstenite::tungstenite::Error::Http(resp))) => {
+ let status = resp.status();
+ let body = resp
+ .body()
+ .as_ref()
+ .map(|b| {
+ String::from_utf8_lossy(b)
+ .chars()
+ .take(200)
+ .collect::<String>()
+ })
+ .unwrap_or_default();
+ return Err(if status.as_u16() == 404 {
+ Error::Unsupported("the relay has no mesh coordinator".into())
+ } else {
+ Error::Refused(format!("HTTP {status}: {body}"))
+ });
+ }
+ Ok(Err(e)) => return Err(Error::Unreachable(e.to_string())),
+ Err(_) => return Err(Error::Unreachable("connect timed out".into())),
+ };
+ let (mut sink, mut stream) = ws.split();
+
+ // Challenge, hello, welcome.
+ let first = tokio::time::timeout(Duration::from_secs(10), stream.next())
+ .await
+ .map_err(|_| Error::Unreachable("no challenge".into()))?;
+ let (server_key, nonce, server_version) = match first {
+ Some(Ok(WsMessage::Text(t))) => match serde_json::from_str::<ServerMsg>(&t) {
+ Ok(ServerMsg::Challenge {
+ version,
+ server_key,
+ nonce,
+ }) => (server_key, nonce, version),
+ Ok(ServerMsg::Error { message }) => return Err(Error::Refused(message)),
+ _ => return Err(Error::Protocol("expected a challenge".into())),
+ },
+ _ => return Err(Error::Protocol("expected a challenge".into())),
+ };
+ if server_version != proto::VERSION {
+ return Err(Error::Unsupported(format!(
+ "coordinator speaks mesh v{server_version}, this node v{}",
+ proto::VERSION
+ )));
+ }
+ let endpoints = control.endpoints.lock().expect("endpoints").clone();
+ let hello = ClientMsg::Hello {
+ version: proto::VERSION,
+ kind: cfg.kind,
+ node_key: identity.public(),
+ disco_key: identity.disco.public(),
+ quic_pin: identity.cert_pin(),
+ name: cfg.name.clone(),
+ endpoints,
+ proof: proto::hello_proof(&identity.node, &server_key, &nonce),
+ ephemeral: cfg.ephemeral,
+ };
+ sink.send(WsMessage::Text(
+ serde_json::to_string(&hello).expect("json").into(),
+ ))
+ .await
+ .map_err(|e| Error::Unreachable(e.to_string()))?;
+ let welcome = tokio::time::timeout(Duration::from_secs(10), stream.next())
+ .await
+ .map_err(|_| Error::Unreachable("no welcome".into()))?;
+ let (mode, stun, version, usage) = match welcome {
+ Some(Ok(WsMessage::Text(t))) => match serde_json::from_str::<ServerMsg>(&t) {
+ Ok(ServerMsg::Welcome {
+ version,
+ addr,
+ mode,
+ stun,
+ usage,
+ }) => {
+ if addr != identity.addr() {
+ return Err(Error::Protocol(
+ "coordinator assigned a foreign address".into(),
+ ));
+ }
+ (mode, stun, version, usage)
+ }
+ Ok(ServerMsg::Error { message }) => return Err(Error::Refused(message)),
+ _ => return Err(Error::Protocol("expected a welcome".into())),
+ },
+ _ => return Err(Error::Protocol("expected a welcome".into())),
+ };
+
+ let (out_tx, mut out_rx) = mpsc::channel::<ClientMsg>(64);
+ let (relay_tx, mut relay_rx) = mpsc::channel::<(PublicKey, Vec<u8>)>(2048);
+ *control.out.lock().expect("out") = Some(out_tx.clone());
+ engine.set_relay(Some(relay_tx));
+ control.state.send_modify(|s| {
+ s.connected = true;
+ s.mode = Some(mode);
+ s.version = Some(version);
+ s.stun = stun;
+ s.last_error = None;
+ s.denied = None;
+ s.unsupported = false;
+ s.connects += 1;
+ s.usage = usage;
+ });
+ tracing::info!(url = %cfg.url, ?mode, "mesh coordinator connected");
+ control.usage_reconnected();
+
+ let mut ping = tokio::time::interval(Duration::from_secs(15));
+ ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ let mut last_heard = tokio::time::Instant::now();
+ loop {
+ tokio::select! {
+ _ = shutdown.cancelled() => {
+ let _ = sink.close().await;
+ return Ok(());
+ }
+ msg = stream.next() => {
+ last_heard = tokio::time::Instant::now();
+ match msg {
+ Some(Ok(WsMessage::Binary(b))) => {
+ if let Some((proto::FRAME_RECV, src, packet)) = proto::parse_frame(&b) {
+ engine.on_relay(src, packet);
+ }
+ }
+ Some(Ok(WsMessage::Text(t))) => {
+ let Ok(msg) = serde_json::from_str::<ServerMsg>(&t) else { continue };
+ handle(cfg, control, engine, mode, msg, &out_tx);
+ }
+ Some(Ok(WsMessage::Ping(p))) => {
+ let _ = sink.send(WsMessage::Pong(p)).await;
+ }
+ Some(Ok(WsMessage::Close(_))) | None => {
+ return Err(Error::Unreachable("coordinator closed the connection".into()));
+ }
+ Some(Ok(_)) => {}
+ Some(Err(e)) => return Err(Error::Unreachable(e.to_string())),
+ }
+ }
+ Some(msg) = out_rx.recv() => {
+ let text = serde_json::to_string(&msg).expect("json");
+ sink.send(WsMessage::Text(text.into())).await.map_err(|e| Error::Unreachable(e.to_string()))?;
+ }
+ Some((dst, packet)) = relay_rx.recv() => {
+ let f = proto::frame(proto::FRAME_SEND, &dst, &packet);
+ sink.feed(WsMessage::Binary(f.into())).await.map_err(|e| Error::Unreachable(e.to_string()))?;
+ // Batch whatever else is queued, then flush once.
+ while let Ok((dst, packet)) = relay_rx.try_recv() {
+ let f = proto::frame(proto::FRAME_SEND, &dst, &packet);
+ sink.feed(WsMessage::Binary(f.into())).await.map_err(|e| Error::Unreachable(e.to_string()))?;
+ }
+ sink.flush().await.map_err(|e| Error::Unreachable(e.to_string()))?;
+ }
+ _ = ping.tick() => {
+ if last_heard.elapsed() > Duration::from_secs(40) {
+ return Err(Error::Unreachable("coordinator stopped answering".into()));
+ }
+ let text = serde_json::to_string(&ClientMsg::Ping).expect("json");
+ sink.send(WsMessage::Text(text.into())).await.map_err(|e| Error::Unreachable(e.to_string()))?;
+ }
+ }
+ }
+}
+
+fn handle(
+ cfg: &ControlConfig,
+ control: &Arc<Control>,
+ engine: &Arc<Engine>,
+ mode: Mode,
+ msg: ServerMsg,
+ out: &mpsc::Sender<ClientMsg>,
+) {
+ match msg {
+ ServerMsg::Netmap { peers } => {
+ let peers = match (&cfg.approved, mode, cfg.kind) {
+ // A static-mode machine only ever talks to clients it
+ // approved itself: the coordinator alone cannot add one.
+ (Some(approved), Mode::Static, NodeKind::Machine) => peers
+ .into_iter()
+ .filter(|p| approved.contains(&p.node_key))
+ .collect(),
+ _ => peers,
+ };
+ engine.set_peers(peers);
+ control.state.send_modify(|s| s.has_netmap = true);
+ }
+ ServerMsg::PairRequest {
+ request_id,
+ client_key,
+ ts,
+ proof,
+ name,
+ } => {
+ let accept = cfg
+ .pair_verifier
+ .as_ref()
+ .is_some_and(|v| v(&client_key, ts, &proof));
+ if accept && let Some(approved) = &cfg.approved {
+ approved.add(client_key);
+ }
+ tracing::info!(client = %client_key.short(), %name, accept, "mesh pairing request");
+ let _ = out.try_send(ClientMsg::PairReply {
+ request_id,
+ accept,
+ reason: if accept {
+ String::new()
+ } else {
+ "the machine did not accept the proof".into()
+ },
+ });
+ }
+ ServerMsg::PairResult {
+ machine_id,
+ ok,
+ reason,
+ } => control.finish_pair(&machine_id, if ok { Ok(()) } else { Err(reason) }),
+ ServerMsg::Pong | ServerMsg::Challenge { .. } | ServerMsg::Welcome { .. } => {}
+ ServerMsg::Error { message } => tracing::warn!(%message, "mesh coordinator error"),
+ }
+}
+
+/// A minimal cancellation token (no extra dependency).
+pub(crate) mod tokio_util_cancel {
+ use std::sync::Arc;
+ use tokio::sync::watch;
+
+ #[derive(Clone)]
+ pub(crate) struct Token(Arc<watch::Sender<bool>>);
+
+ impl Token {
+ pub(crate) fn new() -> Self {
+ Self(Arc::new(watch::channel(false).0))
+ }
+ pub(crate) fn cancel(&self) {
+ self.0.send_replace(true);
+ }
+ pub(crate) fn is_cancelled(&self) -> bool {
+ *self.0.borrow()
+ }
+ pub(crate) async fn cancelled(&self) {
+ let mut rx = self.0.subscribe();
+ let _ = rx.wait_for(|v| *v).await;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn usage(peer: PublicKey, open: u32) -> Vec<PeerUsage> {
+ vec![PeerUsage {
+ peer,
+ user: "ada".into(),
+ open,
+ live: false,
+ }]
+ }
+
+ #[test]
+ fn usage_goes_only_to_a_coordinator_that_meters_it_and_only_when_it_changed() {
+ let control = Control::new();
+ let (tx, mut rx) = mpsc::channel(8);
+ *control.out.lock().unwrap() = Some(tx);
+ let peer = crate::key::SecretKey::generate().public();
+ // An older coordinator (or a static one): nothing is ever sent.
+ control.state.send_modify(|s| {
+ s.connected = true;
+ s.usage = 0;
+ });
+ control.usage_reconnected();
+ control.set_usage(usage(peer, 1));
+ assert!(rx.try_recv().is_err());
+ // One that meters: the snapshot on welcome, then only changes.
+ control
+ .state
+ .send_modify(|s| s.usage = proto::USAGE_VERSION);
+ control.usage_reconnected();
+ assert!(
+ matches!(rx.try_recv(), Ok(ClientMsg::Usage { v: 1, peers }) if peers[0].open == 1)
+ );
+ control.set_usage(usage(peer, 1));
+ assert!(rx.try_recv().is_err());
+ control.set_usage(usage(peer, 2));
+ assert!(matches!(rx.try_recv(), Ok(ClientMsg::Usage { peers, .. }) if peers[0].open == 2));
+ control.set_usage(Vec::new());
+ assert!(matches!(rx.try_recv(), Ok(ClientMsg::Usage { peers, .. }) if peers.is_empty()));
+ // Disconnected: kept, and sent again on the next welcome.
+ control.state.send_modify(|s| s.connected = false);
+ control.set_usage(usage(peer, 3));
+ assert!(rx.try_recv().is_err());
+ control.state.send_modify(|s| s.connected = true);
+ control.usage_reconnected();
+ assert!(matches!(rx.try_recv(), Ok(ClientMsg::Usage { peers, .. }) if peers[0].open == 3));
+ // A fresh connection with nothing open sends nothing.
+ control.set_usage(Vec::new());
+ let _ = rx.try_recv();
+ control.usage_reconnected();
+ assert!(rx.try_recv().is_err());
+ }
+
+ #[test]
+ fn connect_urls() {
+ assert_eq!(
+ super::connect_url("https://relay.example").unwrap(),
+ "wss://relay.example/v1/mesh/connect"
+ );
+ assert_eq!(
+ super::connect_url("http://127.0.0.1:8080/").unwrap(),
+ "ws://127.0.0.1:8080/v1/mesh/connect"
+ );
+ assert!(super::connect_url("ftp://x").is_err());
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/dialer.rs b/libs/cua/crates/cua-mesh/src/dialer.rs
new file mode 100644
index 0000000000..8e5508c37d
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/dialer.rs
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! [`Dialer`]: "reach machine X on relay R over the mesh", for any client
+//! (Spaces, the cluster coordinator, the SDK).
+//!
+//! It runs one client node on the relay's mesh and keeps one loopback
+//! forward per machine. A machine of a static-token relay is paired first
+//! with the machine's env token (only a proof leaves this process). The
+//! caller then talks to `http://<Route::local>` exactly as it would to the
+//! machine's spacesd, sending [`Route::session`] (when set) as the
+//! `x-cua-mesh-session` header so the machine vouches for this device.
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::{AuthProvider, Error, Forward, Mesh, MeshConfig, NodeKind, Result};
+
+/// The spacesd service on a machine.
+pub const SPACESD_SERVICE: &str = "spacesd";
+/// The request header carrying a forward's session key.
+pub const SESSION_HEADER: &str = "x-cua-mesh-session";
+
+/// Where to reach one machine.
+#[derive(Debug, Clone)]
+pub struct Route {
+ /// Loopback address (TCP for spacesd; UDP on the same port reaches the
+ /// machine's QUIC media port when it was free).
+ pub local: SocketAddr,
+ /// Send as [`SESSION_HEADER`] on every request (account relays).
+ pub session: Option<String>,
+ /// The machine's node key.
+ pub peer: crate::PublicKey,
+}
+
+struct Entry {
+ forward: Arc<Forward>,
+ route: Route,
+}
+
+/// A client node on one relay's mesh plus its forwards.
+pub struct Dialer {
+ mesh: Mesh,
+ forwards: tokio::sync::Mutex<HashMap<String, Entry>>,
+}
+
+impl std::fmt::Debug for Dialer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Dialer").field("mesh", &self.mesh).finish()
+ }
+}
+
+impl Drop for Dialer {
+ fn drop(&mut self) {
+ self.mesh.shutdown();
+ }
+}
+
+impl Dialer {
+ /// Joins `relay`'s mesh as a client with `auth` (account relays: the
+ /// account token and device session headers; static relays: none).
+ /// `identity`: a persistent node identity file, or `None` for a
+ /// short-lived node the relay forgets on disconnect.
+ pub async fn start(
+ relay: &str,
+ auth: AuthProvider,
+ identity: Option<PathBuf>,
+ timeout: Duration,
+ ) -> Result<Self> {
+ let cfg = MeshConfig::new(relay.to_owned(), NodeKind::Client, identity, auth);
+ let mesh = Mesh::start(cfg).await?;
+ if let Err(e) = mesh.wait_ready(timeout).await {
+ mesh.shutdown();
+ return Err(e);
+ }
+ Ok(Self {
+ mesh,
+ forwards: tokio::sync::Mutex::new(HashMap::new()),
+ })
+ }
+
+ /// The node.
+ pub fn mesh(&self) -> &Mesh {
+ &self.mesh
+ }
+
+ /// The route to `machine_id`, opening a forward on first use. With
+ /// `env_token` (a static relay), pairs first when the machine is not in
+ /// the map yet.
+ pub async fn route(
+ &self,
+ machine_id: &str,
+ env_token: Option<&str>,
+ wait: Duration,
+ ) -> Result<Route> {
+ let mut forwards = self.forwards.lock().await;
+ if let Some(e) = forwards.get(machine_id)
+ && self.mesh.machine(machine_id).map(|p| p.node_key) == Some(e.route.peer)
+ {
+ return Ok(e.route.clone());
+ }
+ // A static relay's machine is in the map only once paired: pair
+ // right away instead of waiting for a map that will not have it.
+ let mut peer = match env_token {
+ Some(_) => self.mesh.machine(machine_id),
+ None => self.mesh.wait_machine_in_map(machine_id, wait).await,
+ };
+ if peer.is_none()
+ && let Some(token) = env_token
+ {
+ self.mesh.pair(machine_id, token).await?;
+ peer = self.mesh.wait_machine(machine_id, wait).await;
+ }
+ let peer = peer.ok_or_else(|| {
+ Error::NotFound(format!(
+ "machine {machine_id} is not on the mesh (an older cua-spacesd, offline, or not shared)"
+ ))
+ })?;
+ if peer.version != crate::VERSION {
+ return Err(Error::Unsupported(format!(
+ "machine {machine_id} speaks mesh v{}, this node v{}",
+ peer.version,
+ crate::VERSION
+ )));
+ }
+ // Account relays: the machine vouches for this device only on
+ // requests carrying the forward's key. Static relays: the env token
+ // in each request is the credential.
+ let session = env_token
+ .is_none()
+ .then(|| hex::encode(crate::key::os_random::<24>()));
+ let forward = Arc::new(
+ self.mesh
+ .forward(peer.node_key, SPACESD_SERVICE, session.clone())
+ .await?,
+ );
+ let route = Route {
+ local: forward.local,
+ session,
+ peer: peer.node_key,
+ };
+ forwards.insert(
+ machine_id.to_owned(),
+ Entry {
+ forward,
+ route: route.clone(),
+ },
+ );
+ Ok(route)
+ }
+
+ /// Drops the forward to `machine_id` (its path stopped answering).
+ pub async fn forget(&self, machine_id: &str) {
+ if let Some(e) = self.forwards.lock().await.remove(machine_id) {
+ drop(e.forward);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/disco.rs b/libs/cua/crates/cua-mesh/src/disco.rs
new file mode 100644
index 0000000000..1df4221319
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/disco.rs
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Path discovery ("disco") messages: ping, pong and call-me-maybe, sealed
+//! between two nodes' disco keys so neither the relay nor anyone on the path
+//! can forge or read them.
+//!
+//! ```text
+//! packet = "CUAD" | version(1) | sender disco key(32) | nonce(24) | sealed
+//! sealed = XChaCha20-Poly1305(key, nonce, message)
+//! key = HKDF-SHA256(X25519(own disco secret, peer disco key),
+//! salt "cua-mesh-disco-v1", info min(keys)|max(keys))
+//! message = Ping 1 | tx(12) | sender node key(32)
+//! | Pong 2 | tx(12) | observed source (16-byte IP, port u16)
+//! | CallMeMaybe 3 | endpoint(18)*
+//! ```
+
+use std::net::{IpAddr, Ipv6Addr, SocketAddr};
+
+use chacha20poly1305::aead::{Aead as _, KeyInit as _};
+use chacha20poly1305::{XChaCha20Poly1305, XNonce};
+use hkdf::Hkdf;
+use sha2::Sha256;
+
+use crate::key::{PublicKey, SecretKey};
+
+/// Every disco packet starts with this.
+pub const MAGIC: &[u8; 4] = b"CUAD";
+const VERSION: u8 = 1;
+const HEADER: usize = 4 + 1 + 32 + 24;
+
+/// A ping/pong transaction id.
+pub type TxId = [u8; 12];
+
+/// A disco message.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Message {
+ /// Are you there on this path?
+ Ping {
+ /// Transaction id the pong echoes.
+ tx: TxId,
+ /// The sender's node key.
+ node: PublicKey,
+ },
+ /// Yes; and this is the address your ping came from.
+ Pong {
+ /// The ping's transaction id.
+ tx: TxId,
+ /// Where the ping came from, as the receiver saw it.
+ src: SocketAddr,
+ },
+ /// Ping me back on these endpoints (hole punching).
+ CallMeMaybe {
+ /// The sender's candidate endpoints.
+ endpoints: Vec<SocketAddr>,
+ },
+}
+
+/// True when `packet` looks like a disco packet.
+pub fn is_disco(packet: &[u8]) -> bool {
+ packet.len() >= HEADER && &packet[..4] == MAGIC
+}
+
+/// The sender's disco key of a disco packet.
+pub fn sender(packet: &[u8]) -> Option<PublicKey> {
+ if !is_disco(packet) || packet[4] != VERSION {
+ return None;
+ }
+ Some(PublicKey(packet[5..37].try_into().ok()?))
+}
+
+fn shared_key(own: &SecretKey, peer: &PublicKey) -> [u8; 32] {
+ let me = own.public();
+ let (lo, hi) = if me.0 <= peer.0 {
+ (me, *peer)
+ } else {
+ (*peer, me)
+ };
+ let mut info = [0u8; 64];
+ info[..32].copy_from_slice(&lo.0);
+ info[32..].copy_from_slice(&hi.0);
+ let hk = Hkdf::<Sha256>::new(Some(b"cua-mesh-disco-v1"), &own.agree(peer));
+ let mut okm = [0u8; 32];
+ hk.expand(&info, &mut okm)
+ .expect("32 bytes is a valid HKDF length");
+ okm
+}
+
+/// A sealer for one peer (the X25519 and HKDF done once).
+#[derive(Clone)]
+pub struct Sealer {
+ own: PublicKey,
+ cipher: XChaCha20Poly1305,
+}
+
+impl std::fmt::Debug for Sealer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Sealer")
+ }
+}
+
+impl Sealer {
+ /// The sealer between `own` and `peer` disco keys.
+ pub fn new(own: &SecretKey, peer: &PublicKey) -> Self {
+ let key = shared_key(own, peer);
+ Self {
+ own: own.public(),
+ cipher: XChaCha20Poly1305::new((&key).into()),
+ }
+ }
+
+ /// Seals `msg` into a disco packet.
+ pub fn seal(&self, msg: &Message) -> Vec<u8> {
+ let nonce_bytes: [u8; 24] = crate::key::os_random();
+ let nonce = XNonce::from_slice(&nonce_bytes);
+ let sealed = self
+ .cipher
+ .encrypt(nonce, encode(msg).as_slice())
+ .expect("XChaCha20-Poly1305 encryption does not fail");
+ let mut out = Vec::with_capacity(HEADER + sealed.len());
+ out.extend_from_slice(MAGIC);
+ out.push(VERSION);
+ out.extend_from_slice(&self.own.0);
+ out.extend_from_slice(&nonce_bytes);
+ out.extend_from_slice(&sealed);
+ out
+ }
+
+ /// Opens a disco packet sealed by the peer. `None` when it does not
+ /// authenticate or does not parse.
+ pub fn open(&self, packet: &[u8]) -> Option<Message> {
+ if !is_disco(packet) || packet[4] != VERSION {
+ return None;
+ }
+ let nonce = XNonce::from_slice(&packet[37..HEADER]);
+ let plain = self.cipher.decrypt(nonce, &packet[HEADER..]).ok()?;
+ decode(&plain)
+ }
+}
+
+fn put_addr(out: &mut Vec<u8>, a: &SocketAddr) {
+ let ip = match a.ip() {
+ IpAddr::V4(v4) => v4.to_ipv6_mapped(),
+ IpAddr::V6(v6) => v6,
+ };
+ out.extend_from_slice(&ip.octets());
+ out.extend_from_slice(&a.port().to_be_bytes());
+}
+
+fn get_addr(b: &[u8]) -> Option<SocketAddr> {
+ let ip = Ipv6Addr::from(<[u8; 16]>::try_from(b.get(..16)?).ok()?);
+ let port = u16::from_be_bytes([*b.get(16)?, *b.get(17)?]);
+ let ip = match ip.to_ipv4_mapped() {
+ Some(v4) => IpAddr::V4(v4),
+ None => IpAddr::V6(ip),
+ };
+ Some(SocketAddr::new(ip, port))
+}
+
+fn encode(msg: &Message) -> Vec<u8> {
+ let mut out = Vec::new();
+ match msg {
+ Message::Ping { tx, node } => {
+ out.push(1);
+ out.extend_from_slice(tx);
+ out.extend_from_slice(&node.0);
+ }
+ Message::Pong { tx, src } => {
+ out.push(2);
+ out.extend_from_slice(tx);
+ put_addr(&mut out, src);
+ }
+ Message::CallMeMaybe { endpoints } => {
+ out.push(3);
+ for e in endpoints.iter().take(32) {
+ put_addr(&mut out, e);
+ }
+ }
+ }
+ out
+}
+
+fn decode(b: &[u8]) -> Option<Message> {
+ let (&kind, rest) = b.split_first()?;
+ match kind {
+ 1 if rest.len() == 12 + 32 => Some(Message::Ping {
+ tx: rest[..12].try_into().ok()?,
+ node: PublicKey(rest[12..44].try_into().ok()?),
+ }),
+ 2 if rest.len() == 12 + 18 => Some(Message::Pong {
+ tx: rest[..12].try_into().ok()?,
+ src: get_addr(&rest[12..])?,
+ }),
+ 3 if rest.len() % 18 == 0 && rest.len() <= 32 * 18 => Some(Message::CallMeMaybe {
+ endpoints: rest.chunks(18).filter_map(get_addr).collect(),
+ }),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn seal_and_open() {
+ let a = SecretKey::generate();
+ let b = SecretKey::generate();
+ let ab = Sealer::new(&a, &b.public());
+ let ba = Sealer::new(&b, &a.public());
+ let msgs = [
+ Message::Ping {
+ tx: [7; 12],
+ node: SecretKey::generate().public(),
+ },
+ Message::Pong {
+ tx: [9; 12],
+ src: "203.0.113.7:41641".parse().unwrap(),
+ },
+ Message::Pong {
+ tx: [1; 12],
+ src: "[2001:db8::1]:5".parse().unwrap(),
+ },
+ Message::CallMeMaybe {
+ endpoints: vec![
+ "192.168.1.5:41641".parse().unwrap(),
+ "[2001:db8::2]:41641".parse().unwrap(),
+ ],
+ },
+ ];
+ for m in msgs {
+ let p = ab.seal(&m);
+ assert!(is_disco(&p));
+ assert_eq!(sender(&p), Some(a.public()));
+ assert_eq!(ba.open(&p), Some(m));
+ }
+ }
+
+ #[test]
+ fn forgeries_fail() {
+ let a = SecretKey::generate();
+ let b = SecretKey::generate();
+ let c = SecretKey::generate();
+ let p = Sealer::new(&a, &b.public()).seal(&Message::CallMeMaybe { endpoints: vec![] });
+ // A third party cannot open it.
+ assert!(Sealer::new(&c, &a.public()).open(&p).is_none());
+ let mut tampered = p.clone();
+ let n = tampered.len();
+ tampered[n - 1] ^= 1;
+ assert!(Sealer::new(&b, &a.public()).open(&tampered).is_none());
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/engine.rs b/libs/cua/crates/cua-mesh/src/engine.rs
new file mode 100644
index 0000000000..9b0e21d3e2
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/engine.rs
@@ -0,0 +1,985 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The data plane: WireGuard sessions per peer over one UDP socket pair,
+//! path discovery (direct first, hole punching, encrypted relay fallback)
+//! and the virtual network the decrypted packets land on.
+//!
+//! - Every peer has a boringtun [`Tunn`] (the WireGuard protocol state
+//! machine; this crate never touches a TUN device or the kernel).
+//! - A packet to a peer goes to its best direct path when one answered a
+//! disco ping recently, else through the coordinator's relay, which only
+//! ever sees WireGuard or disco ciphertext.
+//! - Discovery pings every candidate endpoint of an active peer and asks
+//! the peer (through the relay) to ping back at the same time, which opens
+//! both NATs. The lowest-latency answering path wins; a path that stops
+//! answering falls back to the relay within [`TRUST`].
+
+use std::collections::HashMap;
+use std::io;
+use std::net::{IpAddr, Ipv6Addr, SocketAddr};
+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, RwLock};
+use std::task::{Context, Poll};
+use std::time::{Duration, Instant};
+
+use boringtun::noise::handshake::parse_handshake_anon;
+use boringtun::noise::{Packet, Tunn, TunnResult};
+use tokio::net::UdpSocket;
+use tokio::sync::{Notify, mpsc, oneshot};
+
+use crate::disco::{self, Message, Sealer};
+use crate::key::{NodeIdentity, PublicKey};
+use crate::proto::PeerInfo;
+use crate::stun;
+use crate::vnet::{Outbound, VNet};
+
+/// How long a direct path stays in use after its last pong.
+pub const TRUST: Duration = Duration::from_millis(6500);
+/// How often an active peer's paths are re-pinged.
+pub const PING_INTERVAL: Duration = Duration::from_millis(2500);
+/// How often call-me-maybe goes out while no direct path works.
+const CMM_INTERVAL: Duration = Duration::from_secs(5);
+/// A peer is active while traffic flowed within this window.
+const ACTIVE: Duration = Duration::from_secs(45);
+/// Largest datagram handled.
+const MAX_DATAGRAM: usize = 65_535;
+
+/// The path a packet takes to a peer.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Path {
+ /// Straight to this UDP endpoint.
+ Direct(SocketAddr),
+ /// Through the coordinator's relay.
+ Relay,
+}
+
+impl std::fmt::Display for Path {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Path::Direct(a) => write!(f, "direct {a}"),
+ Path::Relay => f.write_str("relay"),
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+struct Candidate {
+ last_ping: Option<Instant>,
+ last_pong: Option<Instant>,
+ rtt: Option<Duration>,
+ /// From the peer's own endpoint list (kept across netmaps).
+ advertised: bool,
+}
+
+#[derive(Debug, Default)]
+struct PathState {
+ candidates: HashMap<SocketAddr, Candidate>,
+ pending: HashMap<disco::TxId, (SocketAddr, Instant)>,
+ best: Option<(SocketAddr, Duration, Instant)>,
+ last_round: Option<Instant>,
+ last_cmm: Option<Instant>,
+ switches: u64,
+}
+
+impl PathState {
+ fn current(&self, now: Instant) -> Path {
+ match self.best {
+ Some((addr, _, at)) if now.duration_since(at) < TRUST => Path::Direct(addr),
+ _ => Path::Relay,
+ }
+ }
+}
+
+/// Per-peer counters.
+#[derive(Debug, Default)]
+pub struct PeerCounters {
+ /// Encrypted bytes sent directly.
+ pub tx_direct: AtomicU64,
+ /// Encrypted bytes sent through the relay.
+ pub tx_relay: AtomicU64,
+ /// Encrypted bytes received directly.
+ pub rx_direct: AtomicU64,
+ /// Encrypted bytes received through the relay.
+ pub rx_relay: AtomicU64,
+}
+
+pub(crate) struct Peer {
+ pub(crate) info: RwLock<PeerInfo>,
+ index: u32,
+ tunn: Mutex<Tunn>,
+ sealer: Sealer,
+ path: Mutex<PathState>,
+ last_activity: Mutex<Instant>,
+ pub(crate) counters: PeerCounters,
+}
+
+impl Peer {
+ pub(crate) fn key(&self) -> PublicKey {
+ self.info.read().expect("info").node_key
+ }
+
+ pub(crate) fn path(&self) -> Path {
+ self.path.lock().expect("path").current(Instant::now())
+ }
+
+ pub(crate) fn rtt(&self) -> Option<Duration> {
+ let p = self.path.lock().expect("path");
+ match p.current(Instant::now()) {
+ Path::Direct(_) => p.best.map(|b| b.1),
+ Path::Relay => None,
+ }
+ }
+
+ pub(crate) fn path_switches(&self) -> u64 {
+ self.path.lock().expect("path").switches
+ }
+
+ pub(crate) fn handshake_age(&self) -> Option<Duration> {
+ self.tunn.lock().expect("tunn").time_since_last_handshake()
+ }
+
+ fn touch(&self) {
+ *self.last_activity.lock().expect("activity") = Instant::now();
+ }
+
+ fn active(&self, now: Instant) -> bool {
+ now.duration_since(*self.last_activity.lock().expect("activity")) < ACTIVE
+ }
+}
+
+#[derive(Default)]
+struct PeerTable {
+ by_key: HashMap<PublicKey, Arc<Peer>>,
+ by_addr: HashMap<Ipv6Addr, Arc<Peer>>,
+ by_disco: HashMap<PublicKey, Arc<Peer>>,
+ by_index: HashMap<u32, Arc<Peer>>,
+}
+
+struct Sockets {
+ v4: Arc<UdpSocket>,
+ v6: Option<Arc<UdpSocket>>,
+ tasks: Vec<tokio::task::JoinHandle<()>>,
+}
+
+/// Outgoing relay packets: `(destination node key, packet)`.
+pub(crate) type RelayTx = mpsc::Sender<(PublicKey, Vec<u8>)>;
+
+/// The data plane.
+pub(crate) struct Engine {
+ identity: NodeIdentity,
+ me: PublicKey,
+ pub(crate) vnet: Arc<VNet>,
+ peers: RwLock<PeerTable>,
+ sockets: RwLock<Option<Sockets>>,
+ listen_port: u16,
+ relay_tx: Mutex<Option<RelayTx>>,
+ next_index: AtomicU32,
+ stun_waiters: Mutex<HashMap<stun::TxId, oneshot::Sender<SocketAddr>>>,
+ local_endpoints: RwLock<Vec<SocketAddr>>,
+ disco_kick: Notify,
+ /// Never use direct paths (tests and `CUA_MESH_RELAY_ONLY`).
+ relay_only: AtomicBool,
+ peers_changed: tokio::sync::watch::Sender<u64>,
+}
+
+impl Engine {
+ pub(crate) async fn new(
+ identity: NodeIdentity,
+ listen_port: u16,
+ relay_only: bool,
+ ) -> io::Result<Arc<Self>> {
+ let me = identity.public();
+ let vnet = VNet::new(identity.addr());
+ let (peers_changed, _) = tokio::sync::watch::channel(0);
+ let engine = Arc::new(Self {
+ identity,
+ me,
+ vnet,
+ peers: RwLock::new(PeerTable::default()),
+ sockets: RwLock::new(None),
+ listen_port,
+ relay_tx: Mutex::new(None),
+ next_index: AtomicU32::new(rand::random::<u32>() & 0x00ff_ffff),
+ stun_waiters: Mutex::new(HashMap::new()),
+ local_endpoints: RwLock::new(Vec::new()),
+ disco_kick: Notify::new(),
+ relay_only: AtomicBool::new(relay_only),
+ peers_changed,
+ });
+ let out: Arc<dyn Outbound> = engine.clone();
+ engine.vnet.set_outbound(Arc::downgrade(&out));
+ // `out` is the engine itself; the Weak keeps working as long as the
+ // engine lives.
+ drop(out);
+ engine.bind(listen_port).await?;
+ let weak = Arc::downgrade(&engine);
+ tokio::spawn(async move { maintenance(weak).await });
+ Ok(engine)
+ }
+
+ /// (Re)binds the UDP sockets: `port` 0 picks a fresh one.
+ pub(crate) async fn bind(self: &Arc<Self>, port: u16) -> io::Result<()> {
+ let v4 = bind_udp(SocketAddr::from(([0, 0, 0, 0], port)))?;
+ let v6 = bind_udp(SocketAddr::from((
+ Ipv6Addr::UNSPECIFIED,
+ v4.local_addr()?.port(),
+ )))
+ .or_else(|_| bind_udp(SocketAddr::from((Ipv6Addr::UNSPECIFIED, 0))))
+ .ok();
+ let mut tasks = Vec::new();
+ for sock in std::iter::once(v4.clone()).chain(v6.clone()) {
+ let weak = Arc::downgrade(self);
+ tasks.push(tokio::spawn(async move { recv_loop(weak, sock).await }));
+ }
+ let old = self
+ .sockets
+ .write()
+ .expect("sockets")
+ .replace(Sockets { v4, v6, tasks });
+ if let Some(old) = old {
+ for t in old.tasks {
+ t.abort();
+ }
+ }
+ Ok(())
+ }
+
+ /// Moves to fresh UDP ports (a network change: new NAT mappings) and
+ /// forgets every direct path, so traffic stays on the relay until
+ /// discovery finds the new ones.
+ pub(crate) async fn rebind(self: &Arc<Self>) -> io::Result<()> {
+ self.bind(0).await?;
+ self.forget_paths();
+ Ok(())
+ }
+
+ /// Forgets every direct path (the network changed under us).
+ pub(crate) fn forget_paths(&self) {
+ for p in self.peers.read().expect("peers").by_key.values() {
+ let mut path = p.path.lock().expect("path");
+ path.best = None;
+ path.last_round = None;
+ path.last_cmm = None;
+ path.pending.clear();
+ }
+ self.disco_kick.notify_one();
+ }
+
+ pub(crate) fn local_ports(&self) -> (u16, Option<u16>) {
+ let s = self.sockets.read().expect("sockets");
+ let s = s.as_ref().expect("bound");
+ (
+ s.v4.local_addr()
+ .map(|a| a.port())
+ .unwrap_or(self.listen_port),
+ s.v6.as_ref()
+ .and_then(|v| v.local_addr().ok())
+ .map(|a| a.port()),
+ )
+ }
+
+ pub(crate) fn set_relay(&self, tx: Option<RelayTx>) {
+ *self.relay_tx.lock().expect("relay") = tx;
+ }
+
+ pub(crate) fn set_relay_only(&self, on: bool) {
+ self.relay_only.store(on, Ordering::SeqCst);
+ if on {
+ self.forget_paths();
+ }
+ }
+
+ pub(crate) fn set_local_endpoints(&self, endpoints: Vec<SocketAddr>) {
+ let changed = {
+ let mut eps = self.local_endpoints.write().expect("endpoints");
+ let changed = *eps != endpoints;
+ *eps = endpoints;
+ changed
+ };
+ if changed {
+ // Peers still on the relay hear about the new endpoints now,
+ // not at the next round.
+ for p in self.peers.read().expect("peers").by_key.values() {
+ let mut ps = p.path.lock().expect("path");
+ if ps.current(Instant::now()) == Path::Relay {
+ ps.last_round = None;
+ ps.last_cmm = None;
+ }
+ }
+ self.disco_kick.notify_one();
+ }
+ }
+
+ pub(crate) fn subscribe_peers(&self) -> tokio::sync::watch::Receiver<u64> {
+ self.peers_changed.subscribe()
+ }
+
+ /// Replaces the peer set. Peers whose keys are unchanged keep their
+ /// WireGuard sessions and paths.
+ pub(crate) fn set_peers(&self, infos: Vec<PeerInfo>) {
+ let mut table = self.peers.write().expect("peers");
+ let mut next = PeerTable::default();
+ for info in infos {
+ if info.node_key == self.me || info.addr() == self.vnet_addr() {
+ continue;
+ }
+ let peer = match table.by_key.get(&info.node_key) {
+ Some(existing)
+ if existing.info.read().expect("info").disco_key == info.disco_key =>
+ {
+ {
+ let mut path = existing.path.lock().expect("path");
+ // Keep learned candidates; refresh advertised ones.
+ path.candidates
+ .retain(|_, c| !c.advertised || c.last_pong.is_some());
+ for e in &info.endpoints {
+ path.candidates.entry(*e).or_default().advertised = true;
+ }
+ }
+ *existing.info.write().expect("info") = info.clone();
+ existing.clone()
+ }
+ _ => Arc::new(self.new_peer(info.clone())),
+ };
+ next.by_addr.insert(info.addr(), peer.clone());
+ next.by_disco.insert(info.disco_key, peer.clone());
+ next.by_index.insert(peer.index, peer.clone());
+ next.by_key.insert(info.node_key, peer);
+ }
+ *table = next;
+ drop(table);
+ self.peers_changed.send_modify(|v| *v += 1);
+ self.disco_kick.notify_one();
+ }
+
+ fn vnet_addr(&self) -> Ipv6Addr {
+ self.identity.addr()
+ }
+
+ fn new_peer(&self, info: PeerInfo) -> Peer {
+ let index = self.next_index.fetch_add(1, Ordering::Relaxed) & 0x00ff_ffff;
+ let tunn = Tunn::new(
+ self.identity.node.x25519(),
+ info.node_key.x25519(),
+ None,
+ None,
+ index,
+ None,
+ );
+ let sealer = Sealer::new(&self.identity.disco, &info.disco_key);
+ let mut path = PathState::default();
+ for e in &info.endpoints {
+ path.candidates.entry(*e).or_default().advertised = true;
+ }
+ Peer {
+ info: RwLock::new(info),
+ index,
+ tunn: Mutex::new(tunn),
+ sealer,
+ path: Mutex::new(path),
+ last_activity: Mutex::new(Instant::now() - ACTIVE),
+ counters: PeerCounters::default(),
+ }
+ }
+
+ /// Drops one peer now (a revoked pairing), before the next map.
+ pub(crate) fn remove_peer(&self, key: &PublicKey) {
+ let mut table = self.peers.write().expect("peers");
+ if let Some(p) = table.by_key.remove(key) {
+ let info = p.info.read().expect("info").clone();
+ table.by_addr.remove(&info.addr());
+ table.by_disco.remove(&info.disco_key);
+ table.by_index.remove(&p.index);
+ }
+ drop(table);
+ self.peers_changed.send_modify(|v| *v += 1);
+ }
+
+ pub(crate) fn peer(&self, key: &PublicKey) -> Option<Arc<Peer>> {
+ self.peers.read().expect("peers").by_key.get(key).cloned()
+ }
+
+ pub(crate) fn peer_by_addr(&self, addr: &Ipv6Addr) -> Option<Arc<Peer>> {
+ self.peers.read().expect("peers").by_addr.get(addr).cloned()
+ }
+
+ pub(crate) fn peers(&self) -> Vec<Arc<Peer>> {
+ self.peers
+ .read()
+ .expect("peers")
+ .by_key
+ .values()
+ .cloned()
+ .collect()
+ }
+
+ /// Marks `key` as about to be used, so discovery starts now.
+ pub(crate) fn want(&self, key: &PublicKey) {
+ if let Some(p) = self.peer(key) {
+ p.touch();
+ self.disco_kick.notify_one();
+ }
+ }
+
+ // ---- sending ----
+
+ fn send_udp(&self, dst: SocketAddr, data: &[u8]) -> io::Result<()> {
+ let s = self.sockets.read().expect("sockets");
+ let s = s
+ .as_ref()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "unbound"))?;
+ let sock = match dst {
+ SocketAddr::V4(_) => &s.v4,
+ SocketAddr::V6(_) => {
+ s.v6.as_ref()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "no IPv6 socket"))?
+ }
+ };
+ sock.try_send_to(data, dst).map(|_| ())
+ }
+
+ fn send_relay(&self, dst: PublicKey, data: &[u8]) -> io::Result<()> {
+ let tx = self.relay_tx.lock().expect("relay").clone();
+ match tx {
+ Some(tx) => tx
+ .try_send((dst, data.to_vec()))
+ .map_err(|_| io::Error::new(io::ErrorKind::WouldBlock, "relay queue full")),
+ None => Err(io::Error::new(
+ io::ErrorKind::NotConnected,
+ "relay unavailable",
+ )),
+ }
+ }
+
+ fn send_via(&self, peer: &Peer, path: Path, data: &[u8]) -> io::Result<()> {
+ match path {
+ Path::Direct(addr) => {
+ peer.counters
+ .tx_direct
+ .fetch_add(data.len() as u64, Ordering::Relaxed);
+ self.send_udp(addr, data)
+ }
+ Path::Relay => {
+ peer.counters
+ .tx_relay
+ .fetch_add(data.len() as u64, Ordering::Relaxed);
+ self.send_relay(peer.key(), data)
+ }
+ }
+ }
+
+ fn send_to_peer(&self, peer: &Peer, data: &[u8]) -> io::Result<()> {
+ let path = if self.relay_only.load(Ordering::Relaxed) {
+ Path::Relay
+ } else {
+ peer.path()
+ };
+ let r = self.send_via(peer, path, data);
+ if matches!(&r, Err(e) if e.kind() != io::ErrorKind::WouldBlock) && path != Path::Relay {
+ // A direct send failing outright (no route after a network
+ // change): fall back to the relay for this packet.
+ return self.send_via(peer, Path::Relay, data);
+ }
+ r
+ }
+
+ fn drain(&self, peer: &Peer, path: Path, tunn: &mut Tunn, buf: &mut [u8]) {
+ while let TunnResult::WriteToNetwork(p) = tunn.decapsulate(None, &[], buf) {
+ let _ = self.send_via(peer, path, p);
+ }
+ }
+
+ // ---- receiving ----
+
+ fn on_datagram(&self, path: Path, relay_src: Option<PublicKey>, data: &[u8]) {
+ if matches!(path, Path::Direct(_)) && stun::is_stun(data) {
+ if let Some((tx, mapped)) = stun::parse_response(data)
+ && let Some(w) = self.stun_waiters.lock().expect("stun").remove(&tx)
+ {
+ let _ = w.send(mapped);
+ }
+ return;
+ }
+ if disco::is_disco(data) {
+ self.on_disco(path, relay_src, data);
+ return;
+ }
+ self.on_wireguard(path, relay_src, data);
+ }
+
+ fn on_wireguard(&self, path: Path, relay_src: Option<PublicKey>, data: &[u8]) {
+ let peer = {
+ let table = self.peers.read().expect("peers");
+ match Tunn::parse_incoming_packet(data) {
+ Ok(Packet::HandshakeInit(ref init)) => {
+ let me = self.identity.node.public();
+ match parse_handshake_anon(&self.identity.node.x25519(), &me.x25519(), init) {
+ Ok(half) => table
+ .by_key
+ .get(&PublicKey(half.peer_static_public))
+ .cloned(),
+ Err(_) => None,
+ }
+ }
+ Ok(Packet::HandshakeResponse(r)) => {
+ table.by_index.get(&(r.receiver_idx >> 8)).cloned()
+ }
+ Ok(Packet::PacketCookieReply(c)) => {
+ table.by_index.get(&(c.receiver_idx >> 8)).cloned()
+ }
+ Ok(Packet::PacketData(d)) => table.by_index.get(&(d.receiver_idx >> 8)).cloned(),
+ Err(_) => None,
+ }
+ };
+ let Some(peer) = peer else {
+ return;
+ };
+ if let Some(src) = relay_src
+ && src != peer.key()
+ {
+ // A relayed packet must come from the peer it names.
+ return;
+ }
+ match path {
+ Path::Direct(_) => peer
+ .counters
+ .rx_direct
+ .fetch_add(data.len() as u64, Ordering::Relaxed),
+ Path::Relay => peer
+ .counters
+ .rx_relay
+ .fetch_add(data.len() as u64, Ordering::Relaxed),
+ };
+ let src_ip = match path {
+ Path::Direct(a) => Some(a.ip()),
+ Path::Relay => None,
+ };
+ // Decryption never grows a packet; queued packets flushed after a
+ // handshake are at most one tunnel MTU plus overhead.
+ let mut buf = vec![0u8; (data.len() + 64).max(2048)];
+ let mut tunn = peer.tunn.lock().expect("tunn");
+ match tunn.decapsulate(src_ip, data, &mut buf) {
+ TunnResult::WriteToNetwork(p) => {
+ let _ = self.send_via(&peer, path, p);
+ self.drain(&peer, path, &mut tunn, &mut buf);
+ }
+ TunnResult::WriteToTunnelV6(p, src) => {
+ // Cryptokey routing: the inner source must be the peer's
+ // own address.
+ if src == peer.info.read().expect("info").addr() {
+ peer.touch();
+ self.vnet.deliver(p);
+ }
+ }
+ TunnResult::WriteToTunnelV4(..) | TunnResult::Done | TunnResult::Err(_) => {}
+ }
+ drop(tunn);
+ if let Path::Direct(addr) = path {
+ // Authenticated traffic from an endpoint: worth probing.
+ let mut ps = peer.path.lock().expect("path");
+ if ps.best.is_none() && !ps.candidates.contains_key(&addr) {
+ ps.candidates.insert(addr, Candidate::default());
+ drop(ps);
+ self.disco_kick.notify_one();
+ }
+ }
+ }
+
+ fn on_disco(&self, path: Path, relay_src: Option<PublicKey>, data: &[u8]) {
+ let Some(sender) = disco::sender(data) else {
+ return;
+ };
+ let Some(peer) = self
+ .peers
+ .read()
+ .expect("peers")
+ .by_disco
+ .get(&sender)
+ .cloned()
+ else {
+ return;
+ };
+ if let Some(src) = relay_src
+ && src != peer.key()
+ {
+ return;
+ }
+ let Some(msg) = peer.sealer.open(data) else {
+ return;
+ };
+ let now = Instant::now();
+ match msg {
+ Message::Ping { tx, node } => {
+ if node != peer.key() {
+ return;
+ }
+ let observed = match path {
+ Path::Direct(a) => a,
+ Path::Relay => SocketAddr::from(([0, 0, 0, 0], 0)),
+ };
+ let pong = peer.sealer.seal(&Message::Pong { tx, src: observed });
+ let _ = match path {
+ Path::Direct(a) => self.send_udp(a, &pong),
+ Path::Relay => self.send_relay(peer.key(), &pong),
+ };
+ if let Path::Direct(a) = path
+ && !self.relay_only.load(Ordering::Relaxed)
+ {
+ let mut ps = peer.path.lock().expect("path");
+ let fresh = !ps.candidates.contains_key(&a);
+ ps.candidates.entry(a).or_default();
+ let unconfirmed = ps.candidates.get(&a).is_none_or(|c| c.last_pong.is_none());
+ drop(ps);
+ if fresh || unconfirmed {
+ // Ping back right away: a ping that got through
+ // means our ping back likely gets through too.
+ self.ping(&peer, a);
+ // The peer may have moved: check the current path
+ // too, so a silent one is noticed within a round
+ // trip or two (see `reselect`).
+ let best = peer.path.lock().expect("path").best.map(|b| b.0);
+ if let Some(best) = best
+ && best != a
+ {
+ self.ping(&peer, best);
+ }
+ }
+ }
+ }
+ Message::Pong { tx, src } => {
+ let mut ps = peer.path.lock().expect("path");
+ let Some((addr, sent)) = ps.pending.remove(&tx) else {
+ return;
+ };
+ if path != Path::Direct(addr) {
+ return;
+ }
+ let rtt = now.duration_since(sent);
+ let c = ps.candidates.entry(addr).or_default();
+ c.last_pong = Some(now);
+ c.rtt = Some(rtt);
+ let switch = match ps.best {
+ None => true,
+ Some((b, _, at)) if b == addr => {
+ ps.best = Some((addr, rtt, now));
+ let _ = at;
+ false
+ }
+ Some((best, brtt, at)) => {
+ // The current path leaves a ping unanswered well past
+ // its round trip (the peer moved: a new NAT mapping
+ // or network), it missed its last ping round, or
+ // this one is clearly faster.
+ let overdue = brtt * 2 + Duration::from_millis(100);
+ let best_silent = ps.pending.values().any(|(a, t)| {
+ *a == best && *t > at && now.duration_since(*t) > overdue
+ });
+ best_silent
+ || now.duration_since(at) > PING_INTERVAL + Duration::from_secs(1)
+ || rtt.as_secs_f64() < brtt.as_secs_f64() * 0.8
+ }
+ };
+ if switch {
+ ps.best = Some((addr, rtt, now));
+ ps.switches += 1;
+ tracing::debug!(peer = %peer.key().short(), %addr, ?rtt, "direct path");
+ }
+ drop(ps);
+ if !src.ip().is_unspecified() {
+ let mut eps = self.local_endpoints.write().expect("endpoints");
+ if !eps.contains(&src) && eps.len() < 32 {
+ // Peer-reflexive: how the peer sees us.
+ eps.push(src);
+ }
+ }
+ }
+ Message::CallMeMaybe { endpoints } => {
+ if self.relay_only.load(Ordering::Relaxed) {
+ return;
+ }
+ // Ping what it sent and what the map says, all at once: the
+ // peer is pinging us right now, so both NATs open.
+ let targets: Vec<SocketAddr> = {
+ let mut ps = peer.path.lock().expect("path");
+ for e in &endpoints {
+ ps.candidates.entry(*e).or_default();
+ }
+ ps.candidates.keys().copied().collect()
+ };
+ peer.touch();
+ for e in targets.into_iter().take(32) {
+ if e.port() != 0 && !e.ip().is_unspecified() {
+ self.ping(&peer, e);
+ }
+ }
+ }
+ }
+ }
+
+ fn ping(&self, peer: &Peer, addr: SocketAddr) {
+ let tx: disco::TxId = rand::random();
+ {
+ let mut ps = peer.path.lock().expect("path");
+ let now = Instant::now();
+ ps.pending
+ .retain(|_, (_, at)| now.duration_since(*at) < Duration::from_secs(10));
+ ps.pending.insert(tx, (addr, now));
+ ps.candidates.entry(addr).or_default().last_ping = Some(now);
+ }
+ let msg = peer.sealer.seal(&Message::Ping { tx, node: self.me });
+ let _ = self.send_udp(addr, &msg);
+ }
+
+ /// One discovery round for every active peer.
+ fn discover(&self) {
+ if self.relay_only.load(Ordering::Relaxed) {
+ return;
+ }
+ let now = Instant::now();
+ let endpoints = self.local_endpoints.read().expect("endpoints").clone();
+ for peer in self.peers() {
+ if !peer.active(now) {
+ continue;
+ }
+ let (targets, send_cmm) = {
+ let mut ps = peer.path.lock().expect("path");
+ let fresh_best =
+ matches!(ps.best, Some((_, _, at)) if now.duration_since(at) < PING_INTERVAL);
+ let due = ps
+ .last_round
+ .is_none_or(|t| now.duration_since(t) >= PING_INTERVAL);
+ if fresh_best || !due {
+ continue;
+ }
+ ps.last_round = Some(now);
+ let trusted = matches!(ps.current(now), Path::Direct(_));
+ let targets: Vec<SocketAddr> = match (trusted, ps.best) {
+ // Keep the working path alive; re-probe the others
+ // less often.
+ (true, Some((b, _, _))) => std::iter::once(b)
+ .chain(ps.candidates.iter().filter_map(|(a, c)| {
+ (*a != b
+ && c.last_ping.is_none_or(|t| {
+ now.duration_since(t) > Duration::from_secs(20)
+ }))
+ .then_some(*a)
+ }))
+ .collect(),
+ _ => ps.candidates.keys().copied().collect(),
+ };
+ let send_cmm = !trusted
+ && !endpoints.is_empty()
+ && ps
+ .last_cmm
+ .is_none_or(|t| now.duration_since(t) >= CMM_INTERVAL);
+ if send_cmm {
+ ps.last_cmm = Some(now);
+ }
+ (targets, send_cmm)
+ };
+ if send_cmm {
+ let cmm = peer.sealer.seal(&Message::CallMeMaybe {
+ endpoints: endpoints.clone(),
+ });
+ let _ = self.send_relay(peer.key(), &cmm);
+ }
+ for t in targets.into_iter().take(16) {
+ if t.port() == 0 || t.ip().is_unspecified() {
+ continue;
+ }
+ self.ping(&peer, t);
+ }
+ }
+ }
+
+ /// Leaves a direct path that stopped answering for the candidate that
+ /// answered most recently, without waiting for [`TRUST`] to run out.
+ fn reselect(&self) {
+ let now = Instant::now();
+ for peer in self.peers() {
+ let mut ps = peer.path.lock().expect("path");
+ let Some((best, brtt, at)) = ps.best else {
+ continue;
+ };
+ let overdue = brtt * 2 + Duration::from_millis(150);
+ let silent = ps
+ .pending
+ .values()
+ .any(|(a, t)| *a == best && *t > at && now.duration_since(*t) > overdue);
+ if !silent {
+ continue;
+ }
+ let next = ps
+ .candidates
+ .iter()
+ .filter(|(a, c)| **a != best && c.last_pong.is_some_and(|p| p > at))
+ .max_by_key(|(_, c)| c.last_pong)
+ .map(|(a, c)| (*a, c.rtt.unwrap_or(brtt), c.last_pong.unwrap_or(now)));
+ if let Some(next) = next {
+ tracing::debug!(peer = %peer.key().short(), from = %best, to = %next.0, "direct path moved");
+ ps.best = Some(next);
+ ps.switches += 1;
+ }
+ }
+ }
+
+ fn timers(&self) {
+ let mut buf = vec![0u8; 256];
+ for peer in self.peers() {
+ let mut tunn = peer.tunn.lock().expect("tunn");
+ if let TunnResult::WriteToNetwork(p) = tunn.update_timers(&mut buf) {
+ let p = p.to_vec();
+ drop(tunn);
+ let _ = self.send_to_peer(&peer, &p);
+ }
+ }
+ }
+
+ /// A packet the relay delivered from `src`.
+ pub(crate) fn on_relay(&self, src: PublicKey, data: &[u8]) {
+ self.on_datagram(Path::Relay, Some(src), data);
+ }
+
+ /// Asks a STUN server what our v4 socket maps to.
+ pub(crate) async fn stun(&self, server: SocketAddr, timeout: Duration) -> Option<SocketAddr> {
+ let tx: stun::TxId = rand::random();
+ let (otx, orx) = oneshot::channel();
+ self.stun_waiters.lock().expect("stun").insert(tx, otx);
+ let sent = self.send_udp(server, &stun::request(tx)).is_ok();
+ let got = if sent {
+ tokio::time::timeout(timeout, orx)
+ .await
+ .ok()
+ .and_then(Result::ok)
+ } else {
+ None
+ };
+ self.stun_waiters.lock().expect("stun").remove(&tx);
+ got
+ }
+
+ pub(crate) fn shutdown(&self) {
+ if let Some(s) = self.sockets.write().expect("sockets").take() {
+ for t in s.tasks {
+ t.abort();
+ }
+ }
+ self.set_relay(None);
+ }
+}
+
+impl Outbound for Engine {
+ /// `Ok` unless the direct path's socket is full (`WouldBlock`, which
+ /// QUIC waits out). A datagram that cannot go out otherwise (no path,
+ /// the relay reconnecting or its queue full) is dropped like any lost
+ /// UDP datagram and QUIC retransmits it: any other error would end the
+ /// QUIC connection, and a session must outlive a relay or network blip.
+ fn send_ip(&self, dst: Ipv6Addr, packet: &[u8]) -> io::Result<()> {
+ let Some(peer) = self.peer_by_addr(&dst) else {
+ tracing::trace!(%dst, "no mesh peer; dropping");
+ return Ok(());
+ };
+ peer.touch();
+ let mut buf = vec![0u8; packet.len() + 160];
+ let out = {
+ let mut tunn = peer.tunn.lock().expect("tunn");
+ match tunn.encapsulate(packet, &mut buf) {
+ TunnResult::WriteToNetwork(p) => Some(p.len()),
+ _ => None,
+ }
+ };
+ if let Some(n) = out
+ && let Err(e) = self.send_to_peer(&peer, &buf[..n])
+ {
+ if e.kind() == io::ErrorKind::WouldBlock && matches!(peer.path(), Path::Direct(_)) {
+ return Err(e);
+ }
+ tracing::trace!(error = %e, "mesh send dropped");
+ }
+ Ok(())
+ }
+
+ fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ let s = self.sockets.read().expect("sockets");
+ match s.as_ref() {
+ Some(s) => s.v4.poll_send_ready(cx),
+ // Shut down: sends are dropped (see `send_ip`), never an error
+ // QUIC would report.
+ None => Poll::Ready(Ok(())),
+ }
+ }
+}
+
+/// Socket buffers: room for a window's worth of datagrams at speed, so
+/// bursts are not dropped by the kernel before the receive loop runs.
+const SOCKET_BUFFER: usize = 8 << 20;
+
+fn bind_udp(addr: SocketAddr) -> io::Result<Arc<UdpSocket>> {
+ use socket2::{Domain, Protocol, Socket, Type};
+ let domain = if addr.is_ipv4() {
+ Domain::IPV4
+ } else {
+ Domain::IPV6
+ };
+ let s = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
+ if addr.is_ipv6() {
+ // Native IPv6 only; IPv4 has its own socket on the same port.
+ s.set_only_v6(true)?;
+ }
+ // Best effort: the kernel caps these (net.core.*mem_max on Linux).
+ let _ = s.set_recv_buffer_size(SOCKET_BUFFER);
+ let _ = s.set_send_buffer_size(SOCKET_BUFFER);
+ s.set_nonblocking(true)?;
+ s.bind(&addr.into())?;
+ Ok(Arc::new(UdpSocket::from_std(s.into())?))
+}
+
+async fn recv_loop(engine: std::sync::Weak<Engine>, sock: Arc<UdpSocket>) {
+ let mut buf = vec![0u8; MAX_DATAGRAM];
+ loop {
+ let (n, src) = match sock.recv_from(&mut buf).await {
+ Ok(v) => v,
+ Err(e) => {
+ // ICMP-induced errors (connection refused/reset) are
+ // per-datagram on some platforms; keep going.
+ tracing::trace!(error = %e, "udp recv");
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ continue;
+ }
+ };
+ let Some(engine) = engine.upgrade() else {
+ return;
+ };
+ let src = match src {
+ SocketAddr::V6(v6) => match v6.ip().to_ipv4_mapped() {
+ Some(v4) => SocketAddr::new(IpAddr::V4(v4), v6.port()),
+ None => src,
+ },
+ v4 => v4,
+ };
+ engine.on_datagram(Path::Direct(src), None, &buf[..n]);
+ }
+}
+
+async fn maintenance(engine: std::sync::Weak<Engine>) {
+ let mut timers = tokio::time::interval(Duration::from_millis(250));
+ timers.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ let kick = {
+ let Some(e) = engine.upgrade() else { return };
+ async move { e.disco_kick.notified().await }
+ };
+ tokio::select! {
+ _ = timers.tick() => {}
+ _ = kick => {}
+ }
+ let Some(e) = engine.upgrade() else { return };
+ if e.sockets.read().expect("sockets").is_none() {
+ return;
+ }
+ e.timers();
+ e.reselect();
+ e.discover();
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/key.rs b/libs/cua/crates/cua-mesh/src/key.rs
new file mode 100644
index 0000000000..ad009a878e
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/key.rs
@@ -0,0 +1,325 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Node identity: the WireGuard static key, the disco key, the QUIC
+//! certificate, and the mesh address derived from the node key.
+
+use std::fmt;
+use std::net::Ipv6Addr;
+use std::path::{Path, PathBuf};
+
+use base64::Engine as _;
+use boringtun::x25519;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest as _, Sha256};
+
+use crate::{Error, Result};
+
+/// The mesh's private address prefix (`fd5c:a000::/32`, a unique local
+/// range). Every node's address is the prefix plus 96 bits of the SHA-256 of
+/// its node key, so addresses need no allocation and a peer's address is
+/// checked against its key. They exist only inside Cua: no OS interface ever
+/// carries them, so they cannot clash with a VPN the user already runs.
+pub const MESH_PREFIX: [u8; 4] = [0xfd, 0x5c, 0xa0, 0x00];
+
+/// A 32-byte public key (a node key or a disco key), base64 on the wire.
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct PublicKey(pub [u8; 32]);
+
+impl PublicKey {
+ /// Parses standard base64.
+ pub fn parse(s: &str) -> Result<Self> {
+ let raw = base64::engine::general_purpose::STANDARD
+ .decode(s.trim())
+ .map_err(|e| Error::Protocol(format!("bad key {s:?}: {e}")))?;
+ let bytes: [u8; 32] = raw
+ .try_into()
+ .map_err(|_| Error::Protocol(format!("bad key length {s:?}")))?;
+ Ok(Self(bytes))
+ }
+
+ /// Standard base64.
+ pub fn to_base64(&self) -> String {
+ base64::engine::general_purpose::STANDARD.encode(self.0)
+ }
+
+ /// A short form for logs (`ab12cd34`).
+ pub fn short(&self) -> String {
+ hex::encode(&self.0[..4])
+ }
+
+ /// The mesh address of the node with this node key.
+ pub fn mesh_addr(&self) -> Ipv6Addr {
+ let digest = Sha256::digest(self.0);
+ let mut octets = [0u8; 16];
+ octets[..4].copy_from_slice(&MESH_PREFIX);
+ octets[4..].copy_from_slice(&digest[..12]);
+ Ipv6Addr::from(octets)
+ }
+
+ pub(crate) fn x25519(&self) -> x25519::PublicKey {
+ x25519::PublicKey::from(self.0)
+ }
+}
+
+impl fmt::Debug for PublicKey {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "PublicKey({})", self.short())
+ }
+}
+
+impl fmt::Display for PublicKey {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.to_base64())
+ }
+}
+
+impl Serialize for PublicKey {
+ fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
+ s.serialize_str(&self.to_base64())
+ }
+}
+
+impl<'de> Deserialize<'de> for PublicKey {
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
+ let s = String::deserialize(d)?;
+ Self::parse(&s).map_err(serde::de::Error::custom)
+ }
+}
+
+/// True when `addr` is in the mesh prefix.
+pub fn is_mesh_addr(addr: &Ipv6Addr) -> bool {
+ addr.octets()[..4] == MESH_PREFIX
+}
+
+/// An X25519 secret (a node key or a disco key).
+#[derive(Clone)]
+pub struct SecretKey(x25519::StaticSecret);
+
+impl SecretKey {
+ /// A fresh random key, from the OS RNG.
+ pub fn generate() -> Self {
+ Self(x25519::StaticSecret::from(os_random::<32>()))
+ }
+
+ /// From raw bytes.
+ pub fn from_bytes(bytes: [u8; 32]) -> Self {
+ Self(x25519::StaticSecret::from(bytes))
+ }
+
+ /// The public half.
+ pub fn public(&self) -> PublicKey {
+ PublicKey(x25519::PublicKey::from(&self.0).to_bytes())
+ }
+
+ /// X25519 with `peer`.
+ pub fn agree(&self, peer: &PublicKey) -> [u8; 32] {
+ self.0.diffie_hellman(&peer.x25519()).to_bytes()
+ }
+
+ pub(crate) fn x25519(&self) -> x25519::StaticSecret {
+ self.0.clone()
+ }
+
+ fn to_bytes(&self) -> [u8; 32] {
+ self.0.to_bytes()
+ }
+}
+
+impl fmt::Debug for SecretKey {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "SecretKey(public {})", self.public().short())
+ }
+}
+
+/// Everything a node keeps across restarts: its node key (WireGuard static
+/// key), disco key and QUIC certificate. Stored as one `0600` JSON file.
+#[derive(Clone)]
+pub struct NodeIdentity {
+ /// WireGuard static key.
+ pub node: SecretKey,
+ /// Path-discovery key (separate from the node key, as in other
+ /// WireGuard meshes, so disco never reuses the WireGuard key).
+ pub disco: SecretKey,
+ /// Self-signed QUIC certificate (DER) peers pin by SHA-256.
+ pub cert_der: Vec<u8>,
+ /// Its PKCS#8 private key (DER).
+ pub cert_key_der: Vec<u8>,
+}
+
+#[derive(Serialize, Deserialize)]
+struct StoredIdentity {
+ version: u32,
+ node: String,
+ disco: String,
+ cert: String,
+ cert_key: String,
+}
+
+impl fmt::Debug for NodeIdentity {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("NodeIdentity")
+ .field("node", &self.node.public().short())
+ .field("addr", &self.addr())
+ .finish()
+ }
+}
+
+impl NodeIdentity {
+ /// A fresh identity.
+ pub fn generate() -> Result<Self> {
+ let cert = rcgen::generate_simple_self_signed(vec!["cua-mesh".to_owned()])
+ .map_err(|e| Error::Io(format!("certificate: {e}")))?;
+ Ok(Self {
+ node: SecretKey::generate(),
+ disco: SecretKey::generate(),
+ cert_der: cert.cert.der().to_vec(),
+ cert_key_der: cert.signing_key.serialize_der(),
+ })
+ }
+
+ /// Loads `path`, creating (and saving, `0600`) a fresh identity on
+ /// first use.
+ pub fn load_or_create(path: &Path) -> Result<Self> {
+ if let Ok(raw) = std::fs::read_to_string(path) {
+ return Self::from_json(&raw)
+ .map_err(|e| Error::Io(format!("{}: {e}", path.display())));
+ }
+ let id = Self::generate()?;
+ id.save(path)?;
+ Ok(id)
+ }
+
+ /// Saves to `path` (`0600`, atomically).
+ pub fn save(&self, path: &Path) -> Result<()> {
+ let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b);
+ let stored = StoredIdentity {
+ version: 1,
+ node: b64(&self.node.to_bytes()),
+ disco: b64(&self.disco.to_bytes()),
+ cert: b64(&self.cert_der),
+ cert_key: b64(&self.cert_key_der),
+ };
+ let json = serde_json::to_vec_pretty(&stored).map_err(|e| Error::Io(e.to_string()))?;
+ write_private(path, &json)
+ }
+
+ fn from_json(raw: &str) -> Result<Self> {
+ let s: StoredIdentity =
+ serde_json::from_str(raw).map_err(|e| Error::Protocol(e.to_string()))?;
+ let d = |v: &str| {
+ base64::engine::general_purpose::STANDARD
+ .decode(v)
+ .map_err(|e| Error::Protocol(e.to_string()))
+ };
+ let key = |v: &str| -> Result<SecretKey> {
+ let raw: [u8; 32] = d(v)?
+ .try_into()
+ .map_err(|_| Error::Protocol("bad key length".into()))?;
+ Ok(SecretKey::from_bytes(raw))
+ };
+ Ok(Self {
+ node: key(&s.node)?,
+ disco: key(&s.disco)?,
+ cert_der: d(&s.cert)?,
+ cert_key_der: d(&s.cert_key)?,
+ })
+ }
+
+ /// The node's public key.
+ pub fn public(&self) -> PublicKey {
+ self.node.public()
+ }
+
+ /// The node's mesh address.
+ pub fn addr(&self) -> Ipv6Addr {
+ self.public().mesh_addr()
+ }
+
+ /// SHA-256 of the QUIC certificate, hex (what peers pin).
+ pub fn cert_pin(&self) -> String {
+ hex::encode(Sha256::digest(&self.cert_der))
+ }
+}
+
+/// Writes `bytes` to `path` with mode `0600` (atomically: temp + rename).
+pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
+ use std::io::Write as _;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| Error::Io(e.to_string()))?;
+ }
+ let tmp: PathBuf = path.with_extension(format!("tmp{}", std::process::id()));
+ let mut opts = std::fs::OpenOptions::new();
+ opts.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ opts.mode(0o600);
+ }
+ let mut f = opts
+ .open(&tmp)
+ .map_err(|e| Error::Io(format!("{}: {e}", tmp.display())))?;
+ f.write_all(bytes).map_err(|e| Error::Io(e.to_string()))?;
+ f.sync_all().ok();
+ drop(f);
+ std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))
+}
+
+/// `N` bytes from the OS RNG. Keys and nonces come from here, never from a
+/// userspace PRNG (`rand::random`): its state is copied by a memory snapshot
+/// into every clone of a running machine.
+pub fn os_random<const N: usize>() -> [u8; N] {
+ use rand::TryRngCore as _;
+ let mut bytes = [0u8; N];
+ rand::rngs::OsRng
+ .try_fill_bytes(&mut bytes)
+ .expect("OS random number generator");
+ bytes
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mesh_addresses_follow_the_key() {
+ let k = SecretKey::generate().public();
+ let a = k.mesh_addr();
+ assert!(is_mesh_addr(&a));
+ assert_eq!(a, k.mesh_addr());
+ assert_ne!(a, SecretKey::generate().public().mesh_addr());
+ }
+
+ #[test]
+ fn keys_round_trip() {
+ let k = SecretKey::generate().public();
+ assert_eq!(PublicKey::parse(&k.to_base64()).unwrap(), k);
+ let json = serde_json::to_string(&k).unwrap();
+ assert_eq!(serde_json::from_str::<PublicKey>(&json).unwrap(), k);
+ assert!(PublicKey::parse("AAAA").is_err());
+ }
+
+ #[test]
+ fn agreement_is_symmetric() {
+ let a = SecretKey::generate();
+ let b = SecretKey::generate();
+ assert_eq!(a.agree(&b.public()), b.agree(&a.public()));
+ }
+
+ #[test]
+ fn identity_persists_privately() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("mesh/identity.json");
+ let a = NodeIdentity::load_or_create(&path).unwrap();
+ let b = NodeIdentity::load_or_create(&path).unwrap();
+ assert_eq!(a.public(), b.public());
+ assert_eq!(a.disco.public(), b.disco.public());
+ assert_eq!(a.cert_pin(), b.cert_pin());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let mode = std::fs::metadata(&path).unwrap().permissions().mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/lib.rs b/libs/cua/crates/cua-mesh/src/lib.rs
new file mode 100644
index 0000000000..1b0354a303
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/lib.rs
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A WireGuard®-based mesh inside Cua, for Spaces traffic only.
+//!
+//! Every device and machine runs a userspace node ([`Mesh`]): no TUN
+//! device, no Network Extension, no kernel module, no root, and no clash
+//! with a VPN (Tailscale included) the machine already runs. Mesh addresses
+//! (`fd5c:a000::/32`) exist only inside Cua.
+//!
+//! - **End to end.** Peers talk WireGuard (the Noise protocol state machine
+//! from Cloudflare's BSD-licensed boringtun). The relay never holds a
+//! session key: what it forwards is ciphertext.
+//! - **Direct first.** Each node learns its public endpoint over STUN,
+//! publishes its candidates through the coordinator, and pings a peer's
+//! candidates while asking the peer (through the relay) to ping back at
+//! the same time, which opens both NATs ([`engine`]).
+//! - **Encrypted fallback.** Until a direct path answers, and whenever it
+//! stops answering, packets go through the coordinator's relay, which
+//! forwards WireGuard and disco ciphertext between the two node keys.
+//! - **Streams.** QUIC runs over the tunnel between the two mesh addresses
+//! ([`quic`]); [`Mesh::forward`] turns it into a loopback port any HTTP,
+//! gRPC or WebSocket client can use, and UDP on the same port reaches the
+//! peer's media port (QUIC streaming over the mesh).
+//! - **Survives disruption.** Sessions belong to keys and mesh addresses,
+//! not to paths: a coordinator or relay restart, a NAT rebinding or a
+//! network change moves packets to another path underneath a QUIC
+//! connection that keeps going.
+//!
+//! The coordinator (accounts, devices, share lists, the relay) runs in
+//! Cua's relay service; this crate only speaks its protocol
+//! ([`proto`]). [`testing`] has an in-process stand-in for tests.
+
+pub mod coord;
+pub mod dialer;
+pub mod disco;
+pub mod engine;
+pub mod key;
+pub mod node;
+pub mod packet;
+pub mod policy;
+pub mod proto;
+pub mod quic;
+pub mod stun;
+pub mod vnet;
+
+#[cfg(feature = "testing")]
+pub mod testing;
+
+pub use coord::{AuthFuture, AuthProvider, ControlState, PairVerifier};
+pub use engine::Path;
+pub use key::{NodeIdentity, PublicKey, SecretKey};
+pub use node::{Forward, IncomingStream, MEDIA_UDP_PORT, Mesh, MeshConfig, PeerStatus, Status};
+pub use policy::{Channel, Policy};
+pub use proto::{Grant, MeshInfo, Mode, NodeKind, PeerInfo, PeerUsage, VERSION};
+pub use quic::{MeshStream, STREAM_PORT, StreamHeader};
+
+/// Mesh errors.
+#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
+pub enum Error {
+ /// Local I/O or setup.
+ #[error("mesh: {0}")]
+ Io(String),
+ /// A malformed or unexpected message.
+ #[error("mesh protocol: {0}")]
+ Protocol(String),
+ /// The coordinator or peer is out of reach.
+ #[error("mesh unreachable: {0}")]
+ Unreachable(String),
+ /// Refused (credentials, policy, a pairing proof).
+ #[error("mesh refused: {0}")]
+ Refused(String),
+ /// The other side does not support the mesh (or this version of it).
+ #[error("mesh unsupported: {0}")]
+ Unsupported(String),
+ /// No such peer.
+ #[error("mesh: {0}")]
+ NotFound(String),
+}
+
+/// Mesh results.
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// An [`AuthProvider`] that always sends the same headers.
+pub fn static_auth(headers: Vec<(String, String)>) -> AuthProvider {
+ std::sync::Arc::new(move || {
+ let h = headers.clone();
+ Box::pin(async move { Ok(h) })
+ })
+}
diff --git a/libs/cua/crates/cua-mesh/src/node.rs b/libs/cua/crates/cua-mesh/src/node.rs
new file mode 100644
index 0000000000..c4acb8cf1a
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/node.rs
@@ -0,0 +1,1201 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! [`Mesh`]: one node on the mesh (a client device or a hosted machine).
+
+use std::collections::{BTreeSet, HashMap};
+use std::net::{IpAddr, SocketAddr, SocketAddrV6};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, RwLock};
+use std::time::{Duration, Instant};
+
+use serde::Serialize;
+use tokio::net::{TcpListener, UdpSocket};
+use tokio::sync::mpsc;
+
+use crate::coord::{self, AuthProvider, Control, ControlConfig, ControlState, PairVerifier};
+use crate::engine::{Engine, Path};
+use crate::key::{NodeIdentity, PublicKey};
+use crate::proto::{self, NodeKind, PeerInfo, PeerUsage};
+use crate::quic::{self, MeshStream, StreamHeader};
+use crate::vnet::VSocket;
+use crate::{Error, Result};
+
+/// The mesh UDP port a machine forwards to its local QUIC media port.
+pub const MEDIA_UDP_PORT: u16 = 3212;
+
+/// How a node is set up.
+#[derive(Clone)]
+pub struct MeshConfig {
+ /// The coordinator (the relay's base URL: `https://relay.example`).
+ pub coordinator: String,
+ /// Machine or client.
+ pub kind: NodeKind,
+ /// Display name.
+ pub name: String,
+ /// Where the node identity lives (`0600` JSON, created on first use).
+ /// `None`: a fresh in-memory identity the coordinator forgets when this
+ /// node disconnects (a one-off CLI run).
+ pub identity_path: Option<PathBuf>,
+ /// Credentials for the coordinator, fetched before every connect.
+ pub auth: AuthProvider,
+ /// UDP port (0: any).
+ pub listen_port: u16,
+ /// Static mode, machines: decides pairing requests.
+ pub pair_verifier: Option<PairVerifier>,
+ /// Static mode, machines: where approved client keys persist.
+ pub approved_path: Option<PathBuf>,
+ /// Extra STUN servers (`host:port`) besides the coordinator's.
+ pub stun: Vec<String>,
+ /// Never use direct paths (tests; `CUA_MESH_RELAY_ONLY=1`).
+ pub relay_only: bool,
+}
+
+impl std::fmt::Debug for MeshConfig {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("MeshConfig")
+ .field("coordinator", &self.coordinator)
+ .field("kind", &self.kind)
+ .field("name", &self.name)
+ .finish()
+ }
+}
+
+impl MeshConfig {
+ /// Defaults for a node of `kind` at `coordinator`.
+ pub fn new(
+ coordinator: impl Into<String>,
+ kind: NodeKind,
+ identity_path: Option<PathBuf>,
+ auth: AuthProvider,
+ ) -> Self {
+ Self {
+ coordinator: coordinator.into(),
+ kind,
+ name: hostname(),
+ identity_path,
+ auth,
+ listen_port: 0,
+ pair_verifier: None,
+ approved_path: None,
+ stun: Vec::new(),
+ relay_only: std::env::var("CUA_MESH_RELAY_ONLY").is_ok_and(|v| v == "1"),
+ }
+ }
+}
+
+/// The machine's hostname, for display.
+pub fn hostname() -> String {
+ std::env::var("HOSTNAME")
+ .ok()
+ .filter(|h| !h.is_empty())
+ .or_else(|| {
+ std::process::Command::new("hostname")
+ .output()
+ .ok()
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
+ })
+ .filter(|h| !h.is_empty())
+ .unwrap_or_else(|| "cua".into())
+}
+
+/// Static-mode client keys a machine approved (persisted).
+#[derive(Debug, Default)]
+pub struct Approved {
+ path: Option<PathBuf>,
+ keys: RwLock<BTreeSet<PublicKey>>,
+}
+
+impl Approved {
+ /// Loads from `path` (missing: empty).
+ pub fn load(path: Option<PathBuf>) -> Self {
+ let keys = path
+ .as_ref()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|raw| serde_json::from_str::<Vec<PublicKey>>(&raw).ok())
+ .unwrap_or_default();
+ Self {
+ path,
+ keys: RwLock::new(keys.into_iter().collect()),
+ }
+ }
+
+ /// Approved?
+ pub fn contains(&self, k: &PublicKey) -> bool {
+ self.keys.read().expect("keys").contains(k)
+ }
+
+ /// Approves `k` (and saves).
+ pub fn add(&self, k: PublicKey) {
+ let snapshot: Vec<PublicKey> = {
+ let mut keys = self.keys.write().expect("keys");
+ if !keys.insert(k) {
+ return;
+ }
+ keys.iter().copied().collect()
+ };
+ if let Some(path) = &self.path
+ && let Ok(json) = serde_json::to_vec_pretty(&snapshot)
+ && let Err(e) = crate::key::write_private(path, &json)
+ {
+ tracing::warn!(error = %e, "cannot save approved mesh peers");
+ }
+ }
+
+ /// Revokes `k`.
+ pub fn remove(&self, k: &PublicKey) -> bool {
+ let snapshot: Vec<PublicKey> = {
+ let mut keys = self.keys.write().expect("keys");
+ if !keys.remove(k) {
+ return false;
+ }
+ keys.iter().copied().collect()
+ };
+ if let Some(path) = &self.path
+ && let Ok(json) = serde_json::to_vec_pretty(&snapshot)
+ {
+ let _ = crate::key::write_private(path, &json);
+ }
+ true
+ }
+}
+
+/// A stream a peer opened to this node.
+pub struct IncomingStream {
+ /// Who.
+ pub peer: PeerInfo,
+ /// What it asked for.
+ pub header: StreamHeader,
+ /// The stream.
+ pub stream: MeshStream,
+}
+
+impl std::fmt::Debug for IncomingStream {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("IncomingStream")
+ .field("peer", &self.peer.node_key)
+ .field("service", &self.header.service)
+ .finish()
+ }
+}
+
+/// A peer, for status displays and measurements.
+#[derive(Debug, Clone, Serialize)]
+pub struct PeerStatus {
+ /// Node key.
+ pub node_key: PublicKey,
+ /// Name.
+ pub name: String,
+ /// Machine id (machines).
+ pub machine_id: Option<String>,
+ /// Kind.
+ pub kind: NodeKind,
+ /// Online at the coordinator.
+ pub online: bool,
+ /// `direct <addr>` or `relay`.
+ pub path: String,
+ /// Direct path round trip, when direct.
+ pub rtt_ms: Option<f64>,
+ /// Seconds since the last WireGuard handshake.
+ pub handshake_age_s: Option<f64>,
+ /// Encrypted bytes sent and received, direct and relayed.
+ pub tx_direct: u64,
+ /// See `tx_direct`.
+ pub tx_relay: u64,
+ /// See `tx_direct`.
+ pub rx_direct: u64,
+ /// See `tx_direct`.
+ pub rx_relay: u64,
+ /// Path switches so far.
+ pub path_switches: u64,
+}
+
+/// The node's status.
+#[derive(Debug, Clone, Serialize)]
+pub struct Status {
+ /// Mesh address.
+ pub addr: std::net::Ipv6Addr,
+ /// Node key.
+ pub node_key: PublicKey,
+ /// Coordinator connection.
+ pub connected: bool,
+ /// Account or static.
+ pub mode: Option<proto::Mode>,
+ /// Our candidate endpoints.
+ pub endpoints: Vec<SocketAddr>,
+ /// Peers.
+ pub peers: Vec<PeerStatus>,
+ /// Last coordinator error.
+ pub last_error: Option<String>,
+}
+
+struct Inner {
+ identity: NodeIdentity,
+ engine: Arc<Engine>,
+ control: Arc<Control>,
+ endpoint: quinn::Endpoint,
+ conns: tokio::sync::Mutex<HashMap<PublicKey, quinn::Connection>>,
+ incoming: tokio::sync::Mutex<mpsc::Receiver<IncomingStream>>,
+ stun: Vec<String>,
+ shutdown: coord::tokio_util_cancel::Token,
+ approved: Option<Arc<Approved>>,
+ udp_services: Mutex<Vec<tokio::task::JoinHandle<()>>>,
+ /// The peer flows of every [`Mesh::serve_udp`] service.
+ udp_flows: Mutex<Vec<UdpFlows>>,
+ endpoints: Mutex<Vec<SocketAddr>>,
+ /// Connections peers opened to us, so a peer leaving the map is cut.
+ inbound: Mutex<Vec<(PublicKey, quinn::Connection)>>,
+}
+
+/// One node on the mesh. Cheap to clone.
+#[derive(Clone)]
+pub struct Mesh {
+ inner: Arc<Inner>,
+}
+
+impl std::fmt::Debug for Mesh {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Mesh")
+ .field("addr", &self.inner.identity.addr())
+ .finish()
+ }
+}
+
+impl Mesh {
+ /// Starts the node: binds its UDP sockets, connects to the coordinator
+ /// in the background and serves its stream endpoint. Use
+ /// [`Mesh::wait_ready`] to wait for the first network map.
+ pub async fn start(cfg: MeshConfig) -> Result<Self> {
+ let identity = match &cfg.identity_path {
+ Some(path) => NodeIdentity::load_or_create(path)?,
+ None => NodeIdentity::generate()?,
+ };
+ let engine = Engine::new(identity.clone(), cfg.listen_port, cfg.relay_only)
+ .await
+ .map_err(|e| Error::Io(format!("udp: {e}")))?;
+ let control = Control::new();
+ let approved = match cfg.kind {
+ NodeKind::Machine => Some(Arc::new(Approved::load(cfg.approved_path.clone()))),
+ NodeKind::Client => None,
+ };
+ let sock = engine
+ .vnet
+ .bind(quic::STREAM_PORT)
+ .map_err(|e| Error::Io(e.to_string()))?;
+ let endpoint = quic::endpoint(&identity, sock)?;
+ let (in_tx, in_rx) = mpsc::channel(256);
+ let shutdown = coord::tokio_util_cancel::Token::new();
+ let inner = Arc::new(Inner {
+ identity: identity.clone(),
+ engine: engine.clone(),
+ control: control.clone(),
+ endpoint: endpoint.clone(),
+ conns: tokio::sync::Mutex::new(HashMap::new()),
+ incoming: tokio::sync::Mutex::new(in_rx),
+ stun: cfg.stun.clone(),
+ shutdown: shutdown.clone(),
+ approved: approved.clone(),
+ udp_services: Mutex::new(Vec::new()),
+ udp_flows: Mutex::new(Vec::new()),
+ endpoints: Mutex::new(Vec::new()),
+ inbound: Mutex::new(Vec::new()),
+ });
+ // Coordinator connection.
+ tokio::spawn(coord::run(
+ ControlConfig {
+ url: cfg.coordinator.clone(),
+ kind: cfg.kind,
+ name: cfg.name.clone(),
+ auth: cfg.auth.clone(),
+ pair_verifier: cfg.pair_verifier.clone(),
+ approved,
+ ephemeral: cfg.identity_path.is_none(),
+ },
+ control,
+ engine.clone(),
+ identity,
+ shutdown.clone(),
+ ));
+ // Incoming streams (machines serve; a client refuses any
+ // connection a peer opens to it).
+ tokio::spawn(accept_loop(
+ Arc::downgrade(&inner),
+ endpoint,
+ in_tx,
+ cfg.kind == NodeKind::Machine,
+ ));
+ // Endpoint discovery.
+ tokio::spawn(discovery_loop(Arc::downgrade(&inner)));
+ // A refused device loses every connection at once.
+ tokio::spawn(denial_loop(
+ Arc::downgrade(&inner),
+ inner.control.state.subscribe(),
+ ));
+ // Peers that leave the map lose their connections.
+ tokio::spawn(prune_loop(Arc::downgrade(&inner), engine.subscribe_peers()));
+ Ok(Self { inner })
+ }
+
+ /// Waits until the coordinator welcomed this node and sent a map.
+ pub async fn wait_ready(&self, timeout: Duration) -> Result<()> {
+ let mut rx = self.inner.control.state.subscribe();
+ // Ready, or a coordinator that says it has no mesh or refuses this
+ // node (a revoked device): no point waiting for either to change.
+ let ready = rx.wait_for(|s| {
+ (s.connected && s.has_netmap)
+ || s.denied.is_some()
+ || s.last_error
+ .as_deref()
+ .is_some_and(|e| e.contains("no mesh coordinator"))
+ });
+ match tokio::time::timeout(timeout, ready).await {
+ Ok(Ok(s)) if s.connected && s.has_netmap => Ok(()),
+ _ => {
+ let s = self.inner.control.state.borrow().clone();
+ if let Some(reason) = s.denied {
+ return Err(Error::Refused(reason));
+ }
+ Err(match s.last_error {
+ Some(e) if e.contains("no mesh coordinator") => Error::Unsupported(e),
+ Some(e) => Error::Unreachable(e),
+ None => Error::Unreachable("the mesh coordinator did not answer".into()),
+ })
+ }
+ }
+ }
+
+ /// The coordinator connection's state.
+ pub fn control_state(&self) -> ControlState {
+ self.inner.control.state.borrow().clone()
+ }
+
+ /// This node's key.
+ pub fn node_key(&self) -> PublicKey {
+ self.inner.identity.public()
+ }
+
+ /// This node's mesh address.
+ pub fn addr(&self) -> std::net::Ipv6Addr {
+ self.inner.identity.addr()
+ }
+
+ /// Current peers.
+ pub fn peers(&self) -> Vec<PeerInfo> {
+ self.inner
+ .engine
+ .peers()
+ .iter()
+ .map(|p| p.info.read().expect("info").clone())
+ .collect()
+ }
+
+ /// The peer serving machine `machine_id`, if it is in the map.
+ pub fn machine(&self, machine_id: &str) -> Option<PeerInfo> {
+ self.peers()
+ .into_iter()
+ .find(|p| p.kind == NodeKind::Machine && p.machine_id.as_deref() == Some(machine_id))
+ }
+
+ /// Waits up to `timeout` for machine `machine_id` to be in the map.
+ pub async fn wait_machine(&self, machine_id: &str, timeout: Duration) -> Option<PeerInfo> {
+ let mut rx = self.inner.engine.subscribe_peers();
+ let deadline = tokio::time::Instant::now() + timeout;
+ loop {
+ if let Some(p) = self.machine(machine_id) {
+ return Some(p);
+ }
+ if tokio::time::timeout_at(deadline, rx.changed())
+ .await
+ .is_err()
+ {
+ return None;
+ }
+ }
+ }
+
+ /// [`Self::wait_machine`], but answers as soon as the coordinator's
+ /// network map has arrived: a machine missing from it is not on the
+ /// mesh (an older cua-spacesd, or a machine with the mesh off), so a
+ /// caller that can fall back does not wait out `timeout` for it.
+ pub async fn wait_machine_in_map(
+ &self,
+ machine_id: &str,
+ timeout: Duration,
+ ) -> Option<PeerInfo> {
+ let mut peers = self.inner.engine.subscribe_peers();
+ let mut control = self.inner.control.state.subscribe();
+ let deadline = tokio::time::Instant::now() + timeout;
+ loop {
+ if let Some(p) = self.machine(machine_id) {
+ return Some(p);
+ }
+ if control.borrow_and_update().has_netmap {
+ return None;
+ }
+ let changed = async {
+ tokio::select! {
+ r = peers.changed() => r.is_ok(),
+ r = control.changed() => r.is_ok(),
+ }
+ };
+ match tokio::time::timeout_at(deadline, changed).await {
+ Ok(true) => {}
+ _ => return self.machine(machine_id),
+ }
+ }
+ }
+
+ /// The path traffic to `peer` takes right now.
+ pub fn path(&self, peer: &PublicKey) -> Option<Path> {
+ self.inner.engine.peer(peer).map(|p| p.path())
+ }
+
+ /// Status for displays and measurements.
+ pub fn status(&self) -> Status {
+ let state = self.inner.control.state.borrow().clone();
+ let peers = self
+ .inner
+ .engine
+ .peers()
+ .iter()
+ .map(|p| {
+ let info = p.info.read().expect("info").clone();
+ use std::sync::atomic::Ordering::Relaxed;
+ PeerStatus {
+ node_key: info.node_key,
+ name: info.name.clone(),
+ machine_id: info.machine_id.clone(),
+ kind: info.kind,
+ online: info.online,
+ path: p.path().to_string(),
+ rtt_ms: p.rtt().map(|d| d.as_secs_f64() * 1000.0),
+ handshake_age_s: p.handshake_age().map(|d| d.as_secs_f64()),
+ tx_direct: p.counters.tx_direct.load(Relaxed),
+ tx_relay: p.counters.tx_relay.load(Relaxed),
+ rx_direct: p.counters.rx_direct.load(Relaxed),
+ rx_relay: p.counters.rx_relay.load(Relaxed),
+ path_switches: p.path_switches(),
+ }
+ })
+ .collect();
+ Status {
+ addr: self.addr(),
+ node_key: self.node_key(),
+ connected: state.connected,
+ mode: state.mode,
+ endpoints: self.inner.control_endpoints(),
+ peers,
+ last_error: state.last_error,
+ }
+ }
+
+ async fn connection(&self, peer: &PeerInfo) -> Result<quinn::Connection> {
+ let mut conns = self.inner.conns.lock().await;
+ if let Some(c) = conns.get(&peer.node_key)
+ && c.close_reason().is_none()
+ {
+ return Ok(c.clone());
+ }
+ self.inner.engine.want(&peer.node_key);
+ let c = tokio::time::timeout(
+ Duration::from_secs(20),
+ quic::connect(&self.inner.endpoint, peer.addr(), &peer.quic_pin),
+ )
+ .await
+ .map_err(|_| Error::Unreachable(format!("{} did not answer on the mesh", peer.name)))??;
+ conns.insert(peer.node_key, c.clone());
+ Ok(c)
+ }
+
+ /// Why this node can no longer use the mesh, while it holds: its
+ /// device was refused, or the relay turned its mesh off. Callers with
+ /// a fallback (the relay's HTTPS path) switch to it.
+ pub fn unusable(&self) -> Option<String> {
+ let s = self.inner.control.state.borrow();
+ if s.connected {
+ return None;
+ }
+ s.denied.clone().or_else(|| {
+ s.unsupported.then(|| {
+ s.last_error
+ .clone()
+ .unwrap_or_else(|| "the relay has no mesh coordinator".into())
+ })
+ })
+ }
+
+ /// The coordinator's refusal of this node, while it stands.
+ fn denied(&self) -> Option<String> {
+ let s = self.inner.control.state.borrow();
+ (!s.connected).then(|| s.denied.clone()).flatten()
+ }
+
+ /// Opens a stream to `service` on `peer`.
+ pub async fn open_stream(
+ &self,
+ peer: &PublicKey,
+ service: &str,
+ session: Option<String>,
+ ) -> Result<MeshStream> {
+ // A revoked device: say so now, not after a peer that already
+ // dropped it fails to answer.
+ if let Some(reason) = self.denied() {
+ return Err(Error::Refused(reason));
+ }
+ let info = self
+ .inner
+ .engine
+ .peer(peer)
+ .map(|p| p.info.read().expect("info").clone())
+ .ok_or_else(|| Error::NotFound(format!("peer {} is not in the mesh", peer.short())))?;
+ let header = StreamHeader {
+ service: service.to_owned(),
+ session,
+ };
+ for attempt in 0..2 {
+ let conn = self.connection(&info).await?;
+ match conn.open_bi().await {
+ Ok((mut send, recv)) => {
+ quic::write_header(&mut send, &header).await?;
+ return Ok(quic::join(send, recv));
+ }
+ Err(e) if attempt == 0 => {
+ tracing::debug!(error = %e, "mesh connection went away; reconnecting");
+ self.inner.conns.lock().await.remove(&info.node_key);
+ }
+ Err(e) => return Err(Error::Unreachable(e.to_string())),
+ }
+ }
+ unreachable!("two attempts")
+ }
+
+ /// The next stream a peer opened to this node.
+ pub async fn accept(&self) -> Option<IncomingStream> {
+ self.inner.incoming.lock().await.recv().await
+ }
+
+ /// Forwards a loopback port to `service` on `peer`: every TCP
+ /// connection to the returned address becomes one mesh stream, and
+ /// datagrams to the same port number on UDP go to the peer's
+ /// [`MEDIA_UDP_PORT`]. Dropping the [`Forward`] stops it.
+ pub async fn forward(
+ &self,
+ peer: PublicKey,
+ service: &str,
+ session: Option<String>,
+ ) -> Result<Forward> {
+ let (tcp, udp) = bind_pair().await?;
+ let local = tcp.local_addr().map_err(|e| Error::Io(e.to_string()))?;
+ let me = self.clone();
+ let service = service.to_owned();
+ let session2 = session.clone();
+ let tcp_task = tokio::spawn(async move {
+ loop {
+ let Ok((conn, _)) = tcp.accept().await else {
+ continue;
+ };
+ let me = me.clone();
+ let service = service.clone();
+ let session = session2.clone();
+ tokio::spawn(async move {
+ match me.open_stream(&peer, &service, session).await {
+ Ok(stream) => quic::splice(conn, stream).await,
+ // The process or the node is going away (a short
+ // `cua` run exiting): nothing to warn about.
+ Err(e) if stopping(&e, me.inner.shutdown.is_cancelled()) => {
+ tracing::debug!(error = %e, "mesh forward while stopping")
+ }
+ Err(e) => tracing::warn!(error = %e, "mesh forward"),
+ }
+ });
+ }
+ });
+ let udp_task = udp.map(|udp| {
+ let me = self.clone();
+ tokio::spawn(udp_client_forward(me, Arc::new(udp), peer))
+ });
+ Ok(Forward {
+ local,
+ tasks: [Some(tcp_task), udp_task].into_iter().flatten().collect(),
+ })
+ }
+
+ /// Serves mesh UDP `port` by relaying each peer flow to `target` (a
+ /// local UDP service, e.g. QUIC media).
+ pub fn serve_udp(&self, port: u16, target: SocketAddr) -> Result<()> {
+ let sock = self
+ .inner
+ .engine
+ .vnet
+ .bind(port)
+ .map_err(|e| Error::Io(e.to_string()))?;
+ let flows = UdpFlows {
+ started: Instant::now(),
+ map: Arc::default(),
+ };
+ self.inner
+ .udp_flows
+ .lock()
+ .expect("udp flows")
+ .push(flows.clone());
+ let task = tokio::spawn(udp_server_forward(sock, target, flows));
+ self.inner.udp_services.lock().expect("udp").push(task);
+ Ok(())
+ }
+
+ /// Peers that sent a datagram to a [`Mesh::serve_udp`] service (QUIC
+ /// media) within `within`.
+ pub fn udp_active_peers(&self, within: Duration) -> Vec<PublicKey> {
+ let within = within.as_millis() as u64;
+ let addrs: BTreeSet<std::net::Ipv6Addr> = self
+ .inner
+ .udp_flows
+ .lock()
+ .expect("udp flows")
+ .iter()
+ .flat_map(|f| {
+ let now = f.started.elapsed().as_millis() as u64;
+ f.map
+ .lock()
+ .expect("flows")
+ .iter()
+ .filter(|(_, flow)| {
+ now.saturating_sub(flow.last_ms.load(Ordering::Relaxed)) <= within
+ })
+ .map(|(src, _)| *src.ip())
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ if addrs.is_empty() {
+ return Vec::new();
+ }
+ self.peers()
+ .into_iter()
+ .filter(|p| addrs.contains(&p.addr()))
+ .map(|p| p.node_key)
+ .collect()
+ }
+
+ /// Account mode, machines: reports the streams peers hold open now
+ /// (a full snapshot) to the coordinator, which meters them as it
+ /// meters its own HTTPS path. Sent only when it changed, and again
+ /// after a reconnect; a coordinator that does not meter is sent
+ /// nothing. Cheap to call often.
+ pub fn report_usage(&self, peers: Vec<PeerUsage>) {
+ self.inner.control.set_usage(peers);
+ }
+
+ /// Static mode: pairs this client with machine `machine_id` by proving
+ /// its env token (the proof goes through the coordinator; the token does
+ /// not).
+ pub async fn pair(&self, machine_id: &str, env_token: &str) -> Result<()> {
+ let ts = proto::now_secs();
+ let proof = proto::pair_proof(env_token, machine_id, &self.node_key(), ts);
+ self.inner
+ .control
+ .pair(machine_id, ts, proof, Duration::from_secs(15))
+ .await
+ }
+
+ /// Static mode, machines: forgets an approved client.
+ pub fn revoke(&self, client: &PublicKey) -> bool {
+ let removed = self
+ .inner
+ .approved
+ .as_ref()
+ .is_some_and(|a| a.remove(client));
+ if removed {
+ self.inner.engine.remove_peer(client);
+ }
+ removed
+ }
+
+ /// Moves to new UDP ports (a network change) and re-discovers paths.
+ pub async fn rebind(&self) -> Result<()> {
+ self.inner
+ .engine
+ .rebind()
+ .await
+ .map_err(|e| Error::Io(e.to_string()))?;
+ refresh_endpoints(&self.inner).await;
+ Ok(())
+ }
+
+ /// Never use direct paths from now on (or again).
+ pub fn set_relay_only(&self, on: bool) {
+ self.inner.engine.set_relay_only(on);
+ }
+
+ /// Stops the node.
+ pub fn shutdown(&self) {
+ self.inner.shutdown.cancel();
+ self.inner.endpoint.close(0u32.into(), b"shutdown");
+ self.inner.engine.shutdown();
+ for t in self.inner.udp_services.lock().expect("udp").drain(..) {
+ t.abort();
+ }
+ }
+}
+
+/// Whether a forward's failure only means this node is stopping: it was
+/// shut down, or the QUIC endpoint is (the runtime is ending).
+fn stopping(e: &Error, shut_down: bool) -> bool {
+ shut_down || matches!(e, Error::Unreachable(m) if m.contains("endpoint stopping"))
+}
+
+impl Inner {
+ fn control_endpoints(&self) -> Vec<SocketAddr> {
+ self.endpoints.lock().expect("endpoints").clone()
+ }
+}
+
+/// A loopback forward ([`Mesh::forward`]).
+#[derive(Debug)]
+pub struct Forward {
+ /// Where to connect (TCP, and UDP on the same port when it was free).
+ pub local: SocketAddr,
+ tasks: Vec<tokio::task::JoinHandle<()>>,
+}
+
+impl Drop for Forward {
+ fn drop(&mut self) {
+ for t in &self.tasks {
+ t.abort();
+ }
+ }
+}
+
+async fn bind_pair() -> Result<(TcpListener, Option<UdpSocket>)> {
+ for _ in 0..16 {
+ let tcp = TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .map_err(|e| Error::Io(e.to_string()))?;
+ let port = tcp
+ .local_addr()
+ .map_err(|e| Error::Io(e.to_string()))?
+ .port();
+ if let Ok(udp) = UdpSocket::bind(("127.0.0.1", port)).await {
+ return Ok((tcp, Some(udp)));
+ }
+ }
+ let tcp = TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .map_err(|e| Error::Io(e.to_string()))?;
+ Ok((tcp, None))
+}
+
+async fn accept_loop(
+ inner: std::sync::Weak<Inner>,
+ endpoint: quinn::Endpoint,
+ tx: mpsc::Sender<IncomingStream>,
+ serves: bool,
+) {
+ while let Some(incoming) = endpoint.accept().await {
+ if !serves {
+ incoming.refuse();
+ continue;
+ }
+ let inner = inner.clone();
+ let tx = tx.clone();
+ tokio::spawn(async move {
+ let Ok(conn) = incoming.await else { return };
+ let SocketAddr::V6(remote) = conn.remote_address() else {
+ return;
+ };
+ {
+ let Some(strong) = inner.upgrade() else {
+ return;
+ };
+ let Some(peer) = strong.engine.peer_by_addr(remote.ip()) else {
+ conn.close(1u32.into(), b"not a peer");
+ return;
+ };
+ let mut inbound = strong.inbound.lock().expect("inbound");
+ inbound.retain(|(_, c)| c.close_reason().is_none());
+ inbound.push((peer.key(), conn.clone()));
+ }
+ loop {
+ let Ok((send, mut recv)) = conn.accept_bi().await else {
+ return;
+ };
+ // The peer is whoever owns the source address: WireGuard
+ // already authenticated it.
+ let Some(strong) = inner.upgrade() else {
+ return;
+ };
+ let Some(peer) = strong.engine.peer_by_addr(remote.ip()) else {
+ conn.close(1u32.into(), b"not a peer");
+ return;
+ };
+ let info = peer.info.read().expect("info").clone();
+ drop(strong);
+ let tx = tx.clone();
+ tokio::spawn(async move {
+ let header = match tokio::time::timeout(
+ Duration::from_secs(10),
+ quic::read_header(&mut recv),
+ )
+ .await
+ {
+ Ok(Ok(h)) => h,
+ _ => return,
+ };
+ let _ = tx
+ .send(IncomingStream {
+ peer: info,
+ header,
+ stream: quic::join(send, recv),
+ })
+ .await;
+ });
+ }
+ });
+ }
+}
+
+/// Closes every connection when the coordinator refuses this node (a
+/// revoked device): its peers have dropped it, so open streams would only
+/// hang until the idle timeout.
+async fn denial_loop(
+ inner: std::sync::Weak<Inner>,
+ mut rx: tokio::sync::watch::Receiver<coord::ControlState>,
+) {
+ while rx.changed().await.is_ok() {
+ let denied = {
+ let s = rx.borrow_and_update();
+ !s.connected && s.denied.is_some()
+ };
+ if !denied {
+ continue;
+ }
+ let Some(inner) = inner.upgrade() else { return };
+ for (_, c) in inner.conns.lock().await.drain() {
+ c.close(3u32.into(), b"device refused");
+ }
+ for (_, c) in inner.inbound.lock().expect("inbound").drain(..) {
+ c.close(3u32.into(), b"device refused");
+ }
+ }
+}
+
+async fn prune_loop(inner: std::sync::Weak<Inner>, mut rx: tokio::sync::watch::Receiver<u64>) {
+ while rx.changed().await.is_ok() {
+ let Some(inner) = inner.upgrade() else { return };
+ let current: BTreeSet<PublicKey> = inner.engine.peers().iter().map(|p| p.key()).collect();
+ let mut conns = inner.conns.lock().await;
+ conns.retain(|k, c| {
+ let keep = current.contains(k);
+ if !keep {
+ c.close(2u32.into(), b"peer removed");
+ }
+ keep
+ });
+ drop(conns);
+ // Connections removed peers opened to us end too (a share revoked,
+ // a device removed: cut at once, not at the idle timeout).
+ inner.inbound.lock().expect("inbound").retain(|(k, c)| {
+ let keep = current.contains(k) && c.close_reason().is_none();
+ if !keep {
+ c.close(2u32.into(), b"peer removed");
+ }
+ keep
+ });
+ }
+}
+
+/// An address of another overlay network's tunnel: Tailscale's
+/// 100.64.0.0/10 or fd7a:115c:a1e0::/48 on its interface (`tailscale0`,
+/// a macOS `utun`, Windows' `Tailscale`). Never a mesh endpoint: a path
+/// through it is a tunnel in a tunnel, and often runs through that
+/// network's own relays (DERP), slower than this mesh's relay.
+fn is_overlay(name: &str, ip: IpAddr) -> bool {
+ let name = name.to_ascii_lowercase();
+ if !(name.starts_with("tailscale") || name.starts_with("utun")) {
+ return false;
+ }
+ match ip {
+ IpAddr::V4(a) => {
+ let o = a.octets();
+ o[0] == 100 && (o[1] & 0xc0) == 64
+ }
+ IpAddr::V6(a) => {
+ let s = a.segments();
+ s[0] == 0xfd7a && s[1] == 0x115c && s[2] == 0xa1e0
+ }
+ }
+}
+
+fn interface_endpoints(v4: u16, v6: Option<u16>) -> Vec<SocketAddr> {
+ let mut out = Vec::new();
+ if let Ok(ifs) = if_addrs::get_if_addrs() {
+ for i in ifs {
+ if i.is_loopback() || is_overlay(&i.name, i.ip()) {
+ continue;
+ }
+ match i.ip() {
+ IpAddr::V4(a) if !a.is_link_local() && !a.is_unspecified() => {
+ out.push(SocketAddr::new(IpAddr::V4(a), v4));
+ }
+ IpAddr::V6(a) => {
+ let s = a.segments();
+ let link_local = (s[0] & 0xffc0) == 0xfe80;
+ if let Some(p) = v6
+ && !link_local
+ && !a.is_unspecified()
+ && !crate::key::is_mesh_addr(&a)
+ {
+ out.push(SocketAddr::new(IpAddr::V6(a), p));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ out
+}
+
+async fn resolve(server: &str) -> Option<SocketAddr> {
+ tokio::net::lookup_host(server)
+ .await
+ .ok()?
+ .find(SocketAddr::is_ipv4)
+}
+
+async fn refresh_endpoints(inner: &Arc<Inner>) -> Vec<SocketAddr> {
+ let (v4, v6) = inner.engine.local_ports();
+ let mut eps = interface_endpoints(v4, v6);
+ let mut servers: Vec<String> = inner.control.state.borrow().stun.clone();
+ servers.extend(inner.stun.iter().cloned());
+ for s in servers.iter().take(4) {
+ let t = std::time::Instant::now();
+ let addr = resolve(s).await;
+ let resolved = t.elapsed();
+ let mapped = match addr {
+ Some(addr) => inner.engine.stun(addr, Duration::from_secs(2)).await,
+ None => None,
+ };
+ tracing::debug!(server = %s, ?resolved, took = ?t.elapsed(), ?mapped, "stun");
+ if let Some(mapped) = mapped
+ && !eps.contains(&mapped)
+ {
+ eps.push(mapped);
+ }
+ }
+ eps.sort();
+ eps.dedup();
+ inner.engine.set_local_endpoints(eps.clone());
+ inner.control.set_endpoints(eps.clone());
+ *inner.endpoints.lock().expect("endpoints") = eps.clone();
+ eps
+}
+
+async fn discovery_loop(inner: std::sync::Weak<Inner>) {
+ let mut last_ifs: Vec<SocketAddr> = Vec::new();
+ let mut last_full = None::<tokio::time::Instant>;
+ let mut was_connected = false;
+ loop {
+ let Some(strong) = inner.upgrade() else {
+ return;
+ };
+ if strong.shutdown.is_cancelled() {
+ return;
+ }
+ let (v4, v6) = strong.engine.local_ports();
+ let ifs = interface_endpoints(v4, v6);
+ let connected = strong.control.state.borrow().connected;
+ let changed = ifs != last_ifs;
+ if changed && !last_ifs.is_empty() {
+ // The network changed under us (roaming, Wi-Fi to Ethernet):
+ // stop trusting direct paths and find new ones.
+ tracing::info!("network change: re-discovering mesh paths");
+ strong.engine.forget_paths();
+ }
+ let due = last_full.is_none_or(|t| t.elapsed() > Duration::from_secs(30));
+ if changed || due || (connected && !was_connected) {
+ refresh_endpoints(&strong).await;
+ last_full = Some(tokio::time::Instant::now());
+ last_ifs = ifs;
+ }
+ was_connected = connected;
+ let shutdown = strong.shutdown.clone();
+ let mut state = strong.control.state.subscribe();
+ drop(strong);
+ // Every 2 s, or at once when the coordinator connection changes
+ // (a fresh connection learns its public endpoint right away).
+ tokio::select! {
+ _ = tokio::time::sleep(Duration::from_secs(2)) => {}
+ _ = state.wait_for(|s| s.connected != connected) => {}
+ _ = shutdown.cancelled() => return,
+ }
+ }
+}
+
+/// UDP flows of a client forward: local source to its mesh socket.
+type Flows = HashMap<SocketAddr, (Arc<VSocket>, tokio::time::Instant)>;
+
+async fn udp_client_forward(mesh: Mesh, local: Arc<UdpSocket>, peer: PublicKey) {
+ // One mesh socket per local source, so replies find their way back.
+ let flows: Arc<Mutex<Flows>> = Arc::default();
+ let mut buf = vec![0u8; 65_535];
+ loop {
+ let Ok((n, src)) = local.recv_from(&mut buf).await else {
+ continue;
+ };
+ let Some(info) = mesh
+ .inner
+ .engine
+ .peer(&peer)
+ .map(|p| p.info.read().expect("info").clone())
+ else {
+ continue;
+ };
+ mesh.inner.engine.want(&peer);
+ let dst = SocketAddrV6::new(info.addr(), MEDIA_UDP_PORT, 0, 0);
+ let sock = {
+ let mut f = flows.lock().expect("flows");
+ f.retain(|_, (_, at)| at.elapsed() < Duration::from_secs(180));
+ match f.get_mut(&src) {
+ Some((s, at)) => {
+ *at = tokio::time::Instant::now();
+ s.clone()
+ }
+ None => {
+ let Ok(s) = mesh.inner.engine.vnet.bind(0) else {
+ continue;
+ };
+ f.insert(src, (s.clone(), tokio::time::Instant::now()));
+ let back = local.clone();
+ let reader = s.clone();
+ let flows = flows.clone();
+ tokio::spawn(async move {
+ loop {
+ let r =
+ tokio::time::timeout(Duration::from_secs(180), reader.recv_from())
+ .await;
+ match r {
+ Ok(Ok((data, _))) => {
+ let _ = back.send_to(&data, src).await;
+ }
+ _ => {
+ flows.lock().expect("flows").remove(&src);
+ return;
+ }
+ }
+ }
+ });
+ s
+ }
+ }
+ };
+ let _ = sock.send_to(&buf[..n], dst);
+ }
+}
+
+/// One peer flow of a [`Mesh::serve_udp`] service.
+struct UdpFlow {
+ local: Arc<UdpSocket>,
+ /// When the peer last sent on it (ms since the service started).
+ last_ms: AtomicU64,
+}
+
+/// A [`Mesh::serve_udp`] service's flows by peer address.
+#[derive(Clone)]
+struct UdpFlows {
+ started: Instant,
+ map: Arc<Mutex<HashMap<SocketAddrV6, Arc<UdpFlow>>>>,
+}
+
+async fn udp_server_forward(sock: Arc<VSocket>, target: SocketAddr, flows: UdpFlows) {
+ let started = flows.started;
+ let flows = flows.map;
+ loop {
+ let Ok((data, src)) = sock.recv_from().await else {
+ return;
+ };
+ let now_ms = started.elapsed().as_millis() as u64;
+ let local = {
+ let existing = flows.lock().expect("flows").get(&src).cloned();
+ match existing {
+ Some(f) => {
+ f.last_ms.store(now_ms, Ordering::Relaxed);
+ f.local.clone()
+ }
+ None => {
+ let bind = if target.is_ipv4() {
+ "127.0.0.1:0"
+ } else {
+ "[::1]:0"
+ };
+ let Ok(l) = UdpSocket::bind(bind).await else {
+ continue;
+ };
+ if l.connect(target).await.is_err() {
+ continue;
+ }
+ let l = Arc::new(l);
+ flows.lock().expect("flows").insert(
+ src,
+ Arc::new(UdpFlow {
+ local: l.clone(),
+ last_ms: AtomicU64::new(now_ms),
+ }),
+ );
+ let back = sock.clone();
+ let reader = l.clone();
+ let flows = flows.clone();
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 65_535];
+ loop {
+ match tokio::time::timeout(
+ Duration::from_secs(180),
+ reader.recv(&mut buf),
+ )
+ .await
+ {
+ Ok(Ok(n)) => {
+ let _ = back.send_to(&buf[..n], src);
+ }
+ _ => {
+ flows.lock().expect("flows").remove(&src);
+ return;
+ }
+ }
+ }
+ });
+ l
+ }
+ }
+ };
+ let _ = local.send(&data).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_stopping_node_is_not_a_warning() {
+ let stopping_endpoint = Error::Unreachable("quic connect: endpoint stopping".into());
+ assert!(stopping(&stopping_endpoint, false));
+ assert!(stopping(&Error::Refused("revoked".into()), true));
+ assert!(!stopping(&Error::Refused("revoked".into()), false));
+ assert!(!stopping(&Error::Unreachable("timed out".into()), false));
+ }
+
+ #[test]
+ fn tailscale_tunnel_addresses_are_not_mesh_endpoints() {
+ let v4 = |s: &str| IpAddr::V4(s.parse().unwrap());
+ let v6 = |s: &str| IpAddr::V6(s.parse().unwrap());
+ assert!(is_overlay("utun4", v4("100.101.102.103")));
+ assert!(is_overlay("tailscale0", v4("100.127.1.2")));
+ assert!(is_overlay("Tailscale", v6("fd7a:115c:a1e0::7b38:3e77")));
+ // The same ranges elsewhere (a cloud VPC using 100.64/10) stay.
+ assert!(!is_overlay("eth0", v4("100.101.102.103")));
+ // Other addresses on a tunnel interface stay (another VPN's).
+ assert!(!is_overlay("utun2", v4("10.8.0.2")));
+ assert!(!is_overlay("utun4", v4("100.128.0.1")));
+ assert!(!is_overlay("en0", v4("192.168.1.100")));
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/packet.rs b/libs/cua/crates/cua-mesh/src/packet.rs
new file mode 100644
index 0000000000..79e028072e
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/packet.rs
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The IP packets inside the tunnel: IPv6 + UDP between mesh addresses.
+//!
+//! WireGuard carries IP packets, and the receiver checks each packet's inner
+//! source address against the sending peer's key (cryptokey routing). The
+//! mesh only ever carries UDP (QUIC streams and forwarded UDP), so this is
+//! the whole IP layer: a fixed 40-byte IPv6 header and an 8-byte UDP header.
+
+use std::net::{Ipv6Addr, SocketAddrV6};
+
+/// IPv6 header length.
+pub const IPV6_HEADER: usize = 40;
+/// UDP header length.
+pub const UDP_HEADER: usize = 8;
+/// Bytes of headers before a UDP payload.
+pub const OVERHEAD: usize = IPV6_HEADER + UDP_HEADER;
+/// The tunnel MTU (inner IP packet), as WireGuard's default.
+pub const TUNNEL_MTU: usize = 1420;
+/// The largest UDP payload one tunnel packet carries.
+pub const MAX_UDP_PAYLOAD: usize = TUNNEL_MTU - OVERHEAD;
+
+const NEXT_HEADER_UDP: u8 = 17;
+
+/// Builds an IPv6/UDP packet. Returns `None` when `payload` is larger than
+/// [`MAX_UDP_PAYLOAD`].
+pub fn build_udp(src: SocketAddrV6, dst: SocketAddrV6, payload: &[u8]) -> Option<Vec<u8>> {
+ if payload.len() > MAX_UDP_PAYLOAD {
+ return None;
+ }
+ let udp_len = (UDP_HEADER + payload.len()) as u16;
+ let mut p = Vec::with_capacity(OVERHEAD + payload.len());
+ // Version 6, traffic class 0, flow label 0.
+ p.extend_from_slice(&[0x60, 0, 0, 0]);
+ p.extend_from_slice(&udp_len.to_be_bytes());
+ p.push(NEXT_HEADER_UDP);
+ p.push(64); // hop limit
+ p.extend_from_slice(&src.ip().octets());
+ p.extend_from_slice(&dst.ip().octets());
+ p.extend_from_slice(&src.port().to_be_bytes());
+ p.extend_from_slice(&dst.port().to_be_bytes());
+ p.extend_from_slice(&udp_len.to_be_bytes());
+ p.extend_from_slice(&[0, 0]); // checksum, filled below
+ p.extend_from_slice(payload);
+ let sum = udp_checksum(src.ip(), dst.ip(), &p[IPV6_HEADER..]);
+ p[IPV6_HEADER + 6..IPV6_HEADER + 8].copy_from_slice(&sum.to_be_bytes());
+ Some(p)
+}
+
+/// A parsed IPv6/UDP packet.
+#[derive(Debug, PartialEq, Eq)]
+pub struct UdpPacket<'a> {
+ /// Source.
+ pub src: SocketAddrV6,
+ /// Destination.
+ pub dst: SocketAddrV6,
+ /// UDP payload.
+ pub payload: &'a [u8],
+}
+
+/// Parses an IPv6/UDP packet (no extension headers), verifying lengths and
+/// the UDP checksum. Anything else is `None`.
+pub fn parse_udp(p: &[u8]) -> Option<UdpPacket<'_>> {
+ if p.len() < OVERHEAD || p[0] >> 4 != 6 || p[6] != NEXT_HEADER_UDP {
+ return None;
+ }
+ let payload_len = u16::from_be_bytes([p[4], p[5]]) as usize;
+ if IPV6_HEADER + payload_len > p.len() || payload_len < UDP_HEADER {
+ return None;
+ }
+ let src_ip = Ipv6Addr::from(<[u8; 16]>::try_from(&p[8..24]).ok()?);
+ let dst_ip = Ipv6Addr::from(<[u8; 16]>::try_from(&p[24..40]).ok()?);
+ let udp = &p[IPV6_HEADER..IPV6_HEADER + payload_len];
+ let udp_len = u16::from_be_bytes([udp[4], udp[5]]) as usize;
+ if udp_len != payload_len {
+ return None;
+ }
+ // A correct checksum makes the one's-complement sum over the pseudo
+ // header and the whole datagram all ones.
+ if fold(sum_words(udp, pseudo_header(&src_ip, &dst_ip, udp.len()))) != 0xffff {
+ return None;
+ }
+ let sport = u16::from_be_bytes([udp[0], udp[1]]);
+ let dport = u16::from_be_bytes([udp[2], udp[3]]);
+ Some(UdpPacket {
+ src: SocketAddrV6::new(src_ip, sport, 0, 0),
+ dst: SocketAddrV6::new(dst_ip, dport, 0, 0),
+ payload: &udp[UDP_HEADER..],
+ })
+}
+
+/// The source address of an IPv6 packet (for cryptokey routing checks).
+pub fn source(p: &[u8]) -> Option<Ipv6Addr> {
+ if p.len() < IPV6_HEADER || p[0] >> 4 != 6 {
+ return None;
+ }
+ Some(Ipv6Addr::from(<[u8; 16]>::try_from(&p[8..24]).ok()?))
+}
+
+fn pseudo_header(src: &Ipv6Addr, dst: &Ipv6Addr, len: usize) -> u32 {
+ let mut sum = 0u32;
+ for chunk in src.octets().chunks(2).chain(dst.octets().chunks(2)) {
+ sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
+ }
+ sum += (len as u32) >> 16;
+ sum += (len as u32) & 0xffff;
+ sum += NEXT_HEADER_UDP as u32;
+ sum
+}
+
+fn sum_words(data: &[u8], mut sum: u32) -> u32 {
+ let mut chunks = data.chunks_exact(2);
+ for c in &mut chunks {
+ sum = sum.wrapping_add(u16::from_be_bytes([c[0], c[1]]) as u32);
+ }
+ if let [last] = chunks.remainder() {
+ sum = sum.wrapping_add((*last as u32) << 8);
+ }
+ sum
+}
+
+fn fold(mut sum: u32) -> u16 {
+ while sum >> 16 != 0 {
+ sum = (sum & 0xffff) + (sum >> 16);
+ }
+ sum as u16
+}
+
+/// The UDP checksum over `udp` (header with a zero checksum field, plus
+/// payload). Zero is sent as `0xffff` (IPv6 forbids a zero checksum).
+fn udp_checksum(src: &Ipv6Addr, dst: &Ipv6Addr, udp: &[u8]) -> u16 {
+ let mut sum = pseudo_header(src, dst, udp.len());
+ // Skip the checksum field itself.
+ sum = sum_words(&udp[..6], sum);
+ sum = sum_words(&udp[8..], sum);
+ let c = !fold(sum);
+ if c == 0 { 0xffff } else { c }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn a(last: u16, port: u16) -> SocketAddrV6 {
+ SocketAddrV6::new(
+ Ipv6Addr::new(0xfd5c, 0xa000, 0, 0, 0, 0, 0, last),
+ port,
+ 0,
+ 0,
+ )
+ }
+
+ #[test]
+ fn round_trip() {
+ for len in [0usize, 1, 2, 3, 100, 1371, MAX_UDP_PAYLOAD] {
+ let payload: Vec<u8> = (0..len).map(|i| i as u8).collect();
+ let p = build_udp(a(1, 4000), a(2, 7443), &payload).unwrap();
+ assert_eq!(p.len(), OVERHEAD + len);
+ let parsed = parse_udp(&p).unwrap();
+ assert_eq!(parsed.src, a(1, 4000));
+ assert_eq!(parsed.dst, a(2, 7443));
+ assert_eq!(parsed.payload, &payload[..]);
+ assert_eq!(source(&p), Some(*a(1, 0).ip()));
+ }
+ assert!(build_udp(a(1, 1), a(2, 2), &vec![0; MAX_UDP_PAYLOAD + 1]).is_none());
+ }
+
+ #[test]
+ fn corruption_is_rejected() {
+ let mut p = build_udp(a(1, 4000), a(2, 7443), b"hello mesh").unwrap();
+ let last = p.len() - 1;
+ p[last] ^= 0x40;
+ assert!(parse_udp(&p).is_none());
+ assert!(parse_udp(&p[..10]).is_none());
+ let mut v4 = build_udp(a(1, 1), a(2, 2), b"x").unwrap();
+ v4[0] = 0x45;
+ assert!(parse_udp(&v4).is_none());
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/policy.rs b/libs/cua/crates/cua-mesh/src/policy.rs
new file mode 100644
index 0000000000..2fbbee7942
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/policy.rs
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! When to use the mesh: off unless asked for.
+//!
+//! - `CUA_MESH=prefer|require|off`, where the process runs, always wins
+//! (`cua`, the SDK, the cua daemon, a hosted machine's service).
+//! - Otherwise the Cua Spaces app's update channel decides for the app's
+//! own processes (its cua daemon and this machine's host): the app
+//! records it in `<cua home>/app-update-channel` ([`CHANNEL_FILE`]).
+//! [`ON_IN_BETA`] is the single switch that turns the mesh on for the
+//! Beta channel; it is off in this release, so the mesh is opt-in on
+//! every channel.
+//! - Anything else: [`Policy::Off`], the relay's HTTPS path, as before the
+//! mesh existed.
+
+use std::path::Path;
+
+/// The environment variable that chooses the policy explicitly.
+pub const ENV: &str = "CUA_MESH";
+
+/// The file, in a Cua home, where the Cua Spaces app records its update
+/// channel (`beta` or `stable`).
+pub const CHANNEL_FILE: &str = "app-update-channel";
+
+/// Whether the Beta-channel app uses the mesh without `CUA_MESH`. Off: the
+/// mesh is opt-in on every channel until it is turned on for Beta.
+pub const ON_IN_BETA: bool = false;
+
+/// How relay connections use the mesh.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Policy {
+ /// The mesh when both sides speak it, the relay's HTTPS path otherwise.
+ Prefer,
+ /// The mesh only (a relay that can read sessions is never used).
+ Require,
+ /// The relay's HTTPS path only (the default).
+ Off,
+}
+
+/// The Cua Spaces app's update channel.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Channel {
+ /// Stable releases.
+ Stable,
+ /// Beta (pre)releases.
+ Beta,
+}
+
+impl Policy {
+ /// A `CUA_MESH` value; `None` when it does not choose (unset, empty or
+ /// unknown).
+ pub fn parse(value: &str) -> Option<Self> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "off" | "0" | "false" | "no" => Some(Self::Off),
+ "require" | "required" | "only" => Some(Self::Require),
+ "prefer" | "on" | "1" | "true" | "yes" => Some(Self::Prefer),
+ _ => None,
+ }
+ }
+
+ /// The policy from an explicit `CUA_MESH` value, else the app's channel
+ /// (when this process is the app's), else off.
+ pub fn resolve(explicit: Option<&str>, channel: Option<Channel>, on_in_beta: bool) -> Self {
+ if let Some(p) = explicit.and_then(Self::parse) {
+ return p;
+ }
+ match channel {
+ Some(Channel::Beta) if on_in_beta => Self::Prefer,
+ _ => Self::Off,
+ }
+ }
+
+ /// The policy now: `CUA_MESH`, else the channel recorded in `app_home`
+ /// (the Cua home of the app this process belongs to; `None` for a
+ /// process that is not the app's, such as a plain `cua` run).
+ pub fn current(app_home: Option<&Path>) -> Self {
+ let explicit = std::env::var(ENV).ok();
+ if let Some(p) = explicit.as_deref().and_then(Self::parse) {
+ return p;
+ }
+ let channel = app_home.and_then(read_channel);
+ Self::resolve(None, channel, ON_IN_BETA)
+ }
+
+ /// Whether this policy uses the mesh at all.
+ pub fn uses_mesh(self) -> bool {
+ self != Self::Off
+ }
+}
+
+/// The channel the app recorded in `home` ([`CHANNEL_FILE`]).
+pub fn read_channel(home: &Path) -> Option<Channel> {
+ let raw = std::fs::read_to_string(home.join(CHANNEL_FILE)).ok()?;
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "beta" => Some(Channel::Beta),
+ "stable" => Some(Channel::Stable),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn off_unless_asked_for() {
+ assert_eq!(Policy::resolve(None, None, ON_IN_BETA), Policy::Off);
+ assert_eq!(
+ Policy::resolve(None, Some(Channel::Stable), ON_IN_BETA),
+ Policy::Off
+ );
+ // Unknown and empty values do not choose.
+ assert_eq!(Policy::resolve(Some(""), None, ON_IN_BETA), Policy::Off);
+ assert_eq!(
+ Policy::resolve(Some("maybe"), None, ON_IN_BETA),
+ Policy::Off
+ );
+ }
+
+ #[test]
+ fn the_beta_channel_is_off_in_this_release() {
+ // The one switch: flipping it is the "on for Beta" change, and this
+ // test changes with it.
+ const { assert!(!ON_IN_BETA) };
+ assert_eq!(
+ Policy::resolve(None, Some(Channel::Beta), ON_IN_BETA),
+ Policy::Off
+ );
+ }
+
+ #[test]
+ fn with_the_switch_on_only_beta_prefers_the_mesh() {
+ assert_eq!(
+ Policy::resolve(None, Some(Channel::Beta), true),
+ Policy::Prefer
+ );
+ assert_eq!(
+ Policy::resolve(None, Some(Channel::Stable), true),
+ Policy::Off
+ );
+ assert_eq!(Policy::resolve(None, None, true), Policy::Off);
+ }
+
+ #[test]
+ fn cua_mesh_always_wins() {
+ for channel in [None, Some(Channel::Stable), Some(Channel::Beta)] {
+ for on in [false, true] {
+ assert_eq!(Policy::resolve(Some("prefer"), channel, on), Policy::Prefer);
+ assert_eq!(
+ Policy::resolve(Some(" REQUIRE "), channel, on),
+ Policy::Require
+ );
+ assert_eq!(Policy::resolve(Some("off"), channel, on), Policy::Off);
+ }
+ }
+ }
+
+ #[test]
+ fn the_app_records_its_channel_in_the_cua_home() {
+ let dir = tempfile::tempdir().unwrap();
+ assert_eq!(read_channel(dir.path()), None);
+ std::fs::write(dir.path().join(CHANNEL_FILE), "beta\n").unwrap();
+ assert_eq!(read_channel(dir.path()), Some(Channel::Beta));
+ std::fs::write(dir.path().join(CHANNEL_FILE), "stable").unwrap();
+ assert_eq!(read_channel(dir.path()), Some(Channel::Stable));
+ std::fs::write(dir.path().join(CHANNEL_FILE), "nightly").unwrap();
+ assert_eq!(read_channel(dir.path()), None);
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/proto.rs b/libs/cua/crates/cua-mesh/src/proto.rs
new file mode 100644
index 0000000000..7edf4b5128
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/proto.rs
@@ -0,0 +1,516 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The coordinator protocol: one WebSocket per node (`GET /v1/mesh/connect`)
+//! carries JSON control messages (text frames) and relayed packets (binary
+//! frames).
+//!
+//! ```text
+//! node coordinator
+//! | ---- WebSocket upgrade (credentials) --> |
+//! | <--- challenge {server_key, nonce} ----- |
+//! | ---- hello {keys, endpoints, proof} ---> | proof: HMAC over the
+//! | <--- welcome {addr, mode, stun} -------- | nonce keyed by
+//! | <--- netmap {peers} -------------------- | X25519(node, server)
+//! | ---- endpoints {...} ------------------> | (proves the node key)
+//! | <=== binary: RECV src(32) | packet ===== |
+//! | ==== binary: SEND dst(32) | packet ====> | (WireGuard or disco
+//! ``` ciphertext only)
+//!
+//! The coordinator (accounts, devices, sharing and the relay) runs in Cua's
+//! relay service; this module is the contract
+//! both sides speak.
+
+use std::net::{Ipv6Addr, SocketAddr};
+
+use hmac::{Hmac, Mac as _};
+use serde::{Deserialize, Serialize};
+use sha2::Sha256;
+
+use crate::key::{PublicKey, SecretKey};
+
+/// The mesh protocol version this crate speaks. A coordinator and a peer
+/// agree on the mesh when their versions match; anything else falls back to
+/// the relay's HTTPS path.
+pub const VERSION: u32 = 1;
+
+/// The coordinator's WebSocket path.
+pub const CONNECT_PATH: &str = "/v1/mesh/connect";
+
+/// Header naming a machine's id on its connect (with its machine token or
+/// a static registration token as the bearer).
+pub const MACHINE_ID_HEADER: &str = "x-cua-machine-id";
+
+/// Binary frame: node to coordinator, `dst key | packet`.
+pub const FRAME_SEND: u8 = 1;
+/// Binary frame: coordinator to node, `src key | packet`.
+pub const FRAME_RECV: u8 = 2;
+
+/// Encodes a relay frame.
+pub fn frame(kind: u8, key: &PublicKey, packet: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(33 + packet.len());
+ out.push(kind);
+ out.extend_from_slice(&key.0);
+ out.extend_from_slice(packet);
+ out
+}
+
+/// Decodes a relay frame.
+pub fn parse_frame(b: &[u8]) -> Option<(u8, PublicKey, &[u8])> {
+ if b.len() < 33 {
+ return None;
+ }
+ Some((b[0], PublicKey(b[1..33].try_into().ok()?), &b[33..]))
+}
+
+/// The largest relayed packet the coordinator accepts.
+pub const MAX_RELAY_PACKET: usize = 64 * 1024;
+
+/// What kind of node.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum NodeKind {
+ /// A hosted machine (`cua-spacesd join`): serves Spaces.
+ Machine,
+ /// A client device (the cua daemon, CLI, SDK or app).
+ Client,
+}
+
+/// How the coordinator authorizes peers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Mode {
+ /// cua.ai-style accounts: owners, share lists and enrolled devices.
+ Account,
+ /// Self-hosted static tokens: each client pairs with a machine by
+ /// proving it holds that machine's env token; the machine approves.
+ Static,
+}
+
+/// Who a client peer is, as the coordinator vouches to a machine (account
+/// mode). The machine turns it into the same identity a relay-signed
+/// assertion carries.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
+pub struct Grant {
+ /// User id (`sub`).
+ pub user: String,
+ /// Account id.
+ pub account: String,
+ /// Verified email.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ /// Display name.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// `owner`, `shared` or `viewer`.
+ pub role: String,
+ /// The enrolled device, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub device: Option<String>,
+}
+
+/// A peer in a node's network map.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PeerInfo {
+ /// WireGuard public key.
+ pub node_key: PublicKey,
+ /// Disco public key.
+ pub disco_key: PublicKey,
+ /// SHA-256 (hex) of the peer's QUIC certificate.
+ pub quic_pin: String,
+ /// Machine or client.
+ pub kind: NodeKind,
+ /// The machine id (machines).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub machine_id: Option<String>,
+ /// Display name.
+ #[serde(default)]
+ pub name: String,
+ /// Candidate UDP endpoints (LAN addresses and STUN-learned public ones).
+ #[serde(default)]
+ pub endpoints: Vec<SocketAddr>,
+ /// Connected to the coordinator right now.
+ #[serde(default)]
+ pub online: bool,
+ /// The peer's mesh protocol version.
+ pub version: u32,
+ /// Who the peer is (in a machine's map, for client peers in account
+ /// mode).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub grant: Option<Grant>,
+}
+
+impl PeerInfo {
+ /// The peer's mesh address.
+ pub fn addr(&self) -> Ipv6Addr {
+ self.node_key.mesh_addr()
+ }
+}
+
+/// Coordinator to node.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ServerMsg {
+ /// First message: prove the node key.
+ Challenge {
+ /// Coordinator's protocol version.
+ version: u32,
+ /// Ephemeral X25519 key of this connection.
+ server_key: PublicKey,
+ /// Random nonce (hex).
+ nonce: String,
+ },
+ /// Accepted.
+ Welcome {
+ /// Coordinator's protocol version.
+ version: u32,
+ /// This node's mesh address.
+ addr: Ipv6Addr,
+ /// Account or static.
+ mode: Mode,
+ /// STUN servers (`host:port`).
+ #[serde(default)]
+ stun: Vec<String>,
+ /// The newest [`ClientMsg::Usage`] version this coordinator meters
+ /// (0, or absent from an older one: none, so machines send none).
+ #[serde(default, skip_serializing_if = "is_zero")]
+ usage: u32,
+ },
+ /// The full set of peers this node may talk to.
+ Netmap {
+ /// Peers.
+ peers: Vec<PeerInfo>,
+ },
+ /// Static mode, to a machine: a client asks to pair.
+ PairRequest {
+ /// Echo in the reply.
+ request_id: String,
+ /// The client's node key.
+ client_key: PublicKey,
+ /// Unix seconds the proof was made.
+ ts: u64,
+ /// HMAC proof (hex), see [`pair_proof`].
+ proof: String,
+ /// The client's name.
+ #[serde(default)]
+ name: String,
+ },
+ /// Static mode, to a client: how a pairing went.
+ PairResult {
+ /// The machine.
+ machine_id: String,
+ /// Paired.
+ ok: bool,
+ /// Why not.
+ #[serde(default)]
+ reason: String,
+ },
+ /// Keepalive answer.
+ Pong,
+ /// Refused; the connection closes.
+ Error {
+ /// Why.
+ message: String,
+ },
+}
+
+/// Node to coordinator.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ClientMsg {
+ /// Answer to the challenge.
+ Hello {
+ /// Node's protocol version.
+ version: u32,
+ /// Machine or client.
+ kind: NodeKind,
+ /// WireGuard public key.
+ node_key: PublicKey,
+ /// Disco public key.
+ disco_key: PublicKey,
+ /// SHA-256 (hex) of the QUIC certificate.
+ quic_pin: String,
+ /// Display name.
+ #[serde(default)]
+ name: String,
+ /// Candidate endpoints.
+ #[serde(default)]
+ endpoints: Vec<SocketAddr>,
+ /// HMAC proof (hex), see [`hello_proof`].
+ proof: String,
+ /// A short-lived node (one CLI run): forgotten when it disconnects.
+ #[serde(default)]
+ ephemeral: bool,
+ },
+ /// The node's endpoints changed.
+ Endpoints {
+ /// Candidate endpoints.
+ endpoints: Vec<SocketAddr>,
+ },
+ /// Static mode, from a client: pair with a machine.
+ Pair {
+ /// The machine.
+ machine_id: String,
+ /// Unix seconds.
+ ts: u64,
+ /// HMAC proof (hex), see [`pair_proof`].
+ proof: String,
+ },
+ /// Static mode, from a machine: the answer to a pair request.
+ PairReply {
+ /// The request.
+ request_id: String,
+ /// Accepted.
+ accept: bool,
+ /// Why not.
+ #[serde(default)]
+ reason: String,
+ },
+ /// Keepalive.
+ Ping,
+ /// Account mode, from a machine: the streams its peers hold open now,
+ /// so the coordinator can meter them as it meters its own HTTPS path.
+ /// A full snapshot, sent when it changes (and again after a
+ /// reconnect), only to a coordinator whose welcome asked for
+ /// version `v`. A coordinator ignores versions it does not know.
+ Usage {
+ /// Report version ([`USAGE_VERSION`]).
+ v: u32,
+ /// One entry per peer with something open (or just upgraded).
+ #[serde(default)]
+ peers: Vec<PeerUsage>,
+ },
+}
+
+/// The [`ClientMsg::Usage`] version this crate sends.
+pub const USAGE_VERSION: u32 = 1;
+
+/// The most entries one [`ClientMsg::Usage`] carries.
+pub const MAX_USAGE_PEERS: usize = 256;
+
+/// One peer's streams in a [`ClientMsg::Usage`] report.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PeerUsage {
+ /// The client peer's node key (the coordinator knows its account).
+ pub peer: PublicKey,
+ /// The user its grant named (`sub`); the coordinator checks it against
+ /// the peer's own account and ignores a mismatch.
+ pub user: String,
+ /// Streams the peer holds open now (HTTP requests in flight, upgraded
+ /// WebSockets, active media flows).
+ pub open: u32,
+ /// A WebSocket upgrade or a media flow since the last report: a session
+ /// at once, whatever its length.
+ #[serde(default)]
+ pub live: bool,
+}
+
+fn is_zero(v: &u32) -> bool {
+ *v == 0
+}
+
+type HmacSha256 = Hmac<Sha256>;
+
+/// The hello proof: `HMAC-SHA256(key = X25519(node, server_key), "cua-mesh-hello-v1" | nonce | node key)`.
+pub fn hello_proof(node: &SecretKey, server_key: &PublicKey, nonce: &str) -> String {
+ let mut mac = HmacSha256::new_from_slice(&node.agree(server_key)).expect("any key length");
+ mac.update(b"cua-mesh-hello-v1");
+ mac.update(nonce.as_bytes());
+ mac.update(&node.public().0);
+ hex::encode(mac.finalize().into_bytes())
+}
+
+/// Checks a hello proof on the coordinator (`server` is the connection's
+/// ephemeral secret).
+pub fn verify_hello_proof(
+ server: &SecretKey,
+ node_key: &PublicKey,
+ nonce: &str,
+ proof: &str,
+) -> bool {
+ let Ok(proof) = hex::decode(proof) else {
+ return false;
+ };
+ let mut mac = HmacSha256::new_from_slice(&server.agree(node_key)).expect("any key length");
+ mac.update(b"cua-mesh-hello-v1");
+ mac.update(nonce.as_bytes());
+ mac.update(&node_key.0);
+ mac.verify_slice(&proof).is_ok()
+}
+
+/// How long a pairing proof stays valid.
+pub const PAIR_PROOF_TTL_SECS: u64 = 300;
+
+/// The static-mode pairing proof a client sends to pair with a machine:
+/// `HMAC-SHA256(key = the machine's env token, "cua-mesh-pair-v1" | machine id | client node key | ts)`.
+/// The coordinator only forwards it; the machine checks it against its own
+/// env token, so the coordinator never sees the token.
+pub fn pair_proof(env_token: &str, machine_id: &str, client: &PublicKey, ts: u64) -> String {
+ let mut mac = HmacSha256::new_from_slice(env_token.as_bytes()).expect("any key length");
+ mac.update(b"cua-mesh-pair-v1|");
+ mac.update(machine_id.as_bytes());
+ mac.update(b"|");
+ mac.update(&client.0);
+ mac.update(&ts.to_be_bytes());
+ hex::encode(mac.finalize().into_bytes())
+}
+
+/// Checks a pairing proof on the machine.
+pub fn verify_pair_proof(
+ env_token: &str,
+ machine_id: &str,
+ client: &PublicKey,
+ ts: u64,
+ proof: &str,
+ now: u64,
+) -> bool {
+ if ts + PAIR_PROOF_TTL_SECS < now || ts > now + 60 {
+ return false;
+ }
+ let Ok(proof) = hex::decode(proof) else {
+ return false;
+ };
+ let mut mac = HmacSha256::new_from_slice(env_token.as_bytes()).expect("any key length");
+ mac.update(b"cua-mesh-pair-v1|");
+ mac.update(machine_id.as_bytes());
+ mac.update(b"|");
+ mac.update(&client.0);
+ mac.update(&ts.to_be_bytes());
+ mac.verify_slice(&proof).is_ok()
+}
+
+/// Unix seconds.
+pub fn now_secs() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+/// What a relay advertises about its mesh in `GET /v1/info` (`mesh`).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MeshInfo {
+ /// Protocol version.
+ pub version: u32,
+ /// STUN servers.
+ #[serde(default)]
+ pub stun: Vec<String>,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hello_proof_binds_the_node_key() {
+ let node = SecretKey::generate();
+ let server = SecretKey::generate();
+ let p = hello_proof(&node, &server.public(), "n1");
+ assert!(verify_hello_proof(&server, &node.public(), "n1", &p));
+ assert!(!verify_hello_proof(&server, &node.public(), "n2", &p));
+ let other = SecretKey::generate().public();
+ assert!(!verify_hello_proof(&server, &other, "n1", &p));
+ }
+
+ #[test]
+ fn pair_proof_checks_token_machine_and_time() {
+ let client = SecretKey::generate().public();
+ let now = 1_800_000_000;
+ let p = pair_proof("env-token", "machine-1", &client, now);
+ assert!(verify_pair_proof(
+ "env-token",
+ "machine-1",
+ &client,
+ now,
+ &p,
+ now + 5
+ ));
+ assert!(!verify_pair_proof(
+ "other",
+ "machine-1",
+ &client,
+ now,
+ &p,
+ now
+ ));
+ assert!(!verify_pair_proof(
+ "env-token",
+ "machine-2",
+ &client,
+ now,
+ &p,
+ now
+ ));
+ assert!(!verify_pair_proof(
+ "env-token",
+ "machine-1",
+ &client,
+ now,
+ &p,
+ now + PAIR_PROOF_TTL_SECS + 1
+ ));
+ }
+
+ #[test]
+ fn messages_round_trip() {
+ let k = SecretKey::generate().public();
+ let m = ServerMsg::Netmap {
+ peers: vec![PeerInfo {
+ node_key: k,
+ disco_key: k,
+ quic_pin: "ab".into(),
+ kind: NodeKind::Machine,
+ machine_id: Some("m1".into()),
+ name: "mac".into(),
+ endpoints: vec!["1.2.3.4:5".parse().unwrap()],
+ online: true,
+ version: VERSION,
+ grant: None,
+ }],
+ };
+ let json = serde_json::to_string(&m).unwrap();
+ assert!(json.contains("\"type\":\"netmap\""));
+ assert_eq!(serde_json::from_str::<ServerMsg>(&json).unwrap(), m);
+ let f = frame(FRAME_SEND, &k, b"abc");
+ assert_eq!(parse_frame(&f), Some((FRAME_SEND, k, &b"abc"[..])));
+ }
+
+ #[test]
+ fn usage_is_additive_to_the_protocol() {
+ // A welcome from an older coordinator (no `usage`) asks for none.
+ let old =
+ r#"{"type":"welcome","version":1,"addr":"fd5c:a000::1","mode":"account","stun":[]}"#;
+ match serde_json::from_str::<ServerMsg>(old).unwrap() {
+ ServerMsg::Welcome { usage, .. } => assert_eq!(usage, 0),
+ other => panic!("{other:?}"),
+ }
+ // A newer one says which version it meters; zero is left out.
+ let w = ServerMsg::Welcome {
+ version: VERSION,
+ addr: "fd5c:a000::1".parse().unwrap(),
+ mode: Mode::Account,
+ stun: vec![],
+ usage: 0,
+ };
+ assert!(!serde_json::to_string(&w).unwrap().contains("usage"));
+ let k = SecretKey::generate().public();
+ let m = ClientMsg::Usage {
+ v: USAGE_VERSION,
+ peers: vec![PeerUsage {
+ peer: k,
+ user: "ada".into(),
+ open: 2,
+ live: true,
+ }],
+ };
+ let json = serde_json::to_string(&m).unwrap();
+ assert!(json.contains("\"type\":\"usage\""), "{json}");
+ assert_eq!(serde_json::from_str::<ClientMsg>(&json).unwrap(), m);
+ // A future version still parses (and is ignored by its version).
+ let future = r#"{"type":"usage","v":9,"peers":[],"extra":1}"#;
+ assert!(matches!(
+ serde_json::from_str::<ClientMsg>(future).unwrap(),
+ ClientMsg::Usage { v: 9, .. }
+ ));
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/quic.rs b/libs/cua/crates/cua-mesh/src/quic.rs
new file mode 100644
index 0000000000..37ff1c4434
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/quic.rs
@@ -0,0 +1,240 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Streams between peers: QUIC (quinn) over a virtual mesh socket.
+//!
+//! WireGuard authenticates and encrypts every packet; QUIC on top gives
+//! reliable, congestion-controlled, multiplexed streams that survive path
+//! changes underneath (direct to relay and back, a new NAT mapping) because
+//! the QUIC connection lives between two mesh addresses that never change.
+//! Each stream starts with a small header naming the service it wants.
+//! Each peer's QUIC certificate is pinned by the SHA-256 the coordinator
+//! distributes with its node key.
+
+use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
+use std::sync::Arc;
+use std::time::Duration;
+
+use quinn::crypto::rustls::{QuicClientConfig, QuicServerConfig};
+use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest as _, Sha256};
+use tokio::io::AsyncWriteExt as _;
+
+use crate::key::NodeIdentity;
+use crate::packet::MAX_UDP_PAYLOAD;
+use crate::vnet::VSocket;
+use crate::{Error, Result};
+
+/// The mesh port every node's stream endpoint listens on.
+pub const STREAM_PORT: u16 = 7443;
+/// ALPN of mesh streams.
+pub const ALPN: &[u8] = b"cua-mesh/1";
+const MAGIC: &[u8; 4] = b"CMS1";
+const SERVER_NAME: &str = "cua-mesh";
+
+/// What a stream asks for.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
+pub struct StreamHeader {
+ /// The service (`spacesd`, ...).
+ pub service: String,
+ /// The dialer's per-forward session key, if any (see the crate docs).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub session: Option<String>,
+}
+
+fn transport() -> quinn::TransportConfig {
+ let mut t = quinn::TransportConfig::default();
+ t.keep_alive_interval(Some(Duration::from_secs(10)));
+ // Long enough to ride out a relay or coordinator restart or a network
+ // change; the WireGuard and disco layers recover underneath.
+ t.max_idle_timeout(Some(
+ quinn::IdleTimeout::try_from(Duration::from_secs(120)).expect("valid timeout"),
+ ));
+ t.initial_mtu(1200);
+ let mut mtu = quinn::MtuDiscoveryConfig::default();
+ mtu.upper_bound(MAX_UDP_PAYLOAD as u16);
+ t.mtu_discovery_config(Some(mtu));
+ t.stream_receive_window(quinn::VarInt::from_u32(16 << 20));
+ t.receive_window(quinn::VarInt::from_u32(64 << 20));
+ t.send_window(64 << 20);
+ t.max_concurrent_bidi_streams(quinn::VarInt::from_u32(2048));
+ t.max_concurrent_uni_streams(quinn::VarInt::from_u32(0));
+ t
+}
+
+fn provider() -> Arc<rustls::crypto::CryptoProvider> {
+ Arc::new(rustls::crypto::ring::default_provider())
+}
+
+/// A QUIC endpoint on the mesh.
+pub(crate) fn endpoint(identity: &NodeIdentity, socket: Arc<VSocket>) -> Result<quinn::Endpoint> {
+ let cert = CertificateDer::from(identity.cert_der.clone());
+ let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.cert_key_der.clone()));
+ let mut tls = rustls::ServerConfig::builder_with_provider(provider())
+ .with_protocol_versions(&[&rustls::version::TLS13])
+ .map_err(|e| Error::Io(format!("tls: {e}")))?
+ .with_no_client_auth()
+ .with_single_cert(vec![cert], key)
+ .map_err(|e| Error::Io(format!("tls: {e}")))?;
+ tls.alpn_protocols = vec![ALPN.to_vec()];
+ tls.max_early_data_size = 0;
+ let crypto =
+ QuicServerConfig::try_from(tls).map_err(|e| Error::Io(format!("quic tls: {e}")))?;
+ let mut server = quinn::ServerConfig::with_crypto(Arc::new(crypto));
+ server.transport_config(Arc::new(transport()));
+ quinn::Endpoint::new_with_abstract_socket(
+ quinn::EndpointConfig::default(),
+ Some(server),
+ socket,
+ Arc::new(quinn::TokioRuntime),
+ )
+ .map_err(|e| Error::Io(format!("quic endpoint: {e}")))
+}
+
+/// Client config pinning the peer's certificate SHA-256 (hex).
+pub(crate) fn client_config(pin: &str) -> Result<quinn::ClientConfig> {
+ let pin = hex::decode(pin).map_err(|_| Error::Protocol("bad certificate pin".into()))?;
+ let verifier = Arc::new(PinVerifier {
+ pin,
+ provider: provider(),
+ });
+ let mut tls = rustls::ClientConfig::builder_with_provider(provider())
+ .with_protocol_versions(&[&rustls::version::TLS13])
+ .map_err(|e| Error::Io(format!("tls: {e}")))?
+ .dangerous()
+ .with_custom_certificate_verifier(verifier)
+ .with_no_client_auth();
+ tls.alpn_protocols = vec![ALPN.to_vec()];
+ let crypto =
+ QuicClientConfig::try_from(tls).map_err(|e| Error::Io(format!("quic tls: {e}")))?;
+ let mut cfg = quinn::ClientConfig::new(Arc::new(crypto));
+ cfg.transport_config(Arc::new(transport()));
+ Ok(cfg)
+}
+
+/// Connects to `peer`'s stream endpoint.
+pub(crate) async fn connect(
+ endpoint: &quinn::Endpoint,
+ peer: Ipv6Addr,
+ pin: &str,
+) -> Result<quinn::Connection> {
+ let cfg = client_config(pin)?;
+ let addr = SocketAddr::V6(SocketAddrV6::new(peer, STREAM_PORT, 0, 0));
+ endpoint
+ .connect_with(cfg, addr, SERVER_NAME)
+ .map_err(|e| Error::Unreachable(format!("quic connect: {e}")))?
+ .await
+ .map_err(|e| Error::Unreachable(format!("quic connect: {e}")))
+}
+
+/// Writes a stream header.
+pub(crate) async fn write_header(send: &mut quinn::SendStream, h: &StreamHeader) -> Result<()> {
+ let json = serde_json::to_vec(h).map_err(|e| Error::Protocol(e.to_string()))?;
+ let mut buf = Vec::with_capacity(6 + json.len());
+ buf.extend_from_slice(MAGIC);
+ buf.extend_from_slice(&(json.len() as u16).to_be_bytes());
+ buf.extend_from_slice(&json);
+ send.write_all(&buf)
+ .await
+ .map_err(|e| Error::Unreachable(e.to_string()))
+}
+
+/// Reads a stream header (at most 4 KiB).
+pub(crate) async fn read_header(recv: &mut quinn::RecvStream) -> Result<StreamHeader> {
+ let mut head = [0u8; 6];
+ recv.read_exact(&mut head)
+ .await
+ .map_err(|e| Error::Protocol(format!("stream header: {e}")))?;
+ if &head[..4] != MAGIC {
+ return Err(Error::Protocol("not a mesh stream".into()));
+ }
+ let len = u16::from_be_bytes([head[4], head[5]]) as usize;
+ if len > 4096 {
+ return Err(Error::Protocol("stream header too large".into()));
+ }
+ let mut json = vec![0u8; len];
+ recv.read_exact(&mut json)
+ .await
+ .map_err(|e| Error::Protocol(format!("stream header: {e}")))?;
+ serde_json::from_slice(&json).map_err(|e| Error::Protocol(format!("stream header: {e}")))
+}
+
+/// Certificate pinning: the end-entity certificate's SHA-256 must match;
+/// the handshake signature is still verified with the certificate's key.
+#[derive(Debug)]
+struct PinVerifier {
+ pin: Vec<u8>,
+ provider: Arc<rustls::crypto::CryptoProvider>,
+}
+
+impl rustls::client::danger::ServerCertVerifier for PinVerifier {
+ fn verify_server_cert(
+ &self,
+ end_entity: &CertificateDer<'_>,
+ _intermediates: &[CertificateDer<'_>],
+ _server_name: &ServerName<'_>,
+ _ocsp_response: &[u8],
+ _now: UnixTime,
+ ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
+ let got = Sha256::digest(end_entity.as_ref());
+ if got.as_slice() == self.pin.as_slice() {
+ Ok(rustls::client::danger::ServerCertVerified::assertion())
+ } else {
+ Err(rustls::Error::InvalidCertificate(
+ rustls::CertificateError::ApplicationVerificationFailure,
+ ))
+ }
+ }
+
+ fn verify_tls12_signature(
+ &self,
+ message: &[u8],
+ cert: &CertificateDer<'_>,
+ dss: &rustls::DigitallySignedStruct,
+ ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
+ rustls::crypto::verify_tls12_signature(
+ message,
+ cert,
+ dss,
+ &self.provider.signature_verification_algorithms,
+ )
+ }
+
+ fn verify_tls13_signature(
+ &self,
+ message: &[u8],
+ cert: &CertificateDer<'_>,
+ dss: &rustls::DigitallySignedStruct,
+ ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
+ rustls::crypto::verify_tls13_signature(
+ message,
+ cert,
+ dss,
+ &self.provider.signature_verification_algorithms,
+ )
+ }
+
+ fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
+ self.provider
+ .signature_verification_algorithms
+ .supported_schemes()
+ }
+}
+
+/// Bidirectional stream as one `AsyncRead + AsyncWrite`.
+pub type MeshStream = tokio::io::Join<quinn::RecvStream, quinn::SendStream>;
+
+/// Joins a QUIC stream's halves.
+pub fn join(send: quinn::SendStream, recv: quinn::RecvStream) -> MeshStream {
+ tokio::io::join(recv, send)
+}
+
+/// Copies between a local TCP connection and a mesh stream until both
+/// sides finish.
+pub(crate) async fn splice(mut tcp: tokio::net::TcpStream, mut stream: MeshStream) {
+ let _ = tcp.set_nodelay(true);
+ let _ =
+ tokio::io::copy_bidirectional_with_sizes(&mut tcp, &mut stream, 64 << 10, 64 << 10).await;
+ let _ = stream.shutdown().await;
+}
diff --git a/libs/cua/crates/cua-mesh/src/stun.rs b/libs/cua/crates/cua-mesh/src/stun.rs
new file mode 100644
index 0000000000..7a507078f7
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/stun.rs
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The STUN binding exchange (RFC 8489), just enough to learn the public
+//! address a NAT maps our UDP socket to: the request, the success response
+//! with `XOR-MAPPED-ADDRESS`, and the responder side the coordinator runs.
+
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
+
+const BINDING_REQUEST: u16 = 0x0001;
+const BINDING_SUCCESS: u16 = 0x0101;
+const MAGIC_COOKIE: u32 = 0x2112_a442;
+const ATTR_MAPPED_ADDRESS: u16 = 0x0001;
+const ATTR_XOR_MAPPED_ADDRESS: u16 = 0x0020;
+const ATTR_SOFTWARE: u16 = 0x8022;
+
+/// A STUN transaction id.
+pub type TxId = [u8; 12];
+
+/// A binding request with transaction id `tx`.
+pub fn request(tx: TxId) -> Vec<u8> {
+ let mut p = Vec::with_capacity(20);
+ p.extend_from_slice(&BINDING_REQUEST.to_be_bytes());
+ p.extend_from_slice(&0u16.to_be_bytes());
+ p.extend_from_slice(&MAGIC_COOKIE.to_be_bytes());
+ p.extend_from_slice(&tx);
+ p
+}
+
+/// True when `p` looks like a STUN message (the two zero bits, the magic
+/// cookie and a plausible length). WireGuard and disco packets never do.
+pub fn is_stun(p: &[u8]) -> bool {
+ p.len() >= 20
+ && p[0] & 0xc0 == 0
+ && u32::from_be_bytes([p[4], p[5], p[6], p[7]]) == MAGIC_COOKIE
+ && (u16::from_be_bytes([p[2], p[3]]) as usize) == p.len() - 20
+}
+
+/// The transaction id of a binding request (`None` for anything else).
+pub fn parse_request(p: &[u8]) -> Option<TxId> {
+ if !is_stun(p) || u16::from_be_bytes([p[0], p[1]]) != BINDING_REQUEST {
+ return None;
+ }
+ p[8..20].try_into().ok()
+}
+
+/// The success response to a binding request from `observed`.
+pub fn response(tx: TxId, observed: SocketAddr) -> Vec<u8> {
+ let mut attr = Vec::new();
+ let xport = observed.port() ^ (MAGIC_COOKIE >> 16) as u16;
+ match observed.ip() {
+ IpAddr::V4(v4) => {
+ attr.extend_from_slice(&[0, 0x01]);
+ attr.extend_from_slice(&xport.to_be_bytes());
+ let x = u32::from(v4) ^ MAGIC_COOKIE;
+ attr.extend_from_slice(&x.to_be_bytes());
+ }
+ IpAddr::V6(v6) => {
+ attr.extend_from_slice(&[0, 0x02]);
+ attr.extend_from_slice(&xport.to_be_bytes());
+ let mut key = [0u8; 16];
+ key[..4].copy_from_slice(&MAGIC_COOKIE.to_be_bytes());
+ key[4..].copy_from_slice(&tx);
+ for (o, k) in v6.octets().iter().zip(key) {
+ attr.push(o ^ k);
+ }
+ }
+ }
+ let software = b"cua-mesh";
+ let len = 4 + attr.len() + 4 + software.len();
+ let mut p = Vec::with_capacity(20 + len);
+ p.extend_from_slice(&BINDING_SUCCESS.to_be_bytes());
+ p.extend_from_slice(&(len as u16).to_be_bytes());
+ p.extend_from_slice(&MAGIC_COOKIE.to_be_bytes());
+ p.extend_from_slice(&tx);
+ p.extend_from_slice(&ATTR_XOR_MAPPED_ADDRESS.to_be_bytes());
+ p.extend_from_slice(&(attr.len() as u16).to_be_bytes());
+ p.extend_from_slice(&attr);
+ p.extend_from_slice(&ATTR_SOFTWARE.to_be_bytes());
+ p.extend_from_slice(&(software.len() as u16).to_be_bytes());
+ p.extend_from_slice(software);
+ p
+}
+
+/// Parses a binding success response: its transaction id and the mapped
+/// address (`XOR-MAPPED-ADDRESS`, else `MAPPED-ADDRESS`).
+pub fn parse_response(p: &[u8]) -> Option<(TxId, SocketAddr)> {
+ if !is_stun(p) || u16::from_be_bytes([p[0], p[1]]) != BINDING_SUCCESS {
+ return None;
+ }
+ let tx: TxId = p[8..20].try_into().ok()?;
+ let mut rest = &p[20..];
+ let mut plain = None;
+ while rest.len() >= 4 {
+ let kind = u16::from_be_bytes([rest[0], rest[1]]);
+ let len = u16::from_be_bytes([rest[2], rest[3]]) as usize;
+ let value = rest.get(4..4 + len)?;
+ match kind {
+ ATTR_XOR_MAPPED_ADDRESS => return Some((tx, decode_addr(value, Some(&tx))?)),
+ ATTR_MAPPED_ADDRESS => plain = decode_addr(value, None),
+ _ => {}
+ }
+ let padded = (len + 3) & !3;
+ rest = rest.get(4 + padded..).unwrap_or(&[]);
+ }
+ plain.map(|a| (tx, a))
+}
+
+fn decode_addr(v: &[u8], xor_tx: Option<&TxId>) -> Option<SocketAddr> {
+ if v.len() < 4 {
+ return None;
+ }
+ let mut port = u16::from_be_bytes([v[2], v[3]]);
+ if xor_tx.is_some() {
+ port ^= (MAGIC_COOKIE >> 16) as u16;
+ }
+ match v[1] {
+ 0x01 if v.len() >= 8 => {
+ let mut ip = u32::from_be_bytes([v[4], v[5], v[6], v[7]]);
+ if xor_tx.is_some() {
+ ip ^= MAGIC_COOKIE;
+ }
+ Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::from(ip)), port))
+ }
+ 0x02 if v.len() >= 20 => {
+ let mut o: [u8; 16] = v[4..20].try_into().ok()?;
+ if let Some(tx) = xor_tx {
+ let mut key = [0u8; 16];
+ key[..4].copy_from_slice(&MAGIC_COOKIE.to_be_bytes());
+ key[4..].copy_from_slice(tx);
+ for (b, k) in o.iter_mut().zip(key) {
+ *b ^= k;
+ }
+ }
+ Some(SocketAddr::new(IpAddr::V6(Ipv6Addr::from(o)), port))
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn binding_round_trip() {
+ for observed in ["203.0.113.9:61000", "[2001:db8::42]:3478"] {
+ let observed: SocketAddr = observed.parse().unwrap();
+ let tx: TxId = rand::random();
+ let req = request(tx);
+ assert!(is_stun(&req));
+ assert_eq!(parse_request(&req), Some(tx));
+ let resp = response(tx, observed);
+ assert!(is_stun(&resp));
+ assert_eq!(parse_response(&resp), Some((tx, observed)));
+ assert_eq!(parse_request(&resp), None);
+ }
+ }
+
+ #[test]
+ fn known_vector() {
+ // RFC 5769 section 2.2 (IPv4 response), attributes other than
+ // XOR-MAPPED-ADDRESS removed: 192.0.2.1:32853.
+ let mut p = vec![0x01, 0x01, 0x00, 0x0c, 0x21, 0x12, 0xa4, 0x42];
+ p.extend_from_slice(&[
+ 0xb7, 0xe7, 0xa7, 0x01, 0xbc, 0x34, 0xd6, 0x86, 0xfa, 0x87, 0xdf, 0xae,
+ ]);
+ p.extend_from_slice(&[
+ 0x00, 0x20, 0x00, 0x08, 0x00, 0x01, 0xa1, 0x47, 0xe1, 0x12, 0xa6, 0x43,
+ ]);
+ let (_, a) = parse_response(&p).unwrap();
+ assert_eq!(a, "192.0.2.1:32853".parse().unwrap());
+ }
+
+ #[test]
+ fn not_stun() {
+ assert!(!is_stun(b"CUAD"));
+ let mut wg = vec![4u8, 0, 0, 0];
+ wg.extend_from_slice(&[0; 28]);
+ assert!(!is_stun(&wg));
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/src/testing.rs b/libs/cua/crates/cua-mesh/src/testing.rs
new file mode 100644
index 0000000000..9a9678cfc8
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/testing.rs
@@ -0,0 +1,539 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! An in-process coordinator and relay for tests (never the real one, which
+//! runs in Cua's relay service). It speaks the same protocol: the challenge, the network
+//! map, relayed frames, pairing and STUN.
+//!
+//! - [`Mode::Account`]: every client peers with every machine (machines see
+//! clients with an owner grant).
+//! - [`Mode::Static`]: clients pair with machines by proof, as in
+//! production.
+//!
+//! [`FakeCoordinator::stop`] and [`FakeCoordinator::restart`] simulate a
+//! crash and a restart (the node registry survives, as it is persisted in
+//! the real one); [`FakeCoordinator::set_relay`] drops relayed packets.
+
+use std::collections::{HashMap, HashSet};
+use std::net::SocketAddr;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+
+use futures_util::{SinkExt as _, StreamExt as _};
+use tokio::net::{TcpListener, UdpSocket};
+use tokio::sync::mpsc;
+use tokio_tungstenite::tungstenite::Message as WsMessage;
+use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
+
+use crate::key::{PublicKey, SecretKey};
+use crate::proto::{self, ClientMsg, Grant, Mode, NodeKind, PeerInfo, ServerMsg};
+
+#[derive(Default)]
+struct State {
+ nodes: Mutex<HashMap<PublicKey, PeerInfo>>,
+ conns: Mutex<HashMap<PublicKey, mpsc::UnboundedSender<WsMessage>>>,
+ pairs: Mutex<HashSet<(PublicKey, PublicKey)>>,
+ pending: Mutex<HashMap<String, (PublicKey, String)>>,
+ relay_off: AtomicBool,
+ relayed_bytes: AtomicU64,
+ /// Everything relayed (the first 16 MiB), to check it is ciphertext.
+ capture: Mutex<Vec<u8>>,
+ /// Request headers (`name`, `value`) answered with HTTP 403, as the
+ /// relay answers a revoked device.
+ denied: Mutex<Vec<(String, String)>>,
+ /// The relay's mesh is turned off: every connect gets HTTP 404.
+ mesh_off: AtomicBool,
+}
+
+/// See the module docs.
+pub struct FakeCoordinator {
+ /// `http://127.0.0.1:<port>`.
+ pub url: String,
+ /// The STUN responder (`127.0.0.1:<port>`).
+ pub stun: SocketAddr,
+ mode: Mode,
+ port: u16,
+ state: Arc<State>,
+ tasks: Mutex<Vec<tokio::task::JoinHandle<()>>>,
+}
+
+impl FakeCoordinator {
+ /// Starts on loopback.
+ pub async fn start(mode: Mode) -> Self {
+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
+ let port = listener.local_addr().expect("addr").port();
+ let stun = UdpSocket::bind("127.0.0.1:0").await.expect("stun");
+ let stun_addr = stun.local_addr().expect("addr");
+ let me = Self {
+ url: format!("http://127.0.0.1:{port}"),
+ stun: stun_addr,
+ mode,
+ port,
+ state: Arc::default(),
+ tasks: Mutex::new(Vec::new()),
+ };
+ me.spawn(listener);
+ me.tasks
+ .lock()
+ .expect("tasks")
+ .push(tokio::spawn(stun_loop(stun)));
+ me
+ }
+
+ fn spawn(&self, listener: TcpListener) {
+ let state = self.state.clone();
+ let mode = self.mode;
+ let t = tokio::spawn(async move {
+ // Connections live in this set, so aborting the listener task
+ // (a simulated crash) drops every connection with it.
+ let mut conns = tokio::task::JoinSet::new();
+ loop {
+ tokio::select! {
+ accepted = listener.accept() => {
+ let Ok((tcp, _)) = accepted else { continue };
+ let state = state.clone();
+ conns.spawn(async move { serve(state, mode, tcp).await });
+ }
+ Some(_) = conns.join_next(), if !conns.is_empty() => {}
+ }
+ }
+ });
+ self.tasks.lock().expect("tasks").push(t);
+ }
+
+ /// Simulates a crash: the listener and every connection go away.
+ pub fn stop(&self) {
+ for t in self.tasks.lock().expect("tasks").drain(..) {
+ t.abort();
+ }
+ self.state.conns.lock().expect("conns").clear();
+ }
+
+ /// Comes back on the same port with the same registry.
+ pub async fn restart(&self) {
+ self.stop();
+ let mut listener = None;
+ for _ in 0..50 {
+ match TcpListener::bind(("127.0.0.1", self.port)).await {
+ Ok(l) => {
+ listener = Some(l);
+ break;
+ }
+ Err(_) => tokio::time::sleep(std::time::Duration::from_millis(50)).await,
+ }
+ }
+ self.spawn(listener.expect("rebind the coordinator port"));
+ if let Ok(stun) = UdpSocket::bind(self.stun).await {
+ self.tasks
+ .lock()
+ .expect("tasks")
+ .push(tokio::spawn(stun_loop(stun)));
+ }
+ }
+
+ /// Relays packets (true, the default) or drops them.
+ pub fn set_relay(&self, on: bool) {
+ self.state.relay_off.store(!on, Ordering::SeqCst);
+ }
+
+ /// Bytes relayed so far.
+ pub fn relayed_bytes(&self) -> u64 {
+ self.state.relayed_bytes.load(Ordering::Relaxed)
+ }
+
+ /// True when `needle` appears anywhere in what was relayed.
+ pub fn relayed_contains(&self, needle: &[u8]) -> bool {
+ let c = self.state.capture.lock().expect("capture");
+ !needle.is_empty() && c.windows(needle.len()).any(|w| w == needle)
+ }
+
+ /// Revokes the node that connects with header `name: value` (its
+ /// key is `node`): its connection is closed, every later connect gets
+ /// HTTP 403, and its peers' maps drop it.
+ pub fn deny(&self, name: &str, value: &str, node: &PublicKey) {
+ self.state
+ .denied
+ .lock()
+ .expect("denied")
+ .push((name.to_ascii_lowercase(), value.to_owned()));
+ self.state.nodes.lock().expect("nodes").remove(node);
+ if let Some(tx) = self.state.conns.lock().expect("conns").remove(node) {
+ let _ = tx.send(WsMessage::Close(None));
+ }
+ push_netmaps(&self.state, self.mode);
+ }
+
+ /// Turns the mesh off (`false`: every node is disconnected and each
+ /// reconnect gets HTTP 404, as from a relay that turned its mesh off)
+ /// or back on.
+ pub fn set_mesh(&self, on: bool) {
+ self.state.mesh_off.store(!on, Ordering::SeqCst);
+ if !on {
+ for (_, tx) in self.state.conns.lock().expect("conns").drain() {
+ let _ = tx.send(WsMessage::Close(None));
+ }
+ }
+ }
+
+ /// Nodes connected right now.
+ pub fn connected(&self) -> usize {
+ self.state.conns.lock().expect("conns").len()
+ }
+}
+
+impl Drop for FakeCoordinator {
+ fn drop(&mut self) {
+ self.stop();
+ }
+}
+
+async fn stun_loop(sock: UdpSocket) {
+ let mut buf = [0u8; 1500];
+ loop {
+ let Ok((n, src)) = sock.recv_from(&mut buf).await else {
+ continue;
+ };
+ if let Some(tx) = crate::stun::parse_request(&buf[..n]) {
+ let _ = sock.send_to(&crate::stun::response(tx, src), src).await;
+ }
+ }
+}
+
+fn peers_of(state: &State, mode: Mode, me: &PeerInfo) -> Vec<PeerInfo> {
+ let nodes = state.nodes.lock().expect("nodes");
+ let online = state.conns.lock().expect("conns");
+ let pairs = state.pairs.lock().expect("pairs");
+ nodes
+ .values()
+ .filter(|p| p.node_key != me.node_key && p.kind != me.kind)
+ .filter(|p| match mode {
+ Mode::Account => true,
+ Mode::Static => {
+ let (m, c) = match me.kind {
+ NodeKind::Machine => (me.node_key, p.node_key),
+ NodeKind::Client => (p.node_key, me.node_key),
+ };
+ pairs.contains(&(m, c))
+ }
+ })
+ .map(|p| {
+ let mut p = p.clone();
+ p.online = online.contains_key(&p.node_key);
+ if mode == Mode::Account && me.kind == NodeKind::Machine {
+ p.grant = Some(Grant {
+ user: "user-1".into(),
+ account: "acct-1".into(),
+ email: Some("[email protected]".into()),
+ name: Some("Ada".into()),
+ role: "owner".into(),
+ device: None,
+ });
+ }
+ p
+ })
+ .collect()
+}
+
+fn push_netmaps(state: &State, mode: Mode) {
+ let nodes: Vec<PeerInfo> = state
+ .nodes
+ .lock()
+ .expect("nodes")
+ .values()
+ .cloned()
+ .collect();
+ let conns = state.conns.lock().expect("conns").clone();
+ for n in nodes {
+ if let Some(tx) = conns.get(&n.node_key) {
+ let msg = ServerMsg::Netmap {
+ peers: peers_of(state, mode, &n),
+ };
+ let _ = tx.send(WsMessage::Text(
+ serde_json::to_string(&msg).expect("json").into(),
+ ));
+ }
+ }
+}
+
+fn may_relay(state: &State, mode: Mode, a: &PublicKey, b: &PublicKey) -> bool {
+ let nodes = state.nodes.lock().expect("nodes");
+ let (Some(x), Some(y)) = (nodes.get(a), nodes.get(b)) else {
+ return false;
+ };
+ if x.kind == y.kind {
+ return false;
+ }
+ match mode {
+ Mode::Account => true,
+ Mode::Static => {
+ let (m, c) = if x.kind == NodeKind::Machine {
+ (a, b)
+ } else {
+ (b, a)
+ };
+ state.pairs.lock().expect("pairs").contains(&(*m, *c))
+ }
+ }
+}
+
+#[allow(clippy::result_large_err)]
+async fn serve(state: Arc<State>, mode: Mode, tcp: tokio::net::TcpStream) {
+ let mut machine_id = None::<String>;
+ let denied = state.denied.lock().expect("denied").clone();
+ let mesh_off = state.mesh_off.load(Ordering::SeqCst);
+ let ws = tokio_tungstenite::accept_hdr_async(tcp, |req: &Request, resp: Response| {
+ machine_id = req
+ .headers()
+ .get(proto::MACHINE_ID_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ let refused = denied.iter().any(|(k, v)| {
+ req.headers()
+ .get(k.as_str())
+ .and_then(|h| h.to_str().ok())
+ .is_some_and(|h| h == v)
+ });
+ if mesh_off {
+ let mut off = tokio_tungstenite::tungstenite::handshake::server::ErrorResponse::new(
+ Some("this relay has no mesh coordinator".into()),
+ );
+ *off.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::NOT_FOUND;
+ return Err(off);
+ }
+ if refused {
+ let mut deny = tokio_tungstenite::tungstenite::handshake::server::ErrorResponse::new(
+ Some("this device is not enrolled for your account".into()),
+ );
+ *deny.status_mut() = tokio_tungstenite::tungstenite::http::StatusCode::FORBIDDEN;
+ return Err(deny);
+ }
+ Ok(resp)
+ })
+ .await;
+ let Ok(ws) = ws else { return };
+ let (mut sink, mut stream) = ws.split();
+ let server = SecretKey::generate();
+ let nonce = hex::encode(rand::random::<[u8; 16]>());
+ let challenge = ServerMsg::Challenge {
+ version: proto::VERSION,
+ server_key: server.public(),
+ nonce: nonce.clone(),
+ };
+ if sink
+ .send(WsMessage::Text(
+ serde_json::to_string(&challenge).expect("json").into(),
+ ))
+ .await
+ .is_err()
+ {
+ return;
+ }
+ let Some(Ok(WsMessage::Text(t))) = stream.next().await else {
+ return;
+ };
+ let Ok(ClientMsg::Hello {
+ kind,
+ node_key,
+ disco_key,
+ quic_pin,
+ name,
+ endpoints,
+ proof,
+ version,
+ ..
+ }) = serde_json::from_str::<ClientMsg>(&t)
+ else {
+ return;
+ };
+ if !proto::verify_hello_proof(&server, &node_key, &nonce, &proof) {
+ let _ = sink
+ .send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::Error {
+ message: "bad proof".into(),
+ })
+ .expect("json")
+ .into(),
+ ))
+ .await;
+ return;
+ }
+ let info = PeerInfo {
+ node_key,
+ disco_key,
+ quic_pin,
+ kind,
+ machine_id: if kind == NodeKind::Machine {
+ machine_id
+ } else {
+ None
+ },
+ name,
+ endpoints,
+ online: true,
+ version,
+ grant: None,
+ };
+ let welcome = ServerMsg::Welcome {
+ version: proto::VERSION,
+ addr: node_key.mesh_addr(),
+ mode,
+ stun: Vec::new(),
+ usage: 0,
+ };
+ if sink
+ .send(WsMessage::Text(
+ serde_json::to_string(&welcome).expect("json").into(),
+ ))
+ .await
+ .is_err()
+ {
+ return;
+ }
+ let (tx, mut rx) = mpsc::unbounded_channel::<WsMessage>();
+ state.nodes.lock().expect("nodes").insert(node_key, info);
+ state
+ .conns
+ .lock()
+ .expect("conns")
+ .insert(node_key, tx.clone());
+ push_netmaps(&state, mode);
+ let writer = tokio::spawn(async move {
+ while let Some(m) = rx.recv().await {
+ if sink.send(m).await.is_err() {
+ return;
+ }
+ }
+ });
+ while let Some(Ok(msg)) = stream.next().await {
+ match msg {
+ WsMessage::Binary(b) => {
+ let Some((proto::FRAME_SEND, dst, packet)) = proto::parse_frame(&b) else {
+ continue;
+ };
+ if state.relay_off.load(Ordering::SeqCst)
+ || !may_relay(&state, mode, &node_key, &dst)
+ {
+ continue;
+ }
+ state
+ .relayed_bytes
+ .fetch_add(packet.len() as u64, Ordering::Relaxed);
+ {
+ let mut c = state.capture.lock().expect("capture");
+ if c.len() < 16 << 20 {
+ c.extend_from_slice(packet);
+ }
+ }
+ let target = state.conns.lock().expect("conns").get(&dst).cloned();
+ if let Some(t) = target {
+ let _ = t.send(WsMessage::Binary(
+ proto::frame(proto::FRAME_RECV, &node_key, packet).into(),
+ ));
+ }
+ }
+ WsMessage::Text(t) => match serde_json::from_str::<ClientMsg>(&t) {
+ Ok(ClientMsg::Endpoints { endpoints }) => {
+ if let Some(n) = state.nodes.lock().expect("nodes").get_mut(&node_key) {
+ n.endpoints = endpoints;
+ }
+ push_netmaps(&state, mode);
+ }
+ Ok(ClientMsg::Ping) => {
+ let _ = tx.send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::Pong)
+ .expect("json")
+ .into(),
+ ));
+ }
+ Ok(ClientMsg::Pair {
+ machine_id,
+ ts,
+ proof,
+ }) => {
+ let machine = state
+ .nodes
+ .lock()
+ .expect("nodes")
+ .values()
+ .find(|n| n.machine_id.as_deref() == Some(machine_id.as_str()))
+ .map(|n| n.node_key);
+ let conn =
+ machine.and_then(|m| state.conns.lock().expect("conns").get(&m).cloned());
+ match conn {
+ Some(c) => {
+ let id = hex::encode(rand::random::<[u8; 8]>());
+ state
+ .pending
+ .lock()
+ .expect("pending")
+ .insert(id.clone(), (node_key, machine_id));
+ let _ = c.send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::PairRequest {
+ request_id: id,
+ client_key: node_key,
+ ts,
+ proof,
+ name: String::new(),
+ })
+ .expect("json")
+ .into(),
+ ));
+ }
+ None => {
+ let _ = tx.send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::PairResult {
+ machine_id,
+ ok: false,
+ reason: "machine offline".into(),
+ })
+ .expect("json")
+ .into(),
+ ));
+ }
+ }
+ }
+ Ok(ClientMsg::PairReply {
+ request_id,
+ accept,
+ reason,
+ }) => {
+ let Some((client, machine_id)) =
+ state.pending.lock().expect("pending").remove(&request_id)
+ else {
+ continue;
+ };
+ if accept {
+ state
+ .pairs
+ .lock()
+ .expect("pairs")
+ .insert((node_key, client));
+ push_netmaps(&state, mode);
+ }
+ let c = state.conns.lock().expect("conns").get(&client).cloned();
+ if let Some(c) = c {
+ let _ = c.send(WsMessage::Text(
+ serde_json::to_string(&ServerMsg::PairResult {
+ machine_id,
+ ok: accept,
+ reason,
+ })
+ .expect("json")
+ .into(),
+ ));
+ }
+ }
+ _ => {}
+ },
+ WsMessage::Close(_) => break,
+ _ => {}
+ }
+ }
+ writer.abort();
+ let mut conns = state.conns.lock().expect("conns");
+ if conns.get(&node_key).is_some_and(|c| c.same_channel(&tx)) {
+ conns.remove(&node_key);
+ }
+ drop(conns);
+ push_netmaps(&state, mode);
+}
diff --git a/libs/cua/crates/cua-mesh/src/vnet.rs b/libs/cua/crates/cua-mesh/src/vnet.rs
new file mode 100644
index 0000000000..d83a006acd
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/src/vnet.rs
@@ -0,0 +1,316 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Virtual UDP sockets on the node's mesh address.
+//!
+//! Packets the tunnel decrypts land here by destination port; packets a
+//! socket sends become IPv6/UDP packets the engine encrypts to the peer
+//! that owns the destination address. A [`VSocket`] is also a quinn
+//! [`AsyncUdpSocket`], so QUIC runs over the mesh unchanged.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::io::{self, IoSliceMut};
+use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex, Weak};
+use std::task::{Context, Poll};
+
+use bytes::Bytes;
+use quinn::udp::{RecvMeta, Transmit};
+use quinn::{AsyncUdpSocket, UdpPoller};
+use tokio::sync::mpsc;
+
+use crate::packet;
+
+/// Where the engine sends what a socket writes.
+pub(crate) trait Outbound: Send + Sync + 'static {
+ /// Encrypts and sends one IP packet to the peer owning `dst`.
+ fn send_ip(&self, dst: Ipv6Addr, packet: &[u8]) -> io::Result<()>;
+ /// Ready to send to `dst` (the underlying path's socket is writable).
+ fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
+}
+
+const QUEUE: usize = 4096;
+
+type Inbox = mpsc::Sender<(SocketAddrV6, Bytes)>;
+
+/// The node's virtual network: its address and bound ports.
+pub(crate) struct VNet {
+ addr: Ipv6Addr,
+ ports: Mutex<HashMap<u16, Inbox>>,
+ out: Mutex<Option<Weak<dyn Outbound>>>,
+}
+
+impl fmt::Debug for VNet {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("VNet").field("addr", &self.addr).finish()
+ }
+}
+
+impl VNet {
+ pub(crate) fn new(addr: Ipv6Addr) -> Arc<Self> {
+ Arc::new(Self {
+ addr,
+ ports: Mutex::new(HashMap::new()),
+ out: Mutex::new(None),
+ })
+ }
+
+ pub(crate) fn set_outbound(&self, out: Weak<dyn Outbound>) {
+ *self.out.lock().expect("out") = Some(out);
+ }
+
+ fn outbound(&self) -> io::Result<Arc<dyn Outbound>> {
+ self.out
+ .lock()
+ .expect("out")
+ .as_ref()
+ .and_then(Weak::upgrade)
+ .ok_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "mesh stopped"))
+ }
+
+ /// Delivers a decrypted packet (already checked to come from its
+ /// peer's address). Drops it when nothing listens or the queue is full.
+ pub(crate) fn deliver(&self, p: &[u8]) -> bool {
+ let Some(u) = packet::parse_udp(p) else {
+ return false;
+ };
+ if *u.dst.ip() != self.addr {
+ return false;
+ }
+ let tx = self
+ .ports
+ .lock()
+ .expect("ports")
+ .get(&u.dst.port())
+ .cloned();
+ match tx {
+ Some(tx) => tx
+ .try_send((u.src, Bytes::copy_from_slice(u.payload)))
+ .is_ok(),
+ None => false,
+ }
+ }
+
+ /// Binds `port` (0: an ephemeral one).
+ pub(crate) fn bind(self: &Arc<Self>, port: u16) -> io::Result<Arc<VSocket>> {
+ let mut ports = self.ports.lock().expect("ports");
+ let port = if port == 0 {
+ let mut chosen = None;
+ for _ in 0..64 {
+ let p = rand::random_range(20_000u16..60_000);
+ if !ports.contains_key(&p) {
+ chosen = Some(p);
+ break;
+ }
+ }
+ chosen.ok_or_else(|| io::Error::new(io::ErrorKind::AddrInUse, "no free mesh port"))?
+ } else if ports.contains_key(&port) {
+ return Err(io::Error::new(
+ io::ErrorKind::AddrInUse,
+ format!("mesh port {port} in use"),
+ ));
+ } else {
+ port
+ };
+ let (tx, rx) = mpsc::channel(QUEUE);
+ ports.insert(port, tx);
+ Ok(Arc::new(VSocket {
+ local: SocketAddrV6::new(self.addr, port, 0, 0),
+ rx: Mutex::new(rx),
+ net: Arc::downgrade(self),
+ }))
+ }
+
+ fn unbind(&self, port: u16) {
+ self.ports.lock().expect("ports").remove(&port);
+ }
+}
+
+/// A UDP socket on the mesh.
+pub struct VSocket {
+ local: SocketAddrV6,
+ rx: Mutex<mpsc::Receiver<(SocketAddrV6, Bytes)>>,
+ net: Weak<VNet>,
+}
+
+impl fmt::Debug for VSocket {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("VSocket")
+ .field("local", &self.local)
+ .finish()
+ }
+}
+
+impl Drop for VSocket {
+ fn drop(&mut self) {
+ if let Some(net) = self.net.upgrade() {
+ net.unbind(self.local.port());
+ }
+ }
+}
+
+impl VSocket {
+ /// The bound mesh address.
+ pub fn local(&self) -> SocketAddrV6 {
+ self.local
+ }
+
+ /// Sends one datagram to `dst` on the mesh.
+ pub fn send_to(&self, payload: &[u8], dst: SocketAddrV6) -> io::Result<()> {
+ let p = packet::build_udp(self.local, dst, payload).ok_or_else(|| {
+ io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "datagram larger than the mesh MTU",
+ )
+ })?;
+ let net = self
+ .net
+ .upgrade()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "mesh stopped"))?;
+ net.outbound()?.send_ip(*dst.ip(), &p)
+ }
+
+ /// Receives one datagram.
+ pub async fn recv_from(&self) -> io::Result<(Bytes, SocketAddrV6)> {
+ std::future::poll_fn(|cx| {
+ let mut rx = self.rx.lock().expect("rx");
+ match rx.poll_recv(cx) {
+ Poll::Ready(Some((src, b))) => Poll::Ready(Ok((b, src))),
+ Poll::Ready(None) => Poll::Ready(Err(io::Error::new(
+ io::ErrorKind::NotConnected,
+ "mesh stopped",
+ ))),
+ Poll::Pending => Poll::Pending,
+ }
+ })
+ .await
+ }
+}
+
+#[derive(Debug)]
+struct Poller {
+ net: Weak<VNet>,
+}
+
+impl UdpPoller for Poller {
+ fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
+ match self.net.upgrade().map(|n| n.outbound()) {
+ Some(Ok(out)) => out.poll_send_ready(cx),
+ Some(Err(e)) => Poll::Ready(Err(e)),
+ None => Poll::Ready(Err(io::Error::new(
+ io::ErrorKind::NotConnected,
+ "mesh stopped",
+ ))),
+ }
+ }
+}
+
+impl AsyncUdpSocket for VSocket {
+ fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn UdpPoller>> {
+ Box::pin(Poller {
+ net: self.net.clone(),
+ })
+ }
+
+ fn try_send(&self, t: &Transmit) -> io::Result<()> {
+ let SocketAddr::V6(dst) = t.destination else {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "the mesh is IPv6 only",
+ ));
+ };
+ match t.segment_size {
+ Some(seg) if seg < t.contents.len() => {
+ for chunk in t.contents.chunks(seg) {
+ self.send_to(chunk, dst)?;
+ }
+ Ok(())
+ }
+ _ => self.send_to(t.contents, dst),
+ }
+ }
+
+ fn poll_recv(
+ &self,
+ cx: &mut Context,
+ bufs: &mut [IoSliceMut<'_>],
+ meta: &mut [RecvMeta],
+ ) -> Poll<io::Result<usize>> {
+ let mut rx = self.rx.lock().expect("rx");
+ let mut n = 0;
+ while n < bufs.len() && n < meta.len() {
+ let next = if n == 0 {
+ match rx.poll_recv(cx) {
+ Poll::Ready(Some(v)) => v,
+ Poll::Ready(None) => {
+ return Poll::Ready(Err(io::Error::new(
+ io::ErrorKind::NotConnected,
+ "mesh stopped",
+ )));
+ }
+ Poll::Pending => return Poll::Pending,
+ }
+ } else {
+ match rx.try_recv() {
+ Ok(v) => v,
+ Err(_) => break,
+ }
+ };
+ let (src, payload) = next;
+ let len = payload.len().min(bufs[n].len());
+ bufs[n][..len].copy_from_slice(&payload[..len]);
+ meta[n] = RecvMeta {
+ addr: SocketAddr::V6(src),
+ len,
+ stride: len,
+ ecn: None,
+ dst_ip: Some(std::net::IpAddr::V6(*self.local.ip())),
+ };
+ n += 1;
+ }
+ Poll::Ready(Ok(n))
+ }
+
+ fn local_addr(&self) -> io::Result<SocketAddr> {
+ Ok(SocketAddr::V6(self.local))
+ }
+
+ fn may_fragment(&self) -> bool {
+ false
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ struct Loop(Arc<VNet>);
+ impl Outbound for Loop {
+ fn send_ip(&self, _dst: Ipv6Addr, packet: &[u8]) -> io::Result<()> {
+ self.0.deliver(packet);
+ Ok(())
+ }
+ fn poll_send_ready(&self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ }
+
+ #[tokio::test]
+ async fn sockets_exchange_datagrams() {
+ let addr: Ipv6Addr = "fd5c:a000::1".parse().unwrap();
+ let net = VNet::new(addr);
+ let out: Arc<dyn Outbound> = Arc::new(Loop(net.clone()));
+ net.set_outbound(Arc::downgrade(&out));
+ let a = net.bind(0).unwrap();
+ let b = net.bind(7443).unwrap();
+ assert!(net.bind(7443).is_err());
+ a.send_to(b"ping", b.local()).unwrap();
+ let (got, from) = b.recv_from().await.unwrap();
+ assert_eq!(&got[..], b"ping");
+ assert_eq!(from, a.local());
+ drop(b);
+ assert!(net.bind(7443).is_ok());
+ }
+}
diff --git a/libs/cua/crates/cua-mesh/tests/mesh.rs b/libs/cua/crates/cua-mesh/tests/mesh.rs
new file mode 100644
index 0000000000..9280f20633
--- /dev/null
+++ b/libs/cua/crates/cua-mesh/tests/mesh.rs
@@ -0,0 +1,516 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Two real nodes (UDP sockets, WireGuard, QUIC) and an in-process
+//! coordinator: streams, direct and relayed paths, pairing, UDP
+//! forwarding, and outages (coordinator crash, relay loss, NAT rebinding).
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use cua_mesh::testing::FakeCoordinator;
+use cua_mesh::{Error, Mesh, MeshConfig, Mode, NodeKind, Path, PublicKey, static_auth};
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+const READY: Duration = Duration::from_secs(10);
+
+async fn node(
+ coord: &FakeCoordinator,
+ kind: NodeKind,
+ dir: &std::path::Path,
+ name: &str,
+ relay_only: bool,
+) -> Mesh {
+ let mut headers = Vec::new();
+ if kind == NodeKind::Machine {
+ headers.push(("x-cua-machine-id".to_owned(), format!("machine-{name}")));
+ }
+ let mut cfg = MeshConfig::new(
+ coord.url.clone(),
+ kind,
+ Some(dir.join(format!("{name}.json"))),
+ static_auth(headers),
+ );
+ cfg.name = name.to_owned();
+ cfg.stun = vec![coord.stun.to_string()];
+ cfg.relay_only = relay_only;
+ cfg.approved_path = Some(dir.join(format!("{name}-approved.json")));
+ let m = Mesh::start(cfg).await.expect("start");
+ m.wait_ready(READY).await.expect("ready");
+ m
+}
+
+/// Serves `echo` streams on a machine: every byte comes back.
+fn serve_echo(machine: &Mesh) {
+ let m = machine.clone();
+ tokio::spawn(async move {
+ while let Some(incoming) = m.accept().await {
+ assert_eq!(incoming.header.service, "echo");
+ tokio::spawn(async move {
+ let (mut r, mut w) = tokio::io::split(incoming.stream);
+ let _ = tokio::io::copy(&mut r, &mut w).await;
+ let _ = w.shutdown().await;
+ });
+ }
+ });
+}
+
+async fn wait_peer(m: &Mesh, key: &PublicKey) {
+ for _ in 0..100 {
+ if m.peers().iter().any(|p| &p.node_key == key) {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("peer never appeared");
+}
+
+async fn wait_path(m: &Mesh, key: &PublicKey, want_direct: bool, within: Duration) -> Path {
+ let deadline = tokio::time::Instant::now() + within;
+ loop {
+ let p = m.path(key).expect("peer");
+ if matches!(p, Path::Direct(_)) == want_direct {
+ return p;
+ }
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "path stayed {p} (wanted direct={want_direct})"
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn roundtrip(stream: &mut cua_mesh::MeshStream, n: usize) {
+ let data: Vec<u8> = (0..n).map(|i| (i * 7) as u8).collect();
+ let (mut r, mut w) = tokio::io::split(stream);
+ let writer = async {
+ w.write_all(&data).await.unwrap();
+ w.flush().await.unwrap();
+ };
+ let mut got = vec![0u8; n];
+ let reader = async { r.read_exact(&mut got).await.unwrap() };
+ tokio::time::timeout(Duration::from_secs(30), async {
+ tokio::join!(writer, reader)
+ })
+ .await
+ .expect("roundtrip timed out");
+ assert_eq!(got, data);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn streams_go_direct_and_carry_data() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", false).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let info = client.machine("machine-m").expect("machine in the map");
+ assert_eq!(info.addr(), machine.addr());
+
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 64 * 1024).await;
+ // Discovery moves it off the relay.
+ wait_path(&client, &machine.node_key(), true, Duration::from_secs(10)).await;
+ wait_path(&machine, &client.node_key(), true, Duration::from_secs(10)).await;
+ roundtrip(&mut s, 4 << 20).await;
+ let st = client.status();
+ let peer = st
+ .peers
+ .iter()
+ .find(|p| p.node_key == machine.node_key())
+ .unwrap();
+ assert!(peer.tx_direct > 4 << 20, "{peer:?}");
+ // The machine sees who the client is.
+ let seen = machine
+ .peers()
+ .into_iter()
+ .find(|p| p.node_key == client.node_key())
+ .unwrap();
+ assert_eq!(seen.grant.unwrap().account, "acct-1");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn the_relay_carries_only_ciphertext_when_direct_fails() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", true).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", true).await;
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ let marker = b"PLAINTEXT-MARKER-0123456789".repeat(1000);
+ let (mut r, mut w) = tokio::io::split(&mut s);
+ w.write_all(&marker).await.unwrap();
+ let mut got = vec![0u8; marker.len()];
+ tokio::time::timeout(Duration::from_secs(20), r.read_exact(&mut got))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(got, marker);
+ assert_eq!(client.path(&machine.node_key()), Some(Path::Relay));
+ assert!(coord.relayed_bytes() > marker.len() as u64);
+ // The relay carried every byte, and never a byte of plaintext.
+ assert!(!coord.relayed_contains(b"PLAINTEXT-MARKER"));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn direct_sessions_survive_a_coordinator_crash() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", false).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+ wait_path(&client, &machine.node_key(), true, Duration::from_secs(10)).await;
+
+ coord.stop();
+ // The open stream keeps working, and new streams open, all direct.
+ for _ in 0..5 {
+ roundtrip(&mut s, 256 * 1024).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ let mut s2 = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s2, 1024).await;
+ assert!(!client.control_state().connected);
+
+ coord.restart().await;
+ client.wait_ready(READY).await.unwrap();
+ roundtrip(&mut s, 1024).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn relayed_sessions_resume_after_a_relay_restart() {
+ let _ = tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .with_test_writer()
+ .try_init();
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", true).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", true).await;
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+
+ coord.stop();
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ // Written while the relay is gone: QUIC retransmits once it is back.
+ let pending = tokio::spawn(async move {
+ roundtrip(&mut s, 64 * 1024).await;
+ s
+ });
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ coord.restart().await;
+ let mut s = tokio::time::timeout(Duration::from_secs(40), pending)
+ .await
+ .expect("stream resumed")
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_nat_rebinding_falls_back_and_finds_a_new_direct_path() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", false).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+ let before = wait_path(&client, &machine.node_key(), true, Duration::from_secs(10)).await;
+
+ // The client moves to a new port, as after a network change.
+ client.rebind().await.unwrap();
+ roundtrip(&mut s, 128 * 1024).await;
+ let after = wait_path(&machine, &client.node_key(), true, Duration::from_secs(15)).await;
+ let Path::Direct(before) = before else {
+ unreachable!()
+ };
+ let _ = before;
+ let Path::Direct(after) = after else {
+ unreachable!()
+ };
+ let (v4, _) = client
+ .status()
+ .endpoints
+ .first()
+ .map(|e| (e.port(), ()))
+ .unwrap_or((0, ()));
+ assert_eq!(
+ after.port(),
+ v4,
+ "the machine follows the client's new port"
+ );
+ roundtrip(&mut s, 128 * 1024).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn static_mode_pairs_by_proof_only() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Static).await;
+ let mut cfg = MeshConfig::new(
+ coord.url.clone(),
+ NodeKind::Machine,
+ Some(dir.path().join("m.json")),
+ static_auth(vec![("x-cua-machine-id".into(), "machine-m".into())]),
+ );
+ cfg.approved_path = Some(dir.path().join("approved.json"));
+ cfg.pair_verifier = Some(Arc::new(|client, ts, proof| {
+ cua_mesh::proto::verify_pair_proof(
+ "the-env-token",
+ "machine-m",
+ client,
+ ts,
+ proof,
+ cua_mesh::proto::now_secs(),
+ )
+ }));
+ let machine = Mesh::start(cfg).await.unwrap();
+ machine.wait_ready(READY).await.unwrap();
+ serve_echo(&machine);
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ assert!(client.machine("machine-m").is_none(), "unpaired: no peers");
+
+ let wrong = client.pair("machine-m", "not-the-token").await;
+ assert!(matches!(wrong, Err(Error::Refused(_))), "{wrong:?}");
+ assert!(client.machine("machine-m").is_none());
+
+ client.pair("machine-m", "the-env-token").await.unwrap();
+ let info = client
+ .wait_machine("machine-m", Duration::from_secs(5))
+ .await
+ .expect("paired machine in the map");
+ let mut s = client
+ .open_stream(&info.node_key, "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 32 * 1024).await;
+ // The approval persisted on the machine.
+ let saved = std::fs::read_to_string(dir.path().join("approved.json")).unwrap();
+ assert!(saved.contains(&client.node_key().to_base64()));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn loopback_forwards_carry_tcp_and_udp() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", false).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ serve_echo(&machine);
+ // A local UDP echo service on the machine, served on the media port.
+ let udp_echo = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
+ let echo_addr = udp_echo.local_addr().unwrap();
+ tokio::spawn(async move {
+ let mut buf = [0u8; 2048];
+ loop {
+ let (n, src) = udp_echo.recv_from(&mut buf).await.unwrap();
+ udp_echo.send_to(&buf[..n], src).await.unwrap();
+ }
+ });
+ machine
+ .serve_udp(cua_mesh::MEDIA_UDP_PORT, echo_addr)
+ .unwrap();
+ wait_peer(&client, &machine.node_key()).await;
+
+ let fwd = client
+ .forward(machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ let mut tcp = tokio::net::TcpStream::connect(fwd.local).await.unwrap();
+ tcp.write_all(b"hello over tcp").await.unwrap();
+ let mut got = [0u8; 14];
+ tcp.read_exact(&mut got).await.unwrap();
+ assert_eq!(&got, b"hello over tcp");
+
+ let udp = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
+ let mut ok = false;
+ for _ in 0..20 {
+ udp.send_to(b"hello over udp", fwd.local).await.unwrap();
+ let mut buf = [0u8; 64];
+ if let Ok(Ok((n, _))) =
+ tokio::time::timeout(Duration::from_millis(500), udp.recv_from(&mut buf)).await
+ {
+ assert_eq!(&buf[..n], b"hello over udp");
+ ok = true;
+ break;
+ }
+ }
+ assert!(ok, "udp echo over the mesh");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn removed_peers_are_cut() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Static).await;
+ let mut cfg = MeshConfig::new(
+ coord.url.clone(),
+ NodeKind::Machine,
+ Some(dir.path().join("m.json")),
+ static_auth(vec![("x-cua-machine-id".into(), "machine-m".into())]),
+ );
+ cfg.approved_path = Some(dir.path().join("approved.json"));
+ cfg.pair_verifier = Some(Arc::new(|_, _, _| true));
+ let machine = Mesh::start(cfg).await.unwrap();
+ machine.wait_ready(READY).await.unwrap();
+ serve_echo(&machine);
+ let client = node(&coord, NodeKind::Client, dir.path(), "c", false).await;
+ client.pair("machine-m", "x").await.unwrap();
+ let info = client
+ .wait_machine("machine-m", Duration::from_secs(5))
+ .await
+ .unwrap();
+ let mut s = client
+ .open_stream(&info.node_key, "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+ // The machine revokes the client; the next map drops it and its
+ // connection ends.
+ assert!(machine.revoke(&client.node_key()));
+ coord.restart().await; // a fresh map is pushed on reconnect
+ machine.wait_ready(READY).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ assert!(
+ !machine
+ .peers()
+ .iter()
+ .any(|p| p.node_key == client.node_key())
+ );
+ let (mut r, mut w) = tokio::io::split(&mut s);
+ let _ = w.write_all(b"after revoke").await;
+ let mut buf = [0u8; 12];
+ let res = tokio::time::timeout(Duration::from_secs(10), r.read_exact(&mut buf)).await;
+ assert!(!matches!(res, Ok(Ok(_))), "a revoked client is cut");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_revoked_device_fails_fast_with_the_reason() {
+ let dir = tempfile::tempdir().unwrap();
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m", false).await;
+ let mut cfg = MeshConfig::new(
+ coord.url.clone(),
+ NodeKind::Client,
+ Some(dir.path().join("c.json")),
+ static_auth(vec![("x-test-device".into(), "dev-c".into())]),
+ );
+ cfg.name = "c".into();
+ let client = Mesh::start(cfg).await.unwrap();
+ client.wait_ready(READY).await.unwrap();
+ serve_echo(&machine);
+ wait_peer(&client, &machine.node_key()).await;
+ let mut s = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .unwrap();
+ roundtrip(&mut s, 1024).await;
+
+ // The relay revokes the device: its coordinator connection is closed
+ // and every reconnect is refused with 403.
+ coord.deny("x-test-device", "dev-c", &client.node_key());
+ let t = std::time::Instant::now();
+ while client.control_state().denied.is_none() {
+ assert!(t.elapsed() < Duration::from_secs(10), "no denial seen");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ // New streams fail at once, naming the refusal, instead of waiting
+ // ~20 s on a machine that already dropped this device.
+ let t = std::time::Instant::now();
+ let err = client
+ .open_stream(&machine.node_key(), "echo", None)
+ .await
+ .expect_err("a revoked device opens no stream");
+ assert!(
+ t.elapsed() < Duration::from_secs(1),
+ "took {:?}",
+ t.elapsed()
+ );
+ assert!(
+ matches!(&err, Error::Refused(m) if m.contains("403")),
+ "{err}"
+ );
+ // The open stream ends too.
+ let (mut r, mut w) = tokio::io::split(&mut s);
+ let _ = w.write_all(b"after revoke").await;
+ let mut buf = [0u8; 12];
+ let res = tokio::time::timeout(Duration::from_secs(3), r.read_exact(&mut buf)).await;
+ assert!(
+ matches!(res, Ok(Err(_))),
+ "the open stream is closed: {res:?}"
+ );
+
+ // A new node for the same device (the reconnect after the cut) is
+ // refused at once with the reason, not after the ready timeout.
+ let t = std::time::Instant::now();
+ let Err(err) = cua_mesh::dialer::Dialer::start(
+ &coord.url,
+ static_auth(vec![("x-test-device".into(), "dev-c".into())]),
+ None,
+ Duration::from_secs(10),
+ )
+ .await
+ else {
+ panic!("a revoked device's new node is refused");
+ };
+ assert!(
+ t.elapsed() < Duration::from_secs(3),
+ "took {:?}",
+ t.elapsed()
+ );
+ assert!(
+ matches!(&err, Error::Refused(m) if m.contains("403")),
+ "{err}"
+ );
+}
+
+/// A machine missing from the coordinator's map (an older cua-spacesd, or
+/// one with the mesh off) is reported at once, so `prefer` falls back to
+/// the relay's HTTPS path without waiting out the timeout; a machine that
+/// is on the mesh is found.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_machine_off_the_mesh_is_reported_without_waiting() {
+ let coord = FakeCoordinator::start(Mode::Account).await;
+ let dir = tempfile::tempdir().unwrap();
+ let machine = node(&coord, NodeKind::Machine, dir.path(), "m1", false).await;
+ let client = node(&coord, NodeKind::Client, dir.path(), "c1", false).await;
+ wait_peer(&client, &machine.node_key()).await;
+
+ let started = std::time::Instant::now();
+ let none = client
+ .wait_machine_in_map("machine-not-on-mesh", Duration::from_secs(5))
+ .await;
+ assert!(none.is_none());
+ assert!(
+ started.elapsed() < Duration::from_secs(1),
+ "waited {:?} for a machine the map does not have",
+ started.elapsed()
+ );
+ let found = client
+ .wait_machine_in_map("machine-m1", Duration::from_secs(5))
+ .await
+ .expect("a machine on the mesh is found");
+ assert_eq!(found.node_key, machine.node_key());
+}
diff --git a/libs/cua/crates/cua-spaces/Cargo.toml b/libs/cua/crates/cua-spaces/Cargo.toml
index 11ad4981ce..160df5fd67 100644
--- a/libs/cua/crates/cua-spaces/Cargo.toml
+++ b/libs/cua/crates/cua-spaces/Cargo.toml
@@ -64,6 +64,8 @@ cua-image.workspace = true
cua-sandbox-core.workspace = true
# The cua-relay machine directory (`space://relay/<id>`) and AccountTokens.
cua-host.workspace = true
+# `relay:` Spaces over the WireGuard®-based mesh.
+cua-mesh.workspace = true
async-trait.workspace = true
base64.workspace = true
bytes.workspace = true
@@ -96,6 +98,7 @@ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-
axum = { workspace = true, optional = true, features = ["json"] }
[dev-dependencies]
+cua-mesh = { workspace = true, features = ["testing"] }
cua-sandbox-core = { workspace = true, features = ["testing"] }
cua-host = { workspace = true, features = ["testing"] }
cua-spacesd-client = { workspace = true, features = ["testing"] }
diff --git a/libs/cua/crates/cua-spaces/src/lib.rs b/libs/cua/crates/cua-spaces/src/lib.rs
index 6af853b2bd..d7a0f6ea13 100644
--- a/libs/cua/crates/cua-spaces/src/lib.rs
+++ b/libs/cua/crates/cua-spaces/src/lib.rs
@@ -71,6 +71,7 @@ pub mod fleet_runtime;
pub mod groups;
pub mod host_spaces;
pub mod id;
+pub mod mesh;
pub mod operator;
pub mod registry;
pub mod relay;
diff --git a/libs/cua/crates/cua-spaces/src/mcp/tools.rs b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
index 3d03890d57..0ffa1cc0f3 100644
--- a/libs/cua/crates/cua-spaces/src/mcp/tools.rs
+++ b/libs/cua/crates/cua-spaces/src/mcp/tools.rs
@@ -75,9 +75,19 @@ pub(super) async fn call(
) -> ToolOutcome {
// A former tool name (`drive_ls`) runs as the tool it now is.
let tool = cua_spaces_contract::canonical(tool);
+ let space = arguments
+ .get("space")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
match dispatch(spaces, tool, arguments, broker).await {
Ok(outcome) => outcome,
Err(e) => {
+ // A call cut because the Space's mesh connection went away
+ // says why, not just "broken pipe".
+ let e = match &space {
+ Some(space) => spaces.explain_mesh_cut(space, e).await,
+ None => e,
+ };
tracing::debug!(tool, error = %e, "tool failed");
ToolOutcome::error(&e)
}
diff --git a/libs/cua/crates/cua-spaces/src/mesh.rs b/libs/cua/crates/cua-spaces/src/mesh.rs
new file mode 100644
index 0000000000..455f8340f7
--- /dev/null
+++ b/libs/cua/crates/cua-spaces/src/mesh.rs
@@ -0,0 +1,510 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Relay Spaces over the WireGuard®-based mesh (`cua-mesh`).
+//!
+//! When a relay coordinates a mesh and the machine is on it (same protocol
+//! version), the Space is reached through a loopback forward into the mesh:
+//! WireGuard end to end, direct when the two NATs allow it, through the
+//! relay as ciphertext otherwise.
+//!
+//! - `relay:<machine-id>` (an account relay): the machine's mesh endpoint
+//! identifies this device from the relay's network map, so the account
+//! token never goes to the machine; a per-forward session key (sent as a
+//! request header) keeps another local user from borrowing the forward.
+//! - A Space added by `<relay>/m/<machine-id>` with its env token (a
+//! self-hosted static relay): this device pairs with the machine by
+//! proving it holds the env token (the machine checks it; the relay only
+//! passes the proof along), then sends the env token inside WireGuard.
+//!
+//! The mesh is off unless asked for ([`cua_mesh::policy`]): `CUA_MESH`
+//! picks the policy, and without it the Cua Spaces app's daemon follows the
+//! app's update channel (off on every channel in this release):
+//! - `off` (default): the relay's HTTPS path only, as before the mesh;
+//! - `prefer`: the mesh when both sides support it, the relay's HTTPS path
+//! otherwise (an older relay or machine, or a mesh that does not answer),
+//! with a log line saying so;
+//! - `require`: the mesh or nothing (a relay that can read sessions is
+//! never used).
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cua_mesh::dialer::{Dialer, SESSION_HEADER};
+use cua_spacesd_client::{ConnectOptions, SpacesdClient};
+
+use crate::relay::RelayAccount;
+
+/// How relay Spaces use the mesh (`CUA_MESH`, see [`cua_mesh::policy`]).
+pub use cua_mesh::policy::Policy as MeshPolicy;
+
+/// Set on the cua daemon the Cua Spaces app starts.
+const STARTED_BY_ENV: &str = "CUA_DAEMON_STARTED_BY";
+
+/// The policy for this process now: `CUA_MESH`, else (in the daemon the
+/// Cua Spaces app started) the app's update channel, else off. Read on
+/// every connect, so a change applies to the next connection.
+pub fn policy() -> MeshPolicy {
+ let app = std::env::var(STARTED_BY_ENV).is_ok_and(|v| v == "app");
+ let home = app.then(cua_home::cua_home);
+ MeshPolicy::current(home.as_deref())
+}
+
+/// Which node: the account's (one per relay) or an anonymous one for a
+/// static relay.
+#[derive(Clone, PartialEq, Eq, Hash)]
+enum Key {
+ Account(String),
+ Static(String),
+}
+
+enum Slot {
+ Ready {
+ dialer: Arc<Dialer>,
+ /// Held while the node lives: one persistent identity per home.
+ _lock: Option<std::fs::File>,
+ },
+ /// The mesh cannot be used (the relay has none, or refused this
+ /// device), and why; checked again after a while.
+ Unsupported(Instant, String),
+}
+
+const RECHECK: Duration = Duration::from_secs(600);
+
+/// Per-runtime mesh nodes, started on first use.
+#[derive(Default)]
+pub(crate) struct MeshClients {
+ nodes: tokio::sync::Mutex<HashMap<Key, Slot>>,
+ /// Spaces connected over the mesh, and through which node.
+ routed: std::sync::Mutex<HashMap<String, Key>>,
+}
+
+/// How a relay Space connects, chosen by [`connect_options`].
+pub(crate) enum Route {
+ /// Through the mesh: these options reach the machine's spacesd.
+ Mesh(Box<ConnectOptions>),
+ /// The relay's HTTPS path.
+ Relay,
+}
+
+/// Who a relay Space connects as.
+pub(crate) enum Via<'a> {
+ /// `relay:<id>`: the signed-in account.
+ Account(&'a RelayAccount),
+ /// `<relay>/m/<id>` with the Space's env token.
+ Static {
+ /// Relay base URL.
+ relay: &'a str,
+ /// The env token.
+ token: &'a str,
+ },
+}
+
+fn key_of(via: &Via<'_>) -> Key {
+ match via {
+ Via::Account(a) => Key::Account(a.url.clone()),
+ Via::Static { relay, .. } => Key::Static((*relay).to_owned()),
+ }
+}
+
+impl MeshClients {
+ /// Records that Space `space` (its id) connected over `via`'s mesh.
+ pub(crate) fn note_routed(&self, space: &str, via: &Via<'_>) {
+ self.routed
+ .lock()
+ .expect("routed")
+ .insert(space.to_owned(), key_of(via));
+ }
+
+ /// Why a Space connected over the mesh must reconnect: its node can no
+ /// longer use the mesh (the relay turned it off, or refused this
+ /// device). Reconnecting applies `CUA_MESH` again, so `prefer` moves
+ /// to the relay's HTTPS path and `require` says why it cannot.
+ pub(crate) async fn stale(
+ &self,
+ space: &str,
+ policy: impl FnOnce() -> MeshPolicy,
+ ) -> Option<String> {
+ let key = self.routed.lock().expect("routed").get(space).cloned()?;
+ let reason = if !policy().uses_mesh() {
+ Some("the mesh was turned off".into())
+ } else {
+ None
+ };
+ let reason = match reason {
+ Some(r) => Some(r),
+ None => self.unusable(&key).await,
+ }?;
+ self.routed.lock().expect("routed").remove(space);
+ Some(reason)
+ }
+
+ /// Why Space `space` (its id) lost the mesh, when it was connected over
+ /// it and its node can no longer be used (a revoked device, the mesh
+ /// turned off). Waits up to `wait` for the node to learn it: a call cut
+ /// by the relay fails a moment before the relay's refusal arrives.
+ /// Leaves the Space marked, so its next use reconnects.
+ pub(crate) async fn cut_reason(&self, space: &str, wait: Duration) -> Option<String> {
+ let key = self.routed.lock().expect("routed").get(space).cloned()?;
+ let deadline = Instant::now() + wait;
+ loop {
+ if let Some(reason) = self.unusable(&key).await {
+ return Some(reason);
+ }
+ if Instant::now() >= deadline {
+ return None;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+
+ /// Why `key`'s node can no longer be used, if it cannot.
+ async fn unusable(&self, key: &Key) -> Option<String> {
+ match self.nodes.lock().await.get(key) {
+ Some(Slot::Ready { dialer, .. }) => dialer.mesh().unusable(),
+ _ => Some("the mesh node is gone".into()),
+ }
+ }
+
+ async fn dialer(&self, via: &Via<'_>) -> Result<Arc<Dialer>, String> {
+ let key = key_of(via);
+ let mut nodes = self.nodes.lock().await;
+ match nodes.get(&key) {
+ // A node the relay no longer coordinates (mesh turned off, or
+ // this device refused): start over, which checks the relay.
+ Some(Slot::Ready { dialer, .. }) if dialer.mesh().unusable().is_some() => {
+ // Stop it now (forwards still holding it end): the next node
+ // takes over this home's identity.
+ dialer.mesh().shutdown();
+ nodes.remove(&key);
+ }
+ Some(Slot::Ready { dialer, .. }) => return Ok(dialer.clone()),
+ Some(Slot::Unsupported(at, why)) if at.elapsed() < RECHECK => {
+ return Err(why.clone());
+ }
+ _ => {}
+ }
+ match start(via).await {
+ Ok((d, lock)) => {
+ let d = Arc::new(d);
+ nodes.insert(
+ key,
+ Slot::Ready {
+ dialer: d.clone(),
+ _lock: lock,
+ },
+ );
+ Ok(d)
+ }
+ Err(e) => {
+ nodes.insert(key, Slot::Unsupported(Instant::now(), e.clone()));
+ Err(e)
+ }
+ }
+ }
+
+ /// The status of each node, for displays and measurements.
+ pub(crate) async fn status(&self) -> Vec<(String, cua_mesh::Status)> {
+ self.nodes
+ .lock()
+ .await
+ .iter()
+ .filter_map(|(key, slot)| match (key, slot) {
+ (Key::Account(url) | Key::Static(url), Slot::Ready { dialer, .. }) => {
+ Some((url.clone(), dialer.mesh().status()))
+ }
+ _ => None,
+ })
+ .collect()
+ }
+}
+
+async fn relay_has_mesh(url: &str) -> Result<(), String> {
+ let info = cua_host::RelayClient::new(url)
+ .map_err(|e| e.to_string())?
+ .info()
+ .await
+ .map_err(|e| e.to_string())?;
+ match info.mesh {
+ Some(m) if m.version == cua_mesh::VERSION => Ok(()),
+ Some(m) => Err(format!(
+ "the relay speaks mesh v{}, this cua v{}",
+ m.version,
+ cua_mesh::VERSION
+ )),
+ None => Err("the relay has no mesh coordinator".into()),
+ }
+}
+
+async fn start(via: &Via<'_>) -> Result<(Dialer, Option<std::fs::File>), String> {
+ let (url, auth): (String, cua_mesh::AuthProvider) = match via {
+ Via::Account(account) => {
+ let account = (*account).clone();
+ let url = account.url.clone();
+ let auth: cua_mesh::AuthProvider = Arc::new(move || {
+ let account = account.clone();
+ Box::pin(async move {
+ let token = account
+ .tokens
+ .access_token()
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut headers = vec![(
+ "x-cua-relay-authorization".to_owned(),
+ format!("Bearer {token}"),
+ )];
+ // Asked once per (re)connection to the coordinator: a
+ // fresh session, since a relay that restarted (the usual
+ // reason to reconnect) forgot the cached one.
+ if let Some(device) = &account.device {
+ device.reset_session().await;
+ }
+ if let Some(session) = account.device_session().await {
+ headers.push((cua_host::relay::DEVICE_SESSION_HEADER.to_owned(), session));
+ }
+ Ok(headers)
+ })
+ });
+ (url, auth)
+ }
+ Via::Static { relay, .. } => ((*relay).to_owned(), cua_mesh::static_auth(Vec::new())),
+ };
+ relay_has_mesh(&url).await?;
+ // One persistent node per Cua home and kind; a second process (a CLI
+ // run next to the daemon) gets a short-lived one the relay forgets.
+ let name = match via {
+ Via::Account(_) => "client",
+ Via::Static { .. } => "static-client",
+ };
+ let dir = cua_home::cua_home().join("mesh");
+ let (identity, lock) = match lock_identity(&dir, name) {
+ Some(lock) => (Some(dir.join(format!("{name}.json"))), Some(lock)),
+ None => (None, None),
+ };
+ let dialer = Dialer::start(&url, auth, identity, Duration::from_secs(10))
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok((dialer, lock))
+}
+
+fn lock_identity(dir: &std::path::Path, name: &str) -> Option<std::fs::File> {
+ std::fs::create_dir_all(dir).ok()?;
+ let f = std::fs::OpenOptions::new()
+ .create(true)
+ .truncate(false)
+ .write(true)
+ .open(dir.join(format!("{name}.lock")))
+ .ok()?;
+ f.try_lock().ok()?;
+ Some(f)
+}
+
+/// Picks the route to `machine_id`. With [`MeshPolicy::Require`] an
+/// unusable mesh is an error, never a silent fallback.
+pub(crate) async fn connect_options(
+ clients: &MeshClients,
+ via: Via<'_>,
+ machine_id: &str,
+ policy: MeshPolicy,
+) -> crate::Result<Route> {
+ if policy == MeshPolicy::Off {
+ return Ok(Route::Relay);
+ }
+ match try_mesh(clients, &via, machine_id).await {
+ Ok(options) => Ok(Route::Mesh(Box::new(options))),
+ Err(reason) if policy == MeshPolicy::Require => Err(crate::Error::host(
+ "the mesh",
+ format!(
+ "machine {machine_id} is not reachable over the mesh (CUA_MESH=require): {reason}"
+ ),
+ )),
+ Err(reason) => {
+ tracing::info!(machine = %machine_id, %reason, "using the relay's HTTPS path");
+ Ok(Route::Relay)
+ }
+ }
+}
+
+async fn try_mesh(
+ clients: &MeshClients,
+ via: &Via<'_>,
+ machine_id: &str,
+) -> Result<ConnectOptions, String> {
+ let dialer = clients.dialer(via).await?;
+ let token = match via {
+ Via::Static { token, .. } => Some(*token),
+ Via::Account(_) => None,
+ };
+ let route = dialer
+ .route(machine_id, token, Duration::from_secs(3))
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut options =
+ ConnectOptions::parse(&format!("http://{}", route.local)).map_err(|e| e.to_string())?;
+ if let Some(session) = &route.session {
+ options = options.header(SESSION_HEADER, session.clone());
+ }
+ if let Some(token) = token {
+ options = options.token(token);
+ }
+ // Check the path answers before committing to it.
+ let probe = options.clone().probe_timeout(Duration::from_secs(8));
+ match SpacesdClient::connect(probe).await {
+ Ok(_) => Ok(options),
+ Err(e) => {
+ dialer.forget(machine_id).await;
+ Err(format!("the mesh path did not answer: {e}"))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn account(url: &str) -> RelayAccount {
+ RelayAccount::new(url, Arc::new(cua_host::relay::StaticToken("t".into())))
+ }
+
+ #[tokio::test]
+ async fn policy_off_never_touches_the_mesh() {
+ let clients = MeshClients::default();
+ let a = account("http://127.0.0.1:9");
+ let route = connect_options(&clients, Via::Account(&a), "m1", MeshPolicy::Off)
+ .await
+ .unwrap();
+ assert!(matches!(route, Route::Relay));
+ }
+
+ #[tokio::test]
+ async fn a_relay_without_a_mesh_falls_back_unless_required() {
+ // The fake relay's /v1/info has no `mesh`: an older relay.
+ let relay = cua_host::testing::FakeRelay::start().await;
+ let clients = MeshClients::default();
+ let a = account(&relay.url);
+ let route = connect_options(&clients, Via::Account(&a), "m1", MeshPolicy::Prefer)
+ .await
+ .unwrap();
+ assert!(matches!(route, Route::Relay));
+ let err = connect_options(&clients, Via::Account(&a), "m1", MeshPolicy::Require)
+ .await
+ .err()
+ .expect("require refuses the plaintext path");
+ assert!(err.to_string().contains("CUA_MESH=require"), "{err}");
+ let route = connect_options(
+ &clients,
+ Via::Static {
+ relay: &relay.url,
+ token: "env",
+ },
+ "m1",
+ MeshPolicy::Prefer,
+ )
+ .await
+ .unwrap();
+ assert!(matches!(route, Route::Relay));
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn a_space_on_a_mesh_the_relay_turned_off_reconnects() {
+ let coord = cua_mesh::testing::FakeCoordinator::start(cua_mesh::Mode::Account).await;
+ let dialer = Dialer::start(
+ &coord.url,
+ cua_mesh::static_auth(Vec::new()),
+ None,
+ Duration::from_secs(10),
+ )
+ .await
+ .unwrap();
+ let clients = MeshClients::default();
+ let key = Key::Account(coord.url.clone());
+ clients.nodes.lock().await.insert(
+ key.clone(),
+ Slot::Ready {
+ dialer: Arc::new(dialer),
+ _lock: None,
+ },
+ );
+ clients
+ .routed
+ .lock()
+ .unwrap()
+ .insert("relay:m1".into(), key);
+ assert!(
+ clients
+ .stale("relay:m1", || MeshPolicy::Prefer)
+ .await
+ .is_none(),
+ "mesh still on"
+ );
+
+ // The relay turns its mesh off.
+ coord.set_mesh(false);
+ // A call cut at that moment is explained (the node is unusable).
+ let cut = clients
+ .cut_reason("relay:m1", Duration::from_secs(5))
+ .await
+ .expect("the cut is explained");
+ assert!(cut.contains("no mesh coordinator"), "{cut}");
+ // Spaces that never used the mesh are never explained this way.
+ assert!(
+ clients
+ .cut_reason("relay:other", Duration::from_secs(5))
+ .await
+ .is_none()
+ );
+ let mut reason = None;
+ for _ in 0..200 {
+ reason = clients.stale("relay:m1", || MeshPolicy::Prefer).await;
+ if reason.is_some() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ let reason = reason.expect("the connection is reported stale");
+ assert!(reason.contains("no mesh coordinator"), "{reason}");
+ // Reported once: the reconnect picks the route again.
+ assert!(
+ clients
+ .stale("relay:m1", || MeshPolicy::Prefer)
+ .await
+ .is_none()
+ );
+ }
+
+ #[tokio::test]
+ async fn a_space_on_the_mesh_reconnects_when_the_mesh_is_turned_off() {
+ let clients = MeshClients::default();
+ clients
+ .routed
+ .lock()
+ .unwrap()
+ .insert("relay:m1".into(), Key::Account("http://relay".into()));
+ // Off now (CUA_MESH=off, or the app left the channel that uses it):
+ // the cached connection is dropped and reconnects over HTTPS.
+ let reason = clients.stale("relay:m1", || MeshPolicy::Off).await;
+ assert_eq!(reason.as_deref(), Some("the mesh was turned off"));
+ assert!(
+ clients
+ .stale("relay:m1", || MeshPolicy::Off)
+ .await
+ .is_none()
+ );
+ // A Space that never used the mesh is never stale.
+ assert!(
+ clients
+ .stale("relay:m2", || MeshPolicy::Off)
+ .await
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn the_policy_reads_cua_mesh() {
+ assert_eq!(MeshPolicy::parse("off"), Some(MeshPolicy::Off));
+ assert_eq!(MeshPolicy::parse(" REQUIRE "), Some(MeshPolicy::Require));
+ assert_eq!(MeshPolicy::parse(""), None);
+ assert_eq!(MeshPolicy::parse("prefer"), Some(MeshPolicy::Prefer));
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 3da0f7fb49..af9a1b9b40 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -393,6 +393,7 @@ impl SpacesBuilder {
probe_timeout: self.probe_timeout.unwrap_or(DEFAULT_PROBE_TIMEOUT),
download_dir,
connections: tokio::sync::Mutex::new(HashMap::new()),
+ mesh: crate::mesh::MeshClients::default(),
#[cfg(feature = "spaces-hotspot")]
hotspots: tokio::sync::Mutex::new(BTreeMap::new()),
#[cfg(feature = "spaces-agents")]
@@ -648,6 +649,8 @@ pub(crate) struct Inner {
probe_timeout: Duration,
pub(crate) download_dir: PathBuf,
connections: tokio::sync::Mutex<HashMap<String, Space>>,
+ /// Mesh nodes for `relay:` Spaces ([`crate::mesh`]).
+ pub(crate) mesh: crate::mesh::MeshClients,
#[cfg(feature = "spaces-hotspot")]
pub(crate) hotspots: tokio::sync::Mutex<BTreeMap<String, crate::hotspot::Hotspot>>,
#[cfg(feature = "spaces-agents")]
@@ -873,6 +876,37 @@ impl Spaces {
self.inner.relay_cache.lock().expect("relay cache").clear();
}
+ /// `e`, from a call on `space`, with the reason when the call failed
+ /// because the Space's mesh connection was cut (a revoked device, the
+ /// mesh turned off): a transport error alone ("broken pipe") does not
+ /// say why. Other errors are returned as they are.
+ pub async fn explain_mesh_cut(&self, space: &str, e: Error) -> Error {
+ if !matches!(e, Error::Env(cua_spacesd_client::Error::Transport(_))) {
+ return e;
+ }
+ let Ok(id) = self.resolve(space) else {
+ return e;
+ };
+ match self
+ .inner
+ .mesh
+ .cut_reason(&id.to_string(), Duration::from_secs(2))
+ .await
+ {
+ Some(reason) => Error::host(
+ "the mesh",
+ format!("the connection to {id} over the mesh was cut: {reason}"),
+ ),
+ None => e,
+ }
+ }
+
+ /// The mesh node of each relay this runtime reached over the mesh:
+ /// its peers and, per peer, the path (direct or relayed) and counters.
+ pub async fn mesh_status(&self) -> Vec<(String, cua_mesh::Status)> {
+ self.inner.mesh.status().await
+ }
+
pub(crate) fn relay(&self) -> Result<crate::relay::RelayAccount> {
self.relay_account().ok_or_else(|| {
Error::host(
@@ -1305,8 +1339,17 @@ impl Spaces {
pub async fn space(&self, space: &str) -> Result<Space> {
let id = self.resolve(space)?;
let key = id.to_string();
- if let Some(s) = self.inner.connections.lock().await.get(&key).cloned() {
- return Ok(s);
+ // Bound first: the cache's guard must be gone before the lock is
+ // taken again below.
+ let cached = self.inner.connections.lock().await.get(&key).cloned();
+ if let Some(s) = cached {
+ match self.inner.mesh.stale(&key, crate::mesh::policy).await {
+ None => return Ok(s),
+ Some(reason) => {
+ tracing::info!(space = %key, %reason, "the mesh went away; reconnecting");
+ self.inner.connections.lock().await.remove(&key);
+ }
+ }
}
let name = match (&id, self.inner.registry.get(&key)?) {
(_, Some(record)) => Some(record.name),
@@ -1407,6 +1450,33 @@ impl Spaces {
.unwrap_or_else(|| format!("http://{authority}"));
let mut o = ConnectOptions::parse(&url)?;
o.token = credential.token.clone();
+ // A machine on a self-hosted (static-token) relay: the
+ // mesh when the relay coordinates one (pairing with the
+ // env token), the relay's HTTPS path otherwise.
+ if let (cua_spacesd_client::EndpointKind::Relay { machine_id }, Some(token)) =
+ (o.endpoint.kind().clone(), credential.token.as_deref())
+ {
+ let relay_url = o.endpoint.origin();
+ let via = crate::mesh::Via::Static {
+ relay: &relay_url,
+ token,
+ };
+ if let crate::mesh::Route::Mesh(m) = crate::mesh::connect_options(
+ &self.inner.mesh,
+ crate::mesh::Via::Static {
+ relay: &relay_url,
+ token,
+ },
+ &machine_id,
+ crate::mesh::policy(),
+ )
+ .await?
+ {
+ tracing::info!(machine = %machine_id, "relay Space over the mesh");
+ self.inner.mesh.note_routed(&id.to_string(), &via);
+ o = *m;
+ }
+ }
(Some(o), None)
} else {
// Added by an MCP URL: the token belongs to that server.
@@ -1448,15 +1518,37 @@ impl Spaces {
}
SpaceId::Relay { machine_id } => {
let relay = self.relay()?;
- let url = cua_host::RelayClient::new(&relay.url)?.machine_url(machine_id);
- // The account token rides in `authorization` and this
- // device's session next to it, fetched (and refreshed) per
- // call; the relay checks both and swaps them for its signed
- // identity assertion.
- let bearer = crate::relay::RelayBearer { account: relay };
- let mut o = ConnectOptions::parse(&url)?.fleet_gateway(Arc::new(bearer), None);
- o.token = credential.token.clone();
- (Some(o), None)
+ // The WireGuard®-based mesh first (end to end, direct when
+ // possible); the relay's HTTPS path when the relay or the
+ // machine does not speak it yet (see `crate::mesh`).
+ match crate::mesh::connect_options(
+ &self.inner.mesh,
+ crate::mesh::Via::Account(&relay),
+ machine_id,
+ crate::mesh::policy(),
+ )
+ .await?
+ {
+ crate::mesh::Route::Mesh(o) => {
+ tracing::info!(machine = %machine_id, "relay Space over the mesh");
+ self.inner
+ .mesh
+ .note_routed(&id.to_string(), &crate::mesh::Via::Account(&relay));
+ (Some(*o), None)
+ }
+ crate::mesh::Route::Relay => {
+ let url = cua_host::RelayClient::new(&relay.url)?.machine_url(machine_id);
+ // The account token rides in `authorization` and
+ // this device's session next to it, fetched (and
+ // refreshed) per call; the relay checks both and
+ // swaps them for its signed identity assertion.
+ let bearer = crate::relay::RelayBearer { account: relay };
+ let mut o =
+ ConnectOptions::parse(&url)?.fleet_gateway(Arc::new(bearer), None);
+ o.token = credential.token.clone();
+ (Some(o), None)
+ }
+ }
}
SpaceId::Local { name } => {
let sandbox = self.inner.sandboxes.connect(name).await?;
diff --git a/libs/cua/crates/cua-spacesd-client/src/client.rs b/libs/cua/crates/cua-spacesd-client/src/client.rs
index 483b2033fc..2e66d3c022 100644
--- a/libs/cua/crates/cua-spacesd-client/src/client.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/client.rs
@@ -113,6 +113,9 @@ pub struct ConnectOptions {
/// Probe with `GetCapabilities` while connecting. Disabling it requires
/// an explicit transport and skips `SpacesdNotAvailable` detection.
pub probe: bool,
+ /// Extra headers sent on every request (gRPC, HTTP and WebSocket), as
+ /// sensitive values: for example a mesh forward's session key.
+ pub headers: Vec<(String, String)>,
}
impl ConnectOptions {
@@ -129,6 +132,7 @@ impl ConnectOptions {
keepalive: Keepalive::default(),
retry: RetryPolicy::default(),
probe: true,
+ headers: Vec::new(),
}
}
@@ -179,6 +183,12 @@ impl ConnectOptions {
self
}
+ /// Adds a header sent on every request.
+ pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
+ self.headers.push((name.into(), value.into()));
+ self
+ }
+
/// Enables or disables the connect-time probe.
pub fn probe(mut self, probe: bool) -> Self {
self.probe = probe;
@@ -193,6 +203,7 @@ impl ConnectOptions {
gateway: self.gateway.clone(),
connect_timeout: self.connect_timeout,
keepalive: self.keepalive,
+ headers: self.headers.clone(),
}
}
}
diff --git a/libs/cua/crates/cua-spacesd-client/src/transport.rs b/libs/cua/crates/cua-spacesd-client/src/transport.rs
index 1992e41e5e..7c5933dd40 100644
--- a/libs/cua/crates/cua-spacesd-client/src/transport.rs
+++ b/libs/cua/crates/cua-spacesd-client/src/transport.rs
@@ -173,6 +173,7 @@ pub(crate) struct ChannelConfig {
pub gateway: Option<GatewayAuth>,
pub connect_timeout: Duration,
pub keepalive: Keepalive,
+ pub headers: Vec<(String, String)>,
}
/// Decides the transport order for `pref` and `endpoint`.
@@ -405,6 +406,7 @@ pub(crate) struct HeaderInjector {
principal: Option<HeaderValue>,
gateway: Option<GatewayAuth>,
claim: Option<HeaderValue>,
+ extra: Vec<(http::header::HeaderName, HeaderValue)>,
}
impl HeaderInjector {
@@ -441,12 +443,25 @@ impl HeaderInjector {
.map(HeaderValue::from_str)
.transpose()
.map_err(|_| Error::InvalidEndpoint("claim".into()))?;
+ let extra = cfg
+ .headers
+ .iter()
+ .map(|(name, value)| {
+ let name = http::header::HeaderName::from_bytes(name.as_bytes())
+ .map_err(|_| Error::InvalidEndpoint(format!("header name {name:?}")))?;
+ let mut value = HeaderValue::from_str(value)
+ .map_err(|_| Error::InvalidEndpoint("header value".into()))?;
+ value.set_sensitive(true);
+ Ok((name, value))
+ })
+ .collect::<Result<Vec<_>>>()?;
Ok(Self {
authorization,
env_token_header,
principal,
gateway: cfg.gateway.clone(),
claim,
+ extra,
})
}
@@ -475,6 +490,9 @@ impl HeaderInjector {
if let Some(p) = &self.principal {
headers.insert(metadata::PRINCIPAL_BIN, p.clone());
}
+ for (name, value) in &self.extra {
+ headers.insert(name.clone(), value.clone());
+ }
Ok(())
}
}
@@ -569,6 +587,7 @@ mod extra_header_tests {
}),
connect_timeout: Duration::from_secs(1),
keepalive: Keepalive::default(),
+ headers: Vec::new(),
}
}
diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
index 982b38c8fb..d6eea4abaf 100644
--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock
@@ -644,6 +644,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead 0.5.2",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305 0.10.1",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek 2.0.1",
+]
+
[[package]]
name = "brotli"
version = "8.0.4"
@@ -853,6 +878,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher 0.4.4",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -865,6 +901,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead 0.5.2",
+ "chacha20 0.9.1",
+ "cipher 0.4.4",
+ "poly1305 0.8.0",
+ "zeroize",
+]
+
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
@@ -872,9 +921,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead 0.6.1",
- "chacha20",
+ "chacha20 0.10.2",
"cipher 0.5.2",
- "poly1305",
+ "poly1305 0.9.1",
]
[[package]]
@@ -899,6 +948,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout 0.1.4",
+ "zeroize",
]
[[package]]
@@ -1464,13 +1514,13 @@ dependencies = [
name = "cua-machine-seal"
version = "0.1.0"
dependencies = [
- "chacha20poly1305",
+ "chacha20poly1305 0.11.0",
"cua-home",
"hkdf 0.12.4",
"rand_core 0.9.5",
"sha2 0.10.9",
"thiserror 2.0.20",
- "x25519-dalek",
+ "x25519-dalek 3.0.0",
"zeroize",
]
@@ -1503,6 +1553,36 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305 0.10.1",
+ "futures-util",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1565,6 +1645,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -1792,6 +1873,21 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto 0.2.9",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
@@ -1801,7 +1897,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"curve25519-dalek-derive",
- "fiat-crypto",
+ "fiat-crypto 0.3.0",
"rustc_version",
"subtle",
"zeroize",
@@ -2375,6 +2471,12 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "fiat-crypto"
version = "0.3.0"
@@ -3391,6 +3493,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -3497,6 +3609,28 @@ version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02"
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.1"
@@ -4096,6 +4230,18 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -4875,6 +5021,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash 0.5.1",
+]
+
[[package]]
name = "poly1305"
version = "0.9.1"
@@ -5207,7 +5364,7 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -8408,13 +8565,25 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
- "curve25519-dalek",
+ "curve25519-dalek 5.0.0",
"rand_core 0.10.1",
"zeroize",
]
diff --git a/tests/e2e/cua-sdk/rust/Cargo.lock b/tests/e2e/cua-sdk/rust/Cargo.lock
index 82090637e6..8d810a1c0a 100644
--- a/tests/e2e/cua-sdk/rust/Cargo.lock
+++ b/tests/e2e/cua-sdk/rust/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -83,6 +93,45 @@ dependencies = [
"winnow 0.7.15",
]
+[[package]]
+name = "asn1-rs"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
+dependencies = [
+ "asn1-rs-derive",
+ "asn1-rs-impl",
+ "displaydoc",
+ "nom",
+ "num-traits",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
+[[package]]
+name = "asn1-rs-derive"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure 0.13.2",
+]
+
+[[package]]
+name = "asn1-rs-impl"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "async-compat"
version = "0.2.6"
@@ -673,6 +722,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -685,6 +743,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -746,6 +813,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305",
+ "hex",
+ "hmac 0.12.1",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek",
+]
+
[[package]]
name = "bstr"
version = "1.13.1"
@@ -852,6 +944,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -863,6 +966,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead",
+ "chacha20 0.9.1",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -877,6 +993,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common 0.1.7",
+ "inout",
+ "zeroize",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -1061,6 +1188,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -1335,6 +1463,36 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305",
+ "futures-util",
+ "hex",
+ "hkdf",
+ "hmac 0.12.1",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -1450,6 +1608,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -1559,6 +1718,32 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "cyclops-sdk"
version = "0.1.0"
@@ -1719,6 +1904,20 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "der-parser"
+version = "10.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+dependencies = [
+ "asn1-rs",
+ "displaydoc",
+ "nom",
+ "num-bigint",
+ "num-traits",
+ "rusticata-macros",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1914,6 +2113,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "filetime"
version = "0.2.29"
@@ -2237,6 +2442,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac 0.12.1",
+]
+
[[package]]
name = "hmac"
version = "0.12.1"
@@ -2563,6 +2777,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -2623,6 +2847,37 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -2844,6 +3099,12 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "lazy_static"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
+
[[package]]
name = "libc"
version = "0.2.189"
@@ -2960,6 +3221,18 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -2970,6 +3243,16 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -3037,6 +3320,15 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "oid-registry"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+dependencies = [
+ "asn1-rs",
+]
+
[[package]]
name = "olpc-cjson"
version = "0.1.4"
@@ -3054,6 +3346,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -3147,6 +3445,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "pem"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
+dependencies = [
+ "base64 0.23.1",
+ "serde_core",
+]
+
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -3253,6 +3561,17 @@ dependencies = [
"miniz_oxide 0.8.9",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -3504,7 +3823,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -3562,6 +3881,20 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "rcgen"
+version = "0.14.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
+dependencies = [
+ "pem",
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "x509-parser",
+ "yasna",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -3769,6 +4102,15 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rusticata-macros"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "rustix"
version = "1.1.5"
@@ -4344,6 +4686,17 @@ dependencies = [
"futures-core",
]
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -4998,6 +5351,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -5382,6 +5745,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -5559,6 +5931,36 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
+[[package]]
+name = "x509-parser"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
+dependencies = [
+ "asn1-rs",
+ "data-encoding",
+ "der-parser",
+ "lazy_static",
+ "nom",
+ "oid-registry",
+ "ring",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -5575,6 +5977,16 @@ version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4"
+[[package]]
+name = "yasna"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
+dependencies = [
+ "bit-vec",
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -5595,7 +6007,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -5636,7 +6048,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -5644,6 +6056,20 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
[[package]]
name = "zerotrie"
diff --git a/tests/e2e/local-runtimes/Cargo.lock b/tests/e2e/local-runtimes/Cargo.lock
index 09d032a848..9fe23e4b3b 100644
--- a/tests/e2e/local-runtimes/Cargo.lock
+++ b/tests/e2e/local-runtimes/Cargo.lock
@@ -8,6 +8,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aead"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
+dependencies = [
+ "crypto-common 0.1.7",
+ "generic-array",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.5"
@@ -74,6 +84,45 @@ dependencies = [
"winnow 0.7.15",
]
+[[package]]
+name = "asn1-rs"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
+dependencies = [
+ "asn1-rs-derive",
+ "asn1-rs-impl",
+ "displaydoc",
+ "nom",
+ "num-traits",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
+[[package]]
+name = "asn1-rs-derive"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure 0.13.2",
+]
+
+[[package]]
+name = "asn1-rs-impl"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "async-compat"
version = "0.2.6"
@@ -217,6 +266,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -229,6 +287,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -290,6 +357,31 @@ dependencies = [
"serde_repr",
]
+[[package]]
+name = "boringtun"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939"
+dependencies = [
+ "aead",
+ "base64 0.22.1",
+ "blake2",
+ "chacha20poly1305",
+ "hex",
+ "hmac",
+ "ip_network",
+ "ip_network_table",
+ "libc",
+ "nix",
+ "parking_lot",
+ "portable-atomic",
+ "rand_core 0.6.4",
+ "ring",
+ "tracing",
+ "untrusted",
+ "x25519-dalek",
+]
+
[[package]]
name = "bstr"
version = "1.13.1"
@@ -386,6 +478,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "chacha20"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures 0.2.17",
+]
+
[[package]]
name = "chacha20"
version = "0.10.2"
@@ -397,6 +500,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "chacha20poly1305"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
+dependencies = [
+ "aead",
+ "chacha20 0.9.1",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -411,6 +527,17 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common 0.1.7",
+ "inout",
+ "zeroize",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -571,6 +698,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
+ "rand_core 0.6.4",
"typenum",
]
@@ -806,6 +934,36 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cua-mesh"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "boringtun",
+ "bytes",
+ "chacha20poly1305",
+ "futures-util",
+ "hex",
+ "hkdf",
+ "hmac",
+ "http",
+ "if-addrs",
+ "quinn",
+ "rand 0.9.5",
+ "rcgen",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-tungstenite",
+ "tracing",
+ "url",
+ "webpki-roots 1.0.9",
+]
+
[[package]]
name = "cua-proto"
version = "0.1.0"
@@ -868,6 +1026,7 @@ dependencies = [
"cua-hotspot",
"cua-icon-cache",
"cua-image",
+ "cua-mesh",
"cua-proto",
"cua-sandbox-core",
"cua-spaces-contract",
@@ -977,6 +1136,32 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "cyclops-sdk"
version = "0.1.0"
@@ -1126,6 +1311,20 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "der-parser"
+version = "10.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+dependencies = [
+ "asn1-rs",
+ "displaydoc",
+ "nom",
+ "num-bigint",
+ "num-traits",
+ "rusticata-macros",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1192,6 +1391,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer 0.10.4",
"crypto-common 0.1.7",
+ "subtle",
]
[[package]]
@@ -1274,6 +1474,12 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "filetime"
version = "0.2.29"
@@ -1585,6 +1791,24 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "http"
version = "1.5.0"
@@ -1893,6 +2117,16 @@ dependencies = [
"icu_properties",
]
+[[package]]
+name = "if-addrs"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b2eeee38fef3aa9b4cc5f1beea8a2444fc00e7377cafae396de3f5c2065e24"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -1953,6 +2187,37 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "ip_network"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"
+
+[[package]]
+name = "ip_network_table"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0"
+dependencies = [
+ "ip_network",
+ "ip_network_table-deps-treebitmap",
+]
+
+[[package]]
+name = "ip_network_table-deps-treebitmap"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -2314,6 +2579,18 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nom"
version = "7.1.3"
@@ -2333,12 +2610,31 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2391,6 +2687,15 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "oid-registry"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+dependencies = [
+ "asn1-rs",
+]
+
[[package]]
name = "olpc-cjson"
version = "0.1.4"
@@ -2408,6 +2713,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+[[package]]
+name = "opaque-debug"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
+
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -2483,6 +2794,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "pem"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
+dependencies = [
+ "base64 0.23.1",
+ "serde_core",
+]
+
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -2564,6 +2885,17 @@ dependencies = [
"miniz_oxide 0.8.9",
]
+[[package]]
+name = "poly1305"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
+dependencies = [
+ "cpufeatures 0.2.17",
+ "opaque-debug",
+ "universal-hash",
+]
+
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -2806,7 +3138,7 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
- "chacha20",
+ "chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
@@ -2864,6 +3196,20 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "rcgen"
+version = "0.14.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
+dependencies = [
+ "pem",
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "x509-parser",
+ "yasna",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -3055,6 +3401,15 @@ dependencies = [
"semver",
]
+[[package]]
+name = "rusticata-macros"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "rustix"
version = "1.1.5"
@@ -3605,6 +3960,17 @@ dependencies = [
"futures-core",
]
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -4274,6 +4640,16 @@ dependencies = [
"weedle2",
]
+[[package]]
+name = "universal-hash"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"
+dependencies = [
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
@@ -4627,6 +5003,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -4804,6 +5189,36 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
+[[package]]
+name = "x509-parser"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
+dependencies = [
+ "asn1-rs",
+ "data-encoding",
+ "der-parser",
+ "lazy_static",
+ "nom",
+ "oid-registry",
+ "ring",
+ "rusticata-macros",
+ "thiserror 2.0.20",
+ "time",
+]
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -4814,6 +5229,16 @@ dependencies = [
"rustix",
]
+[[package]]
+name = "yasna"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
+dependencies = [
+ "bit-vec",
+ "time",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
@@ -4834,7 +5259,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -4875,7 +5300,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
- "synstructure",
+ "synstructure 0.14.0",
]
[[package]]
@@ -4883,6 +5308,20 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
[[package]]
name = "zerotrie"