feat(client): protocol v2 wire layer, screen sharing, channel webhooks and secure voice
Verified against the real gateway via tests/gateway_interop.rs.
This commit is contained in:
parent
8460fb28fd
commit
3d7dd5413b
65 changed files with 6048 additions and 1156 deletions
|
|
@ -10,7 +10,18 @@ fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] {
|
|||
nonce
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8]) -> Vec<u8> {
|
||||
encrypt_with_aad(key, cid, seq, plaintext, &[])
|
||||
}
|
||||
|
||||
pub fn encrypt_with_aad(
|
||||
key: &[u8; 32],
|
||||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
plaintext: &[u8],
|
||||
aad: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
|
||||
let nonce_bytes = make_nonce(cid, seq);
|
||||
let nonce = Nonce::from(nonce_bytes);
|
||||
|
|
@ -19,17 +30,28 @@ pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8
|
|||
&nonce,
|
||||
Payload {
|
||||
msg: plaintext,
|
||||
aad: &[],
|
||||
aad,
|
||||
},
|
||||
)
|
||||
.expect("ChaCha20-Poly1305 encryption infallible")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn decrypt_with_key(
|
||||
key: &[u8; 32],
|
||||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
decrypt_with_aad(key, cid, seq, ciphertext, &[])
|
||||
}
|
||||
|
||||
pub fn decrypt_with_aad(
|
||||
key: &[u8; 32],
|
||||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
aad: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
|
||||
let nonce_bytes = make_nonce(cid, seq);
|
||||
|
|
@ -39,7 +61,7 @@ pub fn decrypt_with_key(
|
|||
&nonce,
|
||||
Payload {
|
||||
msg: ciphertext,
|
||||
aad: &[],
|
||||
aad,
|
||||
},
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("decryption failed: {e:?}"))
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ pub struct SessionCrypto {
|
|||
|
||||
impl SessionCrypto {
|
||||
pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self {
|
||||
let salt = b"VNOX-LNEx-KDF-v1";
|
||||
let salt = b"VNOX-LNEx-KDF-v2";
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), shared_secret);
|
||||
|
||||
let mut keys = [0u8; 64];
|
||||
|
|
@ -40,24 +40,16 @@ impl SessionCrypto {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn encrypt_c2s(&self, seq: u64, plaintext: &[u8]) -> Vec<u8> {
|
||||
cipher::encrypt_with_key(&self.c2s_key, &self.cid, seq, plaintext)
|
||||
pub fn encrypt_c2s_aad(&self, seq: u64, plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
|
||||
cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, aad)
|
||||
}
|
||||
|
||||
pub fn decrypt_s2c(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_key(&self.s2c_key, &self.cid, seq, ciphertext)
|
||||
}
|
||||
|
||||
pub fn decrypt_c2s(&self, seq: u64, ciphertext: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_key(&self.c2s_key, &self.cid, seq, ciphertext)
|
||||
}
|
||||
|
||||
pub fn c2s_key(&self) -> &[u8; 32] {
|
||||
&self.c2s_key
|
||||
}
|
||||
|
||||
pub fn cid(&self) -> &[u8; 8] {
|
||||
&self.cid
|
||||
pub fn decrypt_s2c_aad(
|
||||
&self,
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
aad: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_aad(&self.s2c_key, &self.cid, seq, ciphertext, aad)
|
||||
}
|
||||
|
||||
pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) {
|
||||
|
|
@ -82,8 +74,9 @@ mod tests {
|
|||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
||||
|
||||
let plaintext = b"hello encrypted world";
|
||||
let ct = crypto.encrypt_c2s(42, plaintext);
|
||||
let decrypted = crypto.decrypt_c2s(42, &ct).unwrap();
|
||||
let ct = crypto.encrypt_c2s_aad(42, plaintext, b"header");
|
||||
let decrypted =
|
||||
cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 42, &ct, b"header").unwrap();
|
||||
assert_eq!(decrypted, plaintext);
|
||||
}
|
||||
|
||||
|
|
@ -92,8 +85,8 @@ mod tests {
|
|||
let shared_secret = [0xABu8; 32];
|
||||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
||||
|
||||
let mut ct = crypto.encrypt_c2s(0, b"data");
|
||||
let mut ct = crypto.encrypt_c2s_aad(0, b"data", b"header");
|
||||
ct[5] ^= 0xFF;
|
||||
assert!(crypto.decrypt_c2s(0, &ct).is_err());
|
||||
assert!(cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 0, &ct, b"header").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::super::crypto::SessionCrypto;
|
||||
use super::super::payloads::HDR_SIZE;
|
||||
|
|
@ -11,7 +10,10 @@ use super::parse_header;
|
|||
const ENCRYPTED_FLAG: u16 = 1 << 1;
|
||||
const KNOWN_FLAGS: u16 = ENCRYPTED_FLAG;
|
||||
|
||||
pub async fn read_encrypted(stream: &mut TcpStream, crypto: &SessionCrypto) -> Result<RawPacket> {
|
||||
pub async fn read_encrypted(
|
||||
stream: &mut (impl tokio::io::AsyncRead + Unpin),
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<RawPacket> {
|
||||
let mut buf = [0u8; HDR_SIZE];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
||||
|
|
@ -25,27 +27,160 @@ pub async fn read_encrypted(stream: &mut TcpStream, crypto: &SessionCrypto) -> R
|
|||
if !encrypted.is_empty() {
|
||||
stream.read_exact(&mut encrypted).await?;
|
||||
}
|
||||
let payload = crypto.decrypt_s2c(sequence as u64, &encrypted)?;
|
||||
Ok(RawPacket { packet_id, payload })
|
||||
let payload = crypto.decrypt_s2c_aad(sequence as u64, &encrypted, &buf)?;
|
||||
Ok(RawPacket {
|
||||
packet_id,
|
||||
sequence,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn write_encrypted(
|
||||
stream: &mut TcpStream,
|
||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
id: u16,
|
||||
seq: &mut u32,
|
||||
payload: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
let encrypted = crypto.encrypt_c2s(*seq as u64, payload);
|
||||
if *seq == u32::MAX {
|
||||
return Err(anyhow!("session sequence exhausted; reconnect required"));
|
||||
}
|
||||
if payload.len() > super::super::payloads::MAX_PAYLOAD as usize - 16 {
|
||||
return Err(anyhow!("payload too large"));
|
||||
}
|
||||
let mut hdr = [0u8; HDR_SIZE];
|
||||
hdr[0..2].copy_from_slice(&id.to_be_bytes());
|
||||
hdr[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes());
|
||||
hdr[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
hdr[8..12].copy_from_slice(&(encrypted.len() as u32).to_be_bytes());
|
||||
*seq = seq.wrapping_add(1);
|
||||
hdr[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
|
||||
let encrypted = crypto.encrypt_c2s_aad(*seq as u64, payload, &hdr);
|
||||
*seq += 1;
|
||||
let mut frame = Vec::with_capacity(HDR_SIZE + encrypted.len());
|
||||
frame.extend_from_slice(&hdr);
|
||||
frame.extend_from_slice(&encrypted);
|
||||
stream.write_all(&frame).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A dedicated reader retains partial frames across command/timer selection.
|
||||
/// Dropping a session cancels its reader and releases the socket half.
|
||||
pub struct Reader {
|
||||
receiver: tokio::sync::mpsc::Receiver<Result<RawPacket>>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl Reader {
|
||||
pub fn new(
|
||||
mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static,
|
||||
crypto: SessionCrypto,
|
||||
) -> Self {
|
||||
let (sender, receiver) = tokio::sync::mpsc::channel(32);
|
||||
let task = tokio::spawn(async move {
|
||||
let mut expected = 2u32;
|
||||
loop {
|
||||
let result = read_encrypted(&mut stream, &crypto)
|
||||
.await
|
||||
.and_then(|packet| {
|
||||
if packet.sequence != expected {
|
||||
return Err(anyhow!("replayed or reordered control packet"));
|
||||
}
|
||||
expected = expected
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow!("session sequence exhausted"))?;
|
||||
Ok(packet)
|
||||
});
|
||||
let failed = result.is_err();
|
||||
if sender.send(result).await.is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self { receiver, task }
|
||||
}
|
||||
pub async fn next(&mut self) -> Result<RawPacket> {
|
||||
self.receiver
|
||||
.recv()
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("gateway reader stopped"))?
|
||||
}
|
||||
}
|
||||
impl Drop for Reader {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hkdf::Hkdf;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::time::{Duration, timeout};
|
||||
|
||||
fn server_frame(pid: u16, seq: u32, payload: &[u8]) -> Vec<u8> {
|
||||
let mut keys = [0u8; 64];
|
||||
Hkdf::<Sha256>::new(Some(b"VNOX-LNEx-KDF-v2"), &[7; 32])
|
||||
.expand(b"session-keys", &mut keys)
|
||||
.unwrap();
|
||||
let key: [u8; 32] = keys[32..].try_into().unwrap();
|
||||
let cid: [u8; 8] = Sha256::digest(b"fixture-session")[..8].try_into().unwrap();
|
||||
let mut header = [0u8; 12];
|
||||
header[..2].copy_from_slice(&pid.to_be_bytes());
|
||||
header[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes());
|
||||
header[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
header[8..].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
|
||||
let body =
|
||||
crate::net::crypto::cipher::encrypt_with_aad(&key, &cid, seq as u64, payload, &header);
|
||||
[header.as_slice(), body.as_slice()].concat()
|
||||
}
|
||||
fn crypto() -> SessionCrypto {
|
||||
SessionCrypto::derive(&[7; 32], "fixture-session")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_wait_retains_partial_control_frame() {
|
||||
let (reader, mut writer) = tokio::io::duplex(256);
|
||||
let mut reader = Reader::new(reader, crypto());
|
||||
let frame = server_frame(5, 2, b"protobuf");
|
||||
writer.write_all(&frame[..5]).await.unwrap();
|
||||
assert!(
|
||||
timeout(Duration::from_millis(5), reader.next())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
writer.write_all(&frame[5..]).await.unwrap();
|
||||
let packet = timeout(Duration::from_secs(1), reader.next())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(packet.payload, b"protobuf");
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn replayed_control_sequence_is_rejected() {
|
||||
let (reader, mut writer) = tokio::io::duplex(256);
|
||||
let mut reader = Reader::new(reader, crypto());
|
||||
let frame = server_frame(5, 2, b"");
|
||||
writer.write_all(&frame).await.unwrap();
|
||||
reader.next().await.unwrap();
|
||||
writer.write_all(&frame).await.unwrap();
|
||||
assert!(reader.next().await.is_err());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn changing_packet_id_invalidates_authentication() {
|
||||
let (mut reader, mut writer) = tokio::io::duplex(256);
|
||||
let mut frame = server_frame(5, 2, b"same body");
|
||||
frame[1] ^= 1;
|
||||
writer.write_all(&frame).await.unwrap();
|
||||
assert!(read_encrypted(&mut reader, &crypto()).await.is_err());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sequence_exhaustion_never_wraps_nonce() {
|
||||
let (_, mut writer) = tokio::io::duplex(256);
|
||||
let mut seq = u32::MAX;
|
||||
assert!(
|
||||
write_encrypted(&mut writer, 4, &mut seq, b"", &crypto())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(seq, u32::MAX);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::payloads::{HDR_SIZE, MAX_PAYLOAD};
|
||||
|
||||
pub struct RawPacket {
|
||||
pub packet_id: u16,
|
||||
pub sequence: u32,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
|
|
@ -37,29 +37,45 @@ pub fn decode_frame(bytes: &[u8]) -> Result<RawPacket> {
|
|||
return Err(anyhow!("frame too short"));
|
||||
}
|
||||
let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length");
|
||||
let (packet_id, _, _, payload_length) = parse_header(&hdr)?;
|
||||
let (packet_id, flags, sequence, payload_length) = parse_header(&hdr)?;
|
||||
if flags != 0 {
|
||||
return Err(anyhow!("unexpected handshake flags"));
|
||||
}
|
||||
let end = HDR_SIZE + payload_length as usize;
|
||||
if bytes.len() < end {
|
||||
return Err(anyhow!("truncated frame"));
|
||||
}
|
||||
Ok(RawPacket {
|
||||
packet_id,
|
||||
sequence,
|
||||
payload: bytes[HDR_SIZE..end].to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn read(stream: &mut TcpStream) -> Result<RawPacket> {
|
||||
pub async fn read(stream: &mut (impl tokio::io::AsyncRead + Unpin)) -> Result<RawPacket> {
|
||||
let mut buf = [0u8; HDR_SIZE];
|
||||
stream.read_exact(&mut buf).await?;
|
||||
let (packet_id, _, _, payload_length) = parse_header(&buf)?;
|
||||
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
||||
if flags != 0 {
|
||||
return Err(anyhow!("unexpected handshake flags"));
|
||||
}
|
||||
let mut payload = vec![0u8; payload_length as usize];
|
||||
if !payload.is_empty() {
|
||||
stream.read_exact(&mut payload).await?;
|
||||
}
|
||||
Ok(RawPacket { packet_id, payload })
|
||||
Ok(RawPacket {
|
||||
packet_id,
|
||||
sequence,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn write(stream: &mut TcpStream, id: u16, seq: &mut u32, payload: &[u8]) -> Result<()> {
|
||||
pub async fn write(
|
||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
id: u16,
|
||||
seq: &mut u32,
|
||||
payload: &[u8],
|
||||
) -> Result<()> {
|
||||
let frame = encode_frame(id, seq, payload);
|
||||
stream.write_all(&frame).await?;
|
||||
Ok(())
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::{Result, anyhow};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use tracing::{debug, info};
|
||||
|
||||
use super::crypto::SessionCrypto;
|
||||
|
|
@ -12,7 +13,7 @@ use crate::identity::Identity;
|
|||
/// Returns (session_id, node_name, private_mode, crypto).
|
||||
/// All subsequent packets must be encrypted with `crypto`.
|
||||
pub async fn run(
|
||||
stream: &mut TcpStream,
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
identity: &Identity,
|
||||
seq: &mut u32,
|
||||
) -> Result<(String, String, bool, SessionCrypto)> {
|
||||
|
|
@ -21,57 +22,94 @@ pub async fn run(
|
|||
if pkt.packet_id != PID_HELLO {
|
||||
return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id));
|
||||
}
|
||||
let hello: HelloPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
let hello: HelloPayload = wire::decode(&pkt.payload)?;
|
||||
debug!("← HELLO node={}", hello.node_name);
|
||||
|
||||
if pkt.sequence != 0 {
|
||||
return Err(anyhow!("invalid HELLO sequence"));
|
||||
}
|
||||
let server_public: [u8; 32] = hello
|
||||
.server_pubkey
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| anyhow!("invalid server identity key"))?;
|
||||
let server_key = ed25519_dalek::VerifyingKey::from_bytes(&server_public)?;
|
||||
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?;
|
||||
let mut unsigned_hello = hello.clone();
|
||||
unsigned_hello.server_signature.clear();
|
||||
let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec();
|
||||
hello_transcript.extend_from_slice(&wire::encode(&unsigned_hello)?);
|
||||
server_key
|
||||
.verify_strict(&hello_transcript, &signature)
|
||||
.map_err(|_| anyhow!("server handshake signature verification failed"))?;
|
||||
// Keep full signed hello for the client-auth transcript before moving fields.
|
||||
let signed_hello = wire::encode(&hello)?;
|
||||
|
||||
// Generate our own ephemeral X25519 keypair
|
||||
let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral();
|
||||
let eph_pk_hex = hex::encode(eph_pk.as_bytes());
|
||||
let eph_pk_hex = eph_pk.as_bytes().to_vec();
|
||||
|
||||
// Parse server's ephemeral key from HELLO
|
||||
let server_eph_raw =
|
||||
hex::decode(&hello.server_eph_pubkey).map_err(|_| anyhow!("bad server_eph_pubkey hex"))?;
|
||||
let server_eph_raw = hello.server_eph_pubkey;
|
||||
let server_eph_key: [u8; 32] = server_eph_raw
|
||||
.try_into()
|
||||
.map_err(|_| anyhow!("bad server_eph_pubkey length"))?;
|
||||
let server_eph_pk = x25519_dalek::PublicKey::from(server_eph_key);
|
||||
|
||||
// AUTH — include our ephemeral public key
|
||||
let nonce = hex::decode(&hello.challenge_nonce)?;
|
||||
if hello.lnex_version != LNEX_VERSION {
|
||||
return Err(anyhow!("unsupported LNEx version"));
|
||||
}
|
||||
if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 {
|
||||
return Err(anyhow!("invalid server handshake key/challenge"));
|
||||
}
|
||||
let sk = identity
|
||||
.signing_key()
|
||||
.ok_or_else(|| anyhow!("no signing key"))?;
|
||||
use ed25519_dalek::Signer;
|
||||
let sig = sk.sign(&nonce);
|
||||
|
||||
let auth = AuthPayload {
|
||||
client_pubkey: identity.pubkey_hex.clone(),
|
||||
let mut auth = AuthPayload {
|
||||
client_pubkey: sk.verifying_key().to_bytes().to_vec(),
|
||||
nickname: identity.nickname.clone(),
|
||||
lnex_version: LNEX_VERSION.into(),
|
||||
signature: hex::encode(sig.to_bytes()),
|
||||
signature: Vec::new(),
|
||||
client_eph_pubkey: eph_pk_hex,
|
||||
};
|
||||
framing::write(stream, PID_AUTH, seq, &serde_json::to_vec(&auth)?).await?;
|
||||
let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec();
|
||||
auth_transcript.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes());
|
||||
auth_transcript.extend_from_slice(&signed_hello);
|
||||
auth_transcript.extend_from_slice(&wire::encode(&auth)?);
|
||||
auth.signature = sk.sign(&auth_transcript).to_bytes().to_vec();
|
||||
framing::write(stream, PID_AUTH, seq, &wire::encode(&auth)?).await?;
|
||||
debug!("→ AUTH nick={}", identity.nickname);
|
||||
|
||||
// SESSION
|
||||
let pkt = framing::read(stream).await?;
|
||||
if pkt.packet_id == PID_ERROR {
|
||||
let e: ErrorPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
let e: ErrorPayload = wire::decode(&pkt.payload)?;
|
||||
return Err(anyhow!("auth rejected: {}", e.message));
|
||||
}
|
||||
if pkt.packet_id != PID_SESSION {
|
||||
return Err(anyhow!("expected SESSION, got 0x{:04X}", pkt.packet_id));
|
||||
}
|
||||
let sess: SessionPayload = serde_json::from_slice(&pkt.payload)?;
|
||||
if pkt.sequence != 1 {
|
||||
return Err(anyhow!("invalid SESSION sequence"));
|
||||
}
|
||||
let sess: SessionPayload = wire::decode(&pkt.payload)?;
|
||||
|
||||
// Derive encryption keys from ECDH shared secret
|
||||
let shared_secret = SessionCrypto::ecdh(eph_sk, &server_eph_pk);
|
||||
if !shared_secret.was_contributory() {
|
||||
return Err(anyhow!("invalid server ECDH key"));
|
||||
}
|
||||
if sess.session_id.is_empty() || sess.token.is_empty() {
|
||||
return Err(anyhow!("invalid session response"));
|
||||
}
|
||||
let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id);
|
||||
|
||||
info!(
|
||||
"authenticated — session {} encrypted",
|
||||
&sess.session_id[..8]
|
||||
sess.session_id.chars().take(8).collect::<String>()
|
||||
);
|
||||
|
||||
Ok((sess.session_id, hello.node_name, hello.private_mode, crypto))
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::{Result, anyhow};
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::super::super::payloads::*;
|
||||
|
|
@ -9,7 +9,7 @@ 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_CHANNEL_STATE => {
|
||||
let p: ChannelStatePayload = serde_json::from_slice(payload)?;
|
||||
let p: ChannelStatePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelState {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -30,7 +30,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_CHANNEL_CREATE => {
|
||||
let p: ChannelCreatePayload = serde_json::from_slice(payload)?;
|
||||
let p: ChannelCreatePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelCreated {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -41,7 +41,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_CHANNEL_DELETE => {
|
||||
let p: ChannelDeletePayload = serde_json::from_slice(payload)?;
|
||||
let p: ChannelDeletePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelDeleted {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -49,7 +49,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_CHANNEL_LIST => {
|
||||
let p: ChannelListPayload = serde_json::from_slice(payload)?;
|
||||
let p: ChannelListPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChannelListEvent {
|
||||
channels: p
|
||||
|
|
@ -66,7 +66,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_CHAT_MESSAGE => {
|
||||
let p: ChatMessagePayload = serde_json::from_slice(payload)?;
|
||||
let p: ChatMessagePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChatMessage {
|
||||
message_id: p.message_id,
|
||||
|
|
@ -80,7 +80,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_CHAT_HISTORY => {
|
||||
let p: ChatHistoryPayload = serde_json::from_slice(payload)?;
|
||||
let p: ChatHistoryPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ChatHistory {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -99,7 +99,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_USER_JOIN => {
|
||||
let p: UserJoinPayload = serde_json::from_slice(payload)?;
|
||||
let p: UserJoinPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserJoin {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -109,7 +109,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_USER_LEAVE => {
|
||||
let p: UserLeavePayload = serde_json::from_slice(payload)?;
|
||||
let p: UserLeavePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserLeave {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -118,7 +118,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_PONG => {
|
||||
let p: PongPayload = serde_json::from_slice(payload)?;
|
||||
let p: PongPayload = wire::decode(payload)?;
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
|
|
@ -127,20 +127,17 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
let _ = tx.send(NetEvent::LatencyUpdate { rtt_ms }).await;
|
||||
}
|
||||
PID_READ_RECEIPT_BROADCAST => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: ReadReceiptBroadcast = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReadReceiptBroadcast {
|
||||
channel_id: p["channel_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
last_read_message_id: p["last_read_message_id"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
channel_id: p.channel_id,
|
||||
user_id: p.user_id,
|
||||
last_read_message_id: p.last_read_message_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_ERROR => {
|
||||
let p: ErrorPayload = serde_json::from_slice(payload)?;
|
||||
let p: ErrorPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::Error {
|
||||
code: p.code,
|
||||
|
|
@ -150,12 +147,12 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
}
|
||||
PID_DISCONNECT => return Err(anyhow!("server disconnected")),
|
||||
PID_TYPING_START => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: TypingBroadcast = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::TypingStart {
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
nickname: p["nickname"].as_str().unwrap_or_default().into(),
|
||||
channel_id: p["channel_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p.user_id,
|
||||
nickname: p.nickname,
|
||||
channel_id: p.channel_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::debug;
|
||||
|
||||
|
|
@ -9,7 +9,7 @@ use super::super::super::types::*;
|
|||
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_DM_START => {
|
||||
let p: DmStartResponsePayload = serde_json::from_slice(payload)?;
|
||||
let p: DmStartResponsePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmStart {
|
||||
dm_id: p.dm_id,
|
||||
|
|
@ -31,7 +31,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_DM_MESSAGE => {
|
||||
let p: DmMessagePayload = serde_json::from_slice(payload)?;
|
||||
let p: DmMessagePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmMessage {
|
||||
dm_id: p.dm_id,
|
||||
|
|
@ -42,7 +42,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_DM_HISTORY => {
|
||||
let p: DmHistoryPayload = serde_json::from_slice(payload)?;
|
||||
let p: DmHistoryPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::DmHistory {
|
||||
dm_id: p.dm_id,
|
||||
|
|
@ -61,7 +61,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_FRIEND_LIST => {
|
||||
let p: FriendListPayload = serde_json::from_slice(payload)?;
|
||||
let p: FriendListPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendList {
|
||||
friends: p
|
||||
|
|
@ -78,7 +78,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_MESSAGE_REACTION_ADD => {
|
||||
let p: ReactionPayload = serde_json::from_slice(payload)?;
|
||||
let p: ReactionPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReactionAdded {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -89,7 +89,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_MESSAGE_REACTION_REMOVE => {
|
||||
let p: ReactionPayload = serde_json::from_slice(payload)?;
|
||||
let p: ReactionPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::ReactionRemoved {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -100,7 +100,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_MESSAGE_EDIT => {
|
||||
let p: ChatMessagePayload = serde_json::from_slice(payload)?;
|
||||
let p: ChatMessagePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::MessageEdited {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -111,7 +111,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_MESSAGE_DELETE => {
|
||||
let p: MessageDeletePayload = serde_json::from_slice(payload)?;
|
||||
let p: MessageDeletePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::MessageDeleted {
|
||||
channel_id: p.channel_id,
|
||||
|
|
@ -120,9 +120,9 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_FRIEND_EVENT => {
|
||||
let p: FriendEventPayload = serde_json::from_slice(payload)?;
|
||||
match p.event_type.as_str() {
|
||||
"request" => {
|
||||
let p: FriendEventPayload = wire::decode(payload)?;
|
||||
match p.event.as_str() {
|
||||
"request" | "REQUEST_RECEIVED" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendRequested {
|
||||
user_id: p.user_id,
|
||||
|
|
@ -130,7 +130,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
})
|
||||
.await;
|
||||
}
|
||||
"accepted" => {
|
||||
"accepted" | "REQUEST_ACCEPTED" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendAccepted {
|
||||
user_id: p.user_id,
|
||||
|
|
@ -138,16 +138,16 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
})
|
||||
.await;
|
||||
}
|
||||
"removed" => {
|
||||
"removed" | "FRIEND_REMOVED" => {
|
||||
let _ = tx
|
||||
.send(NetEvent::FriendRemoved { user_id: p.user_id })
|
||||
.await;
|
||||
}
|
||||
_ => debug!("unhandled friend event: {}", p.event_type),
|
||||
_ => debug!("unhandled friend event: {}", p.event),
|
||||
}
|
||||
}
|
||||
PID_E2EE_DM_KEY_EXCHANGE => {
|
||||
let p: E2eeDmKeyExchangePayload = serde_json::from_slice(payload)?;
|
||||
let p: E2eeDmKeyExchangePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::E2eeDmKeyExchange {
|
||||
dm_id: p.dm_id,
|
||||
|
|
@ -156,13 +156,13 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_E2EE_DM_KEY_EXCHANGE_ACK => {
|
||||
let p: E2eeDmKeyExchangeAckPayload = serde_json::from_slice(payload)?;
|
||||
let p: E2eeDmKeyExchangeAckPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::E2eeDmKeyExchangeAck { dm_id: p.dm_id })
|
||||
.await;
|
||||
}
|
||||
PID_E2EE_DM_MESSAGE => {
|
||||
let p: E2eeDmMessagePayload = serde_json::from_slice(payload)?;
|
||||
let p: E2eeDmMessagePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::E2eeDmMessage {
|
||||
dm_id: p.dm_id,
|
||||
|
|
@ -173,7 +173,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_E2EE_DM_HISTORY => {
|
||||
let p: E2eeDmHistoryPayload = serde_json::from_slice(payload)?;
|
||||
let p: E2eeDmHistoryPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::E2eeDmHistory {
|
||||
dm_id: p.dm_id,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,35 @@ mod social;
|
|||
|
||||
pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_CHANNEL_STATE
|
||||
PID_MEDIA_EVENT => {
|
||||
let event = crate::net::wire::decode(payload)?;
|
||||
let _ = tx.send(NetEvent::MediaEvent(event)).await;
|
||||
}
|
||||
PID_WEBHOOK_RESULT => {
|
||||
let result: crate::net::wire::WebhookResult = crate::net::wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::WebhookResult(WebhookManagementResult {
|
||||
hook: result.hook,
|
||||
secret: result.secret,
|
||||
request_id: result.request_id,
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
PID_WEBHOOK_ERROR_RESULT => {
|
||||
let _ = tx
|
||||
.send(NetEvent::WebhookError(crate::net::wire::decode(payload)?))
|
||||
.await;
|
||||
}
|
||||
PID_WEBHOOK_LIST_RESULT => {
|
||||
let _ = tx
|
||||
.send(NetEvent::WebhookList(crate::net::wire::decode(payload)?))
|
||||
.await;
|
||||
}
|
||||
|
||||
PID_CHANNEL_CREATE
|
||||
| PID_CHANNEL_DELETE
|
||||
| PID_CHANNEL_LIST
|
||||
| PID_CHANNEL_STATE
|
||||
| PID_CHAT_MESSAGE
|
||||
| PID_CHAT_HISTORY
|
||||
| PID_USER_JOIN
|
||||
|
|
@ -36,7 +64,13 @@ pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) ->
|
|||
| PID_E2EE_DM_MESSAGE
|
||||
| PID_E2EE_DM_HISTORY => dm::handle(pid, payload, tx).await?,
|
||||
|
||||
PID_GUILD_LIST
|
||||
PID_BLOCK_LIST
|
||||
| PID_BLOCK_USER
|
||||
| PID_UNBLOCK_USER
|
||||
| PID_GUILD_AUDIT_LOG
|
||||
| PID_GUILD_MEMBER_LIST
|
||||
| PID_GUILD_ROLE_LIST
|
||||
| PID_GUILD_LIST
|
||||
| PID_GUILD_CREATE
|
||||
| PID_GUILD_DELETE
|
||||
| PID_GUILD_MEMBER_JOIN
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::super::super::payloads::*;
|
||||
|
|
@ -8,35 +8,35 @@ use super::super::super::types::*;
|
|||
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
|
||||
match pid {
|
||||
PID_GUILD_LIST => {
|
||||
let p: GuildListPayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildListPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildList {
|
||||
guilds: p
|
||||
.guilds
|
||||
.into_iter()
|
||||
.map(|g| GuildInfo {
|
||||
guild_id: g.guild_id,
|
||||
guild_id: g.id,
|
||||
name: g.name,
|
||||
owner_id: g.owner_id,
|
||||
icon_url: g.icon_url,
|
||||
member_count: g.member_count,
|
||||
icon_url: None,
|
||||
member_count: g.member_count.clamp(0, u32::MAX as i64) as u32,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_CREATE => {
|
||||
let p: GuildInfoPayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildInfoPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildCreated {
|
||||
guild_id: p.guild_id,
|
||||
guild_id: p.id,
|
||||
name: p.name,
|
||||
owner_id: p.owner_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_DELETE => {
|
||||
let p: GuildDeletePayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildDeletePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildDeleted {
|
||||
guild_id: p.guild_id,
|
||||
|
|
@ -44,26 +44,26 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_JOIN => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: crate::net::wire::GuildMemberJoin = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberJoined {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
nickname: p["nickname"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p.guild_id,
|
||||
user_id: String::new(),
|
||||
nickname: String::new(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_LEAVE => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: crate::net::wire::GuildMemberLeave = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberLeft {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p.guild_id,
|
||||
user_id: p.user_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_USER_ROLE_UPDATE => {
|
||||
let p: UserRoleUpdatePayload = serde_json::from_slice(payload)?;
|
||||
let p: UserRoleUpdatePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::UserColor {
|
||||
user_id: p.user_id,
|
||||
|
|
@ -72,7 +72,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_PRESENCE_SYNC => {
|
||||
let p: PresenceSyncPayload = serde_json::from_slice(payload)?;
|
||||
let p: PresenceSyncPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::PresenceSync {
|
||||
presences: p
|
||||
|
|
@ -81,8 +81,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.map(|p| PresenceInfo {
|
||||
user_id: p.user_id,
|
||||
status: p.status,
|
||||
custom_status: p.custom_status,
|
||||
activity: p.activity,
|
||||
custom_status: None,
|
||||
activity: p.activity_type,
|
||||
activity_text: p.activity_text,
|
||||
})
|
||||
.collect(),
|
||||
|
|
@ -90,27 +90,27 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_PRESENCE_EVENT => {
|
||||
let p: PresenceEventPayload = serde_json::from_slice(payload)?;
|
||||
let p: PresenceEventPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::PresenceUpdated {
|
||||
user_id: p.user_id,
|
||||
status: p.status,
|
||||
custom_status: p.custom_status,
|
||||
activity: p.activity,
|
||||
custom_status: None,
|
||||
activity: p.activity_type,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_KICK => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: crate::net::wire::GuildMemberKick = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberKicked {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
user_id: p["user_id"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p.guild_id,
|
||||
user_id: p.user_id,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_INVITE_CREATE => {
|
||||
let p: InviteInfoPayload = serde_json::from_slice(payload)?;
|
||||
let p: InviteInfoPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteCreated {
|
||||
id: p.id,
|
||||
|
|
@ -126,16 +126,16 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_INVITE_ACCEPT => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: crate::net::wire::InviteAccept = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteAccepted {
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
guild_name: p["guild_name"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p.guild_id,
|
||||
guild_name: p.guild_name,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_INVITE_DELETE => {
|
||||
let p: InviteDeletePayload = serde_json::from_slice(payload)?;
|
||||
let p: InviteDeletePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::InviteDeleted {
|
||||
guild_id: p.guild_id,
|
||||
|
|
@ -144,17 +144,17 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_ROLE_CREATE => {
|
||||
let p: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
let p: crate::net::wire::RoleCreate = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::RoleCreated {
|
||||
role_id: p["id"].as_str().unwrap_or_default().into(),
|
||||
guild_id: p["guild_id"].as_str().unwrap_or_default().into(),
|
||||
name: p["name"].as_str().unwrap_or_default().into(),
|
||||
role_id: p.id,
|
||||
guild_id: p.guild_id,
|
||||
name: p.name,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
PID_ROLE_DELETE => {
|
||||
let p: RoleDeletePayload = serde_json::from_slice(payload)?;
|
||||
let p: RoleDeletePayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::RoleDeleted {
|
||||
role_id: p.role_id,
|
||||
|
|
@ -163,7 +163,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_GUILD_AUDIT_LOG => {
|
||||
let p: GuildAuditLogPayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildAuditLogPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildAuditLog {
|
||||
guild_id: p.guild_id,
|
||||
|
|
@ -172,7 +172,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_GUILD_MEMBER_LIST => {
|
||||
let p: GuildMemberListPayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildMemberListPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildMemberList {
|
||||
guild_id: p.guild_id,
|
||||
|
|
@ -181,7 +181,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_GUILD_ROLE_LIST => {
|
||||
let p: GuildRoleListPayload = serde_json::from_slice(payload)?;
|
||||
let p: GuildRoleListPayload = wire::decode(payload)?;
|
||||
let _ = tx
|
||||
.send(NetEvent::GuildRoleList {
|
||||
guild_id: p.guild_id,
|
||||
|
|
@ -190,41 +190,20 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
|
|||
.await;
|
||||
}
|
||||
PID_BLOCK_LIST => {
|
||||
// Server may send {"blocked": [...]} — try to parse properly first,
|
||||
// fall back to JSON value extraction.
|
||||
let blocked: Vec<String> = match serde_json::from_slice::<BlockListPayload>(payload) {
|
||||
Ok(p) => p.blocked,
|
||||
Err(_) => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload)?;
|
||||
v["blocked"]
|
||||
.as_array()
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|x| x.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
let _ = tx.send(NetEvent::BlockList { blocked }).await;
|
||||
let p: BlockListPayload = wire::decode(payload)?;
|
||||
let _ = tx.send(NetEvent::BlockList { blocked: p.blocked }).await;
|
||||
}
|
||||
PID_BLOCK_USER => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload).unwrap_or_default();
|
||||
let user_id = v["user_id"]
|
||||
.as_str()
|
||||
.or_else(|| v["blocked"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let _ = tx.send(NetEvent::BlockedUser { user_id }).await;
|
||||
}
|
||||
PID_UNBLOCK_USER => {
|
||||
let v: serde_json::Value = serde_json::from_slice(payload).unwrap_or_default();
|
||||
let user_id = v["user_id"]
|
||||
.as_str()
|
||||
.or_else(|| v["unblocked"].as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let _ = tx.send(NetEvent::UnblockedUser { user_id }).await;
|
||||
PID_BLOCK_USER | PID_UNBLOCK_USER => {
|
||||
let p: crate::net::wire::SimpleResponse = wire::decode(payload)?;
|
||||
if p.ok {
|
||||
let user_id = p.user_id.unwrap_or_default();
|
||||
let event = if pid == PID_BLOCK_USER {
|
||||
NetEvent::BlockedUser { user_id }
|
||||
} else {
|
||||
NetEvent::UnblockedUser { user_id }
|
||||
};
|
||||
let _ = tx.send(event).await;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,15 @@ pub mod handshake;
|
|||
mod internal;
|
||||
pub mod payloads;
|
||||
mod session;
|
||||
pub mod transport;
|
||||
mod types;
|
||||
pub mod voice;
|
||||
pub mod wire;
|
||||
|
||||
pub use types::{ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo};
|
||||
pub use types::{
|
||||
ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo,
|
||||
WebhookManagementResult, WebhookOperation,
|
||||
};
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
|
|
|||
|
|
@ -1,156 +1,26 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
// LNEx protobuf payload aliases. Schema: protocol/lnex.proto.
|
||||
pub type HelloPayload = crate::net::wire::Hello;
|
||||
pub type AuthPayload = crate::net::wire::Auth;
|
||||
pub type SessionPayload = crate::net::wire::Session;
|
||||
pub type PingPayload = crate::net::wire::Ping;
|
||||
pub type PongPayload = crate::net::wire::Pong;
|
||||
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 ChannelDeletePayload = crate::net::wire::ChannelDelete;
|
||||
pub type ChannelListPayload = crate::net::wire::ChannelList;
|
||||
pub type ChannelListItem = crate::net::wire::ChannelListItem;
|
||||
pub type WireMember = crate::net::wire::MemberInfo;
|
||||
pub type ChatMessagePayload = crate::net::wire::ChatMessage;
|
||||
pub type ChatHistoryPayload = crate::net::wire::ChatHistory;
|
||||
pub type ReactionPayload = crate::net::wire::ReactionPayload;
|
||||
pub type MessageEditPayload = crate::net::wire::MessageEdit;
|
||||
pub type MessageDeletePayload = crate::net::wire::MessageDelete;
|
||||
pub type UserJoinPayload = crate::net::wire::UserJoin;
|
||||
pub type UserLeavePayload = crate::net::wire::UserLeave;
|
||||
pub type ErrorPayload = crate::net::wire::Error;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct HelloPayload {
|
||||
pub lnex_version: String,
|
||||
pub server_pubkey: String,
|
||||
pub challenge_nonce: String,
|
||||
pub node_name: String,
|
||||
pub server_eph_pubkey: String,
|
||||
#[serde(default)]
|
||||
pub private_mode: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct AuthPayload {
|
||||
pub client_pubkey: String,
|
||||
pub nickname: String,
|
||||
pub lnex_version: String,
|
||||
pub signature: String,
|
||||
pub client_eph_pubkey: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct SessionPayload {
|
||||
pub session_id: String,
|
||||
pub token: String,
|
||||
pub expires_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PingPayload {
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PongPayload {
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct JoinChannelPayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct LeaveChannelPayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ChannelStatePayload {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
pub kind: String,
|
||||
pub members: Vec<WireMember>,
|
||||
pub voice_endpoint: String,
|
||||
#[serde(default)]
|
||||
pub guild_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelCreatePayload {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
/// "text" or "voice".
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub guild_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelDeletePayload {
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelListPayload {
|
||||
pub channels: Vec<ChannelListItem>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelListItem {
|
||||
pub channel_id: String,
|
||||
pub channel_name: String,
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub guild_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct WireMember {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub in_voice: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChatMessagePayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub sender_id: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
#[serde(default)]
|
||||
pub edited: bool,
|
||||
/// Optional message_id this message is replying to.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reply_to: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ChatHistoryPayload {
|
||||
pub channel_id: String,
|
||||
pub messages: Vec<ChatMessagePayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ReactionPayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub emoji: String,
|
||||
#[serde(default)]
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MessageEditPayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct MessageDeletePayload {
|
||||
pub message_id: String,
|
||||
pub channel_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserJoinPayload {
|
||||
pub channel_id: String,
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserLeavePayload {
|
||||
pub channel_id: String,
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct ErrorPayload {
|
||||
pub code: u32,
|
||||
pub message: String,
|
||||
}
|
||||
pub use crate::net::wire::{
|
||||
Disconnect, ReadReceipt, ReadReceiptBroadcast, TypingBroadcast, TypingStart,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,162 +1,23 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct E2eeDmKeyExchangePayload {
|
||||
pub dm_id: String,
|
||||
pub e2ee_public_key: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct E2eeDmKeyExchangeAckPayload {
|
||||
pub dm_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct E2eeDmMessagePayload {
|
||||
pub dm_id: String,
|
||||
pub sender_id: String,
|
||||
#[serde(with = "serde_bytes")]
|
||||
pub ciphertext: Vec<u8>,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct E2eeDmHistoryPayload {
|
||||
pub dm_id: String,
|
||||
#[serde(default)]
|
||||
pub messages: Vec<E2eeDmMessagePayload>,
|
||||
#[serde(default)]
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmStartPayload {
|
||||
pub target_user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmStartResponsePayload {
|
||||
pub dm_id: String,
|
||||
pub other_user_id: String,
|
||||
pub other_nickname: String,
|
||||
pub messages: Vec<DmMessagePayload>,
|
||||
#[serde(default)]
|
||||
pub unread_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct DmMessagePayload {
|
||||
pub dm_id: String,
|
||||
pub sender_id: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct DmHistoryPayload {
|
||||
pub dm_id: String,
|
||||
#[serde(default)]
|
||||
pub messages: Vec<DmMessagePayload>,
|
||||
#[serde(default)]
|
||||
pub search_query: Option<String>,
|
||||
#[serde(default)]
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceUpdatePayload {
|
||||
pub status: String,
|
||||
/// Free-form activity type ("playing", "listening", "watching", "streaming").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_type: Option<String>,
|
||||
/// Free-form activity text (e.g. "CS2 ranked").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
/// Free-form custom status text (Discord-style "what's on your mind?").
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct PresenceInfoPayload {
|
||||
pub user_id: String,
|
||||
pub status: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceSyncPayload {
|
||||
pub presences: Vec<PresenceInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PresenceEventPayload {
|
||||
pub user_id: String,
|
||||
pub status: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub custom_status: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub activity_text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendRequestPayload {
|
||||
pub target_user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendAcceptPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendDeclinePayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendRemovePayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct FriendInfoPayload {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub status: String,
|
||||
pub since: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendListPayload {
|
||||
pub friends: Vec<FriendInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BlockUserPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UnblockUserPayload {
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct BlockListPayload {
|
||||
pub blocked: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FriendEventPayload {
|
||||
pub event_type: String,
|
||||
pub user_id: String,
|
||||
pub nickname: Option<String>,
|
||||
}
|
||||
// LNEx protobuf payload aliases. Schema: protocol/lnex.proto.
|
||||
pub type E2eeDmKeyExchangePayload = crate::net::wire::E2eeDmKeyExchange;
|
||||
pub type E2eeDmKeyExchangeAckPayload = crate::net::wire::E2eeDmKeyExchangeAck;
|
||||
pub type E2eeDmMessagePayload = crate::net::wire::E2eeDmMessage;
|
||||
pub type E2eeDmHistoryPayload = crate::net::wire::E2eeDmHistory;
|
||||
pub type DmStartPayload = crate::net::wire::DmStart;
|
||||
pub type DmStartResponsePayload = crate::net::wire::DmStartResponse;
|
||||
pub type DmMessagePayload = crate::net::wire::DmMessage;
|
||||
pub type DmHistoryPayload = crate::net::wire::DmHistory;
|
||||
pub type PresenceUpdatePayload = crate::net::wire::PresenceUpdate;
|
||||
pub type PresenceInfoPayload = crate::net::wire::PresenceInfo;
|
||||
pub type PresenceSyncPayload = crate::net::wire::PresenceSync;
|
||||
pub type PresenceEventPayload = crate::net::wire::PresenceEvent;
|
||||
pub type FriendRequestPayload = crate::net::wire::FriendRequest;
|
||||
pub type FriendAcceptPayload = crate::net::wire::FriendAccept;
|
||||
pub type FriendDeclinePayload = crate::net::wire::FriendDecline;
|
||||
pub type FriendRemovePayload = crate::net::wire::FriendRemove;
|
||||
pub type FriendInfoPayload = crate::net::wire::FriendInfo;
|
||||
pub type FriendListPayload = crate::net::wire::FriendList;
|
||||
pub type BlockUserPayload = crate::net::wire::BlockUser;
|
||||
pub type UnblockUserPayload = crate::net::wire::UnblockUser;
|
||||
pub type BlockListPayload = crate::net::wire::BlockList;
|
||||
pub type FriendEventPayload = crate::net::wire::FriendEvent;
|
||||
|
|
|
|||
|
|
@ -1,176 +1,25 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildCreatePayload {
|
||||
pub name: String,
|
||||
pub icon_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildInfoPayload {
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub owner_id: String,
|
||||
pub icon_url: Option<String>,
|
||||
pub member_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildListPayload {
|
||||
pub guilds: Vec<GuildInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildDeletePayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildJoinPayload {
|
||||
pub guild_id: String,
|
||||
pub invite_code: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildLeavePayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct UserRoleUpdatePayload {
|
||||
pub user_id: String,
|
||||
pub guild_id: String,
|
||||
pub color: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteCreatePayload {
|
||||
pub guild_id: String,
|
||||
pub max_uses: Option<i64>,
|
||||
pub expires_in_seconds: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteAcceptPayload {
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct InviteDeletePayload {
|
||||
pub guild_id: String,
|
||||
pub invite_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleCreatePayload {
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub color: Option<String>,
|
||||
pub permissions: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleDeletePayload {
|
||||
pub guild_id: String,
|
||||
pub role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildMemberKickPayload {
|
||||
pub guild_id: String,
|
||||
pub user_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct InviteInfoPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub guild_name: String,
|
||||
pub code: String,
|
||||
pub creator_id: String,
|
||||
pub max_uses: Option<i64>,
|
||||
pub uses: i64,
|
||||
pub expires_at: Option<i64>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildAuditLogFetchPayload {
|
||||
pub guild_id: String,
|
||||
#[serde(default = "default_audit_limit")]
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
fn default_audit_limit() -> i64 {
|
||||
50
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct AuditLogEntryPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub actor_id: String,
|
||||
pub action: String,
|
||||
#[serde(default)]
|
||||
pub target_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub target_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildAuditLogPayload {
|
||||
pub guild_id: String,
|
||||
pub entries: Vec<AuditLogEntryPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildMemberListFetchPayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildMemberInfoPayload {
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
pub joined_at: i64,
|
||||
pub role_color: String,
|
||||
pub role_name: String,
|
||||
pub is_owner: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildMemberListPayload {
|
||||
pub guild_id: String,
|
||||
pub members: Vec<GuildMemberInfoPayload>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct RoleAssignPayload {
|
||||
pub guild_id: String,
|
||||
pub user_id: String,
|
||||
pub role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct GuildRoleListFetchPayload {
|
||||
pub guild_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildRoleInfoPayload {
|
||||
pub id: String,
|
||||
pub guild_id: String,
|
||||
pub name: String,
|
||||
pub color: String,
|
||||
pub permissions: u64,
|
||||
pub position: i32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GuildRoleListPayload {
|
||||
pub guild_id: String,
|
||||
pub roles: Vec<GuildRoleInfoPayload>,
|
||||
}
|
||||
// LNEx protobuf payload aliases. Schema: protocol/lnex.proto.
|
||||
pub type GuildCreatePayload = crate::net::wire::GuildCreate;
|
||||
pub type GuildInfoPayload = crate::net::wire::GuildInfo;
|
||||
pub type GuildListPayload = crate::net::wire::GuildList;
|
||||
pub type GuildDeletePayload = crate::net::wire::GuildDelete;
|
||||
pub type GuildJoinPayload = crate::net::wire::GuildMemberJoin;
|
||||
pub type GuildLeavePayload = crate::net::wire::GuildMemberLeave;
|
||||
pub type UserRoleUpdatePayload = crate::net::wire::UserRoleUpdate;
|
||||
pub type InviteCreatePayload = crate::net::wire::InviteCreate;
|
||||
pub type InviteAcceptPayload = crate::net::wire::InviteAccept;
|
||||
pub type InviteDeletePayload = crate::net::wire::InviteDelete;
|
||||
pub type RoleCreatePayload = crate::net::wire::RoleCreate;
|
||||
pub type RoleDeletePayload = crate::net::wire::RoleDelete;
|
||||
pub type GuildMemberKickPayload = crate::net::wire::GuildMemberKick;
|
||||
pub type InviteInfoPayload = crate::net::wire::InviteInfo;
|
||||
pub type GuildAuditLogFetchPayload = crate::net::wire::GuildAuditLogFetch;
|
||||
pub type AuditLogEntryPayload = crate::net::wire::AuditLogEntry;
|
||||
pub type GuildAuditLogPayload = crate::net::wire::GuildAuditLog;
|
||||
pub type GuildMemberListFetchPayload = crate::net::wire::GuildMemberListFetch;
|
||||
pub type GuildMemberInfoPayload = crate::net::wire::GuildMemberInfo;
|
||||
pub type GuildMemberListPayload = crate::net::wire::GuildMemberList;
|
||||
pub type RoleAssignPayload = crate::net::wire::RoleAssign;
|
||||
pub type GuildRoleListFetchPayload = crate::net::wire::GuildRoleListFetch;
|
||||
pub type GuildRoleInfoPayload = crate::net::wire::GuildRoleInfo;
|
||||
pub type GuildRoleListPayload = crate::net::wire::GuildRoleList;
|
||||
|
|
|
|||
|
|
@ -67,7 +67,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 = "v1";
|
||||
pub const LNEX_VERSION: &str = "v2";
|
||||
pub const HDR_SIZE: usize = 12;
|
||||
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
|
||||
|
||||
|
|
@ -78,3 +78,18 @@ mod guild;
|
|||
pub use channel::*;
|
||||
pub use dm::*;
|
||||
pub use guild::*;
|
||||
|
||||
pub const PID_MEDIA_CONTROL: u16 = 0x0180;
|
||||
pub const PID_MEDIA_EVENT: u16 = 0x0181;
|
||||
pub const PID_WEBHOOK_CREATE: u16 = 0x0200;
|
||||
pub const PID_WEBHOOK_LIST: u16 = 0x0201;
|
||||
pub const PID_WEBHOOK_ROTATE: u16 = 0x0202;
|
||||
pub const PID_WEBHOOK_REVOKE: u16 = 0x0203;
|
||||
pub const PID_WEBHOOK_RESULT: u16 = 0x0204;
|
||||
pub const PID_WEBHOOK_LIST_RESULT: u16 = 0x0205;
|
||||
|
||||
pub const PID_WEBHOOK_ERROR_RESULT: u16 = 0x0206;
|
||||
|
||||
pub const PID_VOICE_SESSION: u16 = 0x0012;
|
||||
|
||||
pub const PID_VOICE_STATE: u16 = 0x0011;
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::net::TcpStream;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{MissedTickBehavior, interval};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::net::wire;
|
||||
use crate::net::{
|
||||
framing, handshake, internal,
|
||||
payloads::*,
|
||||
types::{NetCommand, NetEvent},
|
||||
};
|
||||
use serde_json;
|
||||
|
||||
use super::super::switch::ReconnectRequested;
|
||||
use super::{VoiceState, handle_cmd};
|
||||
|
|
@ -25,11 +25,22 @@ pub async fn session_loop(
|
|||
cmd_rx: &mut mpsc::Receiver<NetCommand>,
|
||||
event_tx: &mpsc::Sender<NetEvent>,
|
||||
) -> Result<()> {
|
||||
let mut stream = TcpStream::connect(address).await?;
|
||||
let connection = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
crate::net::transport::connect_with_peer(address),
|
||||
)
|
||||
.await
|
||||
.context("gateway connection timed out")??;
|
||||
let peer = connection.peer;
|
||||
let mut stream = connection.stream;
|
||||
let mut seq = 0u32;
|
||||
|
||||
let (session_id, node_name, private_mode, crypto) =
|
||||
handshake::run(&mut stream, identity, &mut seq).await?;
|
||||
let (session_id, node_name, private_mode, crypto) = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
handshake::run(&mut stream, identity, &mut seq),
|
||||
)
|
||||
.await
|
||||
.context("gateway handshake timed out")??;
|
||||
let _ = event_tx
|
||||
.send(NetEvent::Connected {
|
||||
session_id: session_id.clone(),
|
||||
|
|
@ -44,31 +55,58 @@ pub async fn session_loop(
|
|||
&mut stream,
|
||||
PID_JOIN_CHANNEL,
|
||||
&mut seq,
|
||||
&serde_json::to_vec(&JoinChannelPayload { channel_id })?,
|
||||
&wire::encode(&JoinChannelPayload { channel_id })?,
|
||||
&crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let mut voice_state = VoiceState::new(&crypto, event_tx).await?;
|
||||
let (reader, mut stream) = tokio::io::split(stream);
|
||||
let mut incoming = framing::io::Reader::new(reader, crypto.clone());
|
||||
let mut voice_state: Option<VoiceState> = None;
|
||||
let mut used_voice_routes = std::collections::HashSet::new();
|
||||
let mut voice_endpoint: Option<std::net::SocketAddr> = None;
|
||||
let mut voice_tick = interval(Duration::from_secs(5));
|
||||
voice_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
let mut ping_tick = interval(Duration::from_secs(2));
|
||||
ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = voice_tick.tick() => { if let Some(voice)=voice_state.as_mut() {voice.keep_alive().await?;} }
|
||||
_ = ping_tick.tick() => {
|
||||
let ts = now_ms();
|
||||
let payload = serde_json::to_vec(&PingPayload { timestamp: ts })?;
|
||||
let payload = wire::encode(&PingPayload { timestamp: ts })?;
|
||||
framing::io::write_encrypted(&mut stream, PID_PING, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
result = framing::io::read_encrypted(&mut stream, &crypto) => {
|
||||
result = incoming.next() => {
|
||||
let pkt = result?;
|
||||
if pkt.packet_id == PID_VOICE_SESSION {
|
||||
let session:wire::VoiceSession=wire::decode(&pkt.payload)?;
|
||||
anyhow::ensure!(session.route_id.len()==16 && session.c2s_key.len()==32 && session.s2c_key.len()==32,"invalid voice credentials");
|
||||
anyhow::ensure!(used_voice_routes.len()<1024 && used_voice_routes.insert(session.route_id.clone()),"voice credentials must be fresh; reconnect required");
|
||||
let mut voice=VoiceState::new(event_tx,peer.is_ipv6()).await?;
|
||||
if let Some(endpoint)=voice_endpoint {voice.set_endpoint(endpoint).await?;}
|
||||
voice.configure(session).await?;
|
||||
voice_state=Some(voice);continue;
|
||||
}
|
||||
if pkt.packet_id == PID_VOICE_STATE {
|
||||
let state:wire::VoiceState=wire::decode(&pkt.payload)?;
|
||||
if state.state=="disconnected" && state.user_id==identity.pubkey_hex {
|
||||
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(state.channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
|
||||
channels.retain(|id|id!=&state.channel_id);
|
||||
let _=event_tx.send(NetEvent::VoiceRevoked {channel_id:state.channel_id}).await;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if pkt.packet_id == PID_CHANNEL_STATE
|
||||
&& let Ok(p) = serde_json::from_slice::<ChannelStatePayload>(&pkt.payload)
|
||||
&& !p.voice_endpoint.is_empty()
|
||||
&& let Ok(p) = wire::decode::<ChannelStatePayload>(&pkt.payload)
|
||||
&& p.kind == "voice" && !p.voice_endpoint.is_empty()
|
||||
{
|
||||
voice_endpoint = p.voice_endpoint.parse().ok();
|
||||
let mut endpoint:std::net::SocketAddr=p.voice_endpoint.parse()?;
|
||||
if endpoint.ip().is_unspecified() {endpoint.set_ip(peer.ip());}
|
||||
voice_endpoint=Some(endpoint);
|
||||
if let Some(voice)=voice_state.as_mut(){voice.set_endpoint(endpoint).await?;}
|
||||
}
|
||||
internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?;
|
||||
}
|
||||
|
|
@ -76,7 +114,7 @@ pub async fn session_loop(
|
|||
match cmd {
|
||||
None | Some(NetCommand::Disconnect) => {
|
||||
let _ = framing::io::write_encrypted(&mut stream, PID_DISCONNECT, &mut seq,
|
||||
&serde_json::to_vec(&serde_json::json!({"reason":"bye"})).unwrap(), &crypto).await;
|
||||
&wire::encode(&Disconnect {reason: "bye".into()})?, &crypto).await;
|
||||
return Ok(());
|
||||
}
|
||||
Some(NetCommand::Connect { address, auto_reconnect }) => {
|
||||
|
|
@ -92,15 +130,16 @@ pub async fn session_loop(
|
|||
Some(NetCommand::JoinChannel { channel_id }) => {
|
||||
track_channel(channels, &channel_id);
|
||||
framing::io::write_encrypted(&mut stream, PID_JOIN_CHANNEL, &mut seq,
|
||||
&serde_json::to_vec(&JoinChannelPayload { channel_id })?, &crypto).await?;
|
||||
&wire::encode(&JoinChannelPayload { channel_id })?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::LeaveChannel { 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::io::write_encrypted(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
|
||||
&serde_json::to_vec(&LeaveChannelPayload { channel_id })?, &crypto).await?;
|
||||
&wire::encode(&LeaveChannelPayload { channel_id })?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
|
||||
let payload = serde_json::to_vec(&ChannelCreatePayload {
|
||||
let payload = wire::encode(&ChannelCreatePayload {
|
||||
channel_id,
|
||||
channel_name,
|
||||
kind,
|
||||
|
|
@ -109,11 +148,11 @@ pub async fn session_loop(
|
|||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelDelete { channel_id }) => {
|
||||
let payload = serde_json::to_vec(&ChannelDeletePayload { channel_id })?;
|
||||
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::ChannelList) => {
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"{}", &crypto).await?;
|
||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"", &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
|
||||
let msg = ChatMessagePayload {
|
||||
|
|
@ -123,20 +162,13 @@ pub async fn session_loop(
|
|||
edited: false,
|
||||
reply_to,
|
||||
};
|
||||
framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &serde_json::to_vec(&msg)?, &crypto).await?;
|
||||
framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?, &crypto).await?;
|
||||
}
|
||||
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
|
||||
let sender_pubkey = identity.verifying_key()
|
||||
.map(|k| k.to_bytes())
|
||||
.unwrap_or([0u8; 32]);
|
||||
voice_state.send_voice(channel_id, voice_pkt_seq, timestamp, &opus_data, &crypto, voice_endpoint, &sender_pubkey).await?;
|
||||
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
|
||||
}
|
||||
Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({
|
||||
"channel_id": channel_id,
|
||||
"last_read_message_id": last_read_message_id,
|
||||
"user_id": identity.pubkey_hex.clone(),
|
||||
}))?;
|
||||
let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?;
|
||||
framing::io::write_encrypted(&mut stream, PID_READ_RECEIPT, &mut seq, &payload, &crypto).await?;
|
||||
}
|
||||
Some(other) => handle_cmd(other, &mut stream, &mut seq, &crypto, identity).await?,
|
||||
|
|
|
|||
|
|
@ -1,60 +1,64 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
NetCommand::PresenceUpdate {
|
||||
status,
|
||||
custom_status,
|
||||
custom_status: _,
|
||||
activity,
|
||||
activity_text,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&PresenceUpdatePayload {
|
||||
let payload = wire::encode(&PresenceUpdatePayload {
|
||||
status,
|
||||
activity_type: activity,
|
||||
activity_text,
|
||||
custom_status,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_PRESENCE_UPDATE, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::FriendRequest { target_user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendRequestPayload { target_user_id })?;
|
||||
let payload = wire::encode(&FriendRequestPayload {
|
||||
to_user_id: target_user_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_REQUEST, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendAccept { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendAcceptPayload { user_id })?;
|
||||
let payload = wire::encode(&FriendAcceptPayload {
|
||||
from_user_id: user_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_ACCEPT, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendDecline { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendDeclinePayload { user_id })?;
|
||||
let payload = wire::encode(&FriendDeclinePayload {
|
||||
from_user_id: user_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_DECLINE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendRemove { user_id } => {
|
||||
let payload = serde_json::to_vec(&FriendRemovePayload { user_id })?;
|
||||
let payload = wire::encode(&FriendRemovePayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_REMOVE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::FriendList => {
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"{}", crypto).await?;
|
||||
framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"", crypto).await?;
|
||||
}
|
||||
NetCommand::BlockUser { user_id } => {
|
||||
let payload = serde_json::to_vec(&BlockUserPayload { user_id })?;
|
||||
let payload = wire::encode(&BlockUserPayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_BLOCK_USER, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::UnblockUser { user_id } => {
|
||||
let payload = serde_json::to_vec(&UnblockUserPayload { user_id })?;
|
||||
let payload = wire::encode(&UnblockUserPayload { user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_UNBLOCK_USER, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::BlockList => {
|
||||
framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"{}", crypto).await?;
|
||||
framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"", crypto).await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,43 +1,48 @@
|
|||
use crate::net::wire;
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
NetCommand::GuildCreate { name } => {
|
||||
let payload = serde_json::to_vec(&GuildCreatePayload {
|
||||
name,
|
||||
icon_url: None,
|
||||
})?;
|
||||
let payload = wire::encode(&GuildCreatePayload { name })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildDelete { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildDeletePayload { guild_id })?;
|
||||
let payload = wire::encode(&GuildDeletePayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildList => {
|
||||
framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"{}", crypto).await?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"", crypto).await?;
|
||||
}
|
||||
NetCommand::GuildJoin {
|
||||
guild_id,
|
||||
invite_code,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&GuildJoinPayload {
|
||||
guild_id,
|
||||
invite_code,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto)
|
||||
.await?;
|
||||
if let Some(code) = invite_code {
|
||||
let payload = wire::encode(&InviteAcceptPayload {
|
||||
code,
|
||||
..Default::default()
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto)
|
||||
.await?;
|
||||
} else {
|
||||
let payload = wire::encode(&GuildJoinPayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
NetCommand::GuildLeave { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildLeavePayload { guild_id })?;
|
||||
let payload = wire::encode(&GuildLeavePayload {
|
||||
guild_id,
|
||||
user_id: String::new(),
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
|
|
@ -46,7 +51,7 @@ pub async fn handle_cmd(
|
|||
max_uses,
|
||||
expires_in_seconds,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&InviteCreatePayload {
|
||||
let payload = wire::encode(&InviteCreatePayload {
|
||||
guild_id,
|
||||
max_uses,
|
||||
expires_in_seconds,
|
||||
|
|
@ -54,14 +59,17 @@ pub async fn handle_cmd(
|
|||
framing::io::write_encrypted(stream, PID_INVITE_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::InviteAccept { code } => {
|
||||
let payload = serde_json::to_vec(&InviteAcceptPayload { code })?;
|
||||
let payload = wire::encode(&InviteAcceptPayload {
|
||||
code,
|
||||
..Default::default()
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::InviteDelete {
|
||||
guild_id,
|
||||
invite_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&InviteDeletePayload {
|
||||
let payload = wire::encode(&InviteDeletePayload {
|
||||
guild_id,
|
||||
invite_id,
|
||||
})?;
|
||||
|
|
@ -73,30 +81,31 @@ pub async fn handle_cmd(
|
|||
color,
|
||||
permissions,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleCreatePayload {
|
||||
let payload = wire::encode(&RoleCreatePayload {
|
||||
guild_id,
|
||||
name,
|
||||
color,
|
||||
permissions,
|
||||
id: String::new(),
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_ROLE_CREATE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::RoleDelete { guild_id, role_id } => {
|
||||
let payload = serde_json::to_vec(&RoleDeletePayload { guild_id, role_id })?;
|
||||
let payload = wire::encode(&RoleDeletePayload { guild_id, role_id })?;
|
||||
framing::io::write_encrypted(stream, PID_ROLE_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::GuildMemberKick { guild_id, user_id } => {
|
||||
let payload = serde_json::to_vec(&GuildMemberKickPayload { guild_id, user_id })?;
|
||||
let payload = wire::encode(&GuildMemberKickPayload { guild_id, user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_KICK, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildAuditLogFetch { guild_id, limit } => {
|
||||
let payload = serde_json::to_vec(&GuildAuditLogFetchPayload { guild_id, limit })?;
|
||||
let payload = wire::encode(&GuildAuditLogFetchPayload { guild_id, limit })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::GuildMemberListFetch { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildMemberListFetchPayload { guild_id })?;
|
||||
let payload = wire::encode(&GuildMemberListFetchPayload { guild_id })?;
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_GUILD_MEMBER_LIST_FETCH,
|
||||
|
|
@ -111,7 +120,7 @@ pub async fn handle_cmd(
|
|||
user_id,
|
||||
role_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleAssignPayload {
|
||||
let payload = wire::encode(&RoleAssignPayload {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
|
|
@ -124,7 +133,7 @@ pub async fn handle_cmd(
|
|||
user_id,
|
||||
role_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&RoleAssignPayload {
|
||||
let payload = wire::encode(&RoleAssignPayload {
|
||||
guild_id,
|
||||
user_id,
|
||||
role_id,
|
||||
|
|
@ -133,7 +142,7 @@ pub async fn handle_cmd(
|
|||
.await?;
|
||||
}
|
||||
NetCommand::GuildRoleListFetch { guild_id } => {
|
||||
let payload = serde_json::to_vec(&GuildRoleListFetchPayload { guild_id })?;
|
||||
let payload = wire::encode(&GuildRoleListFetchPayload { guild_id })?;
|
||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload, crypto)
|
||||
.await?;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
mod friends;
|
||||
mod guild;
|
||||
|
||||
use crate::net::wire;
|
||||
use anyhow::Result;
|
||||
use serde_json;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
||||
|
|
@ -12,12 +11,32 @@ use super::core::now_ms;
|
|||
|
||||
pub async fn handle_cmd(
|
||||
cmd: NetCommand,
|
||||
stream: &mut TcpStream,
|
||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
crypto: &SessionCrypto,
|
||||
identity: &Identity,
|
||||
) -> Result<()> {
|
||||
match cmd {
|
||||
NetCommand::MediaControl(message) => {
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_MEDIA_CONTROL,
|
||||
seq,
|
||||
&wire::encode(&message)?,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::Webhook { operation, request } => {
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
operation.packet_id(),
|
||||
seq,
|
||||
&wire::encode(&request)?,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
cmd @ (NetCommand::GuildCreate { .. }
|
||||
| NetCommand::GuildDelete { .. }
|
||||
| NetCommand::GuildList
|
||||
|
|
@ -52,7 +71,7 @@ pub async fn handle_cmd(
|
|||
message_id,
|
||||
emoji,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&ReactionPayload {
|
||||
let payload = wire::encode(&ReactionPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
emoji,
|
||||
|
|
@ -66,7 +85,7 @@ pub async fn handle_cmd(
|
|||
message_id,
|
||||
emoji,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&ReactionPayload {
|
||||
let payload = wire::encode(&ReactionPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
emoji,
|
||||
|
|
@ -86,7 +105,7 @@ pub async fn handle_cmd(
|
|||
message_id,
|
||||
content,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&MessageEditPayload {
|
||||
let payload = wire::encode(&MessageEditPayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
content,
|
||||
|
|
@ -97,14 +116,14 @@ pub async fn handle_cmd(
|
|||
channel_id,
|
||||
message_id,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&MessageDeletePayload {
|
||||
let payload = wire::encode(&MessageDeletePayload {
|
||||
message_id,
|
||||
channel_id,
|
||||
})?;
|
||||
framing::io::write_encrypted(stream, PID_MESSAGE_DELETE, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmStart { target_user_id } => {
|
||||
let payload = serde_json::to_vec(&DmStartPayload { target_user_id })?;
|
||||
let payload = wire::encode(&DmStartPayload { target_user_id })?;
|
||||
framing::io::write_encrypted(stream, PID_DM_START, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmSend { dm_id, content } => {
|
||||
|
|
@ -114,25 +133,19 @@ pub async fn handle_cmd(
|
|||
content,
|
||||
timestamp: now_ms(),
|
||||
};
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_DM_MESSAGE,
|
||||
seq,
|
||||
&serde_json::to_vec(&msg)?,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
framing::io::write_encrypted(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?, crypto)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::TypingStart { channel_id } => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({"channel_id": channel_id}))?;
|
||||
let payload = wire::encode(&TypingStart { channel_id })?;
|
||||
framing::io::write_encrypted(stream, PID_TYPING_START, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmReadAck { dm_id } => {
|
||||
let payload = serde_json::to_vec(&serde_json::json!({"dm_id": dm_id}))?;
|
||||
let payload = wire::encode(&crate::net::wire::DmReadAck { dm_id })?;
|
||||
framing::io::write_encrypted(stream, PID_DM_READ_ACK, seq, &payload, crypto).await?;
|
||||
}
|
||||
NetCommand::DmSearch { dm_id, query } => {
|
||||
let payload = serde_json::to_vec(&DmHistoryPayload {
|
||||
let payload = wire::encode(&DmHistoryPayload {
|
||||
dm_id,
|
||||
messages: vec![],
|
||||
search_query: if query.is_empty() { None } else { Some(query) },
|
||||
|
|
@ -144,7 +157,7 @@ pub async fn handle_cmd(
|
|||
dm_id,
|
||||
e2ee_public_key,
|
||||
} => {
|
||||
let payload = serde_json::to_vec(&E2eeDmKeyExchangePayload {
|
||||
let payload = wire::encode(&E2eeDmKeyExchangePayload {
|
||||
dm_id,
|
||||
e2ee_public_key,
|
||||
})?;
|
||||
|
|
@ -152,7 +165,7 @@ pub async fn handle_cmd(
|
|||
.await?;
|
||||
}
|
||||
NetCommand::E2eeDmKeyExchangeAck { dm_id } => {
|
||||
let payload = serde_json::to_vec(&E2eeDmKeyExchangeAckPayload { dm_id })?;
|
||||
let payload = wire::encode(&E2eeDmKeyExchangeAckPayload { dm_id })?;
|
||||
framing::io::write_encrypted(
|
||||
stream,
|
||||
PID_E2EE_DM_KEY_EXCHANGE_ACK,
|
||||
|
|
@ -173,13 +186,13 @@ pub async fn handle_cmd(
|
|||
stream,
|
||||
PID_E2EE_DM_MESSAGE,
|
||||
seq,
|
||||
&serde_json::to_vec(&msg)?,
|
||||
&wire::encode(&msg)?,
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
NetCommand::E2eeDmHistory { dm_id, limit } => {
|
||||
let payload = serde_json::to_vec(&E2eeDmHistoryPayload {
|
||||
let payload = wire::encode(&E2eeDmHistoryPayload {
|
||||
dm_id,
|
||||
messages: vec![],
|
||||
limit,
|
||||
|
|
|
|||
|
|
@ -1,47 +1,151 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use crate::net::{
|
||||
types::NetEvent,
|
||||
voice::{self, Credentials, ReplayWindow},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::mpsc;
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use tokio::{net::UdpSocket, sync::mpsc};
|
||||
|
||||
use crate::net::{crypto::SessionCrypto, types::NetEvent};
|
||||
|
||||
pub struct State {
|
||||
pub udp: Arc<UdpSocket>,
|
||||
pub seq: u64,
|
||||
struct ReceiveState {
|
||||
credentials: Credentials,
|
||||
endpoint: SocketAddr,
|
||||
replay: ReplayWindow,
|
||||
}
|
||||
pub struct State {
|
||||
udp: Arc<UdpSocket>,
|
||||
credentials: Option<Credentials>,
|
||||
endpoint: Option<SocketAddr>,
|
||||
receive: Arc<Mutex<Option<ReceiveState>>>,
|
||||
receiver: tokio::task::JoinHandle<()>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub async fn new(crypto: &SessionCrypto, event_tx: &mpsc::Sender<NetEvent>) -> Result<Self> {
|
||||
let udp = Arc::new(UdpSocket::bind("0.0.0.0:0").await?);
|
||||
crate::net::voice::spawn_recv(udp.clone(), (*crypto).clone(), event_tx.clone());
|
||||
Ok(Self { udp, seq: 0 })
|
||||
pub async fn new(event_tx: &mpsc::Sender<NetEvent>, ipv6: bool) -> Result<Self> {
|
||||
let udp = Arc::new(UdpSocket::bind(if ipv6 { "[::]:0" } else { "0.0.0.0:0" }).await?);
|
||||
let receive = Arc::new(Mutex::new(None::<ReceiveState>));
|
||||
let worker_udp = udp.clone();
|
||||
let worker_state = receive.clone();
|
||||
let events = event_tx.clone();
|
||||
let receiver = tokio::spawn(async move {
|
||||
let mut bytes = vec![0u8; voice::MAX_DATAGRAM + 1];
|
||||
while let Ok((length, source)) = worker_udp.recv_from(&mut bytes).await {
|
||||
let event = {
|
||||
let Ok(mut state) = worker_state.lock() else {
|
||||
break;
|
||||
};
|
||||
let Some(state) = state.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
if source != state.endpoint {
|
||||
continue;
|
||||
}
|
||||
let Ok((sequence, frame)) = voice::decode(&state.credentials, &bytes[..length])
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !state.replay.accept(sequence) || frame.opus.is_empty() {
|
||||
continue;
|
||||
}
|
||||
NetEvent::VoicePacket {
|
||||
channel_id: voice::channel_key(&frame.channel_id),
|
||||
voice_seq: frame.voice_seq,
|
||||
timestamp: frame.timestamp,
|
||||
sender: source,
|
||||
sender_id: frame.sender_user_id,
|
||||
opus_data: frame.opus,
|
||||
}
|
||||
};
|
||||
if events.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
udp,
|
||||
credentials: None,
|
||||
endpoint: None,
|
||||
receive,
|
||||
receiver,
|
||||
sequence: 0,
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn send_voice(
|
||||
&mut self,
|
||||
channel_id: u64,
|
||||
voice_pkt_seq: u32,
|
||||
timestamp: u32,
|
||||
opus_data: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
endpoint: Option<std::net::SocketAddr>,
|
||||
sender_pubkey: &[u8; 32],
|
||||
) -> Result<()> {
|
||||
if let Some(ep) = endpoint {
|
||||
let pkt = crate::net::voice::build_packet(
|
||||
channel_id,
|
||||
voice_pkt_seq,
|
||||
timestamp,
|
||||
opus_data,
|
||||
crypto,
|
||||
self.seq,
|
||||
sender_pubkey,
|
||||
);
|
||||
let _ = self.udp.send_to(&pkt, ep).await;
|
||||
self.seq += 1;
|
||||
pub async fn configure(&mut self, session: crate::net::wire::VoiceSession) -> Result<()> {
|
||||
let credentials = Credentials::try_from(session)?;
|
||||
if self
|
||||
.credentials
|
||||
.as_ref()
|
||||
.is_some_and(|old| old.route_id == credentials.route_id)
|
||||
{
|
||||
anyhow::bail!("voice credentials must be fresh on each join");
|
||||
}
|
||||
self.credentials = Some(credentials);
|
||||
self.sequence = 0;
|
||||
self.sync_receive();
|
||||
self.keep_alive().await
|
||||
}
|
||||
pub async fn set_endpoint(&mut self, endpoint: SocketAddr) -> Result<()> {
|
||||
if self.endpoint == Some(endpoint) {
|
||||
return Ok(());
|
||||
}
|
||||
self.endpoint = Some(endpoint);
|
||||
self.sync_receive();
|
||||
self.keep_alive().await
|
||||
}
|
||||
fn sync_receive(&self) {
|
||||
if let Ok(mut state) = self.receive.lock() {
|
||||
if let Some((credentials, endpoint)) = self.credentials.as_ref().zip(self.endpoint) {
|
||||
if let Some(existing) = state
|
||||
.as_mut()
|
||||
.filter(|existing| existing.credentials.route_id == credentials.route_id)
|
||||
{
|
||||
existing.endpoint = endpoint;
|
||||
} else {
|
||||
*state = Some(ReceiveState {
|
||||
credentials: credentials.clone(),
|
||||
endpoint,
|
||||
replay: ReplayWindow::default(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
*state = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn channel_id(&self) -> Option<&str> {
|
||||
self.credentials
|
||||
.as_ref()
|
||||
.map(|value| value.channel_id.as_str())
|
||||
}
|
||||
pub async fn keep_alive(&mut self) -> Result<()> {
|
||||
self.send(None, 0, 0, b"").await
|
||||
}
|
||||
pub async fn send(
|
||||
&mut self,
|
||||
channel: Option<u64>,
|
||||
voice_seq: u32,
|
||||
timestamp: u32,
|
||||
opus: &[u8],
|
||||
) -> Result<()> {
|
||||
let Some((credentials, endpoint)) = self.credentials.as_ref().zip(self.endpoint) else {
|
||||
return Ok(());
|
||||
};
|
||||
if channel.is_some_and(|key| key != voice::channel_key(&credentials.channel_id)) {
|
||||
return Ok(());
|
||||
}
|
||||
let packet = voice::encode(credentials, self.sequence, voice_seq, timestamp, opus)?;
|
||||
self.sequence = self
|
||||
.sequence
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow::anyhow!("voice sequence exhausted"))?;
|
||||
self.udp.send_to(&packet, endpoint).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for State {
|
||||
fn drop(&mut self) {
|
||||
self.receiver.abort();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ pub async fn net_task(
|
|||
let mut target: Option<SessionTarget> = None;
|
||||
let mut failures: u32 = 0;
|
||||
|
||||
loop {
|
||||
'session: loop {
|
||||
let Some(mut session) = target.take() else {
|
||||
match wait_for_connect(&mut cmd_rx).await {
|
||||
Some(t) => {
|
||||
|
|
@ -39,7 +39,26 @@ pub async fn net_task(
|
|||
delay_secs: delay.as_secs(),
|
||||
})
|
||||
.await;
|
||||
sleep(delay).await;
|
||||
let delay = sleep(delay);
|
||||
tokio::pin!(delay);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = &mut delay => break,
|
||||
command = cmd_rx.recv() => match command {
|
||||
Some(NetCommand::Connect {address,auto_reconnect}) => {
|
||||
session.address=address;session.auto_reconnect=auto_reconnect;
|
||||
failures=0;target=Some(session);continue 'session;
|
||||
}
|
||||
Some(NetCommand::Disconnect) => {
|
||||
failures=0;
|
||||
let _=event_tx.send(NetEvent::Disconnected {reason:"disconnected".into(),will_retry:false}).await;
|
||||
continue 'session;
|
||||
}
|
||||
None => return,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
|
|
@ -109,8 +128,30 @@ async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<Ses
|
|||
channels: vec!["general".into()],
|
||||
});
|
||||
}
|
||||
Some(NetCommand::Disconnect) | None => return None,
|
||||
None => return None,
|
||||
Some(NetCommand::Disconnect) => continue,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn disconnected_cancel_does_not_disable_later_connections() {
|
||||
let (sender, mut receiver) = mpsc::channel(4);
|
||||
sender.send(NetCommand::Disconnect).await.unwrap();
|
||||
sender
|
||||
.send(NetCommand::Connect {
|
||||
address: "127.0.0.1:7600".into(),
|
||||
auto_reconnect: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
wait_for_connect(&mut receiver).await.unwrap().address,
|
||||
"127.0.0.1:7600"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
112
src/net/transport.rs
Normal file
112
src/net/transport.rs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
//! TCP/TLS transport selection. TLS never falls back to plaintext after an error.
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
pub trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
|
||||
pub type Stream = Box<dyn AsyncStream>;
|
||||
|
||||
pub struct Connected {
|
||||
pub stream: Stream,
|
||||
pub peer: std::net::SocketAddr,
|
||||
}
|
||||
pub async fn connect(address: &str) -> Result<Stream> {
|
||||
Ok(connect_with_peer(address).await?.stream)
|
||||
}
|
||||
pub async fn connect_with_peer(address: &str) -> Result<Connected> {
|
||||
let explicit_plain = address.starts_with("lnex://");
|
||||
let authority = address
|
||||
.strip_prefix("lnexs://")
|
||||
.or_else(|| address.strip_prefix("lnex://"))
|
||||
.unwrap_or(address);
|
||||
if authority.contains('/')
|
||||
|| authority.contains('@')
|
||||
|| authority.contains('?')
|
||||
|| authority.contains('#')
|
||||
{
|
||||
bail!("expected a server host and port");
|
||||
}
|
||||
let (host, port) = if let Some(value) = authority.strip_prefix('[') {
|
||||
let (host, tail) = value.split_once(']').context("invalid IPv6 address")?;
|
||||
let port = if tail.is_empty() {
|
||||
7600
|
||||
} else {
|
||||
tail.strip_prefix(':')
|
||||
.context("invalid server address")?
|
||||
.parse()?
|
||||
};
|
||||
(host, port)
|
||||
} else if let Some((host, port)) = authority.rsplit_once(':') {
|
||||
(host, port.parse()?)
|
||||
} else {
|
||||
(authority, 7600)
|
||||
};
|
||||
if host.is_empty() {
|
||||
bail!("server host is empty");
|
||||
}
|
||||
let tcp = TcpStream::connect((host, port))
|
||||
.await
|
||||
.context("connect to gateway")?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let peer = tcp.peer_addr()?;
|
||||
let loopback_host = host.eq_ignore_ascii_case("localhost")
|
||||
|| host
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok_and(|ip| ip.is_loopback());
|
||||
let plain = explicit_plain || (!address.starts_with("lnexs://") && loopback_host);
|
||||
if plain {
|
||||
if !tcp.peer_addr()?.ip().is_loopback() {
|
||||
bail!("plaintext LNEx is restricted to loopback development; use lnexs://");
|
||||
}
|
||||
return Ok(Connected {
|
||||
stream: Box::new(tcp),
|
||||
peer,
|
||||
});
|
||||
}
|
||||
let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
let config = rustls::ClientConfig::builder_with_provider(
|
||||
rustls::crypto::aws_lc_rs::default_provider().into(),
|
||||
)
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
let server_name = rustls::pki_types::ServerName::try_from(host.to_owned())
|
||||
.context("invalid TLS server name")?;
|
||||
let tls = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
|
||||
.connect(server_name, tcp)
|
||||
.await
|
||||
.context("TLS certificate/connection verification failed")?;
|
||||
Ok(Connected {
|
||||
stream: Box::new(tls),
|
||||
peer,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::io::AsyncReadExt;
|
||||
#[tokio::test]
|
||||
async fn tls_failure_never_retries_plaintext() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let task = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let first = stream.read_u8().await.unwrap();
|
||||
assert_eq!(
|
||||
first, 22,
|
||||
"first record must be a TLS handshake, never LNEx plaintext"
|
||||
);
|
||||
drop(stream);
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(30), listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"certificate/handshake errors must not cause a downgrade reconnect"
|
||||
);
|
||||
});
|
||||
assert!(connect(&format!("lnexs://{address}")).await.is_err());
|
||||
task.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
#[derive(Debug)]
|
||||
pub enum NetCommand {
|
||||
MediaControl(crate::net::wire::MediaControl),
|
||||
Webhook {
|
||||
operation: WebhookOperation,
|
||||
request: crate::net::wire::WebhookRequest,
|
||||
},
|
||||
Connect {
|
||||
address: String,
|
||||
auto_reconnect: bool,
|
||||
|
|
@ -176,3 +181,22 @@ pub enum NetCommand {
|
|||
},
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WebhookOperation {
|
||||
Create,
|
||||
List,
|
||||
Rotate,
|
||||
Revoke,
|
||||
}
|
||||
impl WebhookOperation {
|
||||
pub fn packet_id(self) -> u16 {
|
||||
use crate::net::payloads::*;
|
||||
match self {
|
||||
Self::Create => PID_WEBHOOK_CREATE,
|
||||
Self::List => PID_WEBHOOK_LIST,
|
||||
Self::Rotate => PID_WEBHOOK_ROTATE,
|
||||
Self::Revoke => PID_WEBHOOK_REVOKE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,13 @@ use std::net::SocketAddr;
|
|||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NetEvent {
|
||||
VoiceRevoked {
|
||||
channel_id: String,
|
||||
},
|
||||
MediaEvent(crate::net::wire::MediaEvent),
|
||||
WebhookResult(WebhookManagementResult),
|
||||
WebhookList(crate::net::wire::WebhookListResult),
|
||||
WebhookError(crate::net::wire::WebhookErrorResult),
|
||||
Connected {
|
||||
session_id: String,
|
||||
node_name: String,
|
||||
|
|
@ -244,3 +251,19 @@ pub enum NetEvent {
|
|||
messages: Vec<crate::net::payloads::E2eeDmMessagePayload>,
|
||||
},
|
||||
}
|
||||
|
||||
/// One-time management secret. Debug deliberately omits it.
|
||||
#[derive(Clone)]
|
||||
pub struct WebhookManagementResult {
|
||||
pub request_id: String,
|
||||
pub hook: Option<crate::net::wire::WebhookInfo>,
|
||||
pub secret: String,
|
||||
}
|
||||
impl std::fmt::Debug for WebhookManagementResult {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WebhookManagementResult")
|
||||
.field("hook", &self.hook)
|
||||
.field("secret", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,6 @@ mod command;
|
|||
mod event;
|
||||
mod info;
|
||||
|
||||
pub use command::NetCommand;
|
||||
pub use event::NetEvent;
|
||||
pub use command::{NetCommand, WebhookOperation};
|
||||
pub use event::{NetEvent, WebhookManagementResult};
|
||||
pub use info::{ChannelListItem, ChatMsg, FriendInfo, GuildInfo, MemberInfo, PresenceInfo};
|
||||
|
|
|
|||
|
|
@ -1,84 +1,221 @@
|
|||
use super::crypto::SessionCrypto;
|
||||
use super::payloads::PID_VOICE_PACKET;
|
||||
//! LNEx v2 authenticated UDP voice. Credentials arrive only over encrypted control.
|
||||
use crate::net::wire::VoiceFrame;
|
||||
use anyhow::{Result, bail};
|
||||
use chacha20poly1305::{
|
||||
ChaCha20Poly1305, KeyInit,
|
||||
aead::{Aead, Payload},
|
||||
};
|
||||
use prost::Message;
|
||||
|
||||
mod receive;
|
||||
pub use receive::spawn_recv;
|
||||
pub const HEADER_SIZE: usize = 28;
|
||||
pub const MAX_DATAGRAM: usize = 1472;
|
||||
|
||||
/// Stable string channel id to u64 key for UDP voice packets.
|
||||
/// Stable UI channel key; the wire carries the original string channel identifier.
|
||||
pub fn channel_key(id: &str) -> u64 {
|
||||
let mut h: u64 = 5381;
|
||||
for b in id.bytes() {
|
||||
h = h.wrapping_mul(33).wrapping_add(u64::from(b));
|
||||
}
|
||||
h
|
||||
id.bytes().fold(5381u64, |value, byte| {
|
||||
value.wrapping_mul(33).wrapping_add(u64::from(byte))
|
||||
})
|
||||
}
|
||||
|
||||
/// Build a UDP voice packet with encryption.
|
||||
///
|
||||
/// Plaintext layout (Phase 1.2+):
|
||||
/// `[voice_seq:4][timestamp:4][channel_id:8][sender_id:32][opus_data:N]`
|
||||
///
|
||||
/// `sender_id` is the raw Ed25519 public key of the sender, so receivers can
|
||||
/// attribute the voice activity to a specific user (Phase 1.3 speaking indicators).
|
||||
pub fn build_packet(
|
||||
channel_id: u64,
|
||||
#[derive(Clone)]
|
||||
pub struct Credentials {
|
||||
pub route_id: [u8; 16],
|
||||
pub c2s_key: [u8; 32],
|
||||
pub s2c_key: [u8; 32],
|
||||
pub channel_id: String,
|
||||
}
|
||||
impl TryFrom<crate::net::wire::VoiceSession> for Credentials {
|
||||
type Error = anyhow::Error;
|
||||
fn try_from(value: crate::net::wire::VoiceSession) -> Result<Self> {
|
||||
if value.channel_id.is_empty() {
|
||||
bail!("empty voice channel");
|
||||
}
|
||||
Ok(Self {
|
||||
route_id: value
|
||||
.route_id
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid voice route"))?,
|
||||
c2s_key: value
|
||||
.c2s_key
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid voice key"))?,
|
||||
s2c_key: value
|
||||
.s2c_key
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid voice key"))?,
|
||||
channel_id: value.channel_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn nonce(sequence: u64) -> [u8; 12] {
|
||||
let mut nonce = [0; 12];
|
||||
nonce[4..].copy_from_slice(&sequence.to_be_bytes());
|
||||
nonce
|
||||
}
|
||||
pub fn encode(
|
||||
credentials: &Credentials,
|
||||
sequence: u64,
|
||||
voice_seq: u32,
|
||||
timestamp: u32,
|
||||
opus: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
packet_seq: u64,
|
||||
sender_pubkey: &[u8; 32],
|
||||
) -> Vec<u8> {
|
||||
let mut plaintext = Vec::with_capacity(16 + 32 + opus.len());
|
||||
plaintext.extend_from_slice(&voice_seq.to_be_bytes());
|
||||
plaintext.extend_from_slice(×tamp.to_be_bytes());
|
||||
plaintext.extend_from_slice(&channel_id.to_be_bytes());
|
||||
plaintext.extend_from_slice(sender_pubkey);
|
||||
plaintext.extend_from_slice(opus);
|
||||
|
||||
let encrypted = crypto.encrypt_c2s(packet_seq, &plaintext);
|
||||
|
||||
let mut buf = Vec::with_capacity(4 + encrypted.len());
|
||||
buf.extend_from_slice(&PID_VOICE_PACKET.to_be_bytes());
|
||||
buf.extend_from_slice(&0u16.to_be_bytes());
|
||||
buf.extend_from_slice(&encrypted);
|
||||
buf
|
||||
) -> Result<Vec<u8>> {
|
||||
if sequence == u64::MAX {
|
||||
bail!("voice sequence exhausted; rejoin required");
|
||||
}
|
||||
let frame = VoiceFrame {
|
||||
voice_seq,
|
||||
timestamp,
|
||||
channel_id: credentials.channel_id.clone(),
|
||||
sender_session_id: String::new(),
|
||||
sender_user_id: String::new(),
|
||||
opus: opus.to_vec(),
|
||||
};
|
||||
let plain = frame.encode_to_vec();
|
||||
if HEADER_SIZE + plain.len() + 16 > MAX_DATAGRAM {
|
||||
bail!("voice datagram too large");
|
||||
}
|
||||
let mut header = [0u8; HEADER_SIZE];
|
||||
header[..2].copy_from_slice(&0x0010u16.to_be_bytes());
|
||||
header[2..4].copy_from_slice(&1u16.to_be_bytes());
|
||||
header[4..20].copy_from_slice(&credentials.route_id);
|
||||
header[20..].copy_from_slice(&sequence.to_be_bytes());
|
||||
let cipher = ChaCha20Poly1305::new((&credentials.c2s_key).into());
|
||||
let nonce = nonce(sequence);
|
||||
let encrypted = cipher
|
||||
.encrypt(
|
||||
(&nonce).into(),
|
||||
Payload {
|
||||
msg: &plain,
|
||||
aad: &header,
|
||||
},
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("voice encryption failed"))?;
|
||||
Ok([header.as_slice(), encrypted.as_slice()].concat())
|
||||
}
|
||||
pub fn decode(credentials: &Credentials, data: &[u8]) -> Result<(u64, VoiceFrame)> {
|
||||
if data.len() < HEADER_SIZE + 16 || data.len() > MAX_DATAGRAM {
|
||||
bail!("invalid voice datagram size");
|
||||
}
|
||||
if data[..2] != 0x0010u16.to_be_bytes()
|
||||
|| data[2..4] != 1u16.to_be_bytes()
|
||||
|| data[4..20] != credentials.route_id
|
||||
{
|
||||
bail!("invalid voice datagram header");
|
||||
}
|
||||
let sequence = u64::from_be_bytes(data[20..28].try_into()?);
|
||||
let nonce = nonce(sequence);
|
||||
let cipher = ChaCha20Poly1305::new((&credentials.s2c_key).into());
|
||||
let plain = cipher
|
||||
.decrypt(
|
||||
(&nonce).into(),
|
||||
Payload {
|
||||
msg: &data[HEADER_SIZE..],
|
||||
aad: &data[..HEADER_SIZE],
|
||||
},
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("voice authentication failed"))?;
|
||||
let frame = VoiceFrame::decode(plain.as_slice())?;
|
||||
if frame.channel_id != credentials.channel_id
|
||||
|| (!frame.opus.is_empty()
|
||||
&& (frame.sender_session_id.is_empty() || frame.sender_user_id.is_empty()))
|
||||
{
|
||||
bail!("invalid authenticated voice attribution");
|
||||
}
|
||||
Ok((sequence, frame))
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct ReplayWindow {
|
||||
highest: Option<u64>,
|
||||
bitmap: u128,
|
||||
}
|
||||
impl ReplayWindow {
|
||||
/// Call only after authentication and channel validation.
|
||||
pub fn accept(&mut self, sequence: u64) -> bool {
|
||||
let Some(highest) = self.highest else {
|
||||
self.highest = Some(sequence);
|
||||
self.bitmap = 1;
|
||||
return true;
|
||||
};
|
||||
if sequence > highest {
|
||||
let distance = sequence - highest;
|
||||
self.bitmap = if distance >= 128 {
|
||||
1
|
||||
} else {
|
||||
(self.bitmap << distance) | 1
|
||||
};
|
||||
self.highest = Some(sequence);
|
||||
true
|
||||
} else {
|
||||
let distance = highest - sequence;
|
||||
if distance >= 128 || self.bitmap & (1u128 << distance) != 0 {
|
||||
return false;
|
||||
}
|
||||
self.bitmap |= 1u128 << distance;
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channel_key_is_stable() {
|
||||
assert_eq!(channel_key("voice"), channel_key("voice"));
|
||||
assert_ne!(channel_key("voice"), channel_key("general"));
|
||||
fn credentials() -> Credentials {
|
||||
Credentials {
|
||||
route_id: [1; 16],
|
||||
c2s_key: [2; 32],
|
||||
s2c_key: [3; 32],
|
||||
channel_id: "voice".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_packet_header_layout() {
|
||||
let key = channel_key("voice");
|
||||
let shared = [0u8; 32];
|
||||
let crypto = SessionCrypto::derive(&shared, "test");
|
||||
let sender = [0xABu8; 32];
|
||||
let pkt = build_packet(key, 42, 1000, b"opus", &crypto, 0, &sender);
|
||||
|
||||
let packet_id = u16::from_be_bytes([pkt[0], pkt[1]]);
|
||||
assert_eq!(packet_id, PID_VOICE_PACKET);
|
||||
|
||||
let encrypted_payload = &pkt[4..];
|
||||
let plaintext = crypto.decrypt_c2s(0, encrypted_payload).unwrap();
|
||||
assert_eq!(plaintext.len(), 16 + 32 + 4);
|
||||
|
||||
let pkt_voice_seq = u32::from_be_bytes(plaintext[0..4].try_into().unwrap());
|
||||
let timestamp = u32::from_be_bytes(plaintext[4..8].try_into().unwrap());
|
||||
let channel_id = u64::from_be_bytes(plaintext[8..16].try_into().unwrap());
|
||||
let sender_id: [u8; 32] = plaintext[16..48].try_into().unwrap();
|
||||
|
||||
assert_eq!(pkt_voice_seq, 42);
|
||||
assert_eq!(timestamp, 1000);
|
||||
assert_eq!(channel_id, key);
|
||||
assert_eq!(sender_id, sender);
|
||||
assert_eq!(&plaintext[48..], b"opus");
|
||||
fn replay_window_allows_reordering_but_never_duplicates_or_wrap() {
|
||||
let mut window = ReplayWindow::default();
|
||||
for value in [3, 1, 2, 5, 4] {
|
||||
assert!(window.accept(value));
|
||||
}
|
||||
for value in [1, 2, 3, 4, 5] {
|
||||
assert!(!window.accept(value));
|
||||
}
|
||||
assert!(window.accept(200));
|
||||
assert!(!window.accept(0));
|
||||
assert!(window.accept(u64::MAX));
|
||||
assert!(!window.accept(0));
|
||||
}
|
||||
#[test]
|
||||
fn c2s_datagram_has_explicit_authenticated_sequence_and_no_claimed_sender() {
|
||||
let credentials = credentials();
|
||||
let data = encode(&credentials, 42, 7, 48000, b"opus").unwrap();
|
||||
let nonce = nonce(42);
|
||||
let cipher = ChaCha20Poly1305::new((&credentials.c2s_key).into());
|
||||
let plain = cipher
|
||||
.decrypt(
|
||||
(&nonce).into(),
|
||||
Payload {
|
||||
msg: &data[28..],
|
||||
aad: &data[..28],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let frame = VoiceFrame::decode(plain.as_slice()).unwrap();
|
||||
assert!(frame.sender_user_id.is_empty());
|
||||
assert!(frame.sender_session_id.is_empty());
|
||||
assert_eq!(frame.opus, b"opus");
|
||||
let mut tampered = data.clone();
|
||||
tampered[27] ^= 1;
|
||||
assert!(
|
||||
cipher
|
||||
.decrypt(
|
||||
(&nonce).into(),
|
||||
Payload {
|
||||
msg: &tampered[28..],
|
||||
aad: &tampered[..28]
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn nonce_exhaustion_and_oversized_opus_fail_closed() {
|
||||
assert!(encode(&credentials(), u64::MAX, 0, 0, b"").is_err());
|
||||
assert!(encode(&credentials(), 0, 0, 0, &vec![0; 2000]).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,80 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::warn;
|
||||
|
||||
use super::super::crypto::SessionCrypto;
|
||||
use super::super::payloads::PID_VOICE_PACKET;
|
||||
use super::super::types::NetEvent;
|
||||
|
||||
/// Spawn a task that reads UDP datagrams, decrypts them, and forwards as VoicePacket events.
|
||||
pub fn spawn_recv(udp: Arc<UdpSocket>, crypto: SessionCrypto, tx: mpsc::Sender<NetEvent>) {
|
||||
tokio::spawn(async move {
|
||||
let mut buf = vec![0u8; 1472];
|
||||
let mut voice_seq: u64 = 0;
|
||||
|
||||
loop {
|
||||
match udp.recv_from(&mut buf).await {
|
||||
Ok((len, src)) => {
|
||||
if len < 4 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let packet_id = u16::from_be_bytes([buf[0], buf[1]]);
|
||||
if packet_id != PID_VOICE_PACKET {
|
||||
continue;
|
||||
}
|
||||
|
||||
let encrypted_payload = &buf[4..len];
|
||||
let plaintext = match crypto.decrypt_s2c(voice_seq, encrypted_payload) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
warn!("voice packet decryption failed from {src}: {e}");
|
||||
voice_seq += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Layout: [voice_seq:4][timestamp:4][channel_id:8][sender_id:32][opus]
|
||||
// Legacy format (no sender_id) is 16+ bytes — gracefully handle.
|
||||
if plaintext.len() < 16 {
|
||||
warn!("voice packet payload too short from {src}");
|
||||
voice_seq += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let pkt_voice_seq = u32::from_be_bytes(plaintext[0..4].try_into().unwrap());
|
||||
let timestamp = u32::from_be_bytes(plaintext[4..8].try_into().unwrap());
|
||||
let channel_id = u64::from_be_bytes(plaintext[8..16].try_into().unwrap());
|
||||
|
||||
// sender_id: 32 raw bytes if present, hex-encoded.
|
||||
// Empty string when packet is from legacy sender without sender_id.
|
||||
let (sender_id_hex, opus_data) = if plaintext.len() >= 48 {
|
||||
let sender_bytes: [u8; 32] = plaintext[16..48].try_into().unwrap();
|
||||
(hex::encode(sender_bytes), plaintext[48..].to_vec())
|
||||
} else {
|
||||
// Legacy: no sender_id in payload.
|
||||
(String::new(), plaintext[16..].to_vec())
|
||||
};
|
||||
|
||||
let _ = tx
|
||||
.send(NetEvent::VoicePacket {
|
||||
channel_id,
|
||||
voice_seq: pkt_voice_seq,
|
||||
timestamp,
|
||||
sender: src,
|
||||
sender_id: sender_id_hex,
|
||||
opus_data,
|
||||
})
|
||||
.await;
|
||||
|
||||
voice_seq += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("UDP recv: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
9
src/net/wire/mod.rs
Normal file
9
src/net/wire/mod.rs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
//! Generated LNEx protobuf messages, shared verbatim with the gateway schema.
|
||||
include!(concat!(env!("OUT_DIR"), "/lnex.rs"));
|
||||
|
||||
pub fn encode(message: &impl prost::Message) -> anyhow::Result<Vec<u8>> {
|
||||
Ok(message.encode_to_vec())
|
||||
}
|
||||
pub fn decode<T: prost::Message + Default>(bytes: &[u8]) -> anyhow::Result<T> {
|
||||
Ok(T::decode(bytes)?)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue