community: the encrypted inbox, friend requests and shares travel sealed to a box key when the other side has published one

This commit is contained in:
KeelrLeek committed 2026-09-02 15:26:30 -05:00
1 parent 13c44f731a
commit 4378c4c0cc
14 files changed
+1387 -145

No files matched your search

+193 -122
View File
@@ -4,18 +4,21 @@
//! shown as exactly what it is. Proofs stay on this device; nothing is
//! published.
//!
//! Carry today: the same Soulseek private-message channel the link proof
//! uses (the encrypted inbox of F5 takes over later). The server can see
//! that one account wrote to another; it cannot forge who wrote, which is
//! the one thing these messages need from it.
//! Two carries, chosen per relationship and remembered: the ENCRYPTED
//! INBOX (inbox.rs — sealed to the recipient's box key, offered to their
//! contract) whenever the other persona has published one, else the
//! Soulseek private-message channel the link proof uses. The server can
//! see that one account wrote to another on the PM carry; it cannot forge
//! who wrote, which is the one thing that carry needs from it.
//!
//! Wire: `SSFRIEND1?<b64 request>` asks, `SSFRIEND1!<b64 assertion>`
//! PM wire: `SSFRIEND1?<b64 request>` asks, `SSFRIEND1!<b64 assertion>`
//! accepts or revokes, `SSFRIEND1-<b58 relationship id>` declines. An
//! incoming REQUEST is bound to its sender by the link handshake: the
//! request names a persona key, and the sender is asked (over PM, with a
//! fresh nonce) to prove that key is theirs before the request is shown.
//! That ask waits on a PM, so the pump hands friend messages to a task —
//! awaiting inline would block the very loop that delivers the answer.
//! incoming PM REQUEST is bound to its sender by the link handshake (the
//! request names a key; the sender proves it). An inbox request needs no
//! such step: the envelope header is signed by the same key the request
//! names. That link ask waits on a PM, so PM friend messages are handled
//! on their own task — awaiting inline would block the loop that delivers
//! the answer.
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -26,6 +29,7 @@ use persona_state::slsk_link::normalize_username;
use serde::{Deserialize, Serialize};
use tauri::{Emitter, Manager};
use crate::inbox::{self, Cargo};
use crate::persona;
use crate::slsk_link;
use crate::state::AppState;
@@ -33,13 +37,17 @@ use crate::state::AppState;
const REQ_PREFIX: &str = "SSFRIEND1?";
const ASSERT_PREFIX: &str = "SSFRIEND1!";
const DECLINE_PREFIX: &str = "SSFRIEND1-";
/// A request stays open this long.
const REQUEST_TTL_SECS: u64 = 7 * 24 * 3600;
pub const EVENT: &str = "community:friends";
fn carry_pm() -> String {
"pm".into()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Relationship {
/// Their Soulseek account as the server spelled it when it last spoke.
/// Their Soulseek account as the server spelled it — may be empty for a
/// relationship that only ever travelled the inbox.
username: String,
username_normalized: String,
their_key: String,
@@ -48,11 +56,13 @@ struct Relationship {
request_from_me: bool,
#[serde(default)]
assertions: Vec<fr::FriendAssertion>,
/// Local-only stances the verifier has no signature for.
#[serde(default)]
declined_by_me: bool,
#[serde(default)]
declined_by_them: bool,
/// "inbox" | "pm" — how the last message travelled; replies follow it.
#[serde(default = "carry_pm")]
carry: String,
created_at: u64,
updated_at: u64,
}
@@ -63,7 +73,6 @@ struct Store {
relationships: BTreeMap<String, Relationship>,
}
/// What the UI sees: one row per relationship, status from the verifier.
#[derive(Debug, Serialize)]
pub struct RelationshipView {
pub id: String,
@@ -74,6 +83,7 @@ pub struct RelationshipView {
/// friends | pending-out | pending-in | accepted-waiting | declined |
/// revoked | expired | reacceptance-required
pub state: String,
pub carry: String,
pub since: u64,
pub updated_at: u64,
pub expires_at: u64,
@@ -95,12 +105,7 @@ fn b58(bytes: &[u8]) -> String {
bs58::encode(bytes).into_string()
}
fn key_of(b58s: &str) -> Result<[u8; 32], String> {
bs58::decode(b58s)
.into_vec()
.map_err(|e| format!("bad key: {e}"))?
.as_slice()
.try_into()
.map_err(|_| "key is not 32 bytes".to_string())
inbox::key_of(b58s)
}
fn path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
@@ -178,6 +183,7 @@ fn view_of(id: &str, r: &Relationship, now: u64) -> RelationshipView {
persona_key: r.their_key.clone(),
direction: if r.request_from_me { "out" } else { "in" },
state: state.to_string(),
carry: r.carry.clone(),
since,
updated_at: r.updated_at,
expires_at: r.request.expires_at,
@@ -192,6 +198,9 @@ async fn my_key(app: &tauri::AppHandle) -> Result<[u8; 32], String> {
key_of(&info.public_key)
}
async fn send_pm(app: &tauri::AppHandle, to: &str, text: &str) -> Result<(), String> {
if to.is_empty() {
return Err("no Soulseek account is known for them".into());
}
let st = app.state::<AppState>();
let guard = st.client.lock().await;
guard
@@ -211,21 +220,52 @@ fn decode<T: for<'de> Deserialize<'de>>(b64: &str) -> Option<T> {
bincode::deserialize(&bytes).ok()
}
/// Deliver by the relationship's carry; an inbox that went unreachable
/// falls back to the PM carry when an account is known.
async fn deliver(app: &tauri::AppHandle, rel: &mut Relationship, cargo: Cargo, pm_text: String) -> Result<(), String> {
if rel.carry == "inbox" {
match key_of(&rel.their_key) {
Ok(k) => match inbox::send(app, &k, &cargo).await {
Ok(()) => return Ok(()),
Err(e) => log::info!("friends: inbox carry failed ({e}); trying the Soulseek carry"),
},
Err(e) => return Err(e),
}
}
send_pm(app, &rel.username, &pm_text).await?;
rel.carry = "pm".into();
Ok(())
}
async fn sign_assertion(app: &tauri::AppHandle, mut a: fr::FriendAssertion) -> Result<fr::FriendAssertion, String> {
let adapter = app.state::<AppState>().freenet.clone();
a.sig = persona::sign(&adapter, fr::FRIEND_DOMAIN, fr::assertion_sign_payload(&a)).await?;
Ok(a)
}
fn assertion_for(rel: &Relationship, me: [u8; 32], their: [u8; 32], accepted: bool, now: u64) -> fr::FriendAssertion {
fr::FriendAssertion {
relationship_id: rel.request.relationship_id,
signer: me,
peer: their,
request_hash: fr::request_hash(&rel.request),
accepted,
seq: now,
sig: vec![],
}
}
// ---------------------------------------------------------------- outgoing
/// Ask `username` to be friends. Needs their verified link (the drawer's
/// "Ask for their SoulStream ID") — the request is addressed to a KEY.
pub async fn request(app: &tauri::AppHandle, username: &str) -> Result<RelationshipView, String> {
async fn start_request(
app: &tauri::AppHandle,
their: [u8; 32],
username: String,
) -> Result<RelationshipView, String> {
let me = my_key(app).await?;
let link = slsk_link::known_link(app, username)
.ok_or("verify their SoulStream ID first (the drawer's Ask button)")?;
let their = key_of(&link.persona_key)?;
if their == me {
return Err("that is your own identity".into());
}
let now = now_secs();
let mut req = fr::FriendRequest {
relationship_id: nonce16(),
@@ -239,29 +279,47 @@ pub async fn request(app: &tauri::AppHandle, username: &str) -> Result<Relations
let adapter = app.state::<AppState>().freenet.clone();
req.sig = persona::sign(&adapter, fr::FRIEND_DOMAIN, fr::request_sign_payload(&req)).await?;
let id = b58(&req.relationship_id);
let rel = Relationship {
username: link.username.clone(),
username_normalized: link.username_normalized.clone(),
their_key: link.persona_key.clone(),
let mut rel = Relationship {
username_normalized: normalize_username(&username),
username,
their_key: b58(&their),
my_key: b58(&me),
request: req.clone(),
request_from_me: true,
assertions: vec![],
declined_by_me: false,
declined_by_them: false,
carry: if inbox::reachable(app, &their).await { "inbox".into() } else { "pm".into() },
created_at: now,
updated_at: now,
};
send_pm(app, &link.username, &encode(REQ_PREFIX, &req)?).await?;
deliver(app, &mut rel, Cargo::FriendRequest(req.clone()), encode(REQ_PREFIX, &req)?).await?;
let mut store = load(app);
store.relationships.insert(id.clone(), rel);
save(app, &store)?;
log::info!("friends: request sent to {}", link.username);
Ok(view_of(&id, &store.relationships[&id], now))
let rel = &store.relationships[&id];
log::info!("friends: request sent to {} via {}", if rel.username.is_empty() { &rel.their_key } else { &rel.username }, rel.carry);
Ok(view_of(&id, rel, now))
}
/// Ask a Soulseek account to be friends. Needs their verified link — the
/// request is addressed to a KEY.
pub async fn request(app: &tauri::AppHandle, username: &str) -> Result<RelationshipView, String> {
let link = slsk_link::known_link(app, username)
.ok_or("verify their SoulStream ID first (the drawer's Ask button)")?;
start_request(app, key_of(&link.persona_key)?, link.username.clone()).await
}
/// Ask a SoulStream ID directly — only through their inbox.
pub async fn request_by_key(app: &tauri::AppHandle, persona_key: &str) -> Result<RelationshipView, String> {
let their = key_of(persona_key)?;
if !inbox::reachable(app, &their).await {
return Err("they have not published an inbox — reachable only through a Soulseek account".into());
}
let username = slsk_link::username_for_key(app, persona_key).unwrap_or_default();
start_request(app, their, username).await
}
/// Accept an incoming request: sign our assertion, send it, remember it.
/// Friendship is still one-sided until their reciprocal assertion arrives.
pub async fn accept(app: &tauri::AppHandle, id: &str) -> Result<RelationshipView, String> {
let me = my_key(app).await?;
let mut store = load(app);
@@ -271,20 +329,8 @@ pub async fn accept(app: &tauri::AppHandle, id: &str) -> Result<RelationshipView
}
let their = key_of(&rel.their_key)?;
let now = now_secs();
let a = sign_assertion(
app,
fr::FriendAssertion {
relationship_id: rel.request.relationship_id,
signer: me,
peer: their,
request_hash: fr::request_hash(&rel.request),
accepted: true,
seq: now,
sig: vec![],
},
)
.await?;
send_pm(app, &rel.username, &encode(ASSERT_PREFIX, &a)?).await?;
let a = sign_assertion(app, assertion_for(rel, me, their, true, now)).await?;
deliver(app, rel, Cargo::FriendAssertion(a.clone()), encode(ASSERT_PREFIX, &a)?).await?;
rel.assertions.push(a);
rel.declined_by_me = false;
rel.updated_at = now;
@@ -299,7 +345,7 @@ pub async fn decline(app: &tauri::AppHandle, id: &str) -> Result<RelationshipVie
let now = now_secs();
rel.declined_by_me = true;
rel.updated_at = now;
let _ = send_pm(app, &rel.username, &format!("{DECLINE_PREFIX}{id}")).await;
let _ = deliver(app, rel, Cargo::FriendDecline(rel.request.relationship_id), format!("{DECLINE_PREFIX}{id}")).await;
let v = view_of(id, rel, now);
save(app, &store)?;
Ok(v)
@@ -313,20 +359,8 @@ pub async fn remove(app: &tauri::AppHandle, id: &str) -> Result<RelationshipView
let rel = store.relationships.get_mut(id).ok_or("no such relationship")?;
let their = key_of(&rel.their_key)?;
let now = now_secs();
let a = sign_assertion(
app,
fr::FriendAssertion {
relationship_id: rel.request.relationship_id,
signer: me,
peer: their,
request_hash: fr::request_hash(&rel.request),
accepted: false,
seq: now,
sig: vec![],
},
)
.await?;
let _ = send_pm(app, &rel.username, &encode(ASSERT_PREFIX, &a)?).await;
let a = sign_assertion(app, assertion_for(rel, me, their, false, now)).await?;
let _ = deliver(app, rel, Cargo::FriendAssertion(a.clone()), encode(ASSERT_PREFIX, &a)?).await;
rel.assertions.push(a);
rel.updated_at = now;
let v = view_of(id, rel, now);
@@ -354,87 +388,112 @@ pub fn list(app: &tauri::AppHandle) -> Vec<RelationshipView> {
// ---------------------------------------------------------------- incoming
async fn on_request(app: tauri::AppHandle, from: String, req: fr::FriendRequest) {
/// Who a message came from, as far as its carry can vouch.
enum From {
/// A Soulseek account the server attributed.
Pm(String),
/// A persona key that signed the envelope header.
Inbox([u8; 32]),
}
async fn store_request(app: &tauri::AppHandle, from: From, req: fr::FriendRequest) {
if !fr::verify_request(&req) {
log::warn!("friends: request from {from} does not verify");
log::warn!("friends: a request does not verify");
return;
}
let Ok(me) = my_key(&app).await else {
log::debug!("friends: request from {from}, but no persona here to receive it");
let Ok(me) = my_key(app).await else {
log::debug!("friends: a request arrived, but no persona is here to receive it");
return;
};
if req.recipient != me {
log::debug!("friends: request from {from} is addressed to another persona");
return;
}
let now = now_secs();
if now > req.expires_at {
return;
}
// The request names a key; the sender must prove it is theirs.
let bound = match slsk_link::known_link(&app, &from) {
Some(l) if l.persona_key == b58(&req.sender) => Some(l),
_ => match slsk_link::ask(&app, &from).await {
Ok(l) if l.persona_key == b58(&req.sender) => {
slsk_link::remember(&app, l.clone());
Some(l)
// Bind the request's key to whoever sent it.
let (username, carry) = match from {
From::Inbox(sender) => {
if sender != req.sender {
log::warn!("friends: an inbox request names a key other than its envelope's signer");
return;
}
Ok(_) => {
log::warn!("friends: {from} proved a different key than the request names");
None
}
Err(e) => {
log::warn!("friends: could not bind {from} to the request's key: {e}");
None
}
},
(slsk_link::username_for_key(app, &b58(&sender)).unwrap_or_default(), "inbox")
}
From::Pm(from) => {
let bound = match slsk_link::known_link(app, &from) {
Some(l) if l.persona_key == b58(&req.sender) => Some(l),
_ => match slsk_link::ask(app, &from).await {
Ok(l) if l.persona_key == b58(&req.sender) => {
slsk_link::remember(app, l.clone());
Some(l)
}
Ok(_) => {
log::warn!("friends: {from} proved a different key than the request names");
None
}
Err(e) => {
log::warn!("friends: could not bind {from} to the request's key: {e}");
None
}
},
};
let Some(link) = bound else { return };
(link.username, "pm")
}
};
let Some(link) = bound else { return };
let id = b58(&req.relationship_id);
let mut store = load(&app);
let mut store = load(app);
if store.relationships.contains_key(&id) {
return;
}
let who = if username.is_empty() { b58(&req.sender) } else { username.clone() };
store.relationships.insert(
id,
Relationship {
username: link.username,
username_normalized: link.username_normalized,
their_key: link.persona_key,
username_normalized: normalize_username(&username),
username,
their_key: b58(&req.sender),
my_key: b58(&me),
request: req,
request_from_me: false,
assertions: vec![],
declined_by_me: false,
declined_by_them: false,
carry: carry.into(),
created_at: now,
updated_at: now,
},
);
if let Err(e) = save(&app, &store) {
log::warn!("friends: could not store the request from {from}: {e}");
if let Err(e) = save(app, &store) {
log::warn!("friends: could not store the request from {who}: {e}");
} else {
log::info!("friends: request from {from} verified and waiting");
log::info!("friends: request from {who} verified and waiting (via {carry})");
}
}
async fn on_assertion(app: tauri::AppHandle, from: String, a: fr::FriendAssertion) {
async fn apply_assertion(app: &tauri::AppHandle, from: From, a: fr::FriendAssertion) {
if !fr::verify_assertion(&a) {
log::warn!("friends: assertion from {from} does not verify");
log::warn!("friends: an assertion does not verify");
return;
}
let id = b58(&a.relationship_id);
let mut store = load(&app);
let mut store = load(app);
let Some(rel) = store.relationships.get_mut(&id) else {
log::debug!("friends: assertion from {from} for an unknown relationship");
log::debug!("friends: assertion for an unknown relationship");
return;
};
if normalize_username(&from) != rel.username_normalized
let sender_ok = match &from {
From::Pm(u) => normalize_username(u) == rel.username_normalized,
From::Inbox(k) => b58(k) == rel.their_key,
};
if !sender_ok
|| b58(&a.signer) != rel.their_key
|| b58(&a.peer) != rel.my_key
|| a.request_hash != fr::request_hash(&rel.request)
{
log::warn!("friends: assertion from {from} does not belong to its relationship");
log::warn!("friends: an assertion does not belong to its relationship");
return;
}
if rel
@@ -447,27 +506,17 @@ async fn on_assertion(app: tauri::AppHandle, from: String, a: fr::FriendAssertio
let now = now_secs();
rel.assertions.push(a.clone());
rel.updated_at = now;
if let From::Inbox(_) = from {
rel.carry = "inbox".into();
}
// Their acceptance of OUR request completes with our own assertion.
let mine_exists = rel.assertions.iter().any(|x| b58(&x.signer) == rel.my_key);
if a.accepted && rel.request_from_me && !mine_exists {
if let (Ok(me), Ok(their)) = (key_of(&rel.my_key), key_of(&rel.their_key)) {
match sign_assertion(
&app,
fr::FriendAssertion {
relationship_id: rel.request.relationship_id,
signer: me,
peer: their,
request_hash: fr::request_hash(&rel.request),
accepted: true,
seq: now,
sig: vec![],
},
)
.await
{
match sign_assertion(app, assertion_for(rel, me, their, true, now)).await {
Ok(mine) => {
if let Ok(text) = encode(ASSERT_PREFIX, &mine) {
let _ = send_pm(&app, &rel.username, &text).await;
let _ = deliver(app, rel, Cargo::FriendAssertion(mine.clone()), text).await;
}
rel.assertions.push(mine);
}
@@ -476,17 +525,22 @@ async fn on_assertion(app: tauri::AppHandle, from: String, a: fr::FriendAssertio
}
}
let state = view_of(&id, rel, now).state;
if let Err(e) = save(&app, &store) {
log::warn!("friends: could not store the assertion from {from}: {e}");
let who = if rel.username.is_empty() { rel.their_key.clone() } else { rel.username.clone() };
if let Err(e) = save(app, &store) {
log::warn!("friends: could not store an assertion: {e}");
} else {
log::info!("friends: {from} → {state}");
log::info!("friends: {who} → {state}");
}
}
fn on_decline(app: &tauri::AppHandle, from: &str, id: &str) {
fn apply_decline(app: &tauri::AppHandle, from: From, id: &str) {
let mut store = load(app);
let Some(rel) = store.relationships.get_mut(id) else { return };
if normalize_username(from) != rel.username_normalized || !rel.request_from_me {
let sender_ok = match &from {
From::Pm(u) => normalize_username(u) == rel.username_normalized,
From::Inbox(k) => b58(k) == rel.their_key,
};
if !sender_ok || !rel.request_from_me {
return;
}
rel.declined_by_them = true;
@@ -494,6 +548,17 @@ fn on_decline(app: &tauri::AppHandle, from: &str, id: &str) {
let _ = save(app, &store);
}
/// Sealed cargo from inbox.rs: the envelope's signer is the sender.
pub(crate) async fn on_inbox_request(app: &tauri::AppHandle, sender: [u8; 32], req: fr::FriendRequest) {
store_request(app, From::Inbox(sender), req).await;
}
pub(crate) async fn on_inbox_assertion(app: &tauri::AppHandle, sender: [u8; 32], a: fr::FriendAssertion) {
apply_assertion(app, From::Inbox(sender), a).await;
}
pub(crate) fn on_inbox_decline(app: &tauri::AppHandle, sender: [u8; 32], id: [u8; 16]) {
apply_decline(app, From::Inbox(sender), &b58(&id));
}
/// The event pump hands every private message here after the link proof.
/// True means it was ours and must not surface in the Inbox. Requests and
/// assertions are handled on their own task (see the module note).
@@ -501,18 +566,20 @@ pub fn intercept_pm(app: &tauri::AppHandle, from: &str, message: &str) -> bool {
let msg = message.trim();
if let Some(rest) = msg.strip_prefix(REQ_PREFIX) {
if let Some(req) = decode::<fr::FriendRequest>(rest) {
tauri::async_runtime::spawn(on_request(app.clone(), from.to_string(), req));
let (app, from) = (app.clone(), from.to_string());
tauri::async_runtime::spawn(async move { store_request(&app, From::Pm(from), req).await });
}
return true;
}
if let Some(rest) = msg.strip_prefix(ASSERT_PREFIX) {
if let Some(a) = decode::<fr::FriendAssertion>(rest) {
tauri::async_runtime::spawn(on_assertion(app.clone(), from.to_string(), a));
let (app, from) = (app.clone(), from.to_string());
tauri::async_runtime::spawn(async move { apply_assertion(&app, From::Pm(from), a).await });
}
return true;
}
if let Some(rest) = msg.strip_prefix(DECLINE_PREFIX) {
on_decline(app, from, rest.trim());
apply_decline(app, From::Pm(from.to_string()), rest.trim());
return true;
}
false
@@ -529,6 +596,10 @@ pub async fn friend_request(app: tauri::AppHandle, username: String) -> Result<R
request(&app, &username).await
}
#[tauri::command]
pub async fn friend_request_by_key(app: tauri::AppHandle, persona_key: String) -> Result<RelationshipView, String> {
request_by_key(&app, &persona_key).await
}
#[tauri::command]
pub async fn friend_accept(app: tauri::AppHandle, id: String) -> Result<RelationshipView, String> {
accept(&app, &id).await
}