Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(connections): one-click "connect with Bee" via device-pairing (#4383)

Louis Beaumont8fe35f15e54c
diff --git a/Cargo.lock b/Cargo.lock
index 249862e0e..d12528de7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1592,7 +1592,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
- "windows-sys 0.48.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -2033,6 +2033,35 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "crypto_box"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16182b4f39a82ec8a6851155cc4c0cda3065bb1db33651726a29e1951de0f009"
+dependencies = [
+ "aead 0.5.2",
+ "crypto_secretbox",
+ "curve25519-dalek 4.1.3",
+ "salsa20 0.10.2",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "crypto_secretbox"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1"
+dependencies = [
+ "aead 0.5.2",
+ "cipher 0.4.4",
+ "generic-array 0.14.7",
+ "poly1305",
+ "salsa20 0.10.2",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "ctr"
version = "0.9.2"
@@ -6942,7 +6971,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
- "itertools 0.12.1",
+ "itertools 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -7672,7 +7701,7 @@ dependencies = [
"ring",
"russh-cryptovec",
"russh-util",
- "salsa20",
+ "salsa20 0.11.0",
"scrypt",
"sec1 0.8.1",
"sha1 0.10.6",
@@ -7986,6 +8015,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "salsa20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "salsa20"
version = "0.11.0"
@@ -8210,8 +8248,10 @@ dependencies = [
"base64 0.22.1",
"chrono",
"chrono-tz",
+ "crypto_box",
"dirs 6.0.0",
"eventkit-rs",
+ "getrandom 0.2.17",
"icalendar",
"image",
"lettre",
@@ -8588,7 +8628,7 @@ checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0"
dependencies = [
"cfg-if",
"pbkdf2 0.13.0",
- "salsa20",
+ "salsa20 0.11.0",
"sha2 0.11.0",
]
@@ -11391,7 +11431,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.48.0",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
index 9e4bb7043..0488b1ce1 100644
--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
@@ -2906,6 +2906,102 @@ interface InstanceData {
credentials: Record<string, string>;
}
+/**
+ * One-click "connect with Bee" — drives the engine's device-pairing routes
+ * (POST /connections/bee/pair/{start,poll}). Bee has no redirect OAuth and no
+ * web token portal anymore, so we start a pairing, open the approve URL, and
+ * poll until the sealed token is decrypted + stored server-side.
+ */
+function BeePairPanel({ onConnected }: { onConnected: () => void }) {
+ const [busy, setBusy] = useState(false);
+ const [statusMsg, setStatusMsg] = useState<string | null>(null);
+ const cancelledRef = useRef(false);
+
+ useEffect(() => {
+ return () => {
+ cancelledRef.current = true;
+ };
+ }, []);
+
+ const handleConnect = async () => {
+ setBusy(true);
+ setStatusMsg(null);
+ cancelledRef.current = false;
+ try {
+ const res = await localFetch("/connections/bee/pair/start", { method: "POST" });
+ const body = await res.json();
+ if (!res.ok) {
+ setStatusMsg(body?.error ?? `Couldn't start pairing (HTTP ${res.status})`);
+ setBusy(false);
+ return;
+ }
+ const requestId = body.request_id as string;
+ await openUrl(body.pairing_url as string);
+ setStatusMsg("approve the connection in your browser, then come back…");
+
+ const deadline = Date.now() + 5 * 60 * 1000;
+ const poll = async () => {
+ if (cancelledRef.current) return;
+ if (Date.now() > deadline) {
+ setStatusMsg("pairing timed out — try again");
+ setBusy(false);
+ return;
+ }
+ try {
+ const pr = await localFetch("/connections/bee/pair/poll", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ request_id: requestId }),
+ });
+ const pb = await pr.json();
+ if (pb?.status === "completed") {
+ setStatusMsg(null);
+ setBusy(false);
+ onConnected();
+ return;
+ }
+ if (pb?.status === "expired" || pb?.status === "unknown") {
+ setStatusMsg("pairing expired — try again");
+ setBusy(false);
+ return;
+ }
+ } catch {
+ // transient — keep polling until the deadline
+ }
+ setTimeout(poll, 2000);
+ };
+ setTimeout(poll, 2000);
+ } catch (e) {
+ setStatusMsg(`pairing failed: ${e instanceof Error ? e.message : String(e)}`);
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div className="space-y-2">
+ <Button
+ onClick={handleConnect}
+ disabled={busy}
+ size="sm"
+ className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal whitespace-nowrap"
+ >
+ {busy ? (
+ <>
+ <Loader2 className="h-3 w-3 animate-spin" />
+ waiting for approval…
+ </>
+ ) : (
+ <>
+ <LogIn className="h-3 w-3" />
+ connect with Bee
+ </>
+ )}
+ </Button>
+ {statusMsg && <p className="text-[11px] text-muted-foreground">{statusMsg}</p>}
+ </div>
+ );
+}
+
function ApiIntegrationPanel({ integration, onRefresh }: {
integration: IntegrationInfo;
onRefresh: () => void;
@@ -3921,6 +4017,33 @@ export function ConnectionsSection({
</div>
);
}
+ // Bee has no redirect OAuth, but supports one-click device pairing.
+ // Show the pairing button, keeping the manual token field as an
+ // advanced fallback (e.g. a token pasted from the bee CLI).
+ if (selectedIntegration.id === "bee") {
+ return (
+ <div className="space-y-3">
+ <BeePairPanel
+ onConnected={() => {
+ refreshIntegrationConnection("bee", true);
+ notifyConnectionsUpdated();
+ fetchIntegrations();
+ }}
+ />
+ <details>
+ <summary className="text-[11px] text-muted-foreground cursor-pointer select-none hover:text-foreground">
+ advanced: connect with a token instead
+ </summary>
+ <div className="pt-2">
+ <ApiIntegrationPanel
+ integration={selectedIntegration}
+ onRefresh={fetchIntegrations}
+ />
+ </div>
+ </details>
+ </div>
+ );
+ }
return <ApiIntegrationPanel
integration={selectedIntegration}
onRefresh={fetchIntegrations}
diff --git a/crates/screenpipe-connect/Cargo.toml b/crates/screenpipe-connect/Cargo.toml
index a7f97e0a2..86592956d 100644
--- a/crates/screenpipe-connect/Cargo.toml
+++ b/crates/screenpipe-connect/Cargo.toml
@@ -43,6 +43,11 @@ uuid = { workspace = true }
thiserror = { workspace = true }
base64 = { workspace = true }
sha2 = { workspace = true }
+# Bee "connect" device-pairing flow: NaCl crypto_box (X25519 + XSalsa20-Poly1305)
+# to decrypt the app-pairing token the auth service seals to our ephemeral
+# public key. `salsa20` feature = `SalsaBox` (libsodium/tweetnacl-compatible).
+crypto_box = { version = "0.9", features = ["salsa20"] }
+getrandom = { version = "0.2" }
lettre = { version = "0.11", default-features = false, features = ["smtp-transport", "tokio1-rustls-tls", "builder"] }
mdns-sd = "0.13"
sqlx = { workspace = true }
diff --git a/crates/screenpipe-connect/src/connections/bee.rs b/crates/screenpipe-connect/src/connections/bee.rs
index dfc5b0318..13aa80874 100644
--- a/crates/screenpipe-connect/src/connections/bee.rs
+++ b/crates/screenpipe-connect/src/connections/bee.rs
@@ -8,6 +8,11 @@ use super::{
};
use anyhow::Result;
use async_trait::async_trait;
+use base64::Engine as _;
+use crypto_box::{
+ aead::{generic_array::GenericArray, AeadInPlace},
+ Nonce, PublicKey, SalsaBox, SecretKey,
+};
use screenpipe_secrets::SecretStore;
use serde_json::{Map, Value};
@@ -16,13 +21,13 @@ static DEF: IntegrationDef = IntegrationDef {
name: "Bee",
icon: "bee",
category: Category::Productivity,
- description: "Bee wearable AI — captures in-person conversations, facts, todos, and daily summaries. Pair with screenpipe to cover what you saw on screen plus what you heard out loud. Get a developer token from the Bee iOS app (tap version 5x to enable Developer Mode).",
+ description: "Bee wearable AI — captures in-person conversations, facts, todos, and daily summaries. Pair with screenpipe to cover what you saw on screen plus what you heard out loud. Use \"connect with Bee\" for one-click pairing, or paste a developer token from the Bee app (enable Developer Mode: tap the app version 5x in Settings) or the bee CLI (`bee login`).",
fields: &[FieldDef {
key: "api_key",
label: "Developer Token",
secret: true,
placeholder: "your-bee-developer-token",
- help_url: "https://docs.bee.computer/docs/developer-mode",
+ help_url: "https://docs.bee.computer/docs/cli",
}],
};
@@ -117,6 +122,177 @@ impl Integration for Bee {
}
}
+// ---------------------------------------------------------------------------
+// Bee "connect" device-pairing flow (one-click connect)
+// ---------------------------------------------------------------------------
+//
+// Bee has no redirect-style OAuth and — post-Amazon-acquisition — no web
+// developer portal (the old `developer.bee.computer` host no longer resolves).
+// Its only first-party way for a third party to obtain a user token is the
+// device-pairing flow the `@beeai/cli` (`bee login`) runs. We reconstruct it
+// here so screenpipe can offer one-click "connect with Bee" instead of asking
+// the user to paste a token:
+//
+// 1. generate an ephemeral X25519 keypair
+// 2. POST {app_id, publicKey} to the auth service → {requestId, expiresAt}
+// 3. open https://bee.computer/connect#<requestId>; the signed-in user approves
+// 4. re-POST the same publicKey (~2s cadence) until the response carries an
+// `encryptedToken` — a NaCl crypto_box sealed to our ephemeral public key
+// 5. crypto_box-open it with our secret key → the Bearer JWT, which is the
+// exact same credential the manual "Developer Token" field stores, so the
+// proxy + test() paths above need zero changes.
+//
+// Reverse-engineered from @beeai/[email protected] and confirmed against the live
+// endpoint; the wire contract is pinned by the tests below.
+
+/// Public app identifier the Bee CLI ships for the production auth service.
+/// Not a secret — it's embedded in the public npm package and only names the
+/// "app" the user approves, exactly like an OAuth client_id.
+const BEE_APP_ID: &str = "ph9fssu1kv1b0hns69fxf7rx";
+const BEE_PAIRING_ENDPOINT: &str = "https://auth.beeai-services.com/apps/pairing/request";
+const BEE_CONNECT_URL_PREFIX: &str = "https://bee.computer/connect#";
+
+// Packed `encryptedToken` layout (tweetnacl `box`):
+// version(1) | nonce(24) | ephemeralPublicKey(32) | MAC(16) || ciphertext
+const PAIRING_ENCRYPTION_VERSION: u8 = 1;
+const PAIRING_NONCE_SIZE: usize = 24;
+const PAIRING_PUBLIC_KEY_SIZE: usize = 32;
+const POLY1305_TAG_SIZE: usize = 16;
+
+/// Outcome of one `POST /apps/pairing/request`. The endpoint is polled with the
+/// same public key until it flips from `Pending` to `Completed` (or `Expired`).
+#[derive(Debug)]
+pub enum PairingOutcome {
+ Pending {
+ request_id: String,
+ expires_at: String,
+ },
+ Completed {
+ encrypted_token: String,
+ },
+ Expired,
+}
+
+/// Generate an ephemeral X25519 keypair for one pairing attempt. Returns
+/// `(secret_key_bytes, public_key_base64)` — the base64 public key is sent to
+/// Bee; the secret bytes stay in memory to decrypt the sealed token.
+pub fn generate_pairing_keypair() -> Result<([u8; 32], String)> {
+ let mut sk_bytes = [0u8; 32];
+ getrandom::getrandom(&mut sk_bytes)
+ .map_err(|e| anyhow::anyhow!("failed to generate pairing key: {e}"))?;
+ let sk = SecretKey::from(sk_bytes);
+ let pk_b64 = base64::engine::general_purpose::STANDARD.encode(sk.public_key().as_bytes());
+ Ok((sk_bytes, pk_b64))
+}
+
+/// The browser URL the user opens to approve a pairing request.
+pub fn pairing_connect_url(request_id: &str) -> String {
+ format!("{BEE_CONNECT_URL_PREFIX}{request_id}")
+}
+
+/// One `POST /apps/pairing/request {app_id, publicKey}`. Called once to start
+/// the flow (returns `Pending`) and then repeatedly to poll until the user
+/// approves (`Completed`) or the window closes (`Expired`). Uses a plain client
+/// — the auth host is on a public CA (unlike the Bee data API's private CA).
+pub async fn request_pairing(
+ client: &reqwest::Client,
+ public_key_b64: &str,
+) -> Result<PairingOutcome> {
+ let resp = client
+ .post(BEE_PAIRING_ENDPOINT)
+ .json(&serde_json::json!({ "app_id": BEE_APP_ID, "publicKey": public_key_b64 }))
+ .send()
+ .await?;
+ let status = resp.status();
+ let body: Value = resp
+ .json()
+ .await
+ .map_err(|e| anyhow::anyhow!("bee pairing: non-JSON response (http {status}): {e}"))?;
+ if !status.is_success() || body.get("ok").and_then(Value::as_bool) != Some(true) {
+ let msg = body
+ .get("error")
+ .and_then(Value::as_str)
+ .unwrap_or("unexpected response");
+ anyhow::bail!("bee pairing failed (http {status}): {msg}");
+ }
+ parse_pairing_outcome(&body)
+}
+
+/// Pure parser for the `/apps/pairing/request` JSON body — split out so the
+/// exact wire shape can be unit-tested without a live call.
+fn parse_pairing_outcome(body: &Value) -> Result<PairingOutcome> {
+ match body.get("status").and_then(Value::as_str) {
+ Some("pending") => Ok(PairingOutcome::Pending {
+ request_id: require_field(body, "requestId")?,
+ expires_at: require_field(body, "expiresAt")?,
+ }),
+ Some("completed") => {
+ let encrypted_token = body
+ .get("result")
+ .and_then(|r| r.get("encryptedToken"))
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow::anyhow!("bee pairing: missing encryptedToken"))?;
+ Ok(PairingOutcome::Completed {
+ encrypted_token: encrypted_token.to_string(),
+ })
+ }
+ Some("expired") => Ok(PairingOutcome::Expired),
+ other => anyhow::bail!("bee pairing: unexpected status {other:?}"),
+ }
+}
+
+fn require_field(body: &Value, key: &str) -> Result<String> {
+ body.get(key)
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .ok_or_else(|| anyhow::anyhow!("bee pairing: missing {key}"))
+}
+
+/// Decrypt the base64 `encryptedToken` into the Bearer JWT.
+///
+/// The payload mirrors tweetnacl's `box`: `version(1) | nonce(24) |
+/// ephemeralPublicKey(32) | MAC(16) || ciphertext`. NaCl prepends the Poly1305
+/// MAC, so we hand it to `decrypt_in_place_detached` as an explicit tag (the
+/// RustCrypto AEAD trait would otherwise expect the tag appended).
+pub fn decrypt_pairing_token(encrypted_b64: &str, secret_key: &[u8; 32]) -> Result<String> {
+ let packed = base64::engine::general_purpose::STANDARD
+ .decode(encrypted_b64.trim())
+ .map_err(|e| anyhow::anyhow!("bee pairing: token not base64: {e}"))?;
+
+ let header = 1 + PAIRING_NONCE_SIZE + PAIRING_PUBLIC_KEY_SIZE;
+ if packed.len() < header + POLY1305_TAG_SIZE {
+ anyhow::bail!("bee pairing: token too short");
+ }
+ if packed[0] != PAIRING_ENCRYPTION_VERSION {
+ anyhow::bail!("bee pairing: unsupported token version {}", packed[0]);
+ }
+
+ let nonce = &packed[1..1 + PAIRING_NONCE_SIZE];
+ let mut eph = [0u8; 32];
+ eph.copy_from_slice(&packed[1 + PAIRING_NONCE_SIZE..header]);
+ let (mac, ciphertext) = packed[header..].split_at(POLY1305_TAG_SIZE);
+
+ let salsa_box = SalsaBox::new(&PublicKey::from(eph), &SecretKey::from(*secret_key));
+ let mut buf = ciphertext.to_vec();
+ salsa_box
+ .decrypt_in_place_detached(
+ Nonce::from_slice(nonce),
+ b"",
+ &mut buf,
+ GenericArray::from_slice(mac),
+ )
+ .map_err(|_| anyhow::anyhow!("bee pairing: token decryption failed"))?;
+
+ let token = String::from_utf8(buf)
+ .map_err(|_| anyhow::anyhow!("bee pairing: decrypted token not utf-8"))?
+ .trim()
+ .to_string();
+ if token.is_empty() {
+ anyhow::bail!("bee pairing: empty token");
+ }
+ Ok(token)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -143,6 +319,92 @@ mod tests {
}
}
+ #[test]
+ fn pairing_connect_url_targets_bee_connect_fragment() {
+ assert_eq!(
+ pairing_connect_url("abc123"),
+ "https://bee.computer/connect#abc123"
+ );
+ }
+
+ #[test]
+ fn parses_pending_completed_expired() {
+ let pending = serde_json::json!({
+ "ok": true, "status": "pending",
+ "requestId": "rid", "expiresAt": "2026-06-19T19:59:42.773Z"
+ });
+ match parse_pairing_outcome(&pending).unwrap() {
+ PairingOutcome::Pending {
+ request_id,
+ expires_at,
+ } => {
+ assert_eq!(request_id, "rid");
+ assert_eq!(expires_at, "2026-06-19T19:59:42.773Z");
+ }
+ other => panic!("expected pending, got {other:?}"),
+ }
+
+ let completed = serde_json::json!({
+ "ok": true, "status": "completed",
+ "requestId": "rid", "result": { "encryptedToken": "Zm9v" }
+ });
+ match parse_pairing_outcome(&completed).unwrap() {
+ PairingOutcome::Completed { encrypted_token } => assert_eq!(encrypted_token, "Zm9v"),
+ other => panic!("expected completed, got {other:?}"),
+ }
+
+ let expired = serde_json::json!({ "ok": true, "status": "expired", "requestId": "rid" });
+ assert!(matches!(
+ parse_pairing_outcome(&expired).unwrap(),
+ PairingOutcome::Expired
+ ));
+ }
+
+ /// Round-trips a token through the exact packed `box` layout Bee's auth
+ /// service emits, proving our key handling + the NaCl MAC-prepended →
+ /// RustCrypto detached-tag conversion are correct.
+ #[test]
+ fn decrypts_sealed_pairing_token() {
+ let (our_sk, our_pk_b64) = generate_pairing_keypair().unwrap();
+ let mut our_pub = [0u8; 32];
+ our_pub.copy_from_slice(
+ &base64::engine::general_purpose::STANDARD
+ .decode(our_pk_b64)
+ .unwrap(),
+ );
+
+ // server side: ephemeral keypair + crypto_box(token) sealed to our pubkey
+ let (server_sk_bytes, _) = generate_pairing_keypair().unwrap();
+ let server_sk = SecretKey::from(server_sk_bytes);
+ let server_pub = server_sk.public_key();
+
+ let nonce = [7u8; PAIRING_NONCE_SIZE];
+ let token = "eyJhbGciOi.test.jwt";
+ let mut buf = token.as_bytes().to_vec();
+ let tag = SalsaBox::new(&PublicKey::from(our_pub), &server_sk)
+ .encrypt_in_place_detached(Nonce::from_slice(&nonce), b"", &mut buf)
+ .unwrap();
+
+ // pack: version | nonce | server ephemeral pub | MAC || ciphertext
+ let mut packed = vec![PAIRING_ENCRYPTION_VERSION];
+ packed.extend_from_slice(&nonce);
+ packed.extend_from_slice(server_pub.as_bytes());
+ packed.extend_from_slice(tag.as_slice());
+ packed.extend_from_slice(&buf);
+ let encrypted_b64 = base64::engine::general_purpose::STANDARD.encode(&packed);
+
+ let decrypted = decrypt_pairing_token(&encrypted_b64, &our_sk).unwrap();
+ assert_eq!(decrypted, token);
+ }
+
+ #[test]
+ fn rejects_corrupt_pairing_token() {
+ let (our_sk, _) = generate_pairing_keypair().unwrap();
+ assert!(decrypt_pairing_token("not base64!!", &our_sk).is_err());
+ let too_short = base64::engine::general_purpose::STANDARD.encode([1u8; 8]);
+ assert!(decrypt_pairing_token(&too_short, &our_sk).is_err());
+ }
+
/// The custom CA must parse as a valid PEM certificate that reqwest can
/// hand to rustls. If the embedded blob is corrupted (e.g. line endings
/// mangled by an editor, accidental BOM), every Bee API call would fail
diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rs
index 89b442156..e84979a57 100644
--- a/crates/screenpipe-engine/src/connections_api.rs
+++ b/crates/screenpipe-engine/src/connections_api.rs
@@ -10,7 +10,7 @@ use axum::response::Html;
use axum::routing::{get, post};
use axum::{Json, Router};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
-use screenpipe_connect::connections::ConnectionManager;
+use screenpipe_connect::connections::{bee, ConnectionManager};
use screenpipe_connect::oauth::{self as oauth_store, PENDING_OAUTH};
use screenpipe_connect::whatsapp::WhatsAppGateway;
use screenpipe_secrets::SecretStore;
@@ -19,7 +19,7 @@ use serde_json::{json, Map, Value};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex as StdMutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
@@ -3064,6 +3064,152 @@ async fn browser_run_eval(
}
}
+// ---------------------------------------------------------------------------
+// Bee one-click device-pairing
+// (protocol lives in screenpipe_connect::connections::bee)
+// ---------------------------------------------------------------------------
+
+/// Server-side state for an in-flight Bee pairing. The ephemeral secret key
+/// never leaves the engine — it's held here keyed by `request_id` until the
+/// poll route decrypts the sealed token or the session expires.
+struct BeePairingSession {
+ secret_key: [u8; 32],
+ public_key_b64: String,
+ created_at: Instant,
+}
+
+fn bee_pairing_sessions() -> &'static StdMutex<HashMap<String, BeePairingSession>> {
+ static SESSIONS: OnceLock<StdMutex<HashMap<String, BeePairingSession>>> = OnceLock::new();
+ SESSIONS.get_or_init(|| StdMutex::new(HashMap::new()))
+}
+
+const BEE_PAIRING_SESSION_TTL: Duration = Duration::from_secs(10 * 60);
+
+#[derive(Deserialize)]
+struct BeePairPollBody {
+ request_id: String,
+}
+
+/// POST /connections/bee/pair/start — begin a one-click Bee pairing.
+///
+/// Generates an ephemeral keypair, asks Bee for a pairing request, stashes the
+/// secret key keyed by `request_id`, and returns the URL the user opens to
+/// approve. The UI then polls `pair/poll` until completion.
+async fn bee_pair_start() -> (StatusCode, Json<Value>) {
+ let (secret_key, public_key_b64) = match bee::generate_pairing_keypair() {
+ Ok(kp) => kp,
+ Err(e) => {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({ "error": e.to_string() })),
+ )
+ }
+ };
+ let client = reqwest::Client::new();
+ match bee::request_pairing(&client, &public_key_b64).await {
+ Ok(bee::PairingOutcome::Pending {
+ request_id,
+ expires_at,
+ }) => {
+ let pairing_url = bee::pairing_connect_url(&request_id);
+ {
+ let mut sessions = bee_pairing_sessions().lock().unwrap();
+ let now = Instant::now();
+ sessions.retain(|_, s| now.duration_since(s.created_at) < BEE_PAIRING_SESSION_TTL);
+ sessions.insert(
+ request_id.clone(),
+ BeePairingSession {
+ secret_key,
+ public_key_b64,
+ created_at: now,
+ },
+ );
+ }
+ (
+ StatusCode::OK,
+ Json(json!({
+ "request_id": request_id,
+ "pairing_url": pairing_url,
+ "expires_at": expires_at,
+ })),
+ )
+ }
+ Ok(_) => (
+ StatusCode::BAD_GATEWAY,
+ Json(json!({ "error": "unexpected pairing state from Bee" })),
+ ),
+ Err(e) => (
+ StatusCode::BAD_GATEWAY,
+ Json(json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
+/// POST /connections/bee/pair/poll {request_id} — poll a pending pairing.
+///
+/// Returns `{status: pending|completed|expired|unknown}`. On `completed` it
+/// decrypts the sealed token and stores it as the Bee `api_key` credential —
+/// the same slot the manual "Developer Token" field uses — so the proxy and
+/// `test()` paths need no changes.
+async fn bee_pair_poll(
+ State(state): State<ConnectionsState>,
+ Json(body): Json<BeePairPollBody>,
+) -> (StatusCode, Json<Value>) {
+ let (secret_key, public_key_b64) = {
+ let sessions = bee_pairing_sessions().lock().unwrap();
+ match sessions.get(&body.request_id) {
+ Some(s) => (s.secret_key, s.public_key_b64.clone()),
+ None => return (StatusCode::NOT_FOUND, Json(json!({ "status": "unknown" }))),
+ }
+ };
+
+ let client = reqwest::Client::new();
+ match bee::request_pairing(&client, &public_key_b64).await {
+ Ok(bee::PairingOutcome::Pending { .. }) => {
+ (StatusCode::OK, Json(json!({ "status": "pending" })))
+ }
+ Ok(bee::PairingOutcome::Completed { encrypted_token }) => {
+ let token = match bee::decrypt_pairing_token(&encrypted_token, &secret_key) {
+ Ok(t) => t,
+ Err(e) => {
+ return (
+ StatusCode::BAD_GATEWAY,
+ Json(json!({ "error": e.to_string() })),
+ )
+ }
+ };
+ let mut creds = Map::new();
+ creds.insert("api_key".to_string(), Value::String(token));
+ let result = {
+ let mgr = state.cm.lock().await;
+ mgr.connect("bee", creds).await
+ };
+ bee_pairing_sessions()
+ .lock()
+ .unwrap()
+ .remove(&body.request_id);
+ match result {
+ Ok(()) => (StatusCode::OK, Json(json!({ "status": "completed" }))),
+ Err(e) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(json!({ "error": e.to_string() })),
+ ),
+ }
+ }
+ Ok(bee::PairingOutcome::Expired) => {
+ bee_pairing_sessions()
+ .lock()
+ .unwrap()
+ .remove(&body.request_id);
+ (StatusCode::OK, Json(json!({ "status": "expired" })))
+ }
+ Err(e) => (
+ StatusCode::BAD_GATEWAY,
+ Json(json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
pub fn router<S>(
cm: SharedConnectionManager,
wa: SharedWhatsAppGateway,
@@ -3137,6 +3283,9 @@ where
.route("/whatsapp/pair", post(whatsapp_pair))
.route("/whatsapp/status", get(whatsapp_status))
.route("/whatsapp/disconnect", post(whatsapp_disconnect))
+ // Bee one-click device-pairing (must be before /:id to avoid conflict)
+ .route("/bee/pair/start", post(bee_pair_start))
+ .route("/bee/pair/poll", post(bee_pair_poll))
// Credential proxy — pipes call this instead of external APIs directly
.route("/:id/proxy/*path", axum::routing::any(connection_proxy))
.route("/:id/config", get(connection_config))