chore(client): checkpoint deployed features and unfinished server management

User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
This commit is contained in:
Loki 2026-11-01 15:31:21 +01:00
parent 15f03bf8df
commit f04691c3cd
Signed by: boba
GPG key ID: 253067914055423B
90 changed files with 9599 additions and 371 deletions

845
src/net/account.rs Normal file
View file

@ -0,0 +1,845 @@
//! Real Central browser sign-in and identity-bound account admission.
//!
//! Device/refresh secrets never enter browser URLs or logs. The identity private key
//! stays on this device; account proofs contain only the matching public key.
use crate::identity::Identity;
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{
path::PathBuf,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::sync::{mpsc, watch};
pub const CENTRAL_ORIGIN: &str = "https://central.loki-code.dev";
const MAX_RESPONSE: usize = 32 * 1024;
/// Enrollment is missing or revoked: another browser approval is required.
#[derive(Debug)]
pub struct SignInRequired;
impl std::fmt::Display for SignInRequired {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Central sign-in expired or was revoked; sign in again")
}
}
impl std::error::Error for SignInRequired {}
/// Public account details safe to show in desktop UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AccountSummary {
pub user_id: String,
pub handle: String,
pub display_name: String,
pub avatar_url: Option<String>,
#[serde(default)]
pub profile_complete: bool,
}
/// Non-secret, identity-scoped profile notification; credentials never enter UI events.
#[derive(Clone)]
pub struct ProfileUpdate {
pub proof: Option<Vec<u8>>,
pub epoch: u64,
pub public_key: String,
pub user: AccountSummary,
}
static ENROLLMENT_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub fn enrollment_epoch() -> u64 {
ENROLLMENT_EPOCH.load(std::sync::atomic::Ordering::SeqCst)
}
fn enrollment_changed() {
ENROLLMENT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
static PROFILE_UPDATES: std::sync::LazyLock<watch::Sender<Option<ProfileUpdate>>> =
std::sync::LazyLock::new(|| watch::channel(None).0);
static PROFILE_REQUESTS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static STORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub fn subscribe_profiles() -> watch::Receiver<Option<ProfileUpdate>> {
PROFILE_UPDATES.subscribe()
}
pub fn latest_profile() -> Option<ProfileUpdate> {
PROFILE_UPDATES.borrow().clone()
}
/// A pending login contains a bearer secret. Intentionally does not implement Debug.
pub struct PendingLogin {
pub verification_uri: String,
pub public_key: String,
pub expires_at: i64,
device_secret: String,
}
/// Sign-in progress, containing no device or refresh secret.
#[derive(Debug, Clone)]
pub enum LoginEvent {
ApprovalRequired {
verification_uri: String,
public_key: String,
expires_at: i64,
},
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StoredAccount {
version: u32,
public_key: String,
refresh_secret: String,
user: AccountSummary,
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
fn client() -> Result<reqwest::Client> {
Ok(reqwest::Client::builder()
.https_only(true)
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(10))
.user_agent("VNOX-Desktop/0.1")
.build()?)
}
async fn response_json(response: reqwest::Response) -> Result<Value> {
ensure!(
response.content_length().unwrap_or(0) <= MAX_RESPONSE as u64,
"Central response exceeds size limit"
);
let mut response = response;
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= MAX_RESPONSE,
"Central response exceeds size limit"
);
bytes.extend_from_slice(&chunk);
}
serde_json::from_slice(&bytes).context("Invalid response from Central")
}
async fn post(path: &str, body: &Value) -> Result<reqwest::Response> {
client()?
.post(format!("{CENTRAL_ORIGIN}{path}"))
.json(body)
.send()
.await
.context("Cannot reach Central; check your connection and retry")
}
fn field<'a>(value: &'a Value, key: &str) -> Result<&'a str> {
value
.get(key)
.and_then(Value::as_str)
.with_context(|| format!("Central response is missing {key}"))
}
fn validate_key(identity: &Identity) -> Result<()> {
let key = identity
.signing_key()
.context("Unlock your local identity before signing in")?;
ensure!(
hex::encode(key.verifying_key().to_bytes()) == identity.pubkey_hex,
"Local identity key mismatch"
);
Ok(())
}
/// Start a 10-minute pairing request. Open only its verification_uri in the browser.
pub async fn begin(identity: &Identity) -> Result<PendingLogin> {
validate_key(identity)?;
let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await;
let response = post(
"/v1/auth/desktop/start",
&json!({"public_key":identity.pubkey_hex}),
)
.await?;
ensure!(
response.status().is_success(),
"Central could not start sign-in; retry shortly"
);
let value = response_json(response).await?;
let uri = field(&value, "verification_uri")?.to_owned();
let parsed = reqwest::Url::parse(&uri)?;
ensure!(
parsed.origin().ascii_serialization() == CENTRAL_ORIGIN
&& parsed.path() == "/desktop"
&& parsed.username().is_empty()
&& parsed.password().is_none(),
"Central returned an invalid approval URL"
);
let expires_at = value
.get("expires_at")
.and_then(Value::as_i64)
.context("Missing sign-in expiry")?;
ensure!(
expires_at > now() && expires_at <= now() + 610,
"Invalid sign-in expiry"
);
let device_secret = field(&value, "device_secret")?.to_owned();
ensure!(
device_secret.len() == 64 && hex::decode(&device_secret).is_ok(),
"Invalid device request"
);
Ok(PendingLogin {
verification_uri: uri,
public_key: identity.pubkey_hex.clone(),
expires_at,
device_secret,
})
}
/// Poll once. Call at most once per five seconds. Approved requests are single-use.
pub async fn poll(pending: &PendingLogin, identity: &Identity) -> Result<Option<AccountSummary>> {
ensure!(
pending.public_key == identity.pubkey_hex,
"Identity changed during sign-in"
);
ensure!(pending.expires_at > now(), "Sign-in expired; start again");
let response = post(
"/v1/auth/desktop/poll",
&json!({"device_secret":pending.device_secret}),
)
.await?;
if response.status() == reqwest::StatusCode::ACCEPTED {
return Ok(None);
}
ensure!(
response.status().is_success(),
"Sign-in expired or was canceled; start again"
);
let value = response_json(response).await?;
validate_proof(&value, identity)?;
let user: AccountSummary = serde_json::from_value(
value
.get("user")
.cloned()
.context("Missing Central account")?,
)?;
let refresh_secret = field(&value, "refresh_secret")?.to_owned();
ensure!(
refresh_secret.len() == 64 && hex::decode(&refresh_secret).is_ok(),
"Invalid Central enrollment"
);
save(&StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret,
user: user.clone(),
})?;
Ok(Some(user))
}
/// Cancel a pending pairing. Expiry remains enforced if Central is unreachable.
pub async fn cancel(pending: &PendingLogin) -> Result<()> {
let response = post(
"/v1/auth/desktop/cancel",
&json!({"device_secret":pending.device_secret}),
)
.await?;
ensure!(
response.status().is_success(),
"Could not cancel sign-in at Central"
);
Ok(())
}
/// Run the complete cancellable device flow. The UI opens the URL from LoginEvent.
/// Sending true on cancel stops polling and attempts server-side cancellation.
pub async fn sign_in(
identity: &Identity,
updates: mpsc::UnboundedSender<LoginEvent>,
mut cancellation: watch::Receiver<bool>,
) -> Result<AccountSummary> {
ensure!(!*cancellation.borrow(), "Sign-in canceled");
let pending = begin(identity).await?;
if updates
.send(LoginEvent::ApprovalRequired {
verification_uri: pending.verification_uri.clone(),
public_key: pending.public_key.clone(),
expires_at: pending.expires_at,
})
.is_err()
{
let _ = cancel(&pending).await;
bail!("Sign-in window closed");
}
loop {
tokio::select! {
_=tokio::time::sleep(Duration::from_secs(5))=>{},
_=cancellation.changed()=>{
let _=cancel(&pending).await;
bail!("Sign-in canceled");
}
}
if *cancellation.borrow() {
let _ = cancel(&pending).await;
bail!("Sign-in canceled");
}
// Cancel in-flight polls too. Hub cancellation also revokes a consumed
// enrollment if the approved HTTP reply was lost.
let approved = tokio::select! {
result=poll(&pending,identity)=>match result {
Ok(approved)=>approved,
Err(error)=>{let _=cancel(&pending).await;return Err(error)}
},
_=cancellation.changed()=>{
let _=cancel(&pending).await;
bail!("Sign-in canceled");
}
};
if let Some(user) = approved {
if *cancellation.borrow() {
let cleared = clear();
let _ = cancel(&pending).await;
cleared?;
bail!("Sign-in canceled");
}
return Ok(user);
}
}
}
/// Locally enrolled account for UI startup. Admission always refreshes online.
pub fn current(identity: &Identity) -> Result<Option<AccountSummary>> {
Ok(load(identity)?.map(|stored| stored.user))
}
/// Revoke enrollment and remove local credentials. Disconnect gateway sessions in UI
/// before calling this function; admission proofs expire within ten minutes.
pub async fn sign_out(identity: &Identity) -> Result<()> {
let stored = match load(identity) {
Ok(stored) => stored,
Err(error) => {
clear()?;
return Err(error);
}
};
if let Some(stored) = stored {
// Rename atomically disables admission while preserving the secret needed to
// retry revocation after an outage. Tombstones are never loaded for admission.
let tombstone = {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
let current = load(identity)?.ok_or(SignInRequired)?;
ensure!(
current.refresh_secret == stored.refresh_secret,
"Central enrollment changed during sign-out"
);
let tombstone = queue_revocation(&path())?;
enrollment_changed();
tombstone
};
revoke_secret(&stored.refresh_secret).await?;
std::fs::remove_file(tombstone)?;
} else {
clear()?;
}
Ok(())
}
async fn revoke_secret(secret: &str) -> Result<()> {
let response = post("/v1/auth/desktop/revoke", &json!({"refresh_secret":secret})).await?;
ensure!(
response.status().is_success(),
"Signed out locally; Central revocation is queued for retry"
);
Ok(())
}
fn queue_revocation(active: &std::path::Path) -> Result<PathBuf> {
let directory = active.parent().context("Missing account directory")?;
let tombstone = directory.join(format!("pending-revocation-{}.json", uuid::Uuid::new_v4()));
std::fs::rename(active, &tombstone)?;
#[cfg(unix)]
std::fs::File::open(directory)?.sync_all()?;
Ok(tombstone)
}
/// Retry admission-disabled revocations left by a previous offline sign-out. Callers
/// bound the total attempt time; retries are safe because Hub revocation is idempotent.
pub async fn retry_revocations() -> Result<()> {
let active = path();
let Some(directory) = active.parent() else {
return Ok(());
};
let entries = match std::fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
};
for entry in entries.take(64) {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if !name.starts_with("pending-revocation-") || !name.ends_with(".json") {
continue;
}
let file = std::fs::File::open(entry.path())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"Revocation credentials must remain private"
);
}
ensure!(
file.metadata()?.len() <= MAX_RESPONSE as u64,
"Revocation credentials too large"
);
let stored: StoredAccount = serde_json::from_reader(file)?;
revoke_secret(&stored.refresh_secret).await?;
std::fs::remove_file(entry.path())?;
}
Ok(())
}
/// Obtain a fresh identity-bound signed proof for every gateway admission. Missing or
/// revoked enrollment and Central outage fail closed; no anonymous fallback exists.
pub async fn admission_proof(identity: &Identity) -> Result<Vec<u8>> {
validate_key(identity)?;
let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await;
let value = refresh(identity).await?;
validate_proof(&value, identity)
}
/// Refresh public profile at startup/settings entry and periodically; also refresh admission.
pub async fn refresh_profile(identity: &Identity) -> Result<AccountSummary> {
let value = refresh(identity).await?;
summary(&value, identity, true)
}
async fn refresh(identity: &Identity) -> Result<Value> {
let _request = PROFILE_REQUESTS.lock().await;
validate_key(identity)?;
let stored = load(identity)?.ok_or(SignInRequired)?;
let response = post(
"/v1/auth/desktop/refresh",
&json!({"refresh_secret":stored.refresh_secret}),
)
.await?;
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignInRequired.into());
}
ensure!(
response.status().is_success(),
"Central could not refresh your profile; retry shortly"
);
let value = response_json(response).await?;
let proof = validate_proof(&value, identity)?;
let user = summary(&value, identity, true)?;
update_summary(identity, &stored, user, Some(proof))?;
Ok(value)
}
fn summary(value: &Value, identity: &Identity, proof_required: bool) -> Result<AccountSummary> {
let user: AccountSummary = serde_json::from_value(
value
.get("user")
.cloned()
.context("Missing Central account")?,
)?;
ensure!(
uuid::Uuid::parse_str(&user.user_id).is_ok_and(|id| !id.is_nil()),
"Invalid Central account"
);
ensure!(
!user.display_name.trim().is_empty() && user.display_name.chars().count() <= 64,
"Invalid Central profile name"
);
if proof_required {
let claim: Value = serde_json::from_slice(&hex::decode(field(
value
.get("account_proof")
.context("Missing account proof")?,
"claims",
)?)?)?;
ensure!(
field(&claim, "subject")? == user.user_id
&& field(&claim, "public_key")? == identity.pubkey_hex,
"Central profile does not match admission proof"
);
}
Ok(user)
}
fn update_summary(
identity: &Identity,
enrolled: &StoredAccount,
user: AccountSummary,
proof: Option<Vec<u8>>,
) -> Result<()> {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
update_summary_at(&path(), identity, enrolled, user.clone())?;
PROFILE_UPDATES.send_replace(Some(ProfileUpdate {
proof,
epoch: enrollment_epoch(),
public_key: identity.pubkey_hex.clone(),
user,
}));
Ok(())
}
fn update_summary_at(
account_path: &std::path::Path,
identity: &Identity,
enrolled: &StoredAccount,
user: AccountSummary,
) -> Result<()> {
ensure!(
user.user_id == enrolled.user.user_id,
"Central account changed unexpectedly"
);
let mut current = load_at(account_path, identity)?.ok_or(SignInRequired)?;
ensure!(
current.refresh_secret == enrolled.refresh_secret,
"Central enrollment changed during request"
);
current.user = user;
save_at(account_path, &current)
}
/// Save a cropped PNG to the enrolled Central account, or remove its custom photo.
pub async fn set_avatar(
identity: &Identity,
png: Option<Vec<u8>>,
epoch: u64,
) -> Result<AccountSummary> {
let method = if png.is_some() {
reqwest::Method::POST
} else {
reqwest::Method::DELETE
};
mutation(
identity,
"/v1/auth/desktop/avatar",
method,
png.unwrap_or_default(),
"image/png",
epoch,
)
.await
}
/// Set the account's display name without changing its unique handle or device keys.
pub async fn set_display_name(
identity: &Identity,
name: &str,
epoch: u64,
) -> Result<AccountSummary> {
mutation(
identity,
"/v1/auth/desktop/profile",
reqwest::Method::POST,
serde_json::to_vec(&json!({"display_name":name}))?,
"application/json",
epoch,
)
.await
}
async fn mutation(
identity: &Identity,
path: &str,
method: reqwest::Method,
body: Vec<u8>,
content_type: &str,
epoch: u64,
) -> Result<AccountSummary> {
use ed25519_dalek::Signer;
use sha2::{Digest, Sha256};
let _request = PROFILE_REQUESTS.lock().await;
ensure!(
epoch == enrollment_epoch(),
"Account changed; choose your profile again"
);
validate_key(identity)?;
let stored = load(identity)?.ok_or(SignInRequired)?;
ensure!(
body.len() <= 2 * 1024 * 1024,
"Profile upload exceeds size limit"
);
let timestamp = now().to_string();
let mut transcript = b"VNOX-CENTRAL-PROFILE-v1\0".to_vec();
transcript.extend_from_slice(method.as_str().as_bytes());
transcript.push(0);
transcript.extend_from_slice(path.as_bytes());
transcript.push(0);
transcript.extend_from_slice(timestamp.as_bytes());
transcript.push(0);
transcript.extend_from_slice(&Sha256::digest(&body));
let signature = identity
.signing_key()
.context("Unlock your identity to change your profile")?
.sign(&transcript);
let response = client()?
.request(method, format!("{CENTRAL_ORIGIN}{path}"))
.bearer_auth(&stored.refresh_secret)
.header("x-vnox-public-key", &identity.pubkey_hex)
.header("x-vnox-timestamp", timestamp)
.header("x-vnox-signature", hex::encode(signature.to_bytes()))
.header(reqwest::header::CONTENT_TYPE, content_type)
.body(body)
.send()
.await
.context("Cannot reach Central; profile was not changed")?;
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignInRequired.into());
}
if !response.status().is_success() {
let error = response_json(response).await.unwrap_or_default();
bail!(match error.get("error").and_then(Value::as_str) {
Some("invalid_display_name") =>
"Display name must contain 1–64 characters without control characters",
Some("too_large") => "Photo is too large to upload",
Some("invalid_image" | "unsupported_type") =>
"Central could not read this photo; choose another PNG",
Some("try_later") => "Too many profile changes or Central is busy; retry shortly",
_ => "Central could not update your profile; retry shortly",
});
}
let value = response_json(response).await?;
let user = summary(&value, identity, false)?;
update_summary(identity, &stored, user.clone(), None)?;
Ok(user)
}
fn validate_proof(value: &Value, identity: &Identity) -> Result<Vec<u8>> {
let proof = value
.get("account_proof")
.context("Missing Central account proof")?;
let claims = hex::decode(field(proof, "claims")?).context("Invalid account proof")?;
ensure!(claims.len() <= 4096, "Account proof too large");
let claim: Value = serde_json::from_slice(&claims)?;
ensure!(
field(&claim, "public_key")? == identity.pubkey_hex,
"Central proof belongs to another local identity"
);
ensure!(
field(&claim, "audience")? == "vnox-gateway"
&& claim.get("version").and_then(Value::as_u64) == Some(1),
"Invalid Central proof audience or version"
);
ensure!(
uuid::Uuid::parse_str(field(&claim, "subject")?).is_ok()
&& uuid::Uuid::parse_str(field(&claim, "issuer")?).is_ok(),
"Invalid Central proof identity"
);
let issued = claim
.get("issued_at")
.and_then(Value::as_i64)
.context("Missing proof issue time")?;
let expires = claim
.get("expires_at")
.and_then(Value::as_i64)
.context("Missing proof expiry")?;
ensure!(
issued <= now()
&& expires > now()
&& expires
.checked_sub(issued)
.is_some_and(|ttl| ttl > 0 && ttl <= 600),
"Central account proof expired or has invalid lifetime"
);
ensure!(
hex::decode(field(proof, "signature")?).is_ok_and(|s| s.len() == 64),
"Invalid account proof signature encoding"
);
let bytes = serde_json::to_vec(proof)?;
ensure!(bytes.len() <= 8192, "Account proof too large");
Ok(bytes)
}
fn path() -> PathBuf {
dirs::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("vnox")
.join("account")
.join("central.json")
}
fn load(identity: &Identity) -> Result<Option<StoredAccount>> {
load_at(&path(), identity)
}
fn load_at(account_path: &std::path::Path, identity: &Identity) -> Result<Option<StoredAccount>> {
let file = match std::fs::File::open(account_path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"Central account credentials must use private 0600 permissions"
);
}
ensure!(
file.metadata()?.len() <= MAX_RESPONSE as u64,
"Account credentials too large"
);
let stored: StoredAccount =
serde_json::from_reader(file).context("Invalid saved Central account; sign in again")?;
ensure!(stored.version == 1, "Unsupported account credentials");
if stored.public_key != identity.pubkey_hex {
return Ok(None);
}
Ok(Some(stored))
}
fn save(stored: &StoredAccount) -> Result<()> {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
save_unlocked(stored)?;
enrollment_changed();
Ok(())
}
fn save_unlocked(stored: &StoredAccount) -> Result<()> {
save_at(&path(), stored)
}
fn save_at(path: &std::path::Path, stored: &StoredAccount) -> Result<()> {
let directory = path.parent().context("Missing credential directory")?;
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(directory)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
std::fs::metadata(directory)?.permissions().mode() & 0o077 == 0,
"Central credential directory must use private 0700 permissions"
);
}
let temporary = directory.join(format!("{}.tmp", uuid::Uuid::new_v4()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let result = (|| -> Result<()> {
use std::io::Write;
let mut file = options.open(&temporary)?;
file.write_all(&serde_json::to_vec(stored)?)?;
file.sync_all()?;
std::fs::rename(&temporary, path)?;
#[cfg(unix)]
std::fs::File::open(directory)?.sync_all()?;
Ok(())
})();
let _ = std::fs::remove_file(&temporary);
result
}
fn clear() -> Result<()> {
match std::fs::remove_file(path()) {
Ok(()) => {
enrollment_changed();
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn response(identity: &Identity, issued: i64, expires: i64) -> Value {
let claim = json!({"version":1,"issuer":uuid::Uuid::new_v4().to_string(),"subject":uuid::Uuid::new_v4().to_string(),"public_key":identity.pubkey_hex,"audience":"vnox-gateway","issued_at":issued,"expires_at":expires});
json!({"account_proof":{"claims":hex::encode(serde_json::to_vec(&claim).unwrap()),"signature":"00".repeat(64)}})
}
#[test]
fn refreshed_website_avatar_is_persisted_and_stale_enrollment_cannot_restore_it() {
let identity = crate::identity::generate("profile");
let directory =
std::env::temp_dir().join(format!("vnox-profile-test-{}", uuid::Uuid::new_v4()));
let path = directory.join("central.json");
let original = StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret: "01".repeat(32),
user: AccountSummary {
user_id: uuid::Uuid::new_v4().to_string(),
handle: "profile".into(),
display_name: "Old Name".into(),
avatar_url: Some("/v1/avatars/old".into()),
profile_complete: false,
},
};
save_at(&path, &original).unwrap();
let mut fresh = original.user.clone();
fresh.avatar_url = Some("/v1/avatars/new".into());
fresh.display_name = "New Name".into();
update_summary_at(&path, &identity, &original, fresh.clone()).unwrap();
assert_eq!(load_at(&path, &identity).unwrap().unwrap().user, fresh);
let mut replacement = original;
replacement.refresh_secret = "02".repeat(32);
save_at(&path, &replacement).unwrap();
let mut old_request = replacement.user.clone();
old_request.avatar_url = Some("/v1/avatars/stale".into());
let mut stale = StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret: "01".repeat(32),
user: replacement.user.clone(),
};
assert!(update_summary_at(&path, &identity, &stale, old_request.clone()).is_err());
assert_eq!(
load_at(&path, &identity).unwrap().unwrap().user,
replacement.user
);
stale.refresh_secret = replacement.refresh_secret;
std::fs::remove_file(&path).unwrap();
assert!(update_summary_at(&path, &identity, &stale, old_request).is_err());
assert!(
!path.exists(),
"sign-out must not be undone by late refresh"
);
std::fs::remove_dir(directory).unwrap();
}
#[test]
fn queued_revocation_atomically_disables_admission_and_preserves_retry_secret() {
let directory =
std::env::temp_dir().join(format!("vnox-revoke-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&directory).unwrap();
let active = directory.join("central.json");
std::fs::write(&active, b"retry secret").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&active, std::fs::Permissions::from_mode(0o600)).unwrap();
}
let tombstone = queue_revocation(&active).unwrap();
assert!(!active.exists());
assert_eq!(std::fs::read(&tombstone).unwrap(), b"retry secret");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&tombstone).unwrap().permissions().mode() & 0o077,
0
);
}
std::fs::remove_file(tombstone).unwrap();
std::fs::remove_dir(directory).unwrap();
}
#[test]
fn rejects_other_identity_expiry_and_overlong_proof() {
let identity = crate::identity::generate("test");
let t = now();
assert!(validate_proof(&response(&identity, t, t + 600), &identity).is_ok());
assert!(
validate_proof(
&response(&identity, t, t + 600),
&crate::identity::generate("other")
)
.is_err()
);
assert!(validate_proof(&response(&identity, t - 601, t - 1), &identity).is_err());
assert!(validate_proof(&response(&identity, t, t + 601), &identity).is_err());
assert!(validate_proof(&response(&identity, t + 60, t + 600), &identity).is_err());
}
}

47
src/net/forum.rs Normal file
View file

@ -0,0 +1,47 @@
//! Capability-gated forum packets. Errors retain request correlation and never cancel voice joins.
use super::{framing, payloads::PID_FORUM_REQUEST, types::NetEvent, wire};
use tokio::io::AsyncWrite;
use tokio::sync::mpsc;
pub fn is_mutation(request: &wire::ForumRequest) -> bool {
matches!(wire::ForumOperation::try_from(request.operation), Ok(wire::ForumOperation::Create | wire::ForumOperation::Reply))
}
pub async fn unsupported(request: &wire::ForumRequest, events: &mpsc::Sender<NetEvent>) {
error(request, "This server does not support forums yet.", events).await;
}
pub async fn error(request: &wire::ForumRequest, message: &str, events: &mpsc::Sender<NetEvent>) {
let _ = events.send(NetEvent::ForumResult(wire::ForumResult {
request_id: request.request_id.clone(), operation: request.operation,
channel_id: request.channel_id.clone(), topic_id: request.topic_id.clone(),
error_code: u32::MAX, error: message.into(),
..Default::default()
})).await;
}
pub async fn write(stream: &mut (impl AsyncWrite + Unpin), seq: &mut u32, request: &wire::ForumRequest) -> anyhow::Result<()> {
framing::write(stream, PID_FORUM_REQUEST, seq, &wire::encode(request)?).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn unsupported_server_returns_correlated_forum_error_without_join_error() {
let (tx, mut rx) = mpsc::channel(1);
let request = wire::ForumRequest { request_id: "request".into(), channel_id: "forum".into(), topic_id: "topic".into(), operation: wire::ForumOperation::Open as i32, ..Default::default() };
unsupported(&request, &tx).await;
let NetEvent::ForumResult(result) = rx.recv().await.unwrap() else { panic!("forum errors must stay separate from join errors") };
assert_eq!(result.request_id, "request"); assert_eq!(result.channel_id, "forum"); assert_eq!(result.topic_id, "topic"); assert_ne!(result.error_code, 0);
}
#[tokio::test]
async fn request_wire_keeps_topic_message_and_pagination_fields() {
let request = wire::ForumRequest { request_id: "request".into(), operation: wire::ForumOperation::Create as i32, channel_id: "forum".into(), topic_id: "topic".into(), message_id: "message".into(), title: "Title".into(), content: "First post".into(), offset: 12, limit: 20 };
let (mut sender, mut receiver) = tokio::io::duplex(4096);
write(&mut sender, &mut 0, &request).await.unwrap();
let packet = framing::read(&mut receiver).await.unwrap();
assert_eq!(packet.packet_id, PID_FORUM_REQUEST);
let decoded: wire::ForumRequest = wire::decode(&packet.payload).unwrap();
assert_eq!(decoded, request); assert!(is_mutation(&decoded));
}
}

View file

@ -8,8 +8,8 @@ use super::payloads::*;
use super::trust::TransportError;
use crate::identity::Identity;
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0";
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0";
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v4-server-hello\0";
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v4-client-auth\0";
/// Bytes signed by the server identity: context, TLS exporter, HELLO without signature.
pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec<u8> {
@ -40,6 +40,11 @@ pub struct Outcome {
pub session_id: String,
pub node_name: String,
pub private_mode: bool,
pub node_admin: bool,
pub live_profiles: bool,
pub node_settings: bool,
pub channel_structure: bool,
pub forums: bool,
/// Lower-case hex Ed25519 identity of the server.
pub server_identity: String,
}
@ -56,6 +61,27 @@ pub async fn run(
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
) -> Result<Outcome> {
run_inner(
stream,
identity,
seq,
binding,
trust_key,
expected_identity,
None,
)
.await
}
async fn run_inner(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
identity: &Identity,
seq: &mut u32,
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
supplied_proof: Option<Vec<u8>>,
) -> Result<Outcome> {
// HELLO
let pkt = framing::read(stream).await?;
@ -117,11 +143,20 @@ pub async fn run(
.ok_or_else(|| anyhow!("no signing key"))?;
use ed25519_dalek::Signer;
let account_proof = match supplied_proof {
Some(proof) => proof,
None => crate::net::account::admission_proof(identity).await?,
};
anyhow::ensure!(
!account_proof.is_empty(),
"Central account sign-in required"
);
let mut auth = AuthPayload {
client_pubkey: sk.verifying_key().to_bytes().to_vec(),
nickname: identity.nickname.clone(),
lnex_version: LNEX_VERSION.into(),
signature: Vec::new(),
account_proof,
};
let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?);
auth.signature = sk.sign(&transcript).to_bytes().to_vec();
@ -154,6 +189,11 @@ pub async fn run(
session_id: sess.session_id,
node_name: hello.node_name,
private_mode: hello.private_mode,
node_admin: sess.node_admin,
live_profiles: sess.live_profiles,
node_settings: sess.node_settings,
channel_structure: sess.channel_structure,
forums: sess.forums,
server_identity,
})
}
@ -164,6 +204,26 @@ mod tests {
use ed25519_dalek::{Signer, SigningKey};
use tokio::io::AsyncWriteExt;
async fn run_for_test(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
identity: &Identity,
seq: &mut u32,
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
) -> Result<Outcome> {
run_inner(
stream,
identity,
seq,
binding,
trust_key,
expected_identity,
Some(b"test-account-proof".to_vec()),
)
.await
}
/// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets.
async fn fake_server(
mut stream: tokio::io::DuplexStream,
@ -199,6 +259,8 @@ mod tests {
session_id: "session-1".into(),
token: "token".into(),
expires_at: 0,
node_admin: false,
live_profiles: false,
};
framing::write(
&mut stream,
@ -221,9 +283,9 @@ mod tests {
async fn authenticated_handshake_returns_server_identity_and_binds_signature() {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true));
let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v4", true));
let mut seq = 0;
let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None)
let outcome = run_for_test(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None)
.await
.unwrap();
assert_eq!(outcome.session_id, "session-1");
@ -233,6 +295,7 @@ mod tests {
);
// The AUTH signature is valid for this connection and invalid for any other one.
let (auth, signed_hello) = task.await.unwrap();
assert_eq!(auth.account_proof, b"test-account-proof");
let client_public = ed25519_dalek::VerifyingKey::from_bytes(
&auth.client_pubkey.clone().try_into().unwrap(),
)
@ -263,9 +326,9 @@ mod tests {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
// The relay forwards a HELLO signed for a different TLS session.
tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false));
tokio::spawn(fake_server(server, server_key, [1; 32], "v4", false));
let mut seq = 0;
let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None)
let error = run_for_test(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None)
.await
.unwrap_err();
assert!(error.to_string().contains("signature verification failed"));
@ -276,9 +339,9 @@ mod tests {
async fn changed_server_identity_is_blocked_before_auth() {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false));
tokio::spawn(fake_server(server, server_key, [3; 32], "v4", false));
let mut seq = 0;
let error = run(
let error = run_for_test(
&mut client,
&identity(),
&mut seq,
@ -301,12 +364,59 @@ mod tests {
let (mut client, server) = tokio::io::duplex(8192);
tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false));
let mut seq = 0;
let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None)
let error = run_for_test(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None)
.await
.unwrap_err();
assert!(matches!(
error.downcast_ref::<TransportError>(),
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3")
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v4")
));
}
#[tokio::test]
async fn empty_account_proof_is_rejected_before_auth() {
let key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
let task = tokio::spawn(fake_server(server, key, [9; 32], "v4", false));
let mut seq = 0;
let error = run_inner(
&mut client,
&identity(),
&mut seq,
&[9; 32],
"h:7600",
None,
Some(Vec::new()),
)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("Central account sign-in required")
);
assert_eq!(seq, 0);
drop(client);
task.await.unwrap();
}
}
#[cfg(test)]
mod capability_tests {
use super::*;
#[test]
fn legacy_sessions_do_not_advertise_admin_and_new_flag_roundtrips() {
let legacy: SessionPayload = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap();
assert!(!legacy.node_admin);
assert!(!legacy.live_profiles);
let mut privileged = legacy;
privileged.node_admin = true;
privileged.live_profiles = true;
let bytes = wire::encode(&privileged).unwrap();
assert!(wire::decode::<SessionPayload>(&bytes).unwrap().node_admin);
assert!(
wire::decode::<SessionPayload>(&bytes)
.unwrap()
.live_profiles
);
}
}

View file

@ -8,6 +8,11 @@ use super::super::super::types::{ChannelListItem as InfoChannelListItem, ChatMsg
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
match pid {
PID_ATTACHMENT_RESULT => {
let _ = tx
.send(NetEvent::AttachmentResult(wire::decode(payload)?))
.await;
}
PID_CHANNEL_STATE => {
let p: ChannelStatePayload = wire::decode(payload)?;
let _ = tx
@ -22,10 +27,14 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
user_id: m.user_id,
nickname: m.nickname,
in_voice: m.in_voice,
account_id: m.account_id,
avatar_url: m.avatar_url,
})
.collect(),
voice_endpoint: p.voice_endpoint,
guild_id: p.guild_id,
parent_id: p.parent_id,
position: p.position,
})
.await;
}
@ -37,6 +46,18 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
channel_name: p.channel_name,
kind: p.kind,
guild_id: p.guild_id,
parent_id: p.parent_id,
position: p.position,
})
.await;
}
PID_CHANNEL_EDIT => {
let p: ChannelEditPayload = wire::decode(payload)?;
let _ = tx
.send(NetEvent::ChannelEdited {
channel_id: p.channel_id,
channel_name: p.channel_name,
parent_id: p.parent_id, position: p.position,
})
.await;
}
@ -60,6 +81,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
channel_name: c.channel_name,
kind: c.kind,
guild_id: c.guild_id,
parent_id: c.parent_id, position: c.position,
})
.collect(),
})
@ -102,6 +124,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
let p: UserJoinPayload = wire::decode(payload)?;
let _ = tx
.send(NetEvent::UserJoin {
account_id: p.account_id,
avatar_url: p.avatar_url,
channel_id: p.channel_id,
user_id: p.user_id,
nickname: p.nickname,
@ -160,3 +184,59 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
}
Ok(())
}
#[cfg(test)]
mod profile_tests {
use super::*;
use prost::Message;
#[tokio::test]
async fn central_account_profile_reaches_client_join_event() {
let (tx, mut rx) = mpsc::channel(1);
let message = UserJoinPayload {
channel_id: "general".into(),
user_id: "device-key".into(),
nickname: "Central Name".into(),
account_id: "account-id".into(),
avatar_url: "/v1/avatars/default/account-id".into(),
};
handle(PID_USER_JOIN, &message.encode_to_vec(), &tx)
.await
.unwrap();
match rx.recv().await.unwrap() {
NetEvent::UserJoin {
user_id,
account_id,
avatar_url,
nickname,
..
} => {
assert_eq!(user_id, "device-key");
assert_eq!(account_id, "account-id");
assert_eq!(nickname, "Central Name");
assert_eq!(avatar_url, "/v1/avatars/default/account-id");
}
other => panic!("unexpected {other:?}"),
}
}
}
#[cfg(test)]
mod channel_edit_tests {
use super::*;
#[tokio::test]
async fn existing_channel_edit_packet_reaches_named_event() {
let (tx, mut rx) = mpsc::channel(1);
let bytes = wire::encode(&ChannelEditPayload {
channel_id: "global".into(),
channel_name: "Renamed".into(),
})
.unwrap();
super::super::incoming(PID_CHANNEL_EDIT, &bytes, &tx)
.await
.unwrap();
assert!(
matches!(rx.recv().await.unwrap(),NetEvent::ChannelEdited{channel_id,channel_name} if channel_id=="global" && channel_name=="Renamed")
);
}
}

View file

@ -11,6 +11,13 @@ mod social;
pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
match pid {
PID_FORUM_RESULT => { let _ = tx.send(NetEvent::ForumResult(crate::net::wire::decode(payload)?)).await; }
PID_FORUM_CHANGED => { let _ = tx.send(NetEvent::ForumChanged(crate::net::wire::decode(payload)?)).await; }
PID_PROFILE_UPDATED => {
let _ = tx
.send(NetEvent::ProfileUpdated(crate::net::wire::decode(payload)?))
.await;
}
PID_MEDIA_EVENT => {
let event = crate::net::wire::decode(payload)?;
let _ = tx.send(NetEvent::MediaEvent(event)).await;
@ -36,7 +43,9 @@ pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) ->
.await;
}
PID_CHANNEL_CREATE
PID_ATTACHMENT_RESULT
| PID_CHANNEL_CREATE
| PID_CHANNEL_EDIT
| PID_CHANNEL_DELETE
| PID_CHANNEL_LIST
| PID_CHANNEL_STATE

View file

@ -1,3 +1,5 @@
pub mod account;
pub mod forum;
pub mod framing;
pub mod handshake;
mod internal;

View file

@ -8,6 +8,7 @@ pub type JoinChannelPayload = crate::net::wire::JoinChannel;
pub type LeaveChannelPayload = crate::net::wire::LeaveChannel;
pub type ChannelStatePayload = crate::net::wire::ChannelState;
pub type ChannelCreatePayload = crate::net::wire::ChannelCreate;
pub type ChannelEditPayload = crate::net::wire::ChannelEdit;
pub type ChannelDeletePayload = crate::net::wire::ChannelDelete;
pub type ChannelListPayload = crate::net::wire::ChannelList;
pub type ChannelListItem = crate::net::wire::ChannelListItem;

View file

@ -13,6 +13,7 @@ pub const PID_CHANNEL_STATE: u16 = 0x0032;
pub const PID_CHANNEL_CREATE: u16 = 0x0033;
pub const PID_CHANNEL_DELETE: u16 = 0x0034;
pub const PID_CHANNEL_LIST: u16 = 0x0035;
pub const PID_CHANNEL_EDIT: u16 = 0x0036;
pub const PID_USER_JOIN: u16 = 0x0040;
pub const PID_USER_LEAVE: u16 = 0x0041;
pub const PID_DM_START: u16 = 0x0060;
@ -67,7 +68,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158;
pub const PID_ERROR: u16 = 0x00F0;
pub const PID_DISCONNECT: u16 = 0x00FF;
pub const LNEX_VERSION: &str = "v3";
pub const LNEX_VERSION: &str = "v4";
pub const HDR_SIZE: usize = 12;
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
@ -93,3 +94,18 @@ pub const PID_WEBHOOK_ERROR_RESULT: u16 = 0x0206;
pub const PID_VOICE_SESSION: u16 = 0x0012;
pub const PID_VOICE_STATE: u16 = 0x0011;
pub const PID_ATTACHMENT_UPLOAD: u16 = 0x0220;
pub const PID_ATTACHMENT_FETCH: u16 = 0x0221;
pub const PID_ATTACHMENT_RESULT: u16 = 0x0222;
pub const PID_PROFILE_UPDATE: u16 = 0x0042;
pub const PID_PROFILE_UPDATED: u16 = 0x0043;
pub const PID_FORUM_REQUEST: u16 = 0x0240;
pub const PID_FORUM_RESULT: u16 = 0x0241;
pub const PID_FORUM_CHANGED: u16 = 0x0242;
pub const PID_NODE_SETTINGS_REQUEST: u16 = 0x0230;
pub const PID_NODE_SETTINGS_RESULT: u16 = 0x0231;
pub const PID_CLIENT_FEATURES: u16 = 0x0232;

View file

@ -16,7 +16,7 @@ use crate::net::{
};
use super::super::switch::ReconnectRequested;
use super::{VoiceState, handle_cmd};
use super::{VoiceState, handle_cmd, profile};
pub async fn session_loop(
identity: &Identity,
@ -60,24 +60,62 @@ pub async fn session_loop(
let session_id = outcome.session_id;
let node_name = outcome.node_name;
let private_mode = outcome.private_mode;
let live_profiles = outcome.live_profiles;
let forums = outcome.forums;
let _ = event_tx
.send(NetEvent::Connected {
session_id: session_id.clone(),
node_name,
restored,
private_mode,
node_admin: outcome.node_admin,
node_settings: outcome.node_settings,
channel_structure: outcome.channel_structure,
forums: outcome.forums,
})
.await;
for channel_id in channels.clone() {
framing::write(
if outcome.node_settings || outcome.channel_structure || outcome.forums {
framing::write(&mut stream, PID_CLIENT_FEATURES, &mut seq, &wire::encode(&wire::ClientFeatures {
node_settings: outcome.node_settings, channel_structure: outcome.channel_structure, forums: outcome.forums,
})?).await?;
}
let node_settings = outcome.node_settings;
let mut profile_updates = crate::net::account::subscribe_profiles();
let mut last_profile_proof = None;
let mut pending_profile_actions = std::collections::VecDeque::new();
if live_profiles
&& let Some(update) = crate::net::account::latest_profile()
&& update.public_key == identity.pubkey_hex
&& update.epoch == crate::net::account::enrollment_epoch()
&& let Some(proof) = update.proof
{
profile::send(
live_profiles,
&mut stream,
PID_JOIN_CHANNEL,
&mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
proof,
&mut last_profile_proof,
)
.await?;
}
let profile_ready = !live_profiles || last_profile_proof.is_some();
for channel_id in channels.clone() {
if profile_ready {
framing::write(
&mut stream,
PID_JOIN_CHANNEL,
&mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
)
.await?;
} else {
profile::enqueue(
&mut pending_profile_actions,
NetCommand::JoinChannel { channel_id },
);
}
}
let (reader, mut stream) = tokio::io::split(stream);
let mut incoming = framing::io::Reader::new(reader);
@ -89,8 +127,48 @@ pub async fn session_loop(
let mut ping_tick = interval(Duration::from_secs(2));
ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut last_profile_refresh = profile_ready.then(std::time::Instant::now);
let mut profile_job = profile::RefreshTask::default();
if live_profiles && !profile_ready {
profile_job.task = Some(profile::refresh(identity));
}
loop {
tokio::select! {
changed = profile_updates.changed(), if live_profiles => {
if changed.is_ok() {
let update = profile_updates.borrow_and_update().clone();
if let Some(update) = update
&& update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch() {
if let Some(proof) = update.proof {
profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?;
last_profile_refresh = Some(std::time::Instant::now());
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
} else {
last_profile_refresh = None;
if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));}
}
}
}
}
result = async { profile_job.task.as_mut().expect("guarded profile job").await }, if live_profiles && profile_job.task.is_some() => {
profile_job.task = None;
let latest = crate::net::account::latest_profile().filter(|update|update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch());
match result {
Ok(Ok(proof)) => {
if latest.as_ref().is_some_and(|update|update.proof.is_none()) {
// A mutation committed after this HTTP refresh: obtain its newer proof.
last_profile_refresh=None;profile_job.task=Some(profile::refresh(identity));continue;
}
let proof = latest.and_then(|update|update.proof).unwrap_or(proof);
profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?;
}
_ => {
let _=event_tx.send(NetEvent::ProfileWarning {message:"Central profile refresh failed; using last verified profile".into(),rejected_join:None}).await;
}
}
last_profile_refresh=Some(std::time::Instant::now());
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
}
_ = voice_tick.tick() => { if let Some(voice)=voice_state.as_mut() {voice.keep_alive().await?;} }
_ = ping_tick.tick() => {
let ts = now_ms();
@ -117,6 +195,11 @@ pub async fn session_loop(
}
continue;
}
if pkt.packet_id == PID_NODE_SETTINGS_RESULT && node_settings {
let result = wire::decode(&pkt.payload)?;
let _ = event_tx.send(NetEvent::NodeSettingsResult { session_id: session_id.clone(), result }).await;
continue;
}
if pkt.packet_id == PID_CHANNEL_STATE
&& let Ok(p) = wire::decode::<ChannelStatePayload>(&pkt.payload)
&& p.kind == "voice" && !p.voice_endpoint.is_empty()
@ -129,13 +212,26 @@ pub async fn session_loop(
internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?;
}
cmd = cmd_rx.recv() => {
let cmd = match cmd {
Some(command) => match command_for_session(command, &session_id) {
Some(command) => Some(command),
None => continue,
},
None => None,
};
match cmd {
Some(NetCommand::AttachmentFetch { request_id, channel_id, attachment_id }) => {
framing::write(&mut stream, PID_ATTACHMENT_FETCH, &mut seq,
&wire::encode(&wire::AttachmentFetch { request_id, channel_id, attachment_id })?).await?;
}
None | Some(NetCommand::Disconnect) => {
profile::cancel(&mut profile_job, &mut pending_profile_actions);
let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq,
&wire::encode(&Disconnect {reason: "bye".into()})?).await;
return Ok(());
}
Some(NetCommand::Connect { address, auto_reconnect }) => {
profile::cancel(&mut profile_job, &mut pending_profile_actions);
warn!("connect while connected to {address}, reconnecting");
if channels.is_empty() {
*channels = vec!["general".into()];
@ -145,43 +241,62 @@ pub async fn session_loop(
auto_reconnect,
}));
}
Some(NetCommand::JoinChannel { channel_id }) => {
track_channel(channels, &channel_id);
framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?).await?;
Some(command @ (NetCommand::JoinChannel { .. } | NetCommand::SendChat { .. } | NetCommand::AttachmentUpload { .. } | NetCommand::ForumRequest(_))) => {
if let NetCommand::ForumRequest(request) = &command {
if !forums { crate::net::forum::unsupported(request, event_tx).await; continue; }
if !crate::net::forum::is_mutation(request) { crate::net::forum::write(&mut stream, &mut seq, request).await?; continue; }
}
let rejected_join = if let NetCommand::JoinChannel {channel_id}=&command {Some(channel_id.clone())} else {None};
let upload = if let NetCommand::AttachmentUpload {request_id,channel_id,data}=&command {
if data.is_empty() || data.len()>3*1024*1024 || request_id.len()>128 || channel_id.len()>128 {
let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id:request_id.clone(),channel_id:channel_id.clone(),error:"invalid image upload (maximum 3 MiB)".into(),..Default::default()})).await;continue;
}
Some((request_id.clone(),channel_id.clone()))
} else {None};
let forum_request = if let NetCommand::ForumRequest(request) = &command { Some(wire::ForumRequest { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() }) } else { None };
if !profile::enqueue(&mut pending_profile_actions, command) {
if let Some(request) = forum_request { crate::net::forum::error(&request, "Too many pending profile actions; retry shortly", event_tx).await; continue; }
if let Some((request_id,channel_id))=upload {
let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id,channel_id,error:"Too many pending profile actions; retry shortly".into(),..Default::default()})).await;
} else {let _=event_tx.send(NetEvent::ProfileWarning {message:"Too many pending profile actions; retry shortly".into(),rejected_join}).await;}
continue;
}
if profile::due(live_profiles, last_profile_refresh) {
if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));}
} else {
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
}
}
Some(NetCommand::LeaveChannel { channel_id }) => {
profile::cancel_channel(&mut pending_profile_actions, &channel_id);
channels.retain(|c| c != &channel_id);
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
&wire::encode(&LeaveChannelPayload { channel_id })?).await?;
}
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id, parent_id, position }) => {
let payload = wire::encode(&ChannelCreatePayload {
channel_id,
channel_name,
kind,
guild_id,
guild_id, parent_id, position,
})?;
framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelEdit { channel_id, channel_name, parent_id, position }) => {
let payload = wire::encode(&ChannelEditPayload { channel_id, channel_name, parent_id, position })?;
framing::write(&mut stream, PID_CHANNEL_EDIT, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelDelete { channel_id }) => {
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?;
}
Some(NetCommand::NodeSettingsRequest(request)) => {
if node_settings { framing::write(&mut stream, PID_NODE_SETTINGS_REQUEST, &mut seq, &wire::encode(&request)?).await?; }
}
Some(NetCommand::ChannelList) => {
framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?;
}
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
let msg = ChatMessagePayload {
message_id: uuid_v4(), channel_id,
sender_id: identity.pubkey_hex.clone(),
content, timestamp: now_ms(),
edited: false,
reply_to,
};
framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?;
}
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
}
@ -207,8 +322,73 @@ pub(super) fn uuid_v4() -> String {
uuid::Uuid::new_v4().to_string()
}
fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
pub(super) fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
if !channels.iter().any(|c| c == channel_id) {
channels.push(channel_id.to_string());
}
}
/// UI tasks can outlive a node switch. Only the original authenticated session may
/// consume their channel mutation; wrappers cannot smuggle a connect or arbitrary command.
fn command_for_session(command: NetCommand, current: &str) -> Option<NetCommand> {
match command {
NetCommand::ForSession {
session_id,
command,
} => (session_id == current
&& matches!(
&*command,
NetCommand::ForumRequest(_)
| NetCommand::JoinChannel { .. }
| NetCommand::ChannelCreate { .. }
| NetCommand::ChannelEdit { .. }
| NetCommand::ChannelDelete { .. }
| NetCommand::NodeSettingsRequest(_)
))
.then_some(*command),
command => Some(command),
}
}
#[cfg(test)]
mod session_fence_tests {
use super::*;
#[test]
fn admin_mutations_survive_only_the_session_that_prepared_them() {
for current in ["original-session", "new-session-after-switch"] {
let commands = [
NetCommand::ChannelCreate {
channel_id: "global".into(),
channel_name: "Global".into(),
kind: "text".into(),
guild_id: None,
},
NetCommand::ChannelEdit {
channel_id: "global".into(),
channel_name: "Renamed".into(),
},
NetCommand::ChannelDelete {
channel_id: "global".into(),
},
];
for command in commands {
let command = NetCommand::ForSession {
session_id: "original-session".into(),
command: Box::new(command),
};
assert_eq!(
command_for_session(command, current).is_some(),
current == "original-session"
);
}
}
let command = NetCommand::ForSession {
session_id: "original-session".into(),
command: Box::new(NetCommand::Connect {
address: "another-node".into(),
auto_reconnect: true,
}),
};
assert!(command_for_session(command, "original-session").is_none());
}
}

View file

@ -1,4 +1,5 @@
mod core;
mod profile;
mod social;
mod voice;

View file

@ -0,0 +1,373 @@
//! Coalesced profile refresh helpers. HTTP runs in a separate task, never in the UDP loop.
use crate::{
identity::Identity,
net::{framing, payloads::*, types::NetCommand, wire},
};
use anyhow::{Context, Result};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tokio::io::{AsyncWrite, AsyncWriteExt};
#[derive(Default)]
pub(super) struct RefreshTask {
pub task: Option<tokio::task::JoinHandle<Result<Vec<u8>>>>,
}
impl Drop for RefreshTask {
fn drop(&mut self) {
if let Some(task) = self.task.take() {
task.abort();
}
}
}
pub(super) fn cancel(task: &mut RefreshTask, pending: &mut VecDeque<NetCommand>) {
if let Some(task) = task.task.take() {
task.abort();
}
pending.clear();
}
pub(super) fn cancel_channel(pending: &mut VecDeque<NetCommand>, channel: &str) {
pending.retain(|action| !matches!(action, NetCommand::JoinChannel {channel_id} | NetCommand::SendChat {channel_id,..} | NetCommand::AttachmentUpload {channel_id,..} if channel_id == channel));
}
fn bytes(command: &NetCommand) -> usize {
match command {
NetCommand::AttachmentUpload {
data,
request_id,
channel_id,
} => data.len() + request_id.len() + channel_id.len(),
NetCommand::SendChat {
content,
channel_id,
reply_to,
} => content.len() + channel_id.len() + reply_to.as_ref().map_or(0, String::len),
NetCommand::JoinChannel { channel_id } => channel_id.len(),
NetCommand::ForumRequest(request) => request.request_id.len() + request.channel_id.len() + request.topic_id.len() + request.message_id.len() + request.title.len() + request.content.len(),
_ => 0,
}
}
pub(super) fn enqueue(pending: &mut VecDeque<NetCommand>, command: NetCommand) -> bool {
if let NetCommand::JoinChannel {channel_id}=&command
&& pending.iter().any(|action|matches!(action, NetCommand::JoinChannel {channel_id:queued} if queued==channel_id)) {return true;}
if pending.len() >= 32
|| pending
.iter()
.map(bytes)
.sum::<usize>()
.saturating_add(bytes(&command))
> 4 * 1024 * 1024
{
return false;
}
pending.push_back(command);
true
}
pub(super) const PROFILE_TTL: Duration = Duration::from_secs(5);
pub(super) fn due(enabled: bool, last: Option<Instant>) -> bool {
enabled && last.is_none_or(|at| at.elapsed() >= PROFILE_TTL)
}
pub(super) fn refresh(identity: &Identity) -> tokio::task::JoinHandle<Result<Vec<u8>>> {
let identity = identity.clone();
tokio::spawn(async move {
tokio::time::timeout(
Duration::from_secs(12),
crate::net::account::admission_proof(&identity),
)
.await
.context("Central profile refresh timed out")?
})
}
pub(super) async fn send(
enabled: bool,
stream: &mut (impl AsyncWrite + Unpin),
seq: &mut u32,
proof: Vec<u8>,
last_sent: &mut Option<Vec<u8>>,
) -> Result<()> {
if enabled && last_sent.as_ref() != Some(&proof) {
framing::write(
stream,
PID_PROFILE_UPDATE,
seq,
&wire::encode(&wire::ProfileUpdate {
account_proof: proof.clone(),
})?,
)
.await?;
*last_sent = Some(proof);
}
Ok(())
}
pub(super) async fn actions(
stream: &mut (impl AsyncWrite + Unpin),
seq: &mut u32,
identity: &Identity,
channels: &mut Vec<String>,
pending: &mut VecDeque<NetCommand>,
) -> Result<()> {
while let Some(action) = pending.pop_front() {
match action {
NetCommand::ForumRequest(request) => { crate::net::forum::write(stream, seq, &request).await?; }
NetCommand::JoinChannel { channel_id } => {
super::core::track_channel(channels, &channel_id);
framing::write(
stream,
PID_JOIN_CHANNEL,
seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
)
.await?;
}
NetCommand::SendChat {
channel_id,
content,
reply_to,
} => {
let message = ChatMessagePayload {
message_id: super::core::uuid_v4(),
channel_id,
sender_id: identity.pubkey_hex.clone(),
content,
timestamp: super::core::now_ms(),
edited: false,
reply_to,
};
framing::write(stream, PID_CHAT_MESSAGE, seq, &wire::encode(&message)?).await?;
}
NetCommand::AttachmentUpload {
request_id,
channel_id,
data,
} => {
framing::write(
stream,
PID_ATTACHMENT_UPLOAD,
seq,
&wire::encode(&wire::AttachmentUpload {
request_id,
channel_id,
data,
})?,
)
.await?;
}
_ => unreachable!("only chat, image, forum mutation and join commands can wait for profile refresh"),
}
}
stream.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn legacy_session_without_live_profiles_sends_chat_voice_and_image_without_profile_packet()
{
let legacy: wire::Session = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap();
assert!(!legacy.live_profiles);
assert!(
!due(legacy.live_profiles, None),
"legacy actions never wait for profile HTTP"
);
let identity = crate::identity::generate("legacy");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 2;
let mut sent = None;
send(
legacy.live_profiles,
&mut stream,
&mut seq,
b"not supported".to_vec(),
&mut sent,
)
.await
.unwrap();
assert!(sent.is_none());
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "general".into(),
content: "legacy message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "voice".into(),
},
NetCommand::AttachmentUpload {
request_id: "image".into(),
channel_id: "general".into(),
data: vec![1, 2, 3],
},
]);
actions(
&mut stream,
&mut seq,
&identity,
&mut vec!["general".into()],
&mut pending,
)
.await
.unwrap();
for expected in [PID_CHAT_MESSAGE, PID_JOIN_CHANNEL, PID_ATTACHMENT_UPLOAD] {
assert_eq!(framing::read(&mut peer).await.unwrap().packet_id, expected);
}
}
#[test]
fn image_actions_share_bounded_byte_budget_and_leave_cancels_upload() {
let mut pending = VecDeque::new();
assert!(enqueue(
&mut pending,
NetCommand::AttachmentUpload {
request_id: "one".into(),
channel_id: "general".into(),
data: vec![0; 3 * 1024 * 1024]
}
));
assert!(!enqueue(
&mut pending,
NetCommand::AttachmentUpload {
request_id: "two".into(),
channel_id: "general".into(),
data: vec![0; 3 * 1024 * 1024]
}
));
assert_eq!(pending.len(), 1);
cancel_channel(&mut pending, "general");
assert!(pending.is_empty());
}
#[tokio::test]
async fn disconnect_switch_and_session_drop_cancel_refresh_and_never_replay_pending_actions() {
for session_end in [false, true] {
let identity = crate::identity::generate("test");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "old-node-channel".into(),
content: "old message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "old-voice".into(),
},
]);
let mut job = RefreshTask {
task: Some(tokio::spawn(async {
std::future::pending::<Result<Vec<u8>>>().await
})),
};
let aborted = job.task.as_ref().unwrap().abort_handle();
if session_end {
drop(job);
pending.clear();
} else {
cancel(&mut job, &mut pending);
drop(job);
}
tokio::task::yield_now().await;
assert!(aborted.is_finished());
let mut channels = vec!["new-node-channel".to_owned()];
actions(&mut stream, &mut 2, &identity, &mut channels, &mut pending)
.await
.unwrap();
assert_eq!(channels, vec!["new-node-channel"]);
assert!(
tokio::time::timeout(Duration::from_millis(5), framing::read(&mut peer))
.await
.is_err()
);
}
}
#[test]
fn pending_actions_are_bounded_coalesce_duplicate_joins_and_leave_cancels_channel() {
let mut pending = VecDeque::new();
for _ in 0..100 {
assert!(enqueue(
&mut pending,
NetCommand::JoinChannel {
channel_id: "voice".into()
}
));
}
assert_eq!(pending.len(), 1);
for _ in 0..31 {
assert!(enqueue(
&mut pending,
NetCommand::SendChat {
channel_id: "general".into(),
content: "message".into(),
reply_to: None
}
));
}
assert!(!enqueue(
&mut pending,
NetCommand::JoinChannel {
channel_id: "overflow".into()
}
));
cancel_channel(&mut pending, "voice");
assert_eq!(pending.len(), 31);
cancel_channel(&mut pending, "general");
assert!(pending.is_empty());
}
#[tokio::test]
async fn fresh_proof_precedes_chat_and_voice_join_without_disconnect_or_duplicate_join() {
let identity = crate::identity::generate("old");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "general".into(),
content: "new message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "voice-room".into(),
},
NetCommand::AttachmentUpload {
request_id: "image".into(),
channel_id: "general".into(),
data: vec![1, 2, 3],
},
]);
let mut channels = vec!["general".to_owned()];
let mut seq = 0;
let mut last = None;
send(
true,
&mut stream,
&mut seq,
b"signed fresh proof".to_vec(),
&mut last,
)
.await
.unwrap();
actions(
&mut stream,
&mut seq,
&identity,
&mut channels,
&mut pending,
)
.await
.unwrap();
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_PROFILE_UPDATE
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_CHAT_MESSAGE
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_JOIN_CHANNEL
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_ATTACHMENT_UPLOAD
);
assert!(pending.is_empty());
assert_eq!(channels, vec!["general", "voice-room"]);
assert!(!due(true, Some(Instant::now())));
assert!(due(true, None));
}
}

View file

@ -51,6 +51,9 @@ pub async fn net_task(
session.address=address;session.auto_reconnect=auto_reconnect;
failures=0;target=Some(session);continue 'session;
}
Some(NetCommand::LeaveChannel {channel_id}) => {
forget_rejoin_channel(&mut session, &channel_id);
}
Some(NetCommand::Disconnect) => {
failures=0;
let _=event_tx.send(NetEvent::Disconnected {reason:"disconnected".into(),will_retry:false}).await;
@ -105,7 +108,13 @@ pub async fn net_task(
if let Some(problem) = transport.and_then(TransportError::trust_problem) {
let _ = event_tx.send(NetEvent::TrustProblem(problem)).await;
}
let retry = session.auto_reconnect && transport.is_none();
let account_required = e
.downcast_ref::<crate::net::account::SignInRequired>()
.is_some();
if account_required {
let _ = event_tx.send(NetEvent::AccountRequired).await;
}
let retry = should_retry(&e, session.auto_reconnect);
let _ = event_tx
.send(NetEvent::Disconnected {
reason: e.to_string(),
@ -123,6 +132,19 @@ pub async fn net_task(
}
}
/// An explicit leave during backoff must survive the next successful connection.
fn forget_rejoin_channel(target: &mut SessionTarget, channel_id: &str) {
target.channels.retain(|channel| channel != channel_id);
}
fn should_retry(error: &anyhow::Error, enabled: bool) -> bool {
enabled
&& error.downcast_ref::<TransportError>().is_none()
&& error
.downcast_ref::<crate::net::account::SignInRequired>()
.is_none()
}
async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<SessionTarget> {
loop {
match cmd_rx.recv().await {
@ -146,6 +168,31 @@ async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<Ses
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leave_during_reconnect_backoff_prevents_voice_room_autorejoin() {
let mut target = SessionTarget {
address: "node.example:7600".into(),
auto_reconnect: true,
channels: vec!["general".into(), "voice-room".into(), "pending-room".into()],
};
for channel in ["voice-room", "pending-room"] {
forget_rejoin_channel(&mut target, channel);
}
assert_eq!(target.channels, vec!["general"]);
assert!(target.auto_reconnect);
assert_eq!(target.address, "node.example:7600");
}
#[test]
fn expired_account_stops_retry_but_outage_keeps_retry_policy() {
let account = anyhow::Error::new(crate::net::account::SignInRequired)
.context("gateway handshake failed");
assert!(!should_retry(&account, true));
let outage = anyhow::anyhow!("Central temporarily unavailable");
assert!(should_retry(&outage, true));
assert!(!should_retry(&outage, false));
}
#[tokio::test]
async fn disconnected_cancel_does_not_disable_later_connections() {
let (sender, mut receiver) = mpsc::channel(4);

View file

@ -18,9 +18,9 @@ impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
pub type Stream = Box<dyn AsyncStream>;
/// ALPN protocol id required from the gateway.
pub const ALPN: &[u8] = b"vnox-lnex/3";
pub const ALPN: &[u8] = b"vnox-lnex/4";
/// TLS exporter label of the channel binding (must match the gateway).
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v4-channel-binding";
/// Length of the exported channel binding.
pub const BINDING_LEN: usize = 32;
@ -220,7 +220,7 @@ pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Conn
|| connection.alpn_protocol() != Some(ALPN)
{
return Err(TransportError::ProtocolMismatch(
"The server did not negotiate TLS 1.3 with LNEx v3. Ask its owner to update the server."
"The server did not negotiate TLS 1.3 with LNEx v4. Ask its owner to update the server."
.into(),
)
.into());
@ -237,7 +237,7 @@ pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Conn
})
}
const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server or a non-VNOX port, ask its owner to update it.";
const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v4). It is probably an outdated server or a non-VNOX port, ask its owner to update it.";
fn map_tls_error(
error: std::io::Error,

View file

@ -1,4 +1,4 @@
//! Server trust for the TLS 1.3 control connection (LNEx v3).
//! Server trust for the TLS 1.3 control connection (LNEx v4).
//!
//! Model (see `VNOX-Server/docs/02-protocol/tls.md`):
//! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins,
@ -39,7 +39,7 @@ pub enum TransportError {
},
/// A server marked as CA trusted no longer presents a valid public certificate.
CertificateInvalid { address: String, reason: String },
/// The peer does not speak TLS 1.3 / LNEx v3.
/// The peer does not speak TLS 1.3 / LNEx v4.
ProtocolMismatch(String),
}

View file

@ -1,5 +1,21 @@
#[derive(Debug)]
pub enum NetCommand {
ForumRequest(crate::net::wire::ForumRequest),
/// Fence an administrative channel mutation to the authenticated session that prepared it.
ForSession {
session_id: String,
command: Box<NetCommand>,
},
AttachmentUpload {
request_id: String,
channel_id: String,
data: Vec<u8>,
},
AttachmentFetch {
request_id: String,
channel_id: String,
attachment_id: String,
},
MediaControl(crate::net::wire::MediaControl),
Webhook {
operation: WebhookOperation,
@ -15,11 +31,20 @@ pub enum NetCommand {
LeaveChannel {
channel_id: String,
},
NodeSettingsRequest(crate::net::wire::NodeSettingsRequest),
ChannelCreate {
channel_id: String,
channel_name: String,
kind: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelEdit {
channel_id: String,
channel_name: String,
parent_id: Option<String>,
position: Option<i32>,
},
ChannelDelete {
channel_id: String,

View file

@ -3,6 +3,17 @@ use std::net::SocketAddr;
#[derive(Debug, Clone)]
pub enum NetEvent {
ForumResult(crate::net::wire::ForumResult),
ForumChanged(crate::net::wire::ForumChanged),
/// A local profile refresh/activity warning; it is not a gateway join refusal.
ProfileWarning {
message: String,
rejected_join: Option<String>,
},
ProfileUpdated(crate::net::wire::ProfileUpdated),
/// Central enrollment must be approved again; retries cannot repair it.
AccountRequired,
AttachmentResult(crate::net::wire::AttachmentResult),
VoiceRevoked {
channel_id: String,
},
@ -10,11 +21,16 @@ pub enum NetEvent {
WebhookResult(WebhookManagementResult),
WebhookList(crate::net::wire::WebhookListResult),
WebhookError(crate::net::wire::WebhookErrorResult),
NodeSettingsResult { session_id: String, result: crate::net::wire::NodeSettingsResult },
Connected {
session_id: String,
node_name: String,
restored: bool,
private_mode: bool,
node_admin: bool,
node_settings: bool,
channel_structure: bool,
forums: bool,
},
Disconnected {
reason: String,
@ -33,12 +49,22 @@ pub enum NetEvent {
members: Vec<MemberInfo>,
voice_endpoint: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelCreated {
channel_id: String,
channel_name: String,
kind: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelEdited {
channel_id: String,
channel_name: String,
parent_id: Option<String>,
position: Option<i32>,
},
ChannelDeleted {
channel_id: String,
@ -61,6 +87,8 @@ pub enum NetEvent {
messages: Vec<ChatMsg>,
},
UserJoin {
account_id: String,
avatar_url: String,
channel_id: String,
user_id: String,
nickname: String,

View file

@ -3,6 +3,8 @@ pub struct MemberInfo {
pub user_id: String,
pub nickname: String,
pub in_voice: bool,
pub account_id: String,
pub avatar_url: String,
}
#[derive(Debug, Clone)]
@ -11,6 +13,8 @@ pub struct ChannelListItem {
pub channel_name: String,
pub kind: String,
pub guild_id: Option<String>,
pub parent_id: Option<String>,
pub position: i32,
}
#[derive(Debug, Clone)]