Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host,cloud): pair only phones of the computer's account
leepokaiead5ffcfb21b
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex 3e6e0486..8706cbdc 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1479,5 +1479,7 @@"It's in another account.": "Er ist in einem anderen Konto.","New devices ask for access with a 6-digit code.": "Neue Geräte fragen mit einem 6-stelligen Code nach Zugriff.","Keep it there": "Dort lassen",- "Move here": "Hierher verschieben"+ "Move here": "Hierher verschieben",+ "If the computer asks, check it shows {code}.": "Wenn der Computer fragt, prüfe, dass er {code} anzeigt.",+ "Connect to the internet to pair, so Codync can confirm your account.": "Verbinde dich mit dem Internet, damit Codync beim Koppeln dein Konto bestätigen kann."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 4ad8bfe2..f237e22c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1479,5 +1479,7 @@"It's in another account.": "Está en otra cuenta.","New devices ask for access with a 6-digit code.": "Los dispositivos nuevos piden acceso con un código de 6 dígitos.","Keep it there": "Dejarla ahí",- "Move here": "Mover aquí"+ "Move here": "Mover aquí",+ "If the computer asks, check it shows {code}.": "Si el ordenador lo pregunta, comprueba que muestra {code}.",+ "Connect to the internet to pair, so Codync can confirm your account.": "Conéctate a internet para vincular, así Codync puede confirmar tu cuenta."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 8d40baac..da6d86c8 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1479,5 +1479,7 @@"It's in another account.": "Il est dans un autre compte.","New devices ask for access with a 6-digit code.": "Les nouveaux appareils demandent l'accès avec un code à 6 chiffres.","Keep it there": "Le laisser là",- "Move here": "Déplacer ici"+ "Move here": "Déplacer ici",+ "If the computer asks, check it shows {code}.": "Si l'ordinateur le demande, vérifiez qu'il affiche {code}.",+ "Connect to the internet to pair, so Codync can confirm your account.": "Connectez-vous à Internet pour appairer, afin que Codync confirme votre compte."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 5adef211..f6a7732b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1479,5 +1479,7 @@"It's in another account.": "別のアカウントに入っています。","New devices ask for access with a 6-digit code.": "新しいデバイスは6桁のコードでアクセスをリクエストします。","Keep it there": "そのままにする",- "Move here": "ここに移動"+ "Move here": "ここに移動",+ "If the computer asks, check it shows {code}.": "コンピュータに確認を求められたら、{code} と表示されているか確かめてください。",+ "Connect to the internet to pair, so Codync can confirm your account.": "ペアリングするにはインターネットに接続してください。Codync がアカウントを確認します。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex d23f5b25..603dfcb3 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1479,5 +1479,7 @@"It's in another account.": "다른 계정에 있습니다.","New devices ask for access with a 6-digit code.": "새 기기는 6자리 코드로 접근을 요청합니다.","Keep it there": "그대로 두기",- "Move here": "여기로 옮기기"+ "Move here": "여기로 옮기기",+ "If the computer asks, check it shows {code}.": "컴퓨터가 물으면 {code}가 표시되는지 확인하세요.",+ "Connect to the internet to pair, so Codync can confirm your account.": "페어링하려면 인터넷에 연결하세요. Codync가 계정을 확인해야 합니다."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 4134a885..af0dbf92 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1479,5 +1479,7 @@"It's in another account.": "它在另一个账户里。","New devices ask for access with a 6-digit code.": "新设备要用 6 位验证码请求访问。","Keep it there": "留在原处",- "Move here": "移到这里"+ "Move here": "移到这里",+ "If the computer asks, check it shows {code}.": "如果电脑问你,确认它显示 {code}。",+ "Connect to the internet to pair, so Codync can confirm your account.": "请连上网络再配对,Codync 才能确认你的账户。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 6edae300..2e77a686 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1479,5 +1479,7 @@"It's in another account.": "它在另一個賬戶裡。","New devices ask for access with a 6-digit code.": "新裝置要用 6 位驗證碼請求訪問。","Keep it there": "留在原處",- "Move here": "移到這裡"+ "Move here": "移到這裡",+ "If the computer asks, check it shows {code}.": "如果電腦問你,確認它顯示 {code}。",+ "Connect to the internet to pair, so Codync can confirm your account.": "請連上網路再配對,Codync 才能確認你的賬戶。"}diff --git a/cloud/src/certificate.ts b/cloud/src/certificate.tsnew file mode 100644index 00000000..38fe4ab8--- /dev/null+++ b/cloud/src/certificate.ts@@ -0,0 +1,30 @@+// Device certificates: the cloud vouches that a device key belongs to an account, so a computer can+// check a pairing phone's account offline (docs/plans/require-sign-in.md, phase 2).++import { b64url, utf8 } from "./auth";++/** Long enough to pair at a computer with no network for a while; the phone fetches a new one before it runs out. */+export const CERT_TTL_MS = 7 * 24 * 60 * 60_000;+export const CERT_DOMAIN = "codync/device-cert/v1\n";++export interface CertificatePayload {+ v: 1;+ deviceKey: string;+ userId: string;+ email: string | null;+ exp: number;+}++let signer: Promise<CryptoKey> | undefined;+let signerSource: string | undefined;++/** Signs `payload` with `jwk` (an Ed25519 private key as JWK JSON, the `DEVICE_CERT_KEY` secret). */+export async function certify(jwk: string, payload: CertificatePayload): Promise<{ payload: string; sig: string }> {+ if (signerSource !== jwk) {+ signerSource = jwk;+ signer = crypto.subtle.importKey("jwk", JSON.parse(jwk), { name: "Ed25519" }, false, ["sign"]);+ }+ const text = JSON.stringify(payload);+ const sig = await crypto.subtle.sign({ name: "Ed25519" }, await signer!, utf8(CERT_DOMAIN + text));+ return { payload: text, sig: b64url(new Uint8Array(sig)) };+}diff --git a/cloud/src/index.ts b/cloud/src/index.tsindex 0ba2116c..eb78bd1f 100644--- a/cloud/src/index.ts+++ b/cloud/src/index.ts@@ -32,6 +32,8 @@ export interface Env {CLERK_JWT_KEY?: string;CLERK_AUTHORIZED_PARTIES?: string;CLERK_WEBHOOK_SECRET?: string;+ /** Ed25519 private key (JWK JSON) that signs device certificates; hosts compile in its public half. */+ DEVICE_CERT_KEY?: string;/** GitHub token (Actions: write) that wakes the release gate; unset outside production. */RELEASE_GATE_TOKEN?: string;}@@ -56,6 +58,7 @@ const routes: [string, RegExp, Handler][] = [["GET", /^\/v1\/me$/, api.me],["POST", /^\/v1\/devices$/, api.registerDevice],["GET", /^\/v1\/devices$/, api.listDevices],+ ["POST", /^\/v1\/devices\/certificate$/, api.deviceCertificate],["DELETE", new RegExp(`^/v1/devices/${ID}$`), api.revokeDevice],["POST", /^\/v1\/claims$/, api.createClaim],["POST", new RegExp(`^/v1/claims/${ID}/complete$`), api.completeClaim],diff --git a/cloud/src/routes/account.ts b/cloud/src/routes/account.tsindex 049864d4..35523d71 100644--- a/cloud/src/routes/account.ts+++ b/cloud/src/routes/account.ts@@ -1,6 +1,7 @@// Clerk-authenticated account routes: devices, claims, computers, access requests and grants.import { computerIdFor, fromB64url, randomId, utf8, verifyEd25519 } from "../auth";+import { CERT_TTL_MS, certify } from "../certificate";import {ApiError,audit,@@ -101,6 +102,25 @@ export async function listDevices(c: Ctx) {};}+/** A certificate that this (registered, unrevoked) device key is in the caller's account, for pairing in person. */+export async function deviceCertificate(c: Ctx) {+ const u = await user(c);+ const s = await signed(c);+ if (!c.env.DEVICE_CERT_KEY) throw new ApiError("notConfigured", "This cloud doesn't issue device certificates");+ const known = await c.env.DB.prepare("SELECT 1 FROM devices WHERE owner_user_id = ? AND sign_pub = ? AND revoked_at IS NULL")+ .bind(u.userId, s.kid)+ .first();+ if (!known) throw new ApiError("forbidden", "Register this device with the account first");+ const certificate = await certify(c.env.DEVICE_CERT_KEY, {+ v: 1,+ deviceKey: s.kid,+ userId: u.userId,+ email: u.email,+ exp: c.now + CERT_TTL_MS,+ });+ return { certificate };+}+export async function revokeDevice(c: Ctx, [deviceId]: string[]) {const u = await user(c);const d = await c.env.DB.prepare("SELECT id, revoked_at FROM devices WHERE id = ? AND owner_user_id = ?")diff --git a/cloud/src/routes/common.ts b/cloud/src/routes/common.tsindex df3a9ab3..ff0723e9 100644--- a/cloud/src/routes/common.ts+++ b/cloud/src/routes/common.ts@@ -31,6 +31,7 @@ const STATUS: Record<string, number> = {tooLarge: 413,rateLimited: 429,internal: 500,+ notConfigured: 503,};export class ApiError extends Error {diff --git a/cloud/test/api.test.ts b/cloud/test/api.test.tsindex 05b76cde..212fd191 100644--- a/cloud/test/api.test.ts+++ b/cloud/test/api.test.ts@@ -223,6 +223,22 @@ describe("devices", () => {expect(revoked.status).toBe(403);});+ it("certifies a registered device key for its account, and no other key", async () => {+ const u = await newUser();+ const r = await call("POST", "/v1/devices/certificate", { token: u.token, key: u.key });+ expect(r.status).toBe(200);+ const { payload, sig } = r.body.certificate as { payload: string; sig: string };+ const signed = ref.enc.encode(`codync/device-cert/v1\n${payload}`);+ expect(ref.verify(ref.unb64url(env.TEST_DEVICE_CERT_PUB), ref.unb64url(sig), signed)).toBe(true);+ const claims = JSON.parse(payload);+ expect(claims).toMatchObject({ v: 1, deviceKey: u.dk, userId: u.userId, email: `${u.userId}@example.com` });+ expect(claims.exp).toBeGreaterThan(Date.now() + 6 * 24 * 3600_000);+ // An unregistered key, and a revoked one, get nothing.+ expect((await call("POST", "/v1/devices/certificate", { token: u.token, key: ref.signKey() })).status).toBe(403);+ expect((await call("DELETE", `/v1/devices/${u.deviceId}`, { token: u.token })).status).toBe(200);+ expect((await call("POST", "/v1/devices/certificate", { token: u.token, key: u.key })).status).toBe(403);+ });+it("registers the desktop app on every platform, and no unknown one", async () => {const u = await newUser();for (const platform of ["macos", "linux", "windows"]) {diff --git a/cloud/test/helpers.ts b/cloud/test/helpers.tsindex 4dbd71f0..72db51cf 100644--- a/cloud/test/helpers.ts+++ b/cloud/test/helpers.ts@@ -8,6 +8,8 @@ import { aclMessage, b64url, boxKey, computerId, enc, signKey, signRequest, typeexport interface TestEnv extends Env {TEST_MIGRATIONS: D1Migration[];TEST_CLERK_PRIVATE_JWK: string;+ /** The device certificate key's public half, b64url. */+ TEST_DEVICE_CERT_PUB: string;}export const env = rawEnv as unknown as TestEnv;diff --git a/cloud/vitest.config.ts b/cloud/vitest.config.tsindex 02f0e260..b4c3399d 100644--- a/cloud/vitest.config.ts+++ b/cloud/vitest.config.ts@@ -5,6 +5,8 @@ import { defineConfig } from "vitest/config";// A throwaway Clerk signing key: the Worker verifies networklessly with the public half (CLERK_JWT_KEY),// the tests mint session tokens with the private half.const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });+// The device certificate key, as the DEVICE_CERT_KEY secret holds it; tests check signatures with the public half.+const cert = generateKeyPairSync("ed25519");export default defineConfig(async () => ({plugins: [@@ -19,6 +21,8 @@ export default defineConfig(async () => ({CLERK_JWT_KEY: publicKey.export({ type: "spki", format: "pem" }).toString(),TEST_CLERK_PRIVATE_JWK: JSON.stringify(privateKey.export({ format: "jwk" })),CLERK_WEBHOOK_SECRET: `whsec_${randomBytes(24).toString("base64")}`,+ DEVICE_CERT_KEY: JSON.stringify(cert.privateKey.export({ format: "jwk" })),+ TEST_DEVICE_CERT_PUB: cert.publicKey.export({ format: "jwk" }).x!,},},}),diff --git a/host/Cargo.lock b/host/Cargo.lockindex f602f18f..21148052 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -727,7 +727,7 @@ dependencies = [[[package]]name = "codync-host"-version = "2.34.2"+version = "2.36.0"dependencies = ["anyhow","axum",diff --git a/host/Cargo.toml b/host/Cargo.tomlindex 3832e80d..ca01cbb4 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -1,6 +1,6 @@[package]name = "codync-host"-version = "2.34.2"+version = "2.36.0"edition = "2024"# iroh (codync-network) needs 1.91.rust-version = "1.91"diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rsindex 1fa283d1..339d8673 100644--- a/host/src/analytics/observe/tests.rs+++ b/host/src/analytics/observe/tests.rs@@ -242,6 +242,7 @@ async fn store_lookups_add_fields_choice_and_platform() {lease_until: None,created_at: 0,last_seen_at: None,+ account: None,}).unwrap();let (event, p) = observe_call(&hub, &phone, "respondPermission", &answer).unwrap();diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 1932d842..90f8bb8d 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -63,6 +63,9 @@ const LOCAL_ONLY: &[&str] = &["revokeDevice","accessRequests","decideAccessRequest",+ // Letting a phone in that brings this computer into its account is decided at the computer.+ "pairingRequests",+ "decidePairing","cloudStatus","setCloud","setCloudUrl",diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex f6b9ef55..3ae439d8 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -15,6 +15,7 @@ mod remote;pub use events::{events_stream, term_events};pub use http::router;+pub(crate) use remote::claim_sign;use crate::api::devices::{Caller, Forbidden};use crate::hub::Hub;diff --git a/host/src/api/remote.rs b/host/src/api/remote.rsindex 77dcdf88..a87d1414 100644--- a/host/src/api/remote.rs+++ b/host/src/api/remote.rs@@ -89,6 +89,12 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuejson!({})}"accessRequests" => json!({"requests": hub.cloud.requests_json()}),+ "pairingRequests" => json!({"requests": hub.pairing_requests.json()}),+ "decidePairing" => {+ let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;+ crate::remote::pairing_requests::decide(hub, str_arg(&b, "requestId")?, approve)?;+ json!({})+ }"decideAccessRequest" => {let approve = b["approve"].as_bool().ok_or_else(|| anyhow!("`approve` is required"))?;let id = str_arg(&b, "requestId")?;@@ -150,7 +156,7 @@ async fn pairing(hub: &Arc<Hub>) -> Result<Value> {}/// Signs this computer into an account claim (§4.2 A) for the signed-in desktop app to complete.-async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {+pub(crate) async fn claim_sign(hub: &Arc<Hub>, b: &Value) -> Result<Value> {crate::remote::cloud::require_accounts(&hub.store)?;let field = |k: &str| -> Result<&str> {let v = str_arg(b, k)?;diff --git a/host/src/compat.rs b/host/src/compat.rsindex 4fc9edd5..5c9f1315 100644--- a/host/src/compat.rs+++ b/host/src/compat.rs@@ -8,7 +8,7 @@ use serde_json::Value;/// Raise it only when this host stops sending or accepting something older clients depend on;/// the release gate (tools/release-gate.py) then offers the release once the App Store has that/// iPhone app.-pub const MIN_APP: &str = "2.34.0";+pub const MIN_APP: &str = "2.36.0";/// The oldest host the terminal client works with.pub const MIN_HOST: &str = "2.20.1";diff --git a/host/src/environment.rs b/host/src/environment.rsindex 74bdb10f..4a2ee881 100644--- a/host/src/environment.rs+++ b/host/src/environment.rs@@ -77,6 +77,15 @@ impl Environment {}}+ /// The public half of the cloud's device certificate key (b64url Ed25519), `DEVICE_CERT_KEY` in `cloud/`.+ #[cfg_attr(test, expect(dead_code, reason = "tests sign certificates with a fixed key"))]+ pub const fn device_cert_key(self) -> &'static str {+ match self {+ Self::Main => "jhV6Zn1dssGFaqaQKAKtthx_YGia3RZfF7nQ9iRGif4",+ Self::Dev => "9ppxYC4IiF7d4FEKIxFr0AdUoI0IDOP5y6cZa-OC2YQ",+ }+ }+pub const fn url_scheme(self) -> &'static str {match self {Self::Main => "codync",diff --git a/host/src/hub.rs b/host/src/hub.rsindex 90c0e6ac..0c122d54 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -103,6 +103,8 @@ pub struct Hub {/// change so open channels re-check their device (and the ACL is republished).pub auth: watch::Sender<u64>,pub pairing: Mutex<Pairing>,+ /// Phones waiting for this computer to let them in and join their account.+ pub pairing_requests: crate::remote::pairing_requests::PairingRequests,/// Device key -> open channels that have exchanged at least one frame.pub connected: Mutex<HashMap<String, usize>>,/// The cloud's `/v1/host/state` was applied on the current relay connection;@@ -147,6 +149,7 @@ impl Hub {keep_awake: Mutex::default(),auth: watch::Sender::new(0),pairing: Mutex::default(),+ pairing_requests: crate::remote::pairing_requests::PairingRequests::default(),connected: Mutex::default(),cloud_synced: AtomicBool::new(false),cloud: crate::remote::cloud::Cloud::default(),diff --git a/host/src/main.rs b/host/src/main.rsindex 367ad574..2abf34d7 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -36,7 +36,7 @@ use remote::identity;use anyhow::{Context, Result};use clap::{Parser, Subcommand};-use serde_json::json;+use serde_json::{Value, json};use std::fmt::Write as _;use std::future::IntoFuture;use std::io::Read;@@ -609,9 +609,56 @@ async fn pair(port: u16, as_json: bool) -> Result<()> {"Tip: the phone reaches this computer on the same network only. Turn on the Codync cloud or Tailscale to reach it from anywhere.");}+ if std::io::IsTerminal::is_terminal(&std::io::stdin()) {+ answer_pairing(port, p["expiresAt"].as_i64().unwrap_or_default()).await?;+ }Ok(())}+/// A computer in no account asks before a phone brings it into its own account: answered here, in the terminal,+/// until the code is used or expires (docs/plans/require-sign-in.md, phase 2).+async fn answer_pairing(port: u16, expires_at: i64) -> Result<()> {+ let count = |v: &Value| v["devices"].as_array().map_or(0, Vec::len);+ let before = count(&local_call(port, "devices", json!({})).await?);+ println!("Waiting for the phone… (Ctrl-C to stop)");+ while store::now_ms() < expires_at {+ tokio::time::sleep(Duration::from_secs(1)).await;+ let requests = local_call(port, "pairingRequests", json!({})).await?;+ if let Some(r) = requests["requests"].as_array().and_then(|r| r.first()) {+ let email = r["email"].as_str().unwrap_or("a Codync account");+ println!(+ "+{} wants to use this computer. It joins {email}'s account.+Check the phone shows {}.",+ r["deviceName"].as_str().unwrap_or("A phone"),+ r["code"].as_str().unwrap_or_default()+ );+ let approve = ask_yes_no("Let it in? [y/N] ").await?;+ local_call(port, "decidePairing", json!({"requestId": r["requestId"], "approve": approve})).await?;+ println!("{}", if approve { "Paired. The computer is joining that account." } else { "Turned away." });+ return Ok(());+ }+ if count(&local_call(port, "devices", json!({})).await?) > before {+ println!("Paired.");+ return Ok(());+ }+ }+ println!("The code expired. Run codync-host pair again.");+ Ok(())+}++async fn ask_yes_no(prompt: &str) -> Result<bool> {+ use std::io::Write as _;+ print!("{prompt}");+ std::io::stdout().flush()?;+ let line = tokio::task::spawn_blocking(|| {+ let mut line = String::new();+ std::io::stdin().read_line(&mut line).map(|_| line)+ })+ .await??;+ Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))+}+async fn access(port: u16, action: AccessAction) -> Result<()> {let list = local_call(port, "accessRequests", json!({})).await?;let requests = list["requests"].as_array().cloned().unwrap_or_default();@@ -636,7 +683,7 @@ async fn access(port: u16, action: AccessAction) -> Result<()> {AccessAction::Deny { request } => (request, false),};// A 6-digit code picks the request showing it; it must be the only one.- let matching: Vec<&serde_json::Value> =+ let matching: Vec<&Value> =requests.iter().filter(|r| r["requestId"] == request.as_str() || r["code"] == request.as_str()).collect();let [r] = matching.as_slice() else {anyhow::bail!("No single request matches {request}. See `codync-host access list`.");@@ -687,7 +734,7 @@ async fn info(port: u16, as_json: bool) -> Result<()> {async fn statusline(port: u16, wrapped: String) {let mut input = String::new();let _ = std::io::stdin().read_to_string(&mut input);- let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();+ let v: Value = serde_json::from_str(&input).unwrap_or_default();if let Ok(token) = std::fs::read_to_string(service::data_dir().join("token")) {let _ = http().post(format!("http://127.0.0.1:{port}/ingest/statusline"))diff --git a/host/src/remote/certificate.rs b/host/src/remote/certificate.rsnew file mode 100644index 00000000..6000caa3--- /dev/null+++ b/host/src/remote/certificate.rs@@ -0,0 +1,136 @@+//! Device certificates (docs/plans/require-sign-in.md, phase 2): the Codync cloud vouches that a device key+//! is in an account. Checking one is a signature check with a key compiled in, so pairing in person works+//! with the cloud off, on a private relay, or with no network at all.++use super::crypto;+#[cfg(not(test))]+use crate::environment::Environment;+use serde::Deserialize;+use serde_json::Value;++/// Prefixed to the payload before signing, so the key signs nothing else by accident.+const DOMAIN: &str = "codync/device-cert/v1\n";++/// What a valid certificate says about the device that sent it.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Certified {+ pub user_id: String,+ pub email: Option<String>,+}++#[derive(Debug, PartialEq, Eq)]+pub enum Refusal {+ /// No certificate: an app older than this check.+ Missing,+ /// Not signed by the cloud, expired, or for another key.+ Invalid,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct Payload {+ v: u8,+ device_key: String,+ user_id: String,+ email: Option<String>,+ exp: i64,+}++/// The cloud's public key: this build's environment, or `CODYNC_DEVICE_CERT_KEY` for a self-hosted cloud.+#[cfg(not(test))]+fn cloud_key() -> Option<[u8; 32]> {+ let key =+ std::env::var("CODYNC_DEVICE_CERT_KEY").unwrap_or_else(|_| Environment::current().device_cert_key().into());+ crypto::unb64_n::<32>(&key).ok()+}++/// Tests sign certificates with [`TEST_CLOUD_SEED`].+#[cfg(test)]+#[expect(clippy::unnecessary_wraps, reason = "the same signature as the build's")]+fn cloud_key() -> Option<[u8; 32]> {+ Some(ed25519_dalek::SigningKey::from_bytes(&TEST_CLOUD_SEED).verifying_key().to_bytes())+}++#[cfg(test)]+pub const TEST_CLOUD_SEED: [u8; 32] = [9; 32];++/// A certificate as the cloud would sign it, for tests.+#[cfg(test)]+pub fn test_certificate(device_key: &str, user_id: &str) -> Value {+ let payload = serde_json::json!({"v": 1, "deviceKey": device_key, "userId": user_id,+ "email": format!("{user_id}@example.com"), "exp": crate::store::now_ms() + 60_000})+ .to_string();+ let key = ed25519_dalek::SigningKey::from_bytes(&TEST_CLOUD_SEED);+ let sig = crypto::sign(&key, format!("{DOMAIN}{payload}").as_bytes());+ serde_json::json!({"payload": payload, "sig": crypto::b64(&sig)})+}++/// Checks `certificate` (`{payload, sig}`) for the device whose channel key is `device_key`, at `now` (ms).+pub fn check(certificate: &Value, device_key: &str, now: i64) -> Result<Certified, Refusal> {+ if certificate.is_null() {+ return Err(Refusal::Missing);+ }+ check_with(cloud_key().ok_or(Refusal::Invalid)?, certificate, device_key, now)+}++fn check_with(key: [u8; 32], certificate: &Value, device_key: &str, now: i64) -> Result<Certified, Refusal> {+ let (Some(text), Some(sig)) = (certificate["payload"].as_str(), certificate["sig"].as_str()) else {+ return Err(Refusal::Invalid);+ };+ let sig = crypto::unb64_n::<64>(sig).map_err(|_| Refusal::Invalid)?;+ crypto::verify(&key, format!("{DOMAIN}{text}").as_bytes(), &sig).map_err(|_| Refusal::Invalid)?;+ let p: Payload = serde_json::from_str(text).map_err(|_| Refusal::Invalid)?;+ if p.v != 1 || p.device_key != device_key || p.exp <= now || p.user_id.is_empty() {+ return Err(Refusal::Invalid);+ }+ Ok(Certified { user_id: p.user_id, email: p.email.filter(|e| !e.is_empty()) })+}++/// `[email protected]` → `k•••@example.com`: enough to recognize your own account, not to read someone else's.+pub fn masked(email: &str) -> String {+ match email.split_once('@') {+ Some((name, domain)) => format!("{}•••@{domain}", name.chars().next().unwrap_or('•')),+ None => "•••".into(),+ }+}++#[cfg(test)]+mod tests {+ #![allow(clippy::unwrap_used)]+ use super::*;+ use ed25519_dalek::SigningKey;+ use serde_json::json;++ fn certificate(key: &SigningKey, device_key: &str, exp: i64) -> Value {+ let payload =+ json!({"v": 1, "deviceKey": device_key, "userId": "user_1", "email": "[email protected]", "exp": exp})+ .to_string();+ let sig = crypto::sign(key, format!("{DOMAIN}{payload}").as_bytes());+ json!({"payload": payload, "sig": crypto::b64(&sig)})+ }++ #[test]+ fn only_the_clouds_unexpired_certificate_for_this_key_passes() {+ let cloud = SigningKey::from_bytes(&[7; 32]);+ let key = cloud.verifying_key().to_bytes();+ let good = certificate(&cloud, "dk", 2_000);+ assert_eq!(+ check_with(key, &good, "dk", 1_000),+ Ok(Certified { user_id: "user_1".into(), email: Some("[email protected]".into()) })+ );+ assert_eq!(check_with(key, &good, "other", 1_000), Err(Refusal::Invalid), "another device's");+ assert_eq!(check_with(key, &good, "dk", 2_000), Err(Refusal::Invalid), "expired");+ let forged = certificate(&SigningKey::from_bytes(&[8; 32]), "dk", 2_000);+ assert_eq!(check_with(key, &forged, "dk", 1_000), Err(Refusal::Invalid), "not the cloud's key");+ let mut edited = good.clone();+ edited["payload"] = good["payload"].as_str().unwrap().replace("user_1", "user_2").into();+ assert_eq!(check_with(key, &edited, "dk", 1_000), Err(Refusal::Invalid), "changed after signing");+ assert_eq!(check(&Value::Null, "dk", 1_000), Err(Refusal::Missing));+ }++ #[test]+ fn emails_are_masked() {+ assert_eq!(masked("[email protected]"), "k•••@example.com");+ assert_eq!(masked("nope"), "•••");+ }+}diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rsindex 46590249..bd1ddd29 100644--- a/host/src/remote/channel.rs+++ b/host/src/remote/channel.rs@@ -8,6 +8,7 @@//! The device's authorization is re-checked on every request, whenever the device//! table changes and when its lease runs out; a revoked device is closed at once.+mod pairing;mod subscriptions;use crate::LockExt;@@ -503,79 +504,27 @@ impl Channel {self.send(json!({"id": id, "end": true})).await;}}-- /// A pairing channel: exactly one `pair`, answered, then closed with `4100` (§4.1).- async fn pair(&mut self, incoming: &mut mpsc::Receiver<Value>, mut opener: Opener, source: &str) -> CloseWith {- let protocol = (close::PROTOCOL, "protocolError");- let deadline = Instant::now() + PAIRING_MAX_AGE;- let bytes = loop {- let msg = tokio::select! {- msg = incoming.recv() => msg,- () = sleep_until(deadline) => return (close::PAIRING_EXPIRED, "pairingExpired"),- };- let Some(msg) = msg else { return (close::NORMAL, "") };- match opener.open(&msg) {- Ok(Some(bytes)) => break bytes,- Ok(None) => {}- Err(e) => return frame_close(&e),- }- };- let Ok(v) = serde_json::from_slice::<Value>(&bytes) else { return protocol };- let Some(id) = v["id"].as_u64() else { return protocol };- if v["m"] != "pair" {- return protocol;- }- let b = &v["b"];- let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100);- let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"));- let (Some(name), Some(platform)) = (name, platform) else {- self.send(err(id, 400, "`name` and `platform` (ios, macos or android) are required")).await;- return protocol;- };- if !self.hub.pairing.locked().attempt(source) {- let code = RejectCode::RateLimited;- let _ =- self.tx.send(ToDevice::Plain(json!({"t": "reject", "code": code, "message": code.message()}))).await;- return (code.close_code(), "rateLimited");- }- if !self.hub.pairing.locked().redeem(b["code"].as_str().unwrap_or_default()) {- self.send(err(id, 403, "This pairing code expired. Show a new one on the computer.")).await;- return (close::UNAUTHORIZED, "unauthorized");- }- let device = Device {- key: self.key.clone(),- name: name.to_owned(),- platform: platform.to_owned(),- source: DeviceSource::Local,- grant_id: None,- scopes: vec![Scope::Control, Scope::Screen],- lease_until: None,- created_at: now_ms(),- last_seen_at: None,- };- if let Err(e) = self.hub.store.put_device(&device) {- tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");- self.send(err(id, 500, "couldn't save this device")).await;- return (close::NORMAL, "");- }- tracing::info!(device = self.key, platform, "device paired");- crate::analytics::device_paired(&self.hub, crate::analytics::Via::Qr, platform, false);- let name = crate::service::host_name();- self.send(json!({"id": id, "ok": {"computerId": self.hub.identity.computer_id(), "name": name}})).await;- (close::PAIRED, "paired")- }}#[cfg(test)]mod tests {#![allow(clippy::unwrap_used, clippy::expect_used)]+ mod accounts;mod screen_signaling;use super::*;use crate::remote::identity::Identity;use crate::store::Store;use ed25519_dalek::SigningKey;+ /// A computer in `user_1`'s account, so phones of that account pair without asking.fn temp_hub() -> Arc<Hub> {+ let hub = unowned_hub();+ let owner = crate::remote::cloud::Owner { user_id: "user_1".into(), email: Some("[email protected]".into()) };+ crate::remote::owner::remember(&hub, Some(&owner)).unwrap();+ hub+ }++ fn unowned_hub() -> Arc<Hub> {let dir = std::env::temp_dir().join(format!("codync-ch-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();let store = Store::open(&dir.join("t.db")).unwrap();@@ -583,6 +532,12 @@ mod tests {Hub::new(store, "host".into(), identity, "token".into(), 0)}+ /// A `pair` body for `p`, signed in to `user`.+ fn pair_body(p: &Phone, code: &str, name: &str, platform: &str, user: &str) -> Value {+ json!({"code": code, "name": name, "platform": platform,+ "certificate": crate::remote::certificate::test_certificate(&p.dk(), user)})+ }+/// The device end of a channel, over in-memory pipes.struct Phone {key: SigningKey,@@ -684,7 +639,7 @@ mod tests {let code = hub.pairing.locked().issue().code;let mut p = Phone::direct(hub, key.clone());assert!(matches!(p.hello(hub, true).await, Out::Msg(v) if v["t"] == "welcome"));- p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Kevin's iPhone", "platform": "ios"}})).await;+ p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "Kevin's iPhone", "ios", "user_1")})).await;let reply = p.recv().await.unwrap();assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());assert_eq!(p.recv().await.unwrap_err().0, close::PAIRED);@@ -698,7 +653,7 @@ mod tests {let code = hub.pairing.locked().issue().code;let mut phone = Phone::direct(&hub, key.clone());assert!(matches!(phone.hello(&hub, true).await, Out::Msg(v) if v["t"] == "welcome"));- let reply = phone.call(1, "pair", json!({"code": code, "name": "Android phone", "platform": "android"})).await;+ let reply = phone.call(1, "pair", pair_body(&phone, &code, "Android phone", "android", "user_1")).await;assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());assert_eq!(phone.recv().await.unwrap_err().0, close::PAIRED);let device = hub.store.device(&phone.dk()).unwrap();@@ -789,12 +744,12 @@ mod tests {let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));p.hello(&hub, true).await;- p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "A", "platform": "ios"}})).await;+ p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "A", "ios", "user_1")})).await;assert!(p.recv().await.unwrap()["ok"].is_object());let mut p = Phone::direct(&hub, SigningKey::from_bytes(&crypto::random()));p.hello(&hub, true).await;- p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "B", "platform": "ios"}})).await;+ p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "B", "ios", "user_1")})).await;assert_eq!(p.recv().await.unwrap()["err"]["status"], 403, "a used code doesn't work twice");assert_eq!(p.recv().await.unwrap_err().0, close::UNAUTHORIZED);}@@ -860,6 +815,7 @@ mod tests {lease_until: Some(now_ms() + 300),created_at: now_ms(),last_seen_at: None,+ account: None,};hub.store.put_device(&device).unwrap();let mut p = Phone::direct(&hub, key.clone());@@ -927,7 +883,7 @@ mod tests {auth.mark_unchanged();let mut p = Phone::connect(&hub, key, ChannelKind::Relay { link: "p".into(), dk, pair: true });p.hello(&hub, true).await;- p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "A", "platform": "ios"}})).await;+ p.send(json!({"id": 1, "m": "pair", "b": pair_body(&p, &code, "A", "ios", "user_1")})).await;auth.changed().await.unwrap();// The relay republishes the ACL on this change: the answer and 4100 must already be queued.let mut last = None;diff --git a/host/src/remote/channel/pairing.rs b/host/src/remote/channel/pairing.rsnew file mode 100644index 00000000..2c1cef81--- /dev/null+++ b/host/src/remote/channel/pairing.rs@@ -0,0 +1,125 @@+//! The pairing channel (§4.1): one `pair`, answered, then closed with `4100`. The phone proves its account with a+//! certificate from the cloud (docs/plans/require-sign-in.md, phase 2): a computer in an account lets in phones of+//! that account only; one in no account asks first, then joins the phone's account.++use super::*;+use crate::remote::certificate::{self, Refusal};+use crate::remote::{owner, pairing_requests};++impl Channel {+ pub(super) async fn pair(+ &mut self,+ incoming: &mut mpsc::Receiver<Value>,+ mut opener: Opener,+ source: &str,+ ) -> CloseWith {+ let protocol = (close::PROTOCOL, "protocolError");+ let deadline = Instant::now() + PAIRING_MAX_AGE;+ let bytes = loop {+ let msg = tokio::select! {+ msg = incoming.recv() => msg,+ () = sleep_until(deadline) => return (close::PAIRING_EXPIRED, "pairingExpired"),+ };+ let Some(msg) = msg else { return (close::NORMAL, "") };+ match opener.open(&msg) {+ Ok(Some(bytes)) => break bytes,+ Ok(None) => {}+ Err(e) => return frame_close(&e),+ }+ };+ let Ok(v) = serde_json::from_slice::<Value>(&bytes) else { return protocol };+ let Some(id) = v["id"].as_u64() else { return protocol };+ if v["m"] != "pair" {+ return protocol;+ }+ let b = &v["b"];+ let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100);+ let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"));+ let (Some(name), Some(platform)) = (name, platform) else {+ self.send(err(id, 400, "`name` and `platform` (ios, macos or android) are required")).await;+ return protocol;+ };+ if !self.hub.pairing.locked().attempt(source) {+ return self.reject(RejectCode::RateLimited).await;+ }+ // The code is spent only on a phone that may come in, so a phone of the wrong account doesn't use it up.+ let account = match certificate::check(&b["certificate"], &self.key, now_ms()) {+ Ok(account) => account,+ Err(Refusal::Missing) => return self.reject(RejectCode::UnsupportedVersion).await,+ Err(Refusal::Invalid) => {+ self.send(err(id, 403, "Couldn't confirm your Codync account. Sign in again, then scan a new code."))+ .await;+ return (close::UNAUTHORIZED, "unauthorized");+ }+ };+ let owner = owner::owner(&self.hub.store);+ if let Some(owner) = owner.as_ref().filter(|o| o.user_id != account.user_id) {+ let whose =+ owner.email.as_deref().map_or_else(|| "another".into(), |e| format!("{}'s", certificate::masked(e)));+ let message = format!(+ "This computer is in {whose} account. Move it to your account in Codync on that computer, or sign in with that account."+ );+ self.send(err(id, 403, &message)).await;+ return (close::UNAUTHORIZED, "otherAccount");+ }+ if !self.hub.pairing.locked().redeem(b["code"].as_str().unwrap_or_default()) {+ self.send(err(id, 403, "This pairing code expired. Show a new one on the computer.")).await;+ return (close::UNAUTHORIZED, "unauthorized");+ }+ if owner.is_none() {+ let Ok(device_key) = crypto::unb64_n::<32>(&self.key) else { return protocol };+ let code = pairing_requests::check_code(&device_key, &self.hub.identity.sign_pub());+ if !pairing_requests::ask(&self.hub, name, platform, account.email.as_deref(), code).await {+ self.send(err(id, 403, "The computer didn't let this phone in.")).await;+ return (close::UNAUTHORIZED, "declined");+ }+ }+ let device = Device {+ key: self.key.clone(),+ name: name.to_owned(),+ platform: platform.to_owned(),+ source: DeviceSource::Local,+ grant_id: None,+ scopes: vec![Scope::Control, Scope::Screen],+ lease_until: None,+ created_at: now_ms(),+ last_seen_at: None,+ account: Some(account.user_id.clone()),+ };+ if let Err(e) = self.hub.store.put_device(&device) {+ tracing::error!(error = format!("{e:#}"), "couldn't save a paired device");+ self.send(err(id, 500, "couldn't save this device")).await;+ return (close::NORMAL, "");+ }+ tracing::info!(device = self.key, platform, "device paired");+ crate::analytics::device_paired(&self.hub, crate::analytics::Via::Qr, platform, false);+ let mut ok = json!({"computerId": self.hub.identity.computer_id(), "name": crate::service::host_name()});+ if owner.is_none() {+ // Joining the phone's account: the computer signs the claim the phone made; the phone, which holds+ // the account's session, completes it with the cloud.+ ok["claim"] = self.claim(&b["claim"], &account.user_id).await;+ }+ self.send(json!({"id": id, "ok": ok})).await;+ (close::PAIRED, "paired")+ }++ /// The signed claim for `{claimId, nonce}`, or null without one or with no Codync accounts here.+ async fn claim(&self, claim: &Value, user_id: &str) -> Value {+ if claim.is_null() {+ return Value::Null;+ }+ let request = json!({"claimId": claim["claimId"], "nonce": claim["nonce"], "userId": user_id});+ match api::claim_sign(&self.hub, &request).await {+ Ok(signed) => signed,+ Err(e) => {+ tracing::info!(error = format!("{e:#}"), "paired without joining the account");+ Value::Null+ }+ }+ }++ async fn reject(&self, code: RejectCode) -> CloseWith {+ let _ = self.tx.send(ToDevice::Plain(json!({"t": "reject", "code": code, "message": code.message()}))).await;+ (code.close_code(), if code == RejectCode::RateLimited { "rateLimited" } else { "rejected" })+ }+}diff --git a/host/src/remote/channel/tests/accounts.rs b/host/src/remote/channel/tests/accounts.rsnew file mode 100644index 00000000..56a6c31c--- /dev/null+++ b/host/src/remote/channel/tests/accounts.rs@@ -0,0 +1,73 @@+//! Pairing proves the phone's account (docs/plans/require-sign-in.md, phase 2).++use super::*;++async fn pairing_phone(hub: &Arc<Hub>) -> (Phone, String) {+ let code = hub.pairing.locked().issue().code;+ let mut p = Phone::direct(hub, SigningKey::from_bytes(&crypto::random()));+ assert!(matches!(p.hello(hub, true).await, Out::Msg(v) if v["t"] == "welcome"));+ (p, code)+}++#[tokio::test]+async fn an_app_without_a_certificate_is_told_to_update_and_the_code_stays() {+ let hub = temp_hub();+ let (mut p, code) = pairing_phone(&hub).await;+ p.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Old app", "platform": "ios"}})).await;+ let (close, reject) = p.recv().await.unwrap_err();+ assert_eq!((close, reject["code"].as_str()), (4400, Some("unsupportedVersion")));+ assert!(hub.pairing.locked().open(), "the code isn't used up");+}++#[tokio::test]+async fn a_phone_of_another_account_is_refused_with_the_owner_masked() {+ let hub = temp_hub();+ let (mut p, code) = pairing_phone(&hub).await;+ let body = pair_body(&p, &code, "Pixel", "android", "user_2");+ let reply = p.call(1, "pair", body).await;+ assert_eq!(reply["err"]["status"], 403);+ let message = reply["err"]["message"].as_str().unwrap();+ assert!(message.contains("k•••@example.com's account") && !message.contains("kevin"), "{message}");+ assert!(hub.store.device(&p.dk()).is_none());+ assert!(hub.pairing.locked().open(), "the code isn't used up");++ let (mut p, code) = pairing_phone(&hub).await;+ let mut forged = pair_body(&p, &code, "Pixel", "android", "user_1");+ forged["certificate"] = crate::remote::certificate::test_certificate("someone-else", "user_1");+ assert_eq!(p.call(1, "pair", forged).await["err"]["status"], 403, "a certificate for another key");+}++#[tokio::test]+async fn a_computer_in_no_account_asks_then_joins_the_phones() {+ let hub = unowned_hub();+ for approve in [false, true] {+ let (mut p, code) = pairing_phone(&hub).await;+ let mut body = pair_body(&p, &code, "Pixel", "android", "user_2");+ body["claim"] = json!({"claimId": "clm_1", "nonce": "n1"});+ p.send(json!({"id": 1, "m": "pair", "b": body})).await;+ while hub.pairing_requests.json().is_empty() {+ tokio::task::yield_now().await;+ }+ let request = hub.pairing_requests.json()[0].clone();+ assert_eq!(request["email"], "[email protected]");+ let device_key = crypto::unb64_n::<32>(&p.dk()).unwrap();+ let expected = crate::remote::pairing_requests::check_code(&device_key, &hub.identity.sign_pub());+ assert_eq!(request["code"], expected.as_str(), "the code the phone shows too");+ crate::remote::pairing_requests::decide(&hub, request["requestId"].as_str().unwrap(), approve).unwrap();+ let reply = p.recv().await.unwrap();+ if approve {+ assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());+ assert_eq!(hub.store.device(&p.dk()).unwrap().account.as_deref(), Some("user_2"));+ // Codync accounts are on by default here, so the computer signs the phone's claim.+ let claim = &reply["ok"]["claim"];+ assert_eq!(claim["computerId"], hub.identity.computer_id());+ let input =+ crypto::claim_input("clm_1", "n1", "user_2", &hub.identity.computer_id(), &hub.identity.box_pub_b64());+ let sig = crypto::unb64_n::<64>(claim["sig"].as_str().unwrap()).unwrap();+ crypto::verify(&hub.identity.sign_pub(), input.as_bytes(), &sig).unwrap();+ } else {+ assert_eq!(reply["err"]["status"], 403);+ assert!(hub.store.device(&p.dk()).is_none());+ }+ }+}diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rsindex d31d3f97..aca03ef5 100644--- a/host/src/remote/cloud.rs+++ b/host/src/remote/cloud.rs@@ -332,6 +332,7 @@ pub async fn pull(hub: &Hub, base: &str) -> Result<()> {let state: State = serde_json::from_value(call(hub, base, Method::GET, "/v1/host/state", None).await?).context("reading the cloud state")?;apply_grants(hub, &state.grants)?;+ super::owner::remember(hub, state.owner.as_ref())?;let in_account = state.owner.is_some();// A pull that works also settles an earlier failed one.update_status(hub, |s| {@@ -562,6 +563,8 @@ pub async fn decide(hub: &Hub, id: &str, approve: bool, how: Approval) -> Resultlease_until: Some(now_ms() + LEASE_MS),created_at: now_ms(),last_seen_at: None,+ // Approved through the account the computer is in.+ account: super::owner::owner(&hub.store).map(|o| o.user_id),};hub.store.put_device(&device)?;tracing::info!(grant_id = grant, "account device approved");@@ -659,6 +662,7 @@ mod tests {lease_until: Some(now_ms() + 1000),created_at: now_ms(),last_seen_at: None,+ account: None,}}diff --git a/host/src/remote/mod.rs b/host/src/remote/mod.rsindex 23ea3b7e..bb3aa8c9 100644--- a/host/src/remote/mod.rs+++ b/host/src/remote/mod.rs@@ -1,10 +1,13 @@//! Reaching this computer from other devices: identity keys, wire crypto, the//! E2E channel, the Codync cloud and its relay socket, and push.+pub mod certificate;pub mod channel;pub mod cloud;mod cloud_url;pub mod crypto;pub mod identity;+pub mod owner;+pub mod pairing_requests;pub mod push;pub mod relay;diff --git a/host/src/remote/owner.rs b/host/src/remote/owner.rsnew file mode 100644index 00000000..5ee2c45a--- /dev/null+++ b/host/src/remote/owner.rs@@ -0,0 +1,105 @@+//! The account this computer belongs to, kept on the computer: pairing checks a phone's account against it+//! even with the cloud unreachable, and a change of account drops the old account's devices+//! (docs/architecture/connections.md: "the host changed its account").++use super::cloud::Owner;+use crate::hub::Hub;+use crate::store::Store;+use anyhow::Result;++const OWNER: &str = "account_owner";++/// The account as last seen from the cloud; `None` when the computer isn't in one (or never heard yet).+pub fn owner(store: &Store) -> Option<Owner> {+ store.kv_get(OWNER).and_then(|v| serde_json::from_str::<Option<Owner>>(&v).ok()).flatten()+}++/// Records the account the cloud reports. When it is another one than before (joining one, moving, or leaving),+/// every device let in for another account goes. The first record after an upgrade only records.+pub fn remember(hub: &Hub, now: Option<&Owner>) -> Result<()> {+ let saved = serde_json::to_string(&now)?;+ let before = hub.store.kv_get(OWNER);+ if before.as_deref() == Some(saved.as_str()) {+ return Ok(());+ }+ hub.store.kv_set(OWNER, &saved)?;+ let Some(before) = before else { return Ok(()) };+ let before = serde_json::from_str::<Option<Owner>>(&before).ok().flatten().map(|o| o.user_id);+ let now = now.map(|o| o.user_id.as_str());+ if before.as_deref() != now {+ let gone = hub.store.keep_devices_of(now)?;+ tracing::info!(devices = gone.len(), "the computer changed its account; the old account's devices are gone");+ if !gone.is_empty() {+ hub.auth_changed();+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ #![allow(clippy::unwrap_used)]+ use super::*;+ use crate::remote::identity::Identity;+ use crate::store::{Device, DeviceSource, Scope};+ use std::sync::Arc;++ fn hub() -> Arc<Hub> {+ let dir = std::env::temp_dir().join(format!("codync-owner-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ Hub::new(+ Store::open(&dir.join("t.db")).unwrap(),+ "host".into(),+ Identity::load_or_create(&dir).unwrap(),+ "t".into(),+ 0,+ )+ }++ fn device(hub: &Hub, key: &str, account: Option<&str>) {+ hub.store+ .put_device(&Device {+ key: key.into(),+ name: "Phone".into(),+ platform: "ios".into(),+ source: DeviceSource::Local,+ grant_id: None,+ scopes: vec![Scope::Control],+ lease_until: None,+ created_at: 1,+ last_seen_at: None,+ account: account.map(Into::into),+ })+ .unwrap();+ }++ fn keys(hub: &Hub) -> Vec<String> {+ hub.store.devices().unwrap().into_iter().map(|d| d.key).collect()+ }++ fn account(id: &str) -> Owner {+ Owner { user_id: id.into(), email: Some(format!("{id}@example.com")) }+ }++ #[test]+ fn changing_accounts_drops_the_old_accounts_devices() {+ let hub = hub();+ device(&hub, "a", Some("user_a"));+ device(&hub, "b", Some("user_b"));+ device(&hub, "legacy", None);+ // An upgraded computer records what it finds and drops nothing.+ remember(&hub, Some(&account("user_a"))).unwrap();+ assert_eq!(keys(&hub), ["a", "b", "legacy"]);+ assert_eq!(owner(&hub.store).unwrap().user_id, "user_a");+ // The same account again (a new email included) changes nothing.+ remember(&hub, Some(&Owner { user_id: "user_a".into(), email: None })).unwrap();+ assert_eq!(keys(&hub), ["a", "b", "legacy"]);+ // Moving to B keeps only B's devices.+ remember(&hub, Some(&account("user_b"))).unwrap();+ assert_eq!(keys(&hub), ["b"]);+ // Leaving the account drops the rest.+ remember(&hub, None).unwrap();+ assert!(keys(&hub).is_empty(), "leaving drops every device");+ assert!(owner(&hub.store).is_none());+ }+}diff --git a/host/src/remote/pairing_requests.rs b/host/src/remote/pairing_requests.rsnew file mode 100644index 00000000..7c30c99e--- /dev/null+++ b/host/src/remote/pairing_requests.rs@@ -0,0 +1,133 @@+//! A signed-in phone scanning a computer that isn't in an account (docs/plans/require-sign-in.md, phase 2):+//! the computer confirms in the desktop app, the terminal UI or `codync-host pair` before the phone gets in+//! and the computer joins the phone's account. Both screens show the same 6-digit code.++use crate::LockExt;+use crate::hub::Hub;+use crate::remote::crypto;+use crate::store::now_ms;+use anyhow::{Result, anyhow};+use serde_json::{Value, json};+use std::sync::Mutex;+use std::time::Duration;+use tokio::sync::oneshot;++/// How long the computer has to answer; the phone waits as long.+pub const ASK_FOR: Duration = Duration::from_mins(2);++struct Pending {+ id: String,+ device_name: String,+ platform: String,+ email: Option<String>,+ code: String,+ expires_at: i64,+ answer: Option<oneshot::Sender<bool>>,+}++/// The phones waiting for this computer's answer (memory only: a restart declines them).+#[derive(Default)]+pub struct PairingRequests(Mutex<Vec<Pending>>);++impl PairingRequests {+ pub fn json(&self) -> Vec<Value> {+ self.0+ .locked()+ .iter()+ .map(|p| {+ json!({"requestId": p.id, "deviceName": p.device_name, "platform": p.platform,+ "email": p.email, "code": p.code, "expiresAt": p.expires_at})+ })+ .collect()+ }+}++/// The code a phone and this computer both show: the phone's key and the computer's, hashed. A phone that+/// isn't the one in the user's hand shows another code.+pub fn check_code(device_key: &[u8; 32], host_sign_key: &[u8; 32]) -> String {+ let h = crypto::sha256(&[b"codync/pair-check/v1", device_key, host_sign_key]);+ format!("{:06}", u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000)+}++/// Asks this computer whether the phone may in and bring it into `email`'s account; false when it says no+/// or nobody answers in time.+pub async fn ask(hub: &Hub, device_name: &str, platform: &str, email: Option<&str>, code: String) -> bool {+ let (tx, rx) = oneshot::channel();+ let id = uuid::Uuid::new_v4().to_string();+ hub.pairing_requests.0.locked().push(Pending {+ id: id.clone(),+ device_name: device_name.to_owned(),+ platform: platform.to_owned(),+ email: email.map(str::to_owned),+ code,+ expires_at: now_ms() + i64::try_from(ASK_FOR.as_millis()).unwrap_or(i64::MAX),+ answer: Some(tx),+ });+ emit(hub);+ let answer = tokio::time::timeout(ASK_FOR, rx).await;+ hub.pairing_requests.0.locked().retain(|p| p.id != id);+ emit(hub);+ matches!(answer, Ok(Ok(true)))+}++/// `decidePairing`: this computer's answer to one request.+pub fn decide(hub: &Hub, id: &str, approve: bool) -> Result<()> {+ let answer = hub+ .pairing_requests+ .0+ .locked()+ .iter_mut()+ .find(|p| p.id == id)+ .and_then(|p| p.answer.take())+ .ok_or_else(|| anyhow!("That request is gone. Scan the code again on the phone."))?;+ let _ = answer.send(approve);+ Ok(())+}++fn emit(hub: &Hub) {+ let _ = hub.events.send(json!({"type": "pairingRequests", "requests": hub.pairing_requests.json()}));+}++#[cfg(test)]+mod tests {+ #![allow(clippy::unwrap_used)]+ use super::*;+ use crate::remote::identity::Identity;+ use crate::store::Store;+ use std::sync::Arc;++ /// The vector the phones check against (apps/ios, apps/android).+ #[test]+ fn check_code_vector() {+ assert_eq!(check_code(&[1; 32], &[2; 32]), "855066");+ assert_ne!(check_code(&[1; 32], &[2; 32]), check_code(&[3; 32], &[2; 32]));+ }++ #[tokio::test]+ async fn the_computer_answers() {+ let dir = std::env::temp_dir().join(format!("codync-pr-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let hub = Hub::new(+ Store::open(&dir.join("t.db")).unwrap(),+ "h".into(),+ Identity::load_or_create(&dir).unwrap(),+ "t".into(),+ 0,+ );+ for approve in [true, false] {+ let asking = tokio::spawn({+ let hub = Arc::clone(&hub);+ async move { ask(&hub, "Pixel", "android", Some("[email protected]"), "123456".into()).await }+ });+ while hub.pairing_requests.json().is_empty() {+ tokio::task::yield_now().await;+ }+ let request = hub.pairing_requests.json()[0].clone();+ assert_eq!((request["deviceName"].as_str(), request["code"].as_str()), (Some("Pixel"), Some("123456")));+ decide(&hub, request["requestId"].as_str().unwrap(), approve).unwrap();+ assert_eq!(asking.await.unwrap(), approve);+ assert!(hub.pairing_requests.json().is_empty(), "answered requests go");+ }+ assert!(decide(&hub, "gone", true).is_err());+ }+}diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rsindex 1ccdb67a..94cd50a8 100644--- a/host/src/remote/relay.rs+++ b/host/src/remote/relay.rs@@ -721,6 +721,7 @@ mod tests {lease_until: None,created_at: now_ms(),last_seen_at: None,+ account: None,}).unwrap();let injected = b64(grant_key.verifying_key().as_bytes());@@ -859,6 +860,7 @@ mod tests {lease_until: Some(now_ms() + 60_000),created_at: now_ms(),last_seen_at: None,+ account: None,}).unwrap();*fake.state.lock().unwrap() =@@ -905,6 +907,7 @@ mod tests {lease_until: Some(now_ms() + 60_000),created_at: now_ms(),last_seen_at: None,+ account: None,}).unwrap();*fake.state.lock().unwrap() = json!({"owner": null, "grants": [], "requests": []});diff --git a/host/src/store/devices.rs b/host/src/store/devices.rsindex 8509ee8c..235a79d6 100644--- a/host/src/store/devices.rs+++ b/host/src/store/devices.rs@@ -39,6 +39,9 @@ pub struct Device {pub lease_until: Option<i64>,pub created_at: i64,pub last_seen_at: Option<i64>,+ /// The account this device was let in for (a Clerk user ID); none for devices paired before 2.36.0.+ #[serde(skip)]+ pub account: Option<String>,}/// A push ticket with the device's push key (§6.7) and account context.@@ -48,7 +51,8 @@ pub struct PushTicket {pub ctx: Option<String>,}-const DEVICE_COLS: &str = "key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at";+const DEVICE_COLS: &str =+ "key, name, platform, source, grant_id, scopes, lease_until, created_at, last_seen_at, account";fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {let source: String = r.get(3)?;@@ -65,6 +69,7 @@ fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {lease_until: r.get(6)?,created_at: r.get(7)?,last_seen_at: r.get(8)?,+ account: r.get(9)?,})}@@ -85,10 +90,10 @@ impl Store {pub fn put_device(&self, d: &Device) -> Result<()> {let c = self.db.locked();c.execute(- "INSERT INTO devices(key, name, platform, source, grant_id, scopes, lease_until, created_at)- VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)+ "INSERT INTO devices(key, name, platform, source, grant_id, scopes, lease_until, created_at, account)+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)ON CONFLICT(key) DO UPDATE SET name = ?2, platform = ?3, source = ?4, grant_id = ?5,- scopes = ?6, lease_until = ?7",+ scopes = ?6, lease_until = ?7, account = ?9",params![d.key,d.name,@@ -97,7 +102,8 @@ impl Store {d.grant_id,serde_json::to_string(&d.scopes)?,d.lease_until,- d.created_at+ d.created_at,+ d.account],)?;Ok(())@@ -114,6 +120,25 @@ impl Store {Ok(n > 0)}+ /// The computer changed the account it belongs to: every device let in for another account (or for none,+ /// before devices recorded theirs) goes, with its tickets. `None`: it left its account, and all go.+ /// Returns the removed keys.+ pub fn keep_devices_of(&self, account: Option<&str>) -> Result<Vec<String>> {+ let mut c = self.db.locked();+ let tx = c.transaction()?;+ let gone: Vec<String> = {+ let mut st = tx.prepare("SELECT key FROM devices WHERE account IS NULL OR account IS NOT ?1")?;+ st.query_map([account], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?+ };+ for key in &gone {+ tx.execute("DELETE FROM devices WHERE key = ?1", [key])?;+ tx.execute("DELETE FROM push_tickets WHERE device_key = ?1", [key])?;+ tx.execute("DELETE FROM activity_tickets WHERE device_key = ?1", [key])?;+ }+ tx.commit()?;+ Ok(gone)+ }+/// Extends an account device's lease (the cloud still lists its grant).pub fn set_lease(&self, key: &str, until: i64) -> Result<()> {let c = self.db.locked();@@ -234,6 +259,7 @@ mod tests {lease_until: None,created_at: 1,last_seen_at: None,+ account: None,};s.put_device(&d).unwrap();s.put_device(&Device { key: "dk2".into(), ..d.clone() }).unwrap();diff --git a/host/src/store/schema.rs b/host/src/store/schema.rsindex 49b33def..62fece4e 100644--- a/host/src/store/schema.rs+++ b/host/src/store/schema.rs@@ -7,7 +7,7 @@ use std::path::Path;use std::sync::Mutex;/// Current schema version (kv `schema`).-const SCHEMA: i64 = 6;+const SCHEMA: i64 = 7;/// 3: authorized devices (keys, not push tickets) with their push and Live Activity/// tickets. The old ticket-only `devices` table is dropped; phones re-register on connect.@@ -15,6 +15,8 @@ const SCHEMA: i64 = 6;/// per-bot ones go./// 5: threads merge into their chats (quote replies took their place, see [`migrate_5`])./// 6: the dividers that announced a fresh agent session go; the chat no longer shows session resets.+/// 7: each device records the account it was let in for (`devices.account`), so a computer that changes+/// accounts drops the old account's devices.fn migrate(c: &Connection) -> Result<()> {let version: i64 =c.query_row("SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'schema'", [], |r| r.get(0)).optional()?.unwrap_or(0);@@ -30,7 +32,10 @@ fn migrate(c: &Connection) -> Result<()> {if version < 5 {migrate_5(c)?;}- migrate_6(c)+ if version < 6 {+ migrate_6(c)?;+ }+ migrate_7(c)}fn migrate_3(c: &Connection) -> Result<()> {@@ -131,6 +136,16 @@ fn migrate_6(c: &Connection) -> Result<()> {Ok(())}+fn migrate_7(c: &Connection) -> Result<()> {+ let has: bool =+ c.query_row("SELECT count(*) > 0 FROM pragma_table_info('devices') WHERE name = 'account'", [], |r| r.get(0))?;+ if !has {+ c.execute_batch("ALTER TABLE devices ADD COLUMN account TEXT;")?;+ }+ c.execute_batch("INSERT INTO kv(k, v) VALUES('schema', '7') ON CONFLICT(k) DO UPDATE SET v = '7';")?;+ Ok(())+}+impl Store {pub fn open(path: &Path) -> Result<Self> {let c = Connection::open(path)?;@@ -192,7 +207,7 @@ mod tests {}let s = Store::open(&db).unwrap();assert!(s.devices().unwrap().is_empty());- assert_eq!(s.kv_get("schema").as_deref(), Some("6"));+ assert_eq!(s.kv_get("schema").as_deref(), Some("7"));drop(s);let s = Store::open(&db).unwrap();assert!(s.devices().unwrap().is_empty(), "reopening keeps the new table");@@ -215,7 +230,7 @@ mod tests {let s = Store::open(&db).unwrap();let chat: Vec<String> = s.history("b", i64::MAX, 10).unwrap().into_iter().map(|e| e.id).collect();assert_eq!(chat, ["info"]);- assert_eq!(s.kv_get("schema").as_deref(), Some("6"));+ assert_eq!(s.kv_get("schema").as_deref(), Some("7"));}#[test]diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rsindex 968fccdc..faecdd48 100644--- a/host/tests/common/mod.rs+++ b/host/tests/common/mod.rs@@ -9,6 +9,15 @@ use std::time::{Duration, Instant};/// Runs `codync-host serve` for `home` until it answers: the process and its base URL. A port/// picked here is only free for a moment; when something else takes it before the host binds, the/// host exits and this starts it again on another one.+/// The seed of the cloud key a test host trusts for device certificates.+pub const TEST_CLOUD_SEED: [u8; 32] = [9; 32];++fn test_cloud_key() -> String {+ use base64::Engine as _;+ let key = ed25519_dalek::SigningKey::from_bytes(&TEST_CLOUD_SEED).verifying_key();+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(key.as_bytes())+}+pub async fn serve(home: &Path) -> (Child, String) {let deadline = Instant::now() + Duration::from_secs(30);let _ = std::fs::create_dir_all(home);@@ -21,6 +30,8 @@ pub async fn serve(home: &Path) -> (Child, String) {.args(["serve", "--bind", "127.0.0.1", "--port", &port.to_string()]).env("CODYNC_HOME", home).env("CODYNC_CLOUD", "off")+ // Pairing checks the phone's account: tests sign certificates with `TEST_CLOUD_SEED`.+ .env("CODYNC_DEVICE_CERT_KEY", test_cloud_key()).stdout(Stdio::null()).stderr(std::fs::File::create(&log).map_or_else(|_| Stdio::null(), Stdio::from)).spawn()diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex 2c51d948..61f75796 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -34,6 +34,23 @@ impl Drop for Host {}}+/// A device certificate as the cloud signs it (`cloud/src/certificate.ts`), with the test host's trusted key.+fn test_certificate(device_key: &str, user_id: &str) -> Value {+ let exp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() + 60_000;+ let payload = json!({"v": 1, "deviceKey": device_key, "userId": user_id, "email": "[email protected]", "exp": exp})+ .to_string();+ let key = SigningKey::from_bytes(&common::TEST_CLOUD_SEED);+ let sig = crypto::sign(+ &key,+ format!(+ "codync/device-cert/v1+{payload}"+ )+ .as_bytes(),+ );+ json!({"payload": payload, "sig": crypto::b64(&sig)})+}+async fn start_host() -> Host {let home = std::env::temp_dir().join(format!("codync-e2e-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&home).unwrap();@@ -363,7 +380,20 @@ async fn phone_pairs_and_chats_over_the_direct_channel() {let mut phone = Phone::connect(&host, &key, &sk, true).await;let code = query_param(url, "code");- phone.send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Test iPhone", "platform": "ios"}})).await;+ let certificate = test_certificate(&crypto::b64(key.verifying_key().as_bytes()), "user_1");+ phone+ .send(json!({"id": 1, "m": "pair", "b": {"code": code, "name": "Test iPhone", "platform": "ios", "certificate": certificate}}))+ .await;+ // A computer in no account asks first; the test answers for it.+ let request = loop {+ let list = host.call("pairingRequests", json!({})).await;+ if let Some(r) = list["requests"].as_array().and_then(|r| r.first()) {+ break r.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ };+ assert_eq!(request["deviceName"], "Test iPhone");+ host.call("decidePairing", json!({"requestId": request["requestId"], "approve": true})).await;assert_eq!(phone.inner().await["ok"]["computerId"], crypto::computer_id(&sk));assert!(matches!(phone.recv().await, Frame::Closed(4100)));diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex 81ae1cb1..558af0b6 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -1,5 +1,5 @@{- "minApp": "2.34.0",+ "minApp": "2.36.0","shapes": {"event:bot": "object","event:bot.bot": "object",