Compare commits
No commits in common. "f1883e5001b1734ffcd95e1408c7a81d51065e61" and "bc5157046eb8df9df42d3602700b33dd0dd786f7" have entirely different histories.
f1883e5001
...
bc5157046e
47 changed files with 396 additions and 2846 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
|
@ -3020,10 +3020,6 @@ name = "vnox-voice-node"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chacha20poly1305",
|
||||
"hex",
|
||||
"prost",
|
||||
"prost-build",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
|
|
|
|||
|
|
@ -36,5 +36,3 @@ toml = "1.1"
|
|||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json", "form", "query", "stream"] }
|
||||
hmac = "0.13"
|
||||
subtle = "2.6"
|
||||
prost = "0.14"
|
||||
prost-build = "0.14"
|
||||
|
|
|
|||
|
|
@ -3,18 +3,7 @@
|
|||
This file describes what the repository actually does today.
|
||||
Protocol and security docs may describe future phases. When in doubt, trust this file.
|
||||
|
||||
Last updated: 2026-10-24.
|
||||
|
||||
---
|
||||
|
||||
## Update 2026-10 (protocol v2)
|
||||
|
||||
- Signed v2 handshake and protobuf payloads between client and gateway (verified by `VNOX-Client/tests/gateway_interop.rs`).
|
||||
- Authenticated, encrypted UDP voice relay in voice-node.
|
||||
- Voice access is revoked when a channel is deleted, a member is kicked or permissions change.
|
||||
- Senders get acknowledgements for their own chat messages.
|
||||
- Channel webhooks, GitHub sign-in, hub service, screen sharing and media broadcast.
|
||||
- `cargo audit`: no known vulnerabilities in both workspaces (2026-10-24).
|
||||
Last updated: 2026-06-29.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -62,7 +51,7 @@ Last updated: 2026-10-24.
|
|||
| SDK crate | Present as a stub; not a usable public API yet. |
|
||||
| Federation crate | Stub only (`// TODO`). |
|
||||
| RNNoise | Feature-gated, no-op stub by default. Enable with `--features rnnoise`. |
|
||||
| Slint migration | Done. The client UI is Slint (RU/EN localization, themes, settings). |
|
||||
| Slint migration | Plan exists at `docs/superpowers/plans/2026-05-31-slint-migration.md`; deferred — egui UI continues to be improved. |
|
||||
| Server-side channel creation | Client-side channels work locally; gateway still needs `ChannelCreate` packet + storage (Phase 2). |
|
||||
| Identity export/import UI | Vault API is ready (`identity::save(identity, Some(passphrase))`), but no UI modal yet. |
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ VNOX Client │
|
||||
│ (Rust + Slint) │
|
||||
│ (Rust + egui + wgpu) │
|
||||
└────────────────────┬────────────────────────────────┘
|
||||
│ LNEx v1
|
||||
┌──────────┴──────────┐
|
||||
|
|
@ -104,7 +104,7 @@ Can run on the same machine as the gateway or separately.
|
|||
### client
|
||||
|
||||
Language: Rust
|
||||
UI: Slint
|
||||
UI: egui
|
||||
Renderer: wgpu
|
||||
Audio: cpal + rodio + opus
|
||||
Networking: tokio
|
||||
|
|
@ -151,7 +151,7 @@ Handles cross-node communication:
|
|||
|-----------|----------|----------|
|
||||
| Gateway | Rust | Tokio, serde, sqlx |
|
||||
| Voice node | Rust | opus, tokio |
|
||||
| Client | Rust | Slint, cpal, tokio |
|
||||
| Client | Rust | egui, wgpu, cpal, tokio |
|
||||
| Overlay | Rust | TBD |
|
||||
| Plugins | TypeScript | Deno / QuickJS |
|
||||
|
||||
|
|
@ -175,7 +175,7 @@ without changing the wire framing (header stays identical).
|
|||
|
||||
```
|
||||
vnox/
|
||||
├── client/ # Desktop client (Rust + Slint)
|
||||
├── client/ # Desktop client (Rust + egui)
|
||||
├── gateway/ # TCP gateway (Rust + Tokio)
|
||||
├── voice-node/ # UDP voice relay (Rust)
|
||||
├── federation/ # Federation layer (Phase 3)
|
||||
|
|
@ -259,7 +259,7 @@ client/src/
|
|||
│ ├── config.rs # find() best StreamConfig for device
|
||||
│ ├── capture.rs # cpal input → Opus encode → EncodedFrame channel
|
||||
│ └── playback.rs # Opus decode → cpal output
|
||||
└── ui/ # Slint layout
|
||||
└── ui/ # egui layout
|
||||
├── mod.rs # VnoxApp, eframe::App impl, poll_net()
|
||||
├── state.rs # UiState, ConnState, Channel, ChatMessage
|
||||
├── theme.rs # color constants (BG_BASE, ACCENT, …)
|
||||
|
|
|
|||
|
|
@ -62,11 +62,11 @@ See [features/direct-messages.md](05-features/direct-messages.md). **Backend and
|
|||
- [x] Makes VNOX safe for single-server deployment (OwnCord-style)
|
||||
|
||||
### UI Refresh
|
||||
- [x] Evaluate Slint vs egui: migrated to Slint
|
||||
- [x] Evaluate Slint vs improving egui design system — **staying on egui**
|
||||
- [x] Custom dark theme with accent color support (#E67E22 orange)
|
||||
- [x] Redesigned channel list and user bar
|
||||
- [x] Consistency pass across all settings panels
|
||||
- [x] Slint migration done (client UI is native Slint)
|
||||
- [ ] Slint migration plan exists at `docs/superpowers/plans/2026-05-31-slint-migration.md` (deferred to Phase 2+)
|
||||
|
||||
### Client Polish
|
||||
- [x] Audio device labels in settings (live cpal enumeration)
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
# Channel and role authorization
|
||||
|
||||
Channel create, edit and delete require guild ownership or actual current guild membership with `MANAGE_CHANNELS`. A stale role assignment does not substitute for membership. Client-supplied guild IDs cannot authorize modification of a channel in another guild: edit/delete use the channel's persisted scope. Global/default channels have no modeled server-administrator account and cannot be mutated through these authenticated user operations. Operators configure them server-side.
|
||||
|
||||
The channel list exposes global channels and only those guild channels where the requester is a member. Member and role lists also require current membership.
|
||||
|
||||
Role management requires `MANAGE_ROLES`, membership and a role belonging to that same guild. Assignment/removal requires the target to be a current guild member. A role manager may grant or manage only permissions they hold; guild owners and administrators bypass that subset check. This prevents a limited role manager from assigning the owner's administrative role or creating an administrator role. Permission queries additionally join on matching role/assignment guild IDs, so legacy invalid cross-guild assignments cannot supply permissions.
|
||||
|
||||
Access mutations take the gateway's shared access write lease. Joins and media authorization take a read lease through their state transition. No client socket write holds this lease. This orders membership/permission removal against issuance of fresh room credentials.
|
||||
|
||||
Deleting a channel clears active text/voice subscriptions, revokes the in-process UDP credentials and closes screen-share ownership/subscriptions before removing cached channel metadata. Removing `VOICE_SPEAK` through role deletion/unassignment rechecks active voice sessions and revokes their credentials and screen shares if no remaining role or owner status supplies permission. Voice reconnection requires fresh authorization.
|
||||
|
||||
This policy currently applies within one gateway process. It does not claim distributed locking across multiple gateways sharing a database. Existing queued delivery and in-flight network traffic obey the documented delivery-time checks and cannot be recalled after transmission.
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# Authenticated screen broadcast, LNEx media extension
|
||||
|
||||
The gateway authorizes signalling; established WebRTC transports media directly
|
||||
between consenting clients (ICE + DTLS-SRTP, VP8 video and separate Opus audio).
|
||||
An initial publisher has at most four viewers. This mesh is deliberately bounded;
|
||||
an SFU can replace it later inside the combined daemon. No custom packet crypto,
|
||||
UDP video fragmentation, global discovery signalling endpoint, or separate voice
|
||||
machine is introduced.
|
||||
|
||||
## Wire contract
|
||||
|
||||
The existing authenticated/encrypted LNEx connection carries protobuf packets
|
||||
`MediaControl` (0x0180, client→gateway) and `MediaEvent` (0x0181, gateway→client).
|
||||
Control fields: action(1), channel_id(2), share_id(3), target_session_id(4), body(5),
|
||||
mline_index(6), application_audio(7), microphone(8). Event has identical fields,
|
||||
plus server-stamped sender_session_id(9), publisher_user_id(10). Strings are UTF-8;
|
||||
share_id is a UUID and target_session_id is a server session identifier. Actions:
|
||||
START=1, STOP=2, WATCH=3, UNWATCH=4, OFFER=5, ANSWER=6, ICE=7.
|
||||
|
||||
START creates one live share per publisher session; its ack and announcement
|
||||
carry the authenticated publisher identity and track manifest. WATCH is explicit
|
||||
receiver consent and authorizes only that viewer/publisher pair. The publisher
|
||||
then sends OFFER; the viewer replies ANSWER; both may send ICE. SDP is limited to
|
||||
64 KiB and candidates to 2 KiB; no media bytes travel in these packets. The
|
||||
server never trusts a client-supplied sender, publisher identity, room membership,
|
||||
or subscription. Clients ignore ICE/answers not matching a live authorized peer.
|
||||
|
||||
Every operation requires authenticated membership in the exact voice channel.
|
||||
START additionally checks voice-speaking permissions. Guild membership is
|
||||
revalidated; stale roles do not grant access. Off-channel, unknown-share,
|
||||
non-owner STOP, unsolicited offers/answers and unsubscribed ICE are rejected.
|
||||
Channel leave, kick and disconnect revoke shares/subscriptions and emit STOP or
|
||||
UNWATCH. A viewer's connection is closed on revoke; revocation does not pretend
|
||||
to erase media already received. Control uses a per-session token bucket of 20 messages/s with a burst of 64;
|
||||
its entry is removed on revoke/disconnect. Recipient counts are bounded.
|
||||
|
||||
## Client media and explicit consent
|
||||
|
||||
A local portal-approved capture may be published only after a separate user
|
||||
start action. Video, selected application/output audio and microphone have
|
||||
independent track IDs and are not mixed. Missing application audio is an error;
|
||||
it never enables system audio. The microphone follows existing mute permission
|
||||
and remains disabled unless separately requested. Receiver viewing is opt-in;
|
||||
video is rendered in memory, audio uses the selected voice output, and closing
|
||||
stops peer pipelines. Stop closes every peer, clears frames and sends STOP.
|
||||
|
||||
GStreamer webrtcbin provides SDP/ICE/DTLS/SRTP; installed codec/plugin capability
|
||||
is checked before starting. Host candidates work on reachable networks; optional
|
||||
administrator-configured STUN/TURN is needed across some NATs. No public relay or
|
||||
third-party STUN destination is silently chosen. Synthetic two-peer tests must
|
||||
prove decoded video and distinct application/microphone samples reach the peer;
|
||||
private desktop/audio capture is never part of automated verification.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Community webhook API v1
|
||||
|
||||
Additive LNEx packets `0x0200..0x0206` manage channel-scoped integrations over an already authenticated encrypted session. `MANAGE_WEBHOOKS` is permission bit11. Management requires a persisted text channel in a guild, actual current membership, and the permission (or guild ownership). The operational HTTP listener never exposes management APIs.
|
||||
Additive LNEx packets `0x0200..0x0205` manage channel-scoped integrations over an already authenticated encrypted session. `MANAGE_WEBHOOKS` is permission bit11. Management requires a persisted text channel in a guild, actual current membership, and the permission (or guild ownership). The operational HTTP listener never exposes management APIs.
|
||||
|
||||
- `WebhookCreate`: channel_id, name, direction (`incoming`/`outgoing`), provider (`generic`/`github`), endpoint for outgoing.
|
||||
- `WebhookList`: channel_id; returns descriptors without secrets.
|
||||
|
|
@ -8,8 +8,6 @@ Additive LNEx packets `0x0200..0x0206` manage channel-scoped integrations over a
|
|||
- `WebhookResult`: descriptor plus new secret only for create/rotate.
|
||||
- `WebhookListResult`: descriptors. Descriptors include suspension state. All management requests use the additive `WebhookRequest` message; the packet identifies the operation.
|
||||
|
||||
Requests carry a unique request_id (up to 64 ASCII alphanumeric/hyphen characters), echoed in both success responses and dedicated `WebhookErrorResult` packet `0x0206`. Clients discard stale/unknown replies, including one-time secrets, and refresh after a timeout because a mutation may already have committed.
|
||||
|
||||
Only incoming delivery is public HTTP: `POST /v1/webhooks/{webhook_id}`. Generic integrations use `Authorization: Bearer <secret>` and JSON `{ "content": "..." }`; unknown identity/avatar/mention fields are rejected. Optional `Idempotency-Key` deduplicates retries. GitHub adapters verify `X-Hub-Signature-256` over raw bytes and use `X-GitHub-Delivery` for deduplication. GitHub initially supports push, pull_request, issues, release and ping summaries. Delivery body is capped64KiB, content4000characters; mass mention syntax is denied. A webhook sender has a reserved `webhook:<id>` identity, never a user-provided sender ID. Production publishing requires HTTPS proxying; bearer tokens must not appear in URLs or access logs.
|
||||
|
||||
Incoming generic secrets are random256-bit values stored only as SHA256 hashes. GitHub HMAC and outgoing signing keys require reversible storage and are AEAD-sealed using `VNOX_WEBHOOK_SECRET_KEY` (64hexcharacters, protected environment). Those modes are unavailable if the master key is not configured. Key rotation replaces the active secret and invalidates the old token immediately. No DM/Hub/private-account access is granted.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use ed25519_dalek::SigningKey;
|
|||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct StoredIdentity {
|
||||
pubkey_hex: String,
|
||||
privkey_hex: String,
|
||||
|
|
@ -15,10 +15,6 @@ pub struct ServerIdentity {
|
|||
}
|
||||
|
||||
impl ServerIdentity {
|
||||
pub fn sign(&self, message: &[u8]) -> Vec<u8> {
|
||||
use ed25519_dalek::Signer;
|
||||
self.signing_key.sign(message).to_bytes().to_vec()
|
||||
}
|
||||
pub fn pubkey_hex(&self) -> String {
|
||||
hex::encode(self.signing_key.verifying_key().to_bytes())
|
||||
}
|
||||
|
|
@ -26,16 +22,7 @@ impl ServerIdentity {
|
|||
pub fn load_or_generate(data_dir: &Path) -> Result<Self> {
|
||||
let path = data_dir.join("server_identity.json");
|
||||
|
||||
if std::fs::symlink_metadata(&path).is_ok() {
|
||||
anyhow::ensure!(
|
||||
std::fs::symlink_metadata(&path)?.file_type().is_file(),
|
||||
"server identity must be a regular file"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
if path.exists() {
|
||||
let text = std::fs::read_to_string(&path)?;
|
||||
let stored: StoredIdentity = serde_json::from_str(&text)?;
|
||||
let signing_key = SigningKey::from_bytes(
|
||||
|
|
@ -63,67 +50,8 @@ impl ServerIdentity {
|
|||
};
|
||||
|
||||
std::fs::create_dir_all(data_dir)?;
|
||||
let temporary = data_dir.join(format!(".server-identity-{}.tmp", uuid::Uuid::new_v4()));
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let result = (|| -> Result<()> {
|
||||
use std::io::Write;
|
||||
let mut file = options.open(&temporary)?;
|
||||
file.write_all(serde_json::to_string_pretty(&stored)?.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
std::fs::hard_link(&temporary, &path)?;
|
||||
#[cfg(unix)]
|
||||
std::fs::File::open(data_dir)?.sync_all()?;
|
||||
Ok(())
|
||||
})();
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
if let Err(error) = result {
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| e.kind() == std::io::ErrorKind::AlreadyExists)
|
||||
{
|
||||
return Self::load_or_generate(data_dir);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
std::fs::write(&path, serde_json::to_string_pretty(&stored)?)?;
|
||||
|
||||
Ok(Self { signing_key })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn gateway_identity_is_private_stable_and_never_replaced() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("vnox-private-identity-{}", uuid::Uuid::new_v4()));
|
||||
let first = ServerIdentity::load_or_generate(&dir).unwrap();
|
||||
let second = ServerIdentity::load_or_generate(&dir).unwrap();
|
||||
assert_eq!(first.pubkey_hex(), second.pubkey_hex());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
std::fs::metadata(dir.join("server_identity.json"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode()
|
||||
& 0o777,
|
||||
0o600
|
||||
);
|
||||
}
|
||||
std::fs::write(dir.join("server_identity.json"), "corrupt").unwrap();
|
||||
assert!(ServerIdentity::load_or_generate(&dir).is_err());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("server_identity.json")).unwrap(),
|
||||
"corrupt"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use anyhow::Result;
|
|||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
|
||||
/// Verify Ed25519 signature from AUTH packet.
|
||||
pub fn verify_auth(challenge: &[u8], pubkey: &[u8; 32], signature: &[u8; 64]) -> Result<()> {
|
||||
pub fn verify_auth(challenge: &[u8; 32], pubkey: &[u8; 32], signature: &[u8; 64]) -> Result<()> {
|
||||
let key = VerifyingKey::from_bytes(pubkey).map_err(|_| anyhow::anyhow!("invalid pubkey"))?;
|
||||
let sig = Signature::from_bytes(signature);
|
||||
key.verify_strict(challenge, &sig)
|
||||
|
|
|
|||
|
|
@ -9,9 +9,7 @@ pub struct Session {
|
|||
pub token: String,
|
||||
pub user_id: String,
|
||||
pub nickname: String,
|
||||
/// Viewed text channel; independent of the active voice room.
|
||||
pub channel_id: Option<String>,
|
||||
pub voice_channel_id: Option<String>,
|
||||
}
|
||||
|
||||
pub type SessionStore = Arc<RwLock<HashMap<String, Session>>>;
|
||||
|
|
@ -27,7 +25,6 @@ pub async fn create(store: &SessionStore, user_id: String, nickname: String) ->
|
|||
user_id,
|
||||
nickname,
|
||||
channel_id: None,
|
||||
voice_channel_id: None,
|
||||
};
|
||||
store.write().await.insert(s.session_id.clone(), s.clone());
|
||||
s
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ impl super::super::Storage {
|
|||
match &self.pool {
|
||||
Pool::Sqlite(p) => Ok(sqlx::query_as::<_, RoleRow>(
|
||||
"SELECT r.id,r.guild_id,r.name,r.color,r.permissions,r.position \
|
||||
FROM roles r JOIN member_roles mr ON r.id=mr.role_id AND r.guild_id=mr.guild_id \
|
||||
FROM roles r JOIN member_roles mr ON r.id=mr.role_id \
|
||||
WHERE mr.guild_id=? AND mr.user_id=? ORDER BY r.position DESC",
|
||||
)
|
||||
.bind(guild_id)
|
||||
|
|
@ -73,7 +73,7 @@ impl super::super::Storage {
|
|||
.await?),
|
||||
Pool::Postgres(p) => Ok(sqlx::query_as::<_, RoleRow>(
|
||||
"SELECT r.id,r.guild_id,r.name,r.color,r.permissions,r.position \
|
||||
FROM roles r JOIN member_roles mr ON r.id=mr.role_id AND r.guild_id=mr.guild_id \
|
||||
FROM roles r JOIN member_roles mr ON r.id=mr.role_id \
|
||||
WHERE mr.guild_id=$1 AND mr.user_id=$2 ORDER BY r.position DESC",
|
||||
)
|
||||
.bind(guild_id)
|
||||
|
|
@ -92,7 +92,7 @@ impl super::super::Storage {
|
|||
Pool::Sqlite(p) => {
|
||||
let rows: Vec<P> = sqlx::query_as::<_, P>(
|
||||
"SELECT r.permissions FROM roles r \
|
||||
JOIN member_roles mr ON r.id=mr.role_id AND r.guild_id=mr.guild_id \
|
||||
JOIN member_roles mr ON r.id=mr.role_id \
|
||||
WHERE mr.guild_id=? AND mr.user_id=?",
|
||||
)
|
||||
.bind(guild_id)
|
||||
|
|
@ -104,7 +104,7 @@ impl super::super::Storage {
|
|||
Pool::Postgres(p) => {
|
||||
let rows: Vec<P> = sqlx::query_as::<_, P>(
|
||||
"SELECT r.permissions FROM roles r \
|
||||
JOIN member_roles mr ON r.id=mr.role_id AND r.guild_id=mr.guild_id \
|
||||
JOIN member_roles mr ON r.id=mr.role_id \
|
||||
WHERE mr.guild_id=$1 AND mr.user_id=$2",
|
||||
)
|
||||
.bind(guild_id)
|
||||
|
|
|
|||
|
|
@ -5,7 +5,10 @@ use tracing::{info, warn};
|
|||
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{io, state::State},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{
|
||||
ChannelCreatePayload, ChannelDeletePayload, ChannelListItem, ChannelListPayload,
|
||||
ChannelStatePayload, PacketId, SessionCrypto, encode_packet, to_payload,
|
||||
|
|
@ -59,12 +62,7 @@ pub async fn handle_channel_create(
|
|||
req.channel_name.trim().to_string()
|
||||
};
|
||||
|
||||
if channel_id.is_empty()
|
||||
|| channel_id.len() > 128
|
||||
|| channel_name.chars().count() > 100
|
||||
|| channel_id.chars().any(char::is_control)
|
||||
|| channel_name.chars().any(char::is_control)
|
||||
{
|
||||
if channel_id.is_empty() {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
|
|
@ -98,13 +96,6 @@ pub async fn handle_channel_create(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::may_manage(state, &sess.user_id, req.guild_id.as_deref()).await? {
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let guild_id = req.guild_id.clone();
|
||||
|
||||
let created = channels::create(
|
||||
|
|
@ -116,8 +107,10 @@ pub async fn handle_channel_create(
|
|||
)
|
||||
.await;
|
||||
|
||||
if created
|
||||
&& let Err(error) = state
|
||||
// Persist to DB (best-effort, log and continue on failure).
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if created {
|
||||
if let Err(e) = state
|
||||
.storage
|
||||
.create_channel(
|
||||
&channel_id,
|
||||
|
|
@ -126,12 +119,11 @@ pub async fn handle_channel_create(
|
|||
guild_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
channels::delete(&state.channels, &channel_id).await;
|
||||
return Err(error);
|
||||
{
|
||||
warn!("failed to persist channel to storage: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
drop(access);
|
||||
if !created {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -173,22 +165,22 @@ pub async fn handle_channel_create(
|
|||
)
|
||||
.await?;
|
||||
|
||||
super::notify_guild(
|
||||
state,
|
||||
guild_id.as_deref(),
|
||||
Some(session_id),
|
||||
encode_packet(
|
||||
// Broadcast a ChannelCreate event to all other sessions so their sidebars update.
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
PacketId::ChannelCreate,
|
||||
0,
|
||||
&to_payload(&ChannelCreatePayload {
|
||||
channel_id: channel_id.clone(),
|
||||
channel_name: channel_name.clone(),
|
||||
kind: kind.as_str().into(),
|
||||
guild_id: guild_id.clone(),
|
||||
guild_id: req.guild_id.clone(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -225,23 +217,15 @@ pub async fn handle_channel_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &req.channel_id).await;
|
||||
if !super::may_manage(
|
||||
state,
|
||||
&sess.user_id,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
state.storage.delete_channel(&req.channel_id).await?;
|
||||
super::revoke_channel(state, &req.channel_id).await;
|
||||
let existed = channels::delete(&state.channels, &req.channel_id).await;
|
||||
drop(access);
|
||||
|
||||
// Remove from DB (best-effort).
|
||||
#[allow(clippy::collapsible_if)]
|
||||
if existed {
|
||||
if let Err(e) = state.storage.delete_channel(&req.channel_id).await {
|
||||
warn!("failed to remove channel from storage: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
if !existed {
|
||||
io::send_encrypted(
|
||||
|
|
@ -263,21 +247,19 @@ pub async fn handle_channel_delete(
|
|||
req.channel_id, sess.nickname
|
||||
);
|
||||
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
// Broadcast deletion to all sessions.
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
PacketId::ChannelDelete,
|
||||
0,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: req.channel_id.clone(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -291,10 +273,7 @@ pub async fn handle_channel_list(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let guilds = state.storage.list_user_guilds(&sess.user_id).await?;
|
||||
let _sess = session::get(&state.sessions, session_id).await;
|
||||
|
||||
// Decode optional guild_id filter from request.
|
||||
let filter_guild_id = if !payload.is_empty() {
|
||||
|
|
@ -307,11 +286,6 @@ pub async fn handle_channel_list(
|
|||
let channels = channels::list(&state.channels).await;
|
||||
let items: Vec<ChannelListItem> = channels
|
||||
.iter()
|
||||
.filter(|c| {
|
||||
c.guild_id
|
||||
.as_ref()
|
||||
.is_none_or(|guild| guilds.iter().any(|g| &g.id == guild))
|
||||
})
|
||||
.filter(|c| {
|
||||
filter_guild_id
|
||||
.as_ref()
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
use anyhow::Result;
|
||||
use prost::Message;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tracing::info;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{io, state::State},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{ChannelEditPayload, PacketId, SessionCrypto, encode_packet, to_payload},
|
||||
};
|
||||
|
||||
|
|
@ -26,12 +29,7 @@ pub async fn handle_channel_edit(
|
|||
let channel_id = req.channel_id.trim().to_string();
|
||||
let channel_name = req.channel_name.trim().to_string();
|
||||
|
||||
if channel_id.is_empty()
|
||||
|| channel_name.is_empty()
|
||||
|| channel_id.len() > 128
|
||||
|| channel_name.chars().count() > 100
|
||||
|| channel_name.chars().any(char::is_control)
|
||||
{
|
||||
if channel_id.is_empty() || channel_name.is_empty() {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
|
|
@ -46,26 +44,8 @@ pub async fn handle_channel_edit(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let access = state.access.write().await;
|
||||
let channel = channels::get_channel(&state.channels, &channel_id).await;
|
||||
if !super::may_manage(
|
||||
state,
|
||||
&sess.user_id,
|
||||
channel.as_ref().and_then(|c| c.guild_id.as_deref()),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
super::denied(stream, seq, crypto).await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.update_channel(&channel_id, &channel_name)
|
||||
.await?;
|
||||
let renamed = channels::rename(&state.channels, &channel_id, &channel_name).await;
|
||||
|
||||
drop(access);
|
||||
if !renamed {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -81,18 +61,24 @@ pub async fn handle_channel_edit(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if let Err(e) = state
|
||||
.storage
|
||||
.update_channel(&channel_id, &channel_name)
|
||||
.await
|
||||
{
|
||||
warn!("failed to update channel in storage: {e}");
|
||||
}
|
||||
|
||||
info!(
|
||||
"channel_edit: '{}' renamed to '{}' by {}",
|
||||
channel_id, channel_name, sess.nickname
|
||||
);
|
||||
|
||||
super::notify_guild(
|
||||
state,
|
||||
channel
|
||||
.as_ref()
|
||||
.and_then(|channel| channel.guild_id.as_deref()),
|
||||
None,
|
||||
encode_packet(
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.clone()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(
|
||||
PacketId::ChannelEdit,
|
||||
0,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
|
|
@ -100,8 +86,7 @@ pub async fn handle_channel_edit(
|
|||
channel_name: channel_name.clone(),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
use super::{broadcast_leave, set_channel, set_voice_channel};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
domain::{channels, session},
|
||||
net::{
|
||||
|
|
@ -10,11 +15,11 @@ use crate::{
|
|||
UserJoinPayload, encode_packet, to_payload,
|
||||
},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use super::{broadcast_leave, set_channel};
|
||||
|
||||
const HISTORY_LIMIT: i64 = 50;
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
pub async fn join(
|
||||
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
|
|
@ -22,224 +27,135 @@ pub async fn join(
|
|||
channel_id: &str,
|
||||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
_addr: SocketAddr,
|
||||
addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.read().await;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(ch) = channels::get_channel(&state.channels, channel_id).await else {
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "not found".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
let prev_channel = sess.channel_id;
|
||||
|
||||
let ch = match channels::get_channel(&state.channels, channel_id).await {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::ChannelNotFound as u32,
|
||||
message: "not found".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if let Some(guild) = &ch.guild_id
|
||||
&& !state
|
||||
|
||||
// Validate the destination before changing membership or exposing its history.
|
||||
// Role assignments alone are insufficient: a kicked user can retain stale roles.
|
||||
if let Some(guild_id) = ch.guild_id.as_deref() {
|
||||
let is_member = state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == *guild)
|
||||
{
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild membership required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let is_voice = ch.kind == channels::ChannelKind::Voice;
|
||||
if is_voice && state.voice_member_tx.is_none() {
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::NodeUnavailable as u32,
|
||||
message: "voice requires the combined server process".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if is_voice && let Some(guild) = &ch.guild_id {
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == sess.user_id);
|
||||
let perms = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &sess.user_id)
|
||||
.await?;
|
||||
if !owner
|
||||
&& !crate::domain::permissions::Permissions::from_role_perms(&perms)
|
||||
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
|
||||
{
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
.any(|guild| guild.id == guild_id);
|
||||
if !is_member {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "VOICE_SPEAK permission required".into(),
|
||||
message: "guild membership required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let previous = if is_voice {
|
||||
sess.voice_channel_id.clone()
|
||||
} else {
|
||||
sess.channel_id.clone()
|
||||
};
|
||||
if previous.as_deref() == Some(channel_id) {
|
||||
|
||||
if prev_channel.as_deref() == Some(channel_id) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(previous) = previous {
|
||||
channels::leave(&state.channels, &previous, session_id).await;
|
||||
broadcast_leave(state, &previous, session_id).await;
|
||||
if is_voice {
|
||||
state.media.revoke(state, session_id).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _=tx.send(serde_json::json!({"type":"leave","session_id":session_id,"channel_id":previous,"user_id":sess.user_id}).to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(prev) = prev_channel {
|
||||
channels::leave(&state.channels, &prev, session_id).await;
|
||||
broadcast_leave(state, &prev, session_id).await;
|
||||
}
|
||||
|
||||
channels::join(&state.channels, channel_id, session_id).await;
|
||||
if is_voice {
|
||||
set_voice_channel(state, session_id, Some(channel_id.into())).await;
|
||||
} else {
|
||||
set_channel(state, session_id, Some(channel_id.into())).await;
|
||||
}
|
||||
// Issue/revoke credentials while access mutations are serialized. Never hold this guard while writing to a client socket.
|
||||
let credentials = if is_voice {
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
use rand::Rng;
|
||||
let (route_id, c2s_key, s2c_key) = {
|
||||
let mut rng = rand::rng();
|
||||
let mut r = [0u8; 16];
|
||||
let mut c = [0u8; 32];
|
||||
let mut s = [0u8; 32];
|
||||
rng.fill_bytes(&mut r);
|
||||
rng.fill_bytes(&mut c);
|
||||
rng.fill_bytes(&mut s);
|
||||
(r, c, s)
|
||||
};
|
||||
let event = serde_json::json!({"type":"join","session_id":session_id,"channel_id":channel_id,"user_id":sess.user_id,"route_id":hex::encode(route_id),"c2s_key":hex::encode(c2s_key),"s2c_key":hex::encode(s2c_key)});
|
||||
if tx.send(event.to_string()).is_err() {
|
||||
channels::leave(&state.channels, channel_id, session_id).await;
|
||||
set_voice_channel(state, session_id, None).await;
|
||||
drop(guard);
|
||||
return io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&proto::ErrorPayload {
|
||||
code: proto::ErrorCode::NodeUnavailable as u32,
|
||||
message: "voice service unavailable".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Some(proto::VoiceSession {
|
||||
route_id: route_id.to_vec(),
|
||||
c2s_key: c2s_key.to_vec(),
|
||||
s2c_key: s2c_key.to_vec(),
|
||||
channel_id: channel_id.into(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
set_channel(state, session_id, Some(channel_id.into())).await;
|
||||
|
||||
let mut members = Vec::new();
|
||||
for sid in channels::members(&state.channels, channel_id).await {
|
||||
if let Some(s) = session::get(&state.sessions, &sid).await {
|
||||
members.push(MemberInfo {
|
||||
user_id: s.user_id,
|
||||
nickname: s.nickname,
|
||||
in_voice: is_voice,
|
||||
user_id: s.user_id.clone(),
|
||||
nickname: s.nickname.clone(),
|
||||
in_voice: ch.kind == channels::ChannelKind::Voice,
|
||||
});
|
||||
}
|
||||
}
|
||||
let message = UserJoinPayload {
|
||||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id,
|
||||
nickname: sess.nickname,
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::UserJoin, 0, &to_payload(&message)),
|
||||
});
|
||||
drop(guard);
|
||||
let payload = ChannelStatePayload {
|
||||
channel_id: ch.id,
|
||||
channel_name: ch.name,
|
||||
|
||||
let sp = ChannelStatePayload {
|
||||
channel_id: ch.id.clone(),
|
||||
channel_name: ch.name.clone(),
|
||||
kind: ch.kind.as_str().into(),
|
||||
members,
|
||||
voice_endpoint: state.config.voice.bind.clone(),
|
||||
guild_id: ch.guild_id,
|
||||
guild_id: ch.guild_id.clone(),
|
||||
};
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::ChannelState,
|
||||
seq,
|
||||
&to_payload(&payload),
|
||||
&to_payload(&sp),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
if let Some(credentials) = credentials {
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::VoiceSession,
|
||||
seq,
|
||||
&to_payload(&credentials),
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let history = state.storage.get_history(channel_id, HISTORY_LIMIT).await?;
|
||||
if !history.is_empty() {
|
||||
let hp = ChatHistoryPayload {
|
||||
channel_id: channel_id.into(),
|
||||
messages: history,
|
||||
};
|
||||
io::send_encrypted(stream, PacketId::ChatHistory, seq, &to_payload(&hp), crypto).await?;
|
||||
}
|
||||
if !is_voice {
|
||||
let history = state.storage.get_history(channel_id, HISTORY_LIMIT).await?;
|
||||
if !history.is_empty() {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session_id.into()),
|
||||
data: encode_packet(
|
||||
PacketId::ChatHistory,
|
||||
0,
|
||||
&to_payload(&ChatHistoryPayload {
|
||||
channel_id: channel_id.into(),
|
||||
messages: history,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(sess) = session::get(&state.sessions, session_id).await {
|
||||
let jp = UserJoinPayload {
|
||||
channel_id: channel_id.into(),
|
||||
user_id: sess.user_id.clone(),
|
||||
nickname: sess.nickname.clone(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(channel_id.into()),
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::UserJoin, 0, &to_payload(&jp)),
|
||||
});
|
||||
}
|
||||
|
||||
if ch.kind == channels::ChannelKind::Voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
&& let Some(sess) = session::get(&state.sessions, session_id).await
|
||||
{
|
||||
let event = serde_json::json!({
|
||||
"type": "join",
|
||||
"channel_id": channel_id,
|
||||
"user_id": sess.user_id,
|
||||
"endpoint": format!("{}:{}", addr.ip(), addr.port()),
|
||||
});
|
||||
let _ = tx.send(event.to_string());
|
||||
}
|
||||
|
||||
info!("session {} joined {channel_id}", &session_id[..8]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -143,574 +143,3 @@ async fn guild_member_can_switch_channels() {
|
|||
Some("private")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn text_navigation_preserves_voice_and_leaving_unrelated_channel_is_noop() {
|
||||
let (mut state, sid) = fixture().await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(16);
|
||||
tokio::spawn(async move { while rx.recv().await.is_ok() {} });
|
||||
state.voice_member_tx = Some(tx);
|
||||
attempt_join(&state, &sid, "voice").await;
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("general"));
|
||||
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"other-text",
|
||||
"Other",
|
||||
channels::ChannelKind::Text,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
attempt_join(&state, &sid, "other-text").await;
|
||||
assert!(
|
||||
channels::members(&state.channels, "voice")
|
||||
.await
|
||||
.contains(&sid)
|
||||
);
|
||||
let (mut stream, _) = tokio::io::duplex(65536);
|
||||
super::super::leave(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
"general",
|
||||
&SessionCrypto::derive(&[7; 32], &sid),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
|
||||
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
|
||||
super::super::leave(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
"voice",
|
||||
&SessionCrypto::derive(&[7; 32], &sid),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let sess = session::get(&state.sessions, &sid).await.unwrap();
|
||||
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
|
||||
assert_eq!(sess.voice_channel_id, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_credentials() {
|
||||
use crate::proto::{ChannelDeletePayload, ChannelEditPayload};
|
||||
let (mut state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"managed",
|
||||
"Managed",
|
||||
channels::ChannelKind::Voice,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
state
|
||||
.storage
|
||||
.create_channel("managed", "Managed", "voice", Some(&guild))
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
crate::handler::channel::handle_channel_edit(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: "managed".into(),
|
||||
channel_name: "stolen".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.unwrap()
|
||||
.name,
|
||||
"Managed"
|
||||
);
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: "managed".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
!super::super::may_manage(&state, "owner", None)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let owner = session::create(&state.sessions, "owner".into(), "Owner".into()).await;
|
||||
channels::join(&state.channels, "managed", &owner.session_id).await;
|
||||
super::super::set_voice_channel(&state, &owner.session_id, Some("managed".into())).await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(8);
|
||||
state.voice_member_tx = Some(tx);
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner.session_id,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: "managed".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
channels::get_channel(&state.channels, "managed")
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
session::get(&state.sessions, &owner.session_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.voice_channel_id
|
||||
.is_none()
|
||||
);
|
||||
let event: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
|
||||
assert_eq!(event["type"], "leave");
|
||||
assert_eq!(event["session_id"], owner.session_id);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation() {
|
||||
use crate::domain::permissions::Permissions;
|
||||
use crate::proto::{RoleAssignPayload, RoleDeletePayload};
|
||||
let (state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("visitor", "Owned")
|
||||
.await
|
||||
.unwrap();
|
||||
let other = state
|
||||
.storage
|
||||
.create_guild("elsewhere", "Other")
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign = state
|
||||
.storage
|
||||
.create_role(
|
||||
&other,
|
||||
"foreign",
|
||||
"#fff",
|
||||
Permissions::ADMINISTRATOR.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
crate::handler::guild::handle_role_assign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: guild.clone(),
|
||||
user_id: "visitor".into(),
|
||||
role_id: foreign.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::guild::handle_role_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleDeletePayload {
|
||||
guild_id: guild.clone(),
|
||||
role_id: foreign.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
state
|
||||
.storage
|
||||
.list_guild_roles(&other)
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.id == foreign)
|
||||
);
|
||||
let otherguild = state
|
||||
.storage
|
||||
.create_guild("owner", "Managed")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&otherguild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
let manager = state
|
||||
.storage
|
||||
.create_role(
|
||||
&otherguild,
|
||||
"manager",
|
||||
"#fff",
|
||||
Permissions::MANAGE_ROLES.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.assign_role(&otherguild, "visitor", &manager)
|
||||
.await
|
||||
.unwrap();
|
||||
let powerful = state
|
||||
.storage
|
||||
.create_role(
|
||||
&otherguild,
|
||||
"admin",
|
||||
"#fff",
|
||||
Permissions::ADMINISTRATOR.bits(),
|
||||
2,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::guild::handle_role_assign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&sid,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: otherguild.clone(),
|
||||
user_id: "visitor".into(),
|
||||
role_id: powerful,
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let actual = Permissions::from_role_perms(
|
||||
&state
|
||||
.storage
|
||||
.get_user_role_perms(&otherguild, "visitor")
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(!actual.contains(Permissions::ADMINISTRATOR));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn removing_voice_role_revokes_existing_udp_membership() {
|
||||
use crate::domain::permissions::Permissions;
|
||||
use crate::proto::RoleAssignPayload;
|
||||
let (mut state, sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
let role = state
|
||||
.storage
|
||||
.create_role(
|
||||
&guild,
|
||||
"speaker",
|
||||
"#fff",
|
||||
Permissions::VOICE_SPEAK.bits(),
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.assign_role(&guild, "visitor", &role)
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"managed",
|
||||
"Managed",
|
||||
channels::ChannelKind::Voice,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
channels::join(&state.channels, "managed", &sid).await;
|
||||
super::super::set_voice_channel(&state, &sid, Some("managed".into())).await;
|
||||
let owner = session::create(&state.sessions, "owner".into(), "Owner".into()).await;
|
||||
let (tx, mut rx) = tokio::sync::broadcast::channel(8);
|
||||
state.voice_member_tx = Some(tx);
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
crate::handler::guild::handle_role_unassign(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner.session_id,
|
||||
&to_payload(&RoleAssignPayload {
|
||||
guild_id: guild,
|
||||
user_id: "visitor".into(),
|
||||
role_id: role,
|
||||
}),
|
||||
&SessionCrypto::derive(&[7; 32], &owner.session_id),
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
session::get(&state.sessions, &sid)
|
||||
.await
|
||||
.unwrap()
|
||||
.voice_channel_id
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
!channels::members(&state.channels, "managed")
|
||||
.await
|
||||
.contains(&sid)
|
||||
);
|
||||
let event: serde_json::Value = serde_json::from_str(&rx.try_recv().unwrap()).unwrap();
|
||||
assert_eq!(event["type"], "leave");
|
||||
assert_eq!(event["session_id"], sid);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn private_channel_notifications_target_members_and_acknowledge_editor() {
|
||||
use crate::proto::{ChannelCreatePayload, ChannelDeletePayload, ChannelEditPayload};
|
||||
let (state, owner_sid) = fixture().await;
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("visitor", "Private")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "member")
|
||||
.await
|
||||
.unwrap();
|
||||
let member = session::create(&state.sessions, "member".into(), "Member".into()).await;
|
||||
let outsider = session::create(&state.sessions, "outsider".into(), "Outsider".into()).await;
|
||||
let mut events = state.broadcast.subscribe();
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &owner_sid);
|
||||
let (mut stream, _peer) = tokio::io::duplex(65536);
|
||||
let creation = ChannelCreatePayload {
|
||||
channel_id: "private-notification".into(),
|
||||
channel_name: "Private name".into(),
|
||||
kind: "text".into(),
|
||||
guild_id: Some(guild.clone()),
|
||||
};
|
||||
crate::handler::channel::handle_channel_create(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&creation),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::channel::handle_channel_edit(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&ChannelEditPayload {
|
||||
channel_id: creation.channel_id.clone(),
|
||||
channel_name: "Renamed privately".into(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::handler::channel::handle_channel_delete(
|
||||
&mut stream,
|
||||
&mut 0,
|
||||
&owner_sid,
|
||||
&to_payload(&ChannelDeletePayload {
|
||||
channel_id: creation.channel_id.clone(),
|
||||
}),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut notifications = Vec::new();
|
||||
while let Ok(event) = events.try_recv() {
|
||||
notifications.push(event)
|
||||
}
|
||||
assert_eq!(notifications.len(), 5);
|
||||
assert!(notifications.iter().all(|event|matches!(event.target_session_id.as_deref(),Some(id) if id==owner_sid || id==member.session_id)));
|
||||
assert!(
|
||||
notifications
|
||||
.iter()
|
||||
.all(|event| event.target_session_id.as_deref() != Some(&outsider.session_id))
|
||||
);
|
||||
assert!(
|
||||
notifications.iter().any(
|
||||
|event| event.target_session_id.as_deref() == Some(&owner_sid)
|
||||
&& crate::proto::PacketHeader::from_bytes(event.data[..12].try_into().unwrap())
|
||||
.packet_id
|
||||
== PacketId::ChannelEdit as u16
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
super::super::may_deliver_metadata(
|
||||
&state,
|
||||
&member.session_id,
|
||||
PacketId::ChannelCreate,
|
||||
&to_payload(&creation)
|
||||
)
|
||||
.await
|
||||
);
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&guild, "member")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!super::super::may_deliver_metadata(
|
||||
&state,
|
||||
&member.session_id,
|
||||
PacketId::ChannelCreate,
|
||||
&to_payload(&creation)
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
let (state, sid) = fixture().await;
|
||||
let crypto = SessionCrypto::derive(&[7; 32], &sid);
|
||||
let history = |channel: &str| BroadcastMsg {
|
||||
channel_id: Some(channel.into()),
|
||||
exclude_session: None,
|
||||
target_session_id: Some(sid.clone()),
|
||||
data: encode_packet(
|
||||
PacketId::ChatHistory,
|
||||
0,
|
||||
&to_payload(&ChatHistoryPayload {
|
||||
channel_id: channel.into(),
|
||||
messages: vec![],
|
||||
}),
|
||||
),
|
||||
};
|
||||
// The same queued target/channel envelope is deliverable while subscribed.
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
let mut seq = 2;
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&history("general"),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut first = [0u8; 12];
|
||||
peer.read_exact(&mut first).await.unwrap();
|
||||
assert_eq!(
|
||||
u16::from_be_bytes(first[..2].try_into().unwrap()),
|
||||
PacketId::ChatHistory as u16
|
||||
);
|
||||
assert_eq!(seq, 3);
|
||||
|
||||
super::super::leave(&mut stream, &mut seq, &sid, "general", &crypto, &state)
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&history("general"),
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
seq, 3,
|
||||
"discarded history cannot consume an encryption sequence"
|
||||
);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let guild = state
|
||||
.storage
|
||||
.create_guild("owner", "Private history")
|
||||
.await
|
||||
.unwrap();
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
channels::create(
|
||||
&state.channels,
|
||||
"private-history",
|
||||
"Private",
|
||||
channels::ChannelKind::Text,
|
||||
Some(guild.clone()),
|
||||
)
|
||||
.await;
|
||||
attempt_join(&state, &sid, "private-history").await;
|
||||
let queued = history("private-history");
|
||||
{
|
||||
let _access = state.access.write().await;
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&guild, "visitor")
|
||||
.await
|
||||
.unwrap();
|
||||
super::super::revoke_guild_access(&state, &guild, Some("visitor")).await;
|
||||
}
|
||||
let (mut stream, mut peer) = tokio::io::duplex(65536);
|
||||
crate::handler::deliver::deliver_encrypted(
|
||||
&mut stream,
|
||||
&mut seq,
|
||||
&sid,
|
||||
&queued,
|
||||
&crypto,
|
||||
&state,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(seq, 3);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())
|
||||
.await
|
||||
.is_err(),
|
||||
"history queued before a guild kick must not be delivered afterwards"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use crate::{
|
|||
proto::SessionCrypto,
|
||||
};
|
||||
|
||||
use super::{broadcast_leave, set_channel, set_voice_channel};
|
||||
use super::{broadcast_leave, set_channel};
|
||||
|
||||
pub async fn leave(
|
||||
_stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
|
||||
|
|
@ -18,25 +18,17 @@ pub async fn leave(
|
|||
_crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
let is_voice = sess.voice_channel_id.as_deref() == Some(channel_id);
|
||||
if !is_voice && sess.channel_id.as_deref() != Some(channel_id) {
|
||||
return Ok(());
|
||||
}
|
||||
let user_id = Some(sess.user_id);
|
||||
let user_id = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.map(|s| s.user_id);
|
||||
|
||||
let is_voice = channels::get_channel(&state.channels, channel_id)
|
||||
.await
|
||||
.is_some_and(|c| c.kind == channels::ChannelKind::Voice);
|
||||
|
||||
channels::leave(&state.channels, channel_id, session_id).await;
|
||||
if is_voice {
|
||||
set_voice_channel(state, session_id, None).await;
|
||||
} else {
|
||||
set_channel(state, session_id, None).await;
|
||||
}
|
||||
set_channel(state, session_id, None).await;
|
||||
broadcast_leave(state, channel_id, session_id).await;
|
||||
if is_voice {
|
||||
state.media.revoke(state, session_id).await;
|
||||
}
|
||||
|
||||
if is_voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
|
|
@ -44,7 +36,6 @@ pub async fn leave(
|
|||
{
|
||||
let event = serde_json::json!({
|
||||
"type": "leave",
|
||||
"session_id": session_id,
|
||||
"channel_id": channel_id,
|
||||
"user_id": uid,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -33,274 +33,3 @@ async fn set_channel(state: &State, session_id: &str, ch: Option<String>) {
|
|||
s.channel_id = ch;
|
||||
}
|
||||
}
|
||||
|
||||
async fn set_voice_channel(state: &State, session_id: &str, ch: Option<String>) {
|
||||
if let Some(s) = state.sessions.write().await.get_mut(session_id) {
|
||||
s.voice_channel_id = ch;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove active subscriptions and UDP credentials when guild access is revoked.
|
||||
pub async fn revoke_guild_access(state: &State, guild: &str, user: Option<&str>) {
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| user.is_none_or(|u| u == s.user_id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for sess in sessions {
|
||||
for (voice, ch) in [(false, sess.channel_id), (true, sess.voice_channel_id)] {
|
||||
let Some(ch) = ch else { continue };
|
||||
if !crate::domain::channels::get_channel(&state.channels, &ch)
|
||||
.await
|
||||
.is_some_and(|c| c.guild_id.as_deref() == Some(guild))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
crate::domain::channels::leave(&state.channels, &ch, &sess.session_id).await;
|
||||
if voice {
|
||||
set_voice_channel(state, &sess.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _=tx.send(serde_json::json!({"type":"leave","session_id":sess.session_id,"channel_id":ch,"user_id":sess.user_id}).to_string());
|
||||
}
|
||||
state.media.revoke(state, &sess.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: sess.user_id.clone(),
|
||||
channel_id: ch.clone(),
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(sess.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
} else {
|
||||
set_channel(state, &sess.session_id, None).await;
|
||||
}
|
||||
broadcast_leave(state, &ch, &sess.session_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Global channels have no modeled server administrator: authenticated users cannot mutate them.
|
||||
pub(super) async fn may_manage(
|
||||
state: &State,
|
||||
user: &str,
|
||||
guild: Option<&str>,
|
||||
) -> anyhow::Result<bool> {
|
||||
let Some(guild) = guild else { return Ok(false) };
|
||||
let Some(info) = state.storage.get_guild(guild).await? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if info.owner_id == user {
|
||||
return Ok(true);
|
||||
}
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(user)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == guild)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let roles = state.storage.get_user_role_perms(guild, user).await?;
|
||||
Ok(
|
||||
crate::domain::permissions::Permissions::from_role_perms(&roles)
|
||||
.has(crate::domain::permissions::Permissions::MANAGE_CHANNELS),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn denied(
|
||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||
seq: &mut u32,
|
||||
crypto: &crate::proto::SessionCrypto,
|
||||
) -> anyhow::Result<()> {
|
||||
crate::net::io::send_encrypted(
|
||||
stream,
|
||||
PacketId::Error,
|
||||
seq,
|
||||
&to_payload(&crate::proto::ErrorPayload {
|
||||
code: crate::proto::ErrorCode::PermissionDenied as u32,
|
||||
message: "guild MANAGE_CHANNELS permission required".into(),
|
||||
}),
|
||||
crypto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Caller serializes access mutation against joins. Revoke before removing cached channel metadata.
|
||||
pub async fn revoke_channel(state: &State, channel: &str) {
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| {
|
||||
s.channel_id.as_deref() == Some(channel)
|
||||
|| s.voice_channel_id.as_deref() == Some(channel)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
for session in sessions {
|
||||
crate::domain::channels::leave(&state.channels, channel, &session.session_id).await;
|
||||
if session.channel_id.as_deref() == Some(channel) {
|
||||
set_channel(state, &session.session_id, None).await;
|
||||
}
|
||||
if session.voice_channel_id.as_deref() == Some(channel) {
|
||||
set_voice_channel(state, &session.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _ = tx.send(
|
||||
serde_json::json!({"type":"leave","session_id":session.session_id}).to_string(),
|
||||
);
|
||||
}
|
||||
state.media.revoke(state, &session.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: session.user_id,
|
||||
channel_id: channel.into(),
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
broadcast_leave(state, channel, &session.session_id).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Removing voice permission also invalidates existing relay credentials and screen shares.
|
||||
pub async fn recheck_voice_permissions(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
user: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
let owner = state.storage.get_guild(guild).await?.map(|g| g.owner_id);
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| user.is_none_or(|u| u == s.user_id))
|
||||
.cloned()
|
||||
.collect();
|
||||
for session in sessions {
|
||||
let Some(channel) = session.voice_channel_id else {
|
||||
continue;
|
||||
};
|
||||
if !crate::domain::channels::get_channel(&state.channels, &channel)
|
||||
.await
|
||||
.is_some_and(|c| c.guild_id.as_deref() == Some(guild))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if owner.as_deref() == Some(&session.user_id) {
|
||||
continue;
|
||||
}
|
||||
let roles = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &session.user_id)
|
||||
.await?;
|
||||
if crate::domain::permissions::Permissions::from_role_perms(&roles)
|
||||
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
crate::domain::channels::leave(&state.channels, &channel, &session.session_id).await;
|
||||
set_voice_channel(state, &session.session_id, None).await;
|
||||
if let Some(tx) = &state.voice_member_tx {
|
||||
let _ = tx.send(
|
||||
serde_json::json!({"type":"leave","session_id":session.session_id}).to_string(),
|
||||
);
|
||||
}
|
||||
state.media.revoke(state, &session.session_id).await;
|
||||
let event = crate::proto::VoiceState {
|
||||
user_id: session.user_id,
|
||||
channel_id: channel,
|
||||
state: "disconnected".into(),
|
||||
};
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(session.session_id.clone()),
|
||||
data: encode_packet(PacketId::VoiceState, 0, &to_payload(&event)),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Metadata is addressed only to currently persisted guild members, including non-subscribers.
|
||||
pub(super) async fn notify_guild(
|
||||
state: &State,
|
||||
guild: Option<&str>,
|
||||
exclude: Option<&str>,
|
||||
data: Vec<u8>,
|
||||
) -> anyhow::Result<()> {
|
||||
let Some(guild) = guild else { return Ok(()) };
|
||||
let _access = state.access.read().await;
|
||||
let members = state.storage.list_guild_members(guild).await?;
|
||||
let sessions: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|session| {
|
||||
Some(session.session_id.as_str()) != exclude
|
||||
&& members
|
||||
.iter()
|
||||
.any(|member| member.user_id == session.user_id)
|
||||
})
|
||||
.map(|session| session.session_id.clone())
|
||||
.collect();
|
||||
for target in sessions {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(target),
|
||||
data: data.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creation/rename payloads queued before removal must not disclose new metadata afterwards.
|
||||
pub async fn may_deliver_metadata(
|
||||
state: &State,
|
||||
recipient: &str,
|
||||
packet: PacketId,
|
||||
payload: &[u8],
|
||||
) -> bool {
|
||||
use prost::Message;
|
||||
let guild = match packet {
|
||||
PacketId::ChannelCreate => match crate::proto::ChannelCreatePayload::decode(payload) {
|
||||
Ok(message) => message.guild_id,
|
||||
Err(_) => return false,
|
||||
},
|
||||
PacketId::ChannelEdit => match crate::proto::ChannelEditPayload::decode(payload) {
|
||||
Ok(message) => {
|
||||
match crate::domain::channels::get_channel(&state.channels, &message.channel_id)
|
||||
.await
|
||||
{
|
||||
Some(channel) => channel.guild_id,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
Err(_) => return false,
|
||||
},
|
||||
_ => return true,
|
||||
};
|
||||
let Some(guild) = guild else { return true };
|
||||
let Some(session) = crate::domain::session::get(&state.sessions, recipient).await else {
|
||||
return false;
|
||||
};
|
||||
state
|
||||
.storage
|
||||
.list_user_guilds(&session.user_id)
|
||||
.await
|
||||
.is_ok_and(|guilds| guilds.iter().any(|g| g.id == guild))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,12 +48,15 @@ pub async fn handle(session_id: &str, mut msg: ChatMessagePayload, state: &State
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(msg.channel_id.clone()),
|
||||
exclude_session: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::ChatMessage, 0, &to_payload(&msg)),
|
||||
});
|
||||
|
||||
debug!(channel=%msg.channel_id,message_id=%msg.message_id,"chat message accepted");
|
||||
debug!(
|
||||
"chat {} → {}: {}",
|
||||
sess.nickname, msg.channel_id, msg.content
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ pub async fn handle_message_edit(session_id: &str, payload: &[u8], state: &State
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(edit.channel_id.clone()),
|
||||
exclude_session: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageEdit, 0, &to_payload(&broadcast_msg)),
|
||||
});
|
||||
|
|
@ -81,7 +81,7 @@ pub async fn handle_message_delete(session_id: &str, payload: &[u8], state: &Sta
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(delete.channel_id.clone()),
|
||||
exclude_session: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageDelete, 0, &to_payload(&delete)),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ pub async fn handle_reaction_add(
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(payload.channel_id.clone()),
|
||||
exclude_session: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageReactionAdd, 0, &to_payload(&payload)),
|
||||
});
|
||||
|
|
@ -79,7 +79,7 @@ pub async fn handle_reaction_remove(
|
|||
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: Some(payload.channel_id.clone()),
|
||||
exclude_session: None,
|
||||
exclude_session: Some(session_id.into()),
|
||||
target_session_id: None,
|
||||
data: encode_packet(PacketId::MessageReactionRemove, 0, &to_payload(&payload)),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,59 +15,25 @@ pub async fn deliver_encrypted(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
if msg.exclude_session.as_deref() == Some(session_id)
|
||||
|| msg
|
||||
.target_session_id
|
||||
.as_deref()
|
||||
.is_some_and(|target| target != session_id)
|
||||
{
|
||||
if msg.exclude_session.as_deref() == Some(session_id) {
|
||||
return Ok(());
|
||||
}
|
||||
if msg.data.len() >= crate::proto::PacketHeader::SIZE {
|
||||
let hdr = crate::proto::PacketHeader::from_bytes(
|
||||
msg.data[..crate::proto::PacketHeader::SIZE]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if let Some(packet) = crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
&& matches!(
|
||||
packet,
|
||||
crate::proto::PacketId::ChannelCreate | crate::proto::PacketId::ChannelEdit
|
||||
)
|
||||
&& !crate::handler::channel::may_deliver_metadata(
|
||||
state,
|
||||
session_id,
|
||||
packet,
|
||||
&msg.data[crate::proto::PacketHeader::SIZE..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if crate::proto::PacketId::from_u16(hdr.packet_id)
|
||||
== Some(crate::proto::PacketId::MediaEvent)
|
||||
&& !crate::media::may_deliver(
|
||||
state,
|
||||
session_id,
|
||||
&msg.data[crate::proto::PacketHeader::SIZE..],
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let Some(ref target) = msg.target_session_id {
|
||||
if target != session_id {
|
||||
return Ok(());
|
||||
}
|
||||
io::deliver_encrypted(stream, crypto, seq, &msg.data).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(ref ch) = msg.channel_id {
|
||||
let access = state.access.read().await;
|
||||
let in_ch = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.is_some_and(|s| {
|
||||
s.channel_id.as_deref() == Some(ch.as_str())
|
||||
|| s.voice_channel_id.as_deref() == Some(ch.as_str())
|
||||
});
|
||||
.and_then(|s| s.channel_id)
|
||||
.as_deref()
|
||||
== Some(ch.as_str());
|
||||
if !in_ch {
|
||||
return Ok(());
|
||||
}
|
||||
drop(access);
|
||||
}
|
||||
io::deliver_encrypted(stream, crypto, seq, &msg.data).await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
addr: std::net::SocketAddr,
|
||||
) -> Result<()> {
|
||||
match pid {
|
||||
PacketId::MediaControl => crate::media::handle(ctx, session_id, payload).await?,
|
||||
PacketId::WebhookCreate
|
||||
| PacketId::WebhookList
|
||||
| PacketId::WebhookRotate
|
||||
|
|
|
|||
|
|
@ -35,26 +35,3 @@ pub use decline::handle_friend_decline;
|
|||
pub use list::handle_friend_list;
|
||||
pub use manage::{handle_block_list, handle_block_user, handle_friend_remove, handle_unblock_user};
|
||||
pub use requests::{handle_friend_accept, handle_friend_request};
|
||||
|
||||
async fn notify_user(
|
||||
state: &crate::net::state::State,
|
||||
user: &str,
|
||||
event: &crate::proto::FriendEventPayload,
|
||||
) {
|
||||
let ids: Vec<_> = state
|
||||
.sessions
|
||||
.read()
|
||||
.await
|
||||
.values()
|
||||
.filter(|s| s.user_id == user)
|
||||
.map(|s| s.session_id.clone())
|
||||
.collect();
|
||||
for id in ids {
|
||||
let _ = state.broadcast.send(crate::net::state::BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(id),
|
||||
data: crate::proto::encode_packet(PacketId::FriendEvent, 0, &to_payload(event)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
|
|||
|
||||
use crate::{
|
||||
domain::session,
|
||||
net::{io, state::State},
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{
|
||||
FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, SessionCrypto,
|
||||
to_payload,
|
||||
encode_packet, to_payload,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -79,7 +82,12 @@ pub async fn handle_friend_request(
|
|||
user_id: sess.user_id.clone(),
|
||||
nickname: Some(sess.nickname.clone()),
|
||||
};
|
||||
super::notify_user(state, &req.to_user_id, &ev).await;
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(req.to_user_id.clone()),
|
||||
data: encode_packet(PacketId::FriendRequest, *seq, &to_payload(&ev)),
|
||||
});
|
||||
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -128,7 +136,12 @@ pub async fn handle_friend_accept(
|
|||
user_id: sess.user_id.clone(),
|
||||
nickname: Some(sess.nickname.clone()),
|
||||
};
|
||||
super::notify_user(state, &req.from_user_id, &ev).await;
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(req.from_user_id.clone()),
|
||||
data: encode_packet(PacketId::FriendAccept, *seq, &to_payload(&ev)),
|
||||
});
|
||||
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
|
|||
|
|
@ -75,7 +75,6 @@ pub async fn handle_guild_delete(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = crate::proto::GuildDeletePayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -87,7 +86,6 @@ pub async fn handle_guild_delete(
|
|||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("guild not found"))?;
|
||||
if guild.owner_id != sess.user_id {
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -99,7 +97,6 @@ pub async fn handle_guild_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, None).await;
|
||||
state.storage.delete_guild(&req.guild_id).await?;
|
||||
state
|
||||
.storage
|
||||
|
|
@ -113,7 +110,6 @@ pub async fn handle_guild_delete(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildDelete,
|
||||
|
|
|
|||
|
|
@ -21,30 +21,11 @@ pub async fn handle_guild_member_join(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberJoinPayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"a valid invitation is required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.add_guild_member(&req.guild_id, &sess.user_id)
|
||||
|
|
@ -60,7 +41,6 @@ pub async fn handle_guild_member_join(
|
|||
.map(|r| r.color.clone())
|
||||
.unwrap_or_else(|| "#ffffff".into());
|
||||
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberJoin,
|
||||
|
|
@ -95,7 +75,6 @@ pub async fn handle_guild_member_leave(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberLeavePayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -106,29 +85,10 @@ pub async fn handle_guild_member_leave(
|
|||
} else {
|
||||
req.user_id.clone()
|
||||
};
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == target);
|
||||
if target != sess.user_id || owner {
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"only a non-owner may leave their own membership",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&req.guild_id, target.as_str())
|
||||
.await?;
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&target)).await;
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberLeave,
|
||||
|
|
@ -151,7 +111,6 @@ pub async fn handle_guild_member_kick(
|
|||
crypto: &SessionCrypto,
|
||||
state: &State,
|
||||
) -> Result<()> {
|
||||
let guard = state.access.write().await;
|
||||
let req = GuildMemberKickPayload::decode(payload)?;
|
||||
let sess = session::get(&state.sessions, session_id)
|
||||
.await
|
||||
|
|
@ -165,7 +124,6 @@ pub async fn handle_guild_member_kick(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -177,28 +135,10 @@ pub async fn handle_guild_member_kick(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == req.user_id)
|
||||
{
|
||||
drop(guard);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild owner cannot be kicked",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_guild_member(&req.guild_id, &req.user_id)
|
||||
.await?;
|
||||
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&req.user_id)).await;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -210,7 +150,6 @@ pub async fn handle_guild_member_kick(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(guard);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildMemberKick,
|
||||
|
|
|
|||
|
|
@ -29,24 +29,7 @@ pub async fn handle_member_list_fetch(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild membership required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
// Membership is checked before listing identities.
|
||||
// Optional: verify the requester is a member of the guild.
|
||||
let owner_id = state
|
||||
.storage
|
||||
.get_guild(&req.guild_id)
|
||||
|
|
@ -96,7 +79,6 @@ pub async fn handle_role_assign(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -105,7 +87,6 @@ pub async fn handle_role_assign(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -117,31 +98,6 @@ pub async fn handle_role_assign(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let role = super::roles::role_permissions(state, &req.guild_id, &req.role_id).await?;
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&req.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
|| match role {
|
||||
Some(permissions) => {
|
||||
!super::roles::may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role or target not permitted in this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.assign_role(&req.guild_id, &req.user_id, &req.role_id)
|
||||
|
|
@ -158,7 +114,6 @@ pub async fn handle_role_assign(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(access);
|
||||
// Confirm to caller.
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
|
|
@ -190,7 +145,6 @@ pub async fn handle_role_unassign(
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -199,7 +153,6 @@ pub async fn handle_role_unassign(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -211,37 +164,10 @@ pub async fn handle_role_unassign(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let role = super::roles::role_permissions(state, &req.guild_id, &req.role_id).await?;
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&req.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
|| match role {
|
||||
Some(permissions) => {
|
||||
!super::roles::may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role or target not permitted in this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state
|
||||
.storage
|
||||
.remove_role_from_user(&req.guild_id, &req.user_id, &req.role_id)
|
||||
.await?;
|
||||
crate::handler::channel::recheck_voice_permissions(state, &req.guild_id, Some(&req.user_id))
|
||||
.await?;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -254,7 +180,6 @@ pub async fn handle_role_unassign(
|
|||
)
|
||||
.await?;
|
||||
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::GuildRoleUnassign,
|
||||
|
|
@ -280,26 +205,7 @@ pub async fn handle_role_list_fetch(
|
|||
state: &State,
|
||||
) -> Result<()> {
|
||||
let req = GuildRoleListFetchPayload::decode(payload)?;
|
||||
let Some(sess) = session::get(&state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&sess.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == req.guild_id)
|
||||
{
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"guild membership required",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
let _sess = session::get(&state.sessions, session_id).await;
|
||||
|
||||
let rows = state.storage.list_guild_roles(&req.guild_id).await?;
|
||||
let roles: Vec<GuildRoleInfoPayload> = rows
|
||||
|
|
|
|||
|
|
@ -46,15 +46,6 @@ async fn require_perm(
|
|||
{
|
||||
return Ok(true);
|
||||
}
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|g| g.id == guild_id)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let perms = state.storage.get_user_role_perms(guild_id, user_id).await?;
|
||||
Ok(Permissions::from_role_perms(&perms).has(required))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ pub async fn handle_role_create(
|
|||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -32,7 +31,6 @@ pub async fn handle_role_create(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -46,22 +44,6 @@ pub async fn handle_role_create(
|
|||
|
||||
let color = req.color.as_deref().unwrap_or("#ffffff");
|
||||
let permissions = req.permissions.unwrap_or(0);
|
||||
if req.name.trim().is_empty()
|
||||
|| req.name.chars().count() > 64
|
||||
|| req.name.chars().any(char::is_control)
|
||||
|| !may_grant(state, &req.guild_id, &sess.user_id, permissions).await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"cannot grant requested role",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
let role_id = state
|
||||
.storage
|
||||
.create_role(&req.guild_id, &req.name, color, permissions, 1)
|
||||
|
|
@ -78,7 +60,6 @@ pub async fn handle_role_create(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::RoleCreate,
|
||||
|
|
@ -109,7 +90,6 @@ pub async fn handle_role_delete(
|
|||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session not found"))?;
|
||||
|
||||
let access = state.access.write().await;
|
||||
if !super::require_perm(
|
||||
state,
|
||||
&req.guild_id,
|
||||
|
|
@ -118,7 +98,6 @@ pub async fn handle_role_delete(
|
|||
)
|
||||
.await?
|
||||
{
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -130,32 +109,7 @@ pub async fn handle_role_delete(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(permissions) = role_permissions(state, &req.guild_id, &req.role_id).await? else {
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"role is outside this guild",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
};
|
||||
if !may_grant(state, &req.guild_id, &sess.user_id, permissions).await? {
|
||||
drop(access);
|
||||
send_err(
|
||||
stream,
|
||||
seq,
|
||||
crate::proto::ErrorCode::PermissionDenied,
|
||||
"cannot manage requested role",
|
||||
crypto,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
state.storage.delete_role(&req.role_id).await?;
|
||||
crate::handler::channel::recheck_voice_permissions(state, &req.guild_id, None).await?;
|
||||
state
|
||||
.storage
|
||||
.append_audit_log(
|
||||
|
|
@ -167,7 +121,6 @@ pub async fn handle_role_delete(
|
|||
None,
|
||||
)
|
||||
.await?;
|
||||
drop(access);
|
||||
io::send_encrypted(
|
||||
stream,
|
||||
PacketId::RoleDelete,
|
||||
|
|
@ -181,36 +134,3 @@ pub async fn handle_role_delete(
|
|||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A role manager cannot create/assign permissions they do not themselves hold.
|
||||
pub(super) async fn may_grant(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
actor: &str,
|
||||
permissions: u64,
|
||||
) -> Result<bool> {
|
||||
if state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == actor)
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let held =
|
||||
Permissions::from_role_perms(&state.storage.get_user_role_perms(guild, actor).await?);
|
||||
Ok(held.has(Permissions::ADMINISTRATOR) || permissions & !held.bits() == 0)
|
||||
}
|
||||
pub(super) async fn role_permissions(
|
||||
state: &State,
|
||||
guild: &str,
|
||||
role: &str,
|
||||
) -> Result<Option<u64>> {
|
||||
Ok(state
|
||||
.storage
|
||||
.list_guild_roles(guild)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|r| r.id == role)
|
||||
.map(|r| r.permissions as u64))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,10 +25,9 @@ pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
crypto,
|
||||
state,
|
||||
};
|
||||
let mut reader = io::EncryptedReader::default();
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = reader.read(ctx.stream, ctx.crypto) => {
|
||||
result = io::read_encrypted(ctx.stream, ctx.crypto) => {
|
||||
let (hdr, payload) = result?;
|
||||
let pid = match PacketId::from_u16(hdr.packet_id) {
|
||||
Some(p) => p,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ pub mod admin;
|
|||
pub mod bootstrap;
|
||||
pub mod domain;
|
||||
pub mod handler;
|
||||
pub mod media;
|
||||
pub mod net;
|
||||
pub mod proto;
|
||||
pub mod webhooks;
|
||||
|
|
@ -229,11 +228,7 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
|
|||
state: State,
|
||||
) -> Result<()> {
|
||||
let mut seq = 0u32;
|
||||
let (sess, crypto) = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(15),
|
||||
net::handshake::run(&mut stream, addr, &state, &mut seq),
|
||||
)
|
||||
.await??;
|
||||
let (sess, crypto) = net::handshake::run(&mut stream, addr, &state, &mut seq).await?;
|
||||
let sid = sess.session_id.clone();
|
||||
state
|
||||
.sessions_count
|
||||
|
|
@ -298,27 +293,29 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
|
|||
});
|
||||
}
|
||||
|
||||
if let Some(sess) = session::get(&state.sessions, &sid).await {
|
||||
for ch in [sess.channel_id, sess.voice_channel_id]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
if let Some(ch) = session::get(&state.sessions, &sid)
|
||||
.await
|
||||
.and_then(|s| s.channel_id)
|
||||
{
|
||||
let is_voice = channels::get_channel(&state.channels, &ch)
|
||||
.await
|
||||
.is_some_and(|c| c.kind == channels::ChannelKind::Voice);
|
||||
|
||||
channels::leave(&state.channels, &ch, &sid).await;
|
||||
handler::channel::broadcast_leave(&state, &ch, &sid).await;
|
||||
|
||||
if is_voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
&& let Some(ref uid) = user_id
|
||||
{
|
||||
let is_voice = channels::get_channel(&state.channels, &ch)
|
||||
.await
|
||||
.is_some_and(|c| c.kind == channels::ChannelKind::Voice);
|
||||
channels::leave(&state.channels, &ch, &sid).await;
|
||||
handler::channel::broadcast_leave(&state, &ch, &sid).await;
|
||||
if is_voice
|
||||
&& let Some(tx) = &state.voice_member_tx
|
||||
&& let Some(ref uid) = user_id
|
||||
{
|
||||
let _ = tx.send(
|
||||
serde_json::json!({"type":"leave","session_id":sid,"channel_id":ch,"user_id":uid}).to_string(),
|
||||
);
|
||||
}
|
||||
let event = serde_json::json!({
|
||||
"type": "leave",
|
||||
"channel_id": ch,
|
||||
"user_id": uid,
|
||||
});
|
||||
let _ = tx.send(event.to_string());
|
||||
}
|
||||
}
|
||||
state.media.revoke(&state, &sid).await;
|
||||
session::remove(&state.sessions, &sid).await;
|
||||
state
|
||||
.sessions_count
|
||||
|
|
|
|||
|
|
@ -1,524 +0,0 @@
|
|||
//! Bounded authenticated signalling. No media packets or bearer auth endpoints.
|
||||
use crate::{
|
||||
domain::{
|
||||
channels::{self, ChannelKind},
|
||||
permissions::Permissions,
|
||||
session,
|
||||
},
|
||||
handler::Ctx,
|
||||
net::{
|
||||
io,
|
||||
state::{BroadcastMsg, State},
|
||||
},
|
||||
proto::{self, MediaControl, MediaEvent, PacketId, encode_packet, to_payload},
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use prost::Message;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite},
|
||||
sync::Mutex,
|
||||
};
|
||||
|
||||
pub const START: u32 = 1;
|
||||
pub const STOP: u32 = 2;
|
||||
pub const WATCH: u32 = 3;
|
||||
pub const UNWATCH: u32 = 4;
|
||||
pub const OFFER: u32 = 5;
|
||||
pub const ANSWER: u32 = 6;
|
||||
pub const ICE: u32 = 7;
|
||||
const MAX_VIEWERS: usize = 4;
|
||||
const MAX_SHARES: usize = 128;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Share {
|
||||
channel: String,
|
||||
owner: String,
|
||||
user: String,
|
||||
viewers: HashSet<String>,
|
||||
audio: bool,
|
||||
mic: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Runtime {
|
||||
shares: Mutex<HashMap<String, Share>>,
|
||||
rates: Mutex<HashMap<String, SignalBudget>>,
|
||||
}
|
||||
struct SignalBudget {
|
||||
updated: std::time::Instant,
|
||||
tokens: f64,
|
||||
}
|
||||
impl SignalBudget {
|
||||
fn consume(&mut self) -> bool {
|
||||
let now = std::time::Instant::now();
|
||||
self.tokens =
|
||||
(self.tokens + now.duration_since(self.updated).as_secs_f64() * 20.0).min(64.0);
|
||||
self.updated = now;
|
||||
if self.tokens < 1.0 {
|
||||
return false;
|
||||
}
|
||||
self.tokens -= 1.0;
|
||||
true
|
||||
}
|
||||
}
|
||||
struct Route {
|
||||
target: String,
|
||||
event: MediaEvent,
|
||||
}
|
||||
|
||||
impl Share {
|
||||
fn event(&self, action: u32, id: &str, sender: &str) -> MediaEvent {
|
||||
MediaEvent {
|
||||
action,
|
||||
channel_id: self.channel.clone(),
|
||||
share_id: id.into(),
|
||||
target_session_id: String::new(),
|
||||
body: String::new(),
|
||||
mline_index: 0,
|
||||
application_audio: self.audio,
|
||||
microphone: self.mic,
|
||||
sender_session_id: sender.into(),
|
||||
publisher_user_id: self.user.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Runtime {
|
||||
async fn apply(
|
||||
&self,
|
||||
sender: &str,
|
||||
user: &str,
|
||||
req: &MediaControl,
|
||||
members: &HashSet<String>,
|
||||
) -> Result<Vec<Route>> {
|
||||
validate(req)?;
|
||||
let mut shares = self.shares.lock().await;
|
||||
if req.action == START {
|
||||
if shares.len() >= MAX_SHARES
|
||||
|| shares.contains_key(&req.share_id)
|
||||
|| shares.values().any(|share| share.owner == sender)
|
||||
{
|
||||
bail!("share already active or server capacity reached");
|
||||
}
|
||||
let share = Share {
|
||||
channel: req.channel_id.clone(),
|
||||
owner: sender.into(),
|
||||
user: user.into(),
|
||||
viewers: HashSet::new(),
|
||||
audio: req.application_audio,
|
||||
mic: req.microphone,
|
||||
};
|
||||
let routes = members
|
||||
.iter()
|
||||
.map(|target| Route {
|
||||
target: target.clone(),
|
||||
event: share.event(START, &req.share_id, sender),
|
||||
})
|
||||
.collect();
|
||||
shares.insert(req.share_id.clone(), share);
|
||||
return Ok(routes);
|
||||
}
|
||||
// WATCH with an empty share ID requests current announcements, not a subscription.
|
||||
if req.action == WATCH && req.share_id.is_empty() {
|
||||
return Ok(shares
|
||||
.iter()
|
||||
.filter(|(_, share)| share.channel == req.channel_id)
|
||||
.map(|(id, share)| Route {
|
||||
target: sender.into(),
|
||||
event: share.event(START, id, &share.owner),
|
||||
})
|
||||
.collect());
|
||||
}
|
||||
let share = shares
|
||||
.get_mut(&req.share_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("unknown or expired share"))?;
|
||||
if share.channel != req.channel_id {
|
||||
bail!("share belongs to another voice channel");
|
||||
}
|
||||
let mut routes = Vec::new();
|
||||
match req.action {
|
||||
STOP => {
|
||||
if share.owner != sender {
|
||||
bail!("only publisher may stop a share");
|
||||
}
|
||||
for target in members {
|
||||
routes.push(Route {
|
||||
target: target.clone(),
|
||||
event: share.event(STOP, &req.share_id, sender),
|
||||
});
|
||||
}
|
||||
shares.remove(&req.share_id);
|
||||
}
|
||||
WATCH => {
|
||||
if share.owner == sender || !members.contains(&share.owner) {
|
||||
bail!("publisher unavailable or self subscription");
|
||||
}
|
||||
if !share.viewers.contains(sender) && share.viewers.len() >= MAX_VIEWERS {
|
||||
bail!("share viewer limit reached");
|
||||
}
|
||||
if share.viewers.insert(sender.into()) {
|
||||
routes.push(Route {
|
||||
target: share.owner.clone(),
|
||||
event: share.event(WATCH, &req.share_id, sender),
|
||||
});
|
||||
}
|
||||
routes.push(Route {
|
||||
target: sender.into(),
|
||||
event: share.event(WATCH, &req.share_id, &share.owner),
|
||||
});
|
||||
}
|
||||
UNWATCH => {
|
||||
if !share.viewers.remove(sender) {
|
||||
bail!("subscription not active");
|
||||
}
|
||||
routes.push(Route {
|
||||
target: share.owner.clone(),
|
||||
event: share.event(UNWATCH, &req.share_id, sender),
|
||||
});
|
||||
routes.push(Route {
|
||||
target: sender.into(),
|
||||
event: share.event(UNWATCH, &req.share_id, &share.owner),
|
||||
});
|
||||
}
|
||||
OFFER | ANSWER | ICE => {
|
||||
let target = req.target_session_id.as_str();
|
||||
if target == sender || !members.contains(target) {
|
||||
bail!("target is not a voice peer");
|
||||
}
|
||||
let publisher_to_viewer = share.owner == sender && share.viewers.contains(target);
|
||||
let viewer_to_publisher = share.owner == target && share.viewers.contains(sender);
|
||||
if !(publisher_to_viewer || viewer_to_publisher)
|
||||
|| req.action == OFFER && !publisher_to_viewer
|
||||
|| req.action == ANSWER && !viewer_to_publisher
|
||||
{
|
||||
bail!("signal is not authorized for this subscription");
|
||||
}
|
||||
let mut event = share.event(req.action, &req.share_id, sender);
|
||||
event.target_session_id = target.into();
|
||||
event.body = req.body.clone();
|
||||
event.mline_index = req.mline_index;
|
||||
routes.push(Route {
|
||||
target: target.into(),
|
||||
event,
|
||||
});
|
||||
}
|
||||
_ => bail!("unknown media action"),
|
||||
}
|
||||
Ok(routes)
|
||||
}
|
||||
|
||||
/// Revoke all publishing/viewing rights for a leaving or disconnected session.
|
||||
pub async fn revoke(&self, state: &State, leaving: &str) {
|
||||
self.rates.lock().await.remove(leaving);
|
||||
let channels = state.channels.read().await;
|
||||
let mut shares = self.shares.lock().await;
|
||||
let mut routes = Vec::new();
|
||||
shares.retain(|id, share| {
|
||||
if share.owner == leaving {
|
||||
let mut targets = share.viewers.clone();
|
||||
targets.insert(leaving.to_owned());
|
||||
if let Some(channel) = channels.get(&share.channel) {
|
||||
targets.extend(channel.members.iter().cloned());
|
||||
}
|
||||
for target in targets {
|
||||
routes.push(Route {
|
||||
target,
|
||||
event: share.event(STOP, id, leaving),
|
||||
});
|
||||
}
|
||||
false
|
||||
} else {
|
||||
if share.viewers.remove(leaving) {
|
||||
routes.push(Route {
|
||||
target: share.owner.clone(),
|
||||
event: share.event(UNWATCH, id, leaving),
|
||||
});
|
||||
routes.push(Route {
|
||||
target: leaving.to_owned(),
|
||||
event: share.event(UNWATCH, id, &share.owner),
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
});
|
||||
drop(shares);
|
||||
send(state, routes);
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(req: &MediaControl) -> Result<()> {
|
||||
if req.channel_id.is_empty() || req.channel_id.len() > 128 || req.target_session_id.len() > 64 {
|
||||
bail!("invalid media scope");
|
||||
}
|
||||
if !(req.action == WATCH && req.share_id.is_empty())
|
||||
&& uuid::Uuid::parse_str(&req.share_id).is_err()
|
||||
{
|
||||
bail!("share ID must be a UUID");
|
||||
}
|
||||
match req.action {
|
||||
OFFER | ANSWER if req.body.is_empty() || req.body.len() > 65_536 => {
|
||||
bail!("SDP size out of bounds")
|
||||
}
|
||||
ICE if req.body.len() > 2048 || req.mline_index > 2 => bail!("ICE candidate out of bounds"),
|
||||
START | STOP | WATCH | UNWATCH
|
||||
if !req.body.is_empty() || !req.target_session_id.is_empty() =>
|
||||
{
|
||||
bail!("unexpected media control data")
|
||||
}
|
||||
START..=ICE => {}
|
||||
_ => bail!("unknown media action"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send(state: &State, routes: Vec<Route>) {
|
||||
for route in routes {
|
||||
let _ = state.broadcast.send(BroadcastMsg {
|
||||
channel_id: None,
|
||||
exclude_session: None,
|
||||
target_session_id: Some(route.target),
|
||||
data: encode_packet(PacketId::MediaEvent, 0, &to_payload(&route.event)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Invoked only by authenticated LNEx dispatch, never by an HTTP endpoint.
|
||||
pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
ctx: &mut Ctx<'_, S>,
|
||||
sender: &str,
|
||||
payload: &[u8],
|
||||
) -> Result<()> {
|
||||
let outcome = authorize_and_apply(ctx.state, sender, payload).await;
|
||||
match outcome {
|
||||
Ok(routes) => {
|
||||
send(ctx.state, routes);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
io::send_encrypted(
|
||||
ctx.stream,
|
||||
PacketId::Error,
|
||||
ctx.seq,
|
||||
&to_payload(&proto::Error {
|
||||
code: proto::ErrorCode::PermissionDenied as u32,
|
||||
message: format!("media: {error}"),
|
||||
}),
|
||||
ctx.crypto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn authorize_and_apply(state: &State, sender: &str, payload: &[u8]) -> Result<Vec<Route>> {
|
||||
if payload.len() > 67_000 {
|
||||
bail!("media control too large");
|
||||
}
|
||||
let req = MediaControl::decode(payload)?;
|
||||
validate(&req)?;
|
||||
{
|
||||
let mut rates = state.media.rates.lock().await;
|
||||
let budget = rates.entry(sender.into()).or_insert(SignalBudget {
|
||||
updated: std::time::Instant::now(),
|
||||
tokens: 64.0,
|
||||
});
|
||||
if !budget.consume() {
|
||||
bail!("media control rate exceeded");
|
||||
}
|
||||
}
|
||||
// Shared authorization lease covers fresh guild/channel checks and mutation.
|
||||
// It is dropped on return before the caller performs any socket I/O.
|
||||
let _access = state.access.read().await;
|
||||
let session = session::get(&state.sessions, sender)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("session expired"))?;
|
||||
let channel = channels::get_channel(&state.channels, &req.channel_id)
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("voice channel unavailable"))?;
|
||||
if channel.kind != ChannelKind::Voice || !channel.members.contains(sender) {
|
||||
bail!("voice membership required");
|
||||
}
|
||||
if let Some(guild) = channel.guild_id.as_deref() {
|
||||
if !state
|
||||
.storage
|
||||
.list_user_guilds(&session.user_id)
|
||||
.await?
|
||||
.iter()
|
||||
.any(|item| item.id == guild)
|
||||
{
|
||||
bail!("guild membership required");
|
||||
}
|
||||
if req.action == START {
|
||||
let owner = state
|
||||
.storage
|
||||
.get_guild(guild)
|
||||
.await?
|
||||
.is_some_and(|g| g.owner_id == session.user_id);
|
||||
let perms = state
|
||||
.storage
|
||||
.get_user_role_perms(guild, &session.user_id)
|
||||
.await?;
|
||||
if !owner && !Permissions::from_role_perms(&perms).has(Permissions::VOICE_SPEAK) {
|
||||
bail!("VOICE_SPEAK permission required");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Hold current channel membership through the runtime mutation; leave/revoke
|
||||
// uses the same ordering (membership first, then media) to prevent resurrection.
|
||||
let channels = state.channels.read().await;
|
||||
let channel = channels
|
||||
.get(&req.channel_id)
|
||||
.ok_or_else(|| anyhow::anyhow!("voice channel unavailable"))?;
|
||||
if !channel.members.contains(sender) {
|
||||
bail!("voice membership revoked");
|
||||
}
|
||||
state
|
||||
.media
|
||||
.apply(sender, &session.user_id, &req, &channel.members)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Delivery-time membership check prevents queued SDP/ICE escaping after a leave.
|
||||
pub async fn may_deliver(state: &State, recipient: &str, payload: &[u8]) -> bool {
|
||||
let Ok(event) = MediaEvent::decode(payload) else {
|
||||
return false;
|
||||
};
|
||||
if event.action == STOP || event.action == UNWATCH {
|
||||
return true;
|
||||
}
|
||||
let channels = state.channels.read().await;
|
||||
let Some(channel) = channels.get(&event.channel_id) else {
|
||||
return false;
|
||||
};
|
||||
if channel.kind != ChannelKind::Voice
|
||||
|| !channel.members.contains(recipient)
|
||||
|| !channel.members.contains(&event.sender_session_id)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let shares = state.media.shares.lock().await;
|
||||
let Some(share) = shares.get(&event.share_id) else {
|
||||
return false;
|
||||
};
|
||||
if share.channel != event.channel_id || !channel.members.contains(&share.owner) {
|
||||
return false;
|
||||
}
|
||||
match event.action {
|
||||
START => true,
|
||||
WATCH | OFFER | ANSWER | ICE => {
|
||||
(share.owner == recipient && share.viewers.contains(&event.sender_session_id))
|
||||
|| (share.owner == event.sender_session_id && share.viewers.contains(recipient))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn req(action: u32, id: &str) -> MediaControl {
|
||||
MediaControl {
|
||||
action,
|
||||
channel_id: "voice".into(),
|
||||
share_id: id.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn only_authorized_subscription_can_exchange_signals() {
|
||||
let runtime = Runtime::default();
|
||||
let members = ["publisher", "viewer", "other"]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
runtime
|
||||
.apply("publisher", "owner-user", &req(START, &id), &members)
|
||||
.await
|
||||
.expect("start");
|
||||
let mut offer = req(OFFER, &id);
|
||||
offer.target_session_id = "viewer".into();
|
||||
offer.body = "v=0\r\n".into();
|
||||
assert!(
|
||||
runtime
|
||||
.apply("publisher", "owner-user", &offer, &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &req(WATCH, &id), &members)
|
||||
.await
|
||||
.expect("watch");
|
||||
let routes = runtime
|
||||
.apply("publisher", "owner-user", &offer, &members)
|
||||
.await
|
||||
.expect("authorized offer");
|
||||
assert_eq!(routes[0].target, "viewer");
|
||||
assert_eq!(routes[0].event.sender_session_id, "publisher");
|
||||
assert_eq!(routes[0].event.publisher_user_id, "owner-user");
|
||||
assert!(
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &offer, &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
offer.action = ICE;
|
||||
offer.target_session_id = "publisher".into();
|
||||
assert!(
|
||||
runtime
|
||||
.apply("other", "other-user", &offer, &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &req(UNWATCH, &id), &members)
|
||||
.await
|
||||
.expect("unwatch");
|
||||
assert!(
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &offer, &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &req(STOP, &id), &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
runtime
|
||||
.apply("publisher", "owner-user", &req(STOP, &id), &members)
|
||||
.await
|
||||
.expect("stop");
|
||||
assert!(
|
||||
runtime
|
||||
.apply("viewer", "viewer-user", &req(WATCH, &id), &members)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn signalling_budget_bounds_bursts_and_refills() {
|
||||
let mut budget = SignalBudget {
|
||||
updated: std::time::Instant::now(),
|
||||
tokens: 64.0,
|
||||
};
|
||||
for _ in 0..64 {
|
||||
assert!(budget.consume());
|
||||
}
|
||||
assert!(!budget.consume());
|
||||
budget.updated = std::time::Instant::now() - std::time::Duration::from_secs(1);
|
||||
assert!(budget.consume());
|
||||
assert!(budget.tokens < 20.1);
|
||||
}
|
||||
#[test]
|
||||
fn signalling_limits_reject_unbounded_data() {
|
||||
let mut signal = req(OFFER, &uuid::Uuid::new_v4().to_string());
|
||||
signal.body = "x".repeat(65_537);
|
||||
assert!(validate(&signal).is_err());
|
||||
signal.action = ICE;
|
||||
signal.body = "x".repeat(2049);
|
||||
assert!(validate(&signal).is_err());
|
||||
signal.body.clear();
|
||||
signal.mline_index = 3;
|
||||
assert!(validate(&signal).is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@ use crate::{
|
|||
proto::{self, AuthPayload, HelloPayload, PacketId, SessionCrypto, SessionPayload, to_payload},
|
||||
};
|
||||
|
||||
const LNEX_VERSION: &str = "v2";
|
||||
const LNEX_VERSION: &str = "v1";
|
||||
|
||||
/// Run HELLO → AUTH → SESSION with X25519 ECDH key exchange.
|
||||
///
|
||||
|
|
@ -29,27 +29,20 @@ pub async fn run(
|
|||
// HELLO — include server's ephemeral public key + privacy mode
|
||||
let challenge = auth::new_challenge();
|
||||
let private_mode = state.config.is_private();
|
||||
let mut hello = HelloPayload {
|
||||
let hello = HelloPayload {
|
||||
lnex_version: LNEX_VERSION.into(),
|
||||
server_pubkey: hex::decode(state.server_identity.pubkey_hex())?,
|
||||
challenge_nonce: challenge.to_vec(),
|
||||
node_name: state.config.node.name.clone(),
|
||||
server_eph_pubkey: eph_pk_raw.to_vec(),
|
||||
private_mode,
|
||||
server_signature: Vec::new(),
|
||||
};
|
||||
let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec();
|
||||
hello_transcript.extend_from_slice(&hello.encode_to_vec());
|
||||
hello.server_signature = state.server_identity.sign(&hello_transcript);
|
||||
io::send_packet(stream, PacketId::Hello, seq, &to_payload(&hello)).await?;
|
||||
debug!("{addr} ← HELLO (eph key included)");
|
||||
|
||||
// AUTH — receive client's ephemeral public key
|
||||
let (hdr, payload) = io::read_packet(stream).await?;
|
||||
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth)
|
||||
|| hdr.flags != 0
|
||||
|| hdr.sequence != 0
|
||||
{
|
||||
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth) {
|
||||
io::send_error(
|
||||
stream,
|
||||
seq,
|
||||
|
|
@ -61,11 +54,7 @@ pub async fn run(
|
|||
}
|
||||
|
||||
let msg = AuthPayload::decode(payload.as_slice())?;
|
||||
anyhow::ensure!(
|
||||
!msg.nickname.trim().is_empty() && msg.nickname.chars().count() <= 64,
|
||||
"invalid nickname"
|
||||
);
|
||||
debug!("{addr} → AUTH");
|
||||
debug!("{addr} → AUTH nick={}", msg.nickname);
|
||||
|
||||
if msg.lnex_version != LNEX_VERSION {
|
||||
io::send_error(
|
||||
|
|
@ -81,14 +70,7 @@ pub async fn run(
|
|||
let pubkey: [u8; 32] = msg.client_pubkey.as_slice().try_into()?;
|
||||
let sig: [u8; 64] = msg.signature.as_slice().try_into()?;
|
||||
|
||||
let mut auth_without_signature = msg.clone();
|
||||
auth_without_signature.signature.clear();
|
||||
let hello_bytes = hello.encode_to_vec();
|
||||
let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec();
|
||||
auth_transcript.extend_from_slice(&(hello_bytes.len() as u32).to_be_bytes());
|
||||
auth_transcript.extend_from_slice(&hello_bytes);
|
||||
auth_transcript.extend_from_slice(&auth_without_signature.encode_to_vec());
|
||||
if let Err(e) = auth::verify_auth(&auth_transcript, &pubkey, &sig) {
|
||||
if let Err(e) = auth::verify_auth(&challenge, &pubkey, &sig) {
|
||||
warn!("{addr} auth failed: {e}");
|
||||
state.metrics.inc(&state.metrics.auth_failures);
|
||||
io::send_error(
|
||||
|
|
@ -120,7 +102,6 @@ pub async fn run(
|
|||
let client_eph_raw: [u8; 32] = msg.client_eph_pubkey.as_slice().try_into()?;
|
||||
let client_eph_pk = x25519_dalek::PublicKey::from(client_eph_raw);
|
||||
let shared_secret = SessionCrypto::ecdh(eph_sk, &client_eph_pk);
|
||||
anyhow::ensure!(shared_secret.was_contributory(), "invalid ephemeral key");
|
||||
|
||||
// SESSION
|
||||
let sess = session::create(
|
||||
|
|
|
|||
|
|
@ -60,19 +60,14 @@ pub async fn send_encrypted(
|
|||
payload: &[u8],
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<()> {
|
||||
anyhow::ensure!(*seq < u32::MAX, "session sequence exhausted");
|
||||
anyhow::ensure!(
|
||||
payload.len() <= MAX_PAYLOAD as usize - 16,
|
||||
"payload too large"
|
||||
);
|
||||
let encrypted = crypto.encrypt_s2c(*seq as u64, payload);
|
||||
let flags_val = flags::ENCRYPTED;
|
||||
let mut hdr_buf = [0u8; PacketHeader::SIZE];
|
||||
hdr_buf[0..2].copy_from_slice(&(id as u16).to_be_bytes());
|
||||
hdr_buf[2..4].copy_from_slice(&flags_val.to_be_bytes());
|
||||
hdr_buf[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
hdr_buf[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
|
||||
let encrypted = crypto.encrypt_s2c_frame(*seq as u64, payload, &hdr_buf);
|
||||
*seq += 1;
|
||||
hdr_buf[8..12].copy_from_slice(&(encrypted.len() as u32).to_be_bytes());
|
||||
*seq = seq.wrapping_add(1);
|
||||
|
||||
let mut out = Vec::with_capacity(PacketHeader::SIZE + encrypted.len());
|
||||
out.extend_from_slice(&hdr_buf);
|
||||
|
|
@ -101,7 +96,7 @@ pub async fn read_encrypted(
|
|||
if !encrypted.is_empty() {
|
||||
stream.read_exact(&mut encrypted).await?;
|
||||
}
|
||||
let payload = crypto.decrypt_c2s_frame(hdr.sequence as u64, &encrypted, &buf)?;
|
||||
let payload = crypto.decrypt_c2s(hdr.sequence as u64, &encrypted)?;
|
||||
Ok((hdr, payload))
|
||||
}
|
||||
|
||||
|
|
@ -127,115 +122,3 @@ pub async fn deliver_encrypted(
|
|||
let payload = &raw_data[PacketHeader::SIZE..];
|
||||
send_encrypted(stream, pid, seq, payload, crypto).await
|
||||
}
|
||||
|
||||
/// Incremental framing state survives cancellation by broadcast delivery.
|
||||
pub struct EncryptedReader {
|
||||
bytes: Vec<u8>,
|
||||
expected_sequence: u32,
|
||||
}
|
||||
impl Default for EncryptedReader {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
expected_sequence: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl EncryptedReader {
|
||||
pub async fn read(
|
||||
&mut self,
|
||||
stream: &mut (impl AsyncRead + Unpin),
|
||||
crypto: &SessionCrypto,
|
||||
) -> Result<(PacketHeader, Vec<u8>)> {
|
||||
loop {
|
||||
let needed = if self.bytes.len() < PacketHeader::SIZE {
|
||||
PacketHeader::SIZE
|
||||
} else {
|
||||
let header: &[u8; PacketHeader::SIZE] =
|
||||
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
|
||||
let hdr = PacketHeader::from_bytes(header);
|
||||
anyhow::ensure!(
|
||||
hdr.flags == flags::ENCRYPTED,
|
||||
"unsupported encrypted frame flags"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
hdr.payload_length >= 16 && hdr.payload_length <= MAX_PAYLOAD,
|
||||
"invalid encrypted payload size"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
hdr.sequence == self.expected_sequence && hdr.sequence < u32::MAX,
|
||||
"invalid packet sequence"
|
||||
);
|
||||
PacketHeader::SIZE + hdr.payload_length as usize
|
||||
};
|
||||
if self.bytes.len() == needed && needed > PacketHeader::SIZE {
|
||||
let header: &[u8; PacketHeader::SIZE] =
|
||||
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
|
||||
let hdr = PacketHeader::from_bytes(header);
|
||||
let payload = crypto.decrypt_c2s_frame(
|
||||
hdr.sequence as u64,
|
||||
&self.bytes[PacketHeader::SIZE..],
|
||||
header,
|
||||
)?;
|
||||
self.bytes.clear();
|
||||
self.expected_sequence += 1;
|
||||
return Ok((hdr, payload));
|
||||
}
|
||||
let mut chunk = [0u8; 8192];
|
||||
let limit = (needed - self.bytes.len()).min(chunk.len());
|
||||
let count = stream.read(&mut chunk[..limit]).await?;
|
||||
anyhow::ensure!(count > 0, "connection closed during frame");
|
||||
self.bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reader_tests {
|
||||
use super::*;
|
||||
fn frame(crypto: &SessionCrypto, seq: u32) -> Vec<u8> {
|
||||
let mut header = [0u8; 12];
|
||||
header[..2].copy_from_slice(&(PacketId::Ping as u16).to_be_bytes());
|
||||
header[2..4].copy_from_slice(&flags::ENCRYPTED.to_be_bytes());
|
||||
header[4..8].copy_from_slice(&seq.to_be_bytes());
|
||||
header[8..].copy_from_slice(&20u32.to_be_bytes());
|
||||
let mut bytes = header.to_vec();
|
||||
bytes.extend_from_slice(&crypto.encrypt_c2s_frame(seq as u64, b"ping", &header));
|
||||
bytes
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn cancelled_partial_read_preserves_framing_and_rejects_replay() {
|
||||
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
|
||||
let bytes = frame(&crypto, 1);
|
||||
let (mut server, mut peer) = tokio::io::duplex(128);
|
||||
let mut reader = EncryptedReader::default();
|
||||
peer.write_all(&bytes[..5]).await.unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_millis(2),
|
||||
reader.read(&mut server, &crypto)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
peer.write_all(&bytes[5..]).await.unwrap();
|
||||
let (_, body) = reader.read(&mut server, &crypto).await.unwrap();
|
||||
assert_eq!(body, b"ping");
|
||||
peer.write_all(&bytes).await.unwrap();
|
||||
assert!(reader.read(&mut server, &crypto).await.is_err());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn modifying_authenticated_packet_type_is_rejected() {
|
||||
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
|
||||
let mut bytes = frame(&crypto, 1);
|
||||
bytes[1] ^= 1;
|
||||
let (mut server, mut peer) = tokio::io::duplex(128);
|
||||
peer.write_all(&bytes).await.unwrap();
|
||||
assert!(
|
||||
EncryptedReader::default()
|
||||
.read(&mut server, &crypto)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@ pub type VoiceMemberTx = tokio::sync::broadcast::Sender<String>;
|
|||
|
||||
#[derive(Clone)]
|
||||
pub struct State {
|
||||
pub access: Arc<tokio::sync::RwLock<()>>,
|
||||
pub media: Arc<crate::media::Runtime>,
|
||||
pub webhooks: Arc<crate::webhooks::Runtime>,
|
||||
pub sessions: SessionStore,
|
||||
pub channels: ChannelStore,
|
||||
|
|
@ -59,8 +57,6 @@ impl State {
|
|||
let burst = config.gateway.message_rate_burst.unwrap_or(10);
|
||||
let rate_limiter = Arc::new(RateLimiter::new(rate_per_sec, burst));
|
||||
Self {
|
||||
access: Arc::default(),
|
||||
media: Arc::default(),
|
||||
webhooks: Arc::default(),
|
||||
sessions,
|
||||
channels,
|
||||
|
|
|
|||
|
|
@ -15,16 +15,6 @@ pub(super) fn encrypt_with_key(
|
|||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
plaintext: &[u8],
|
||||
) -> Vec<u8> {
|
||||
encrypt_with_aad(key, cid, seq, plaintext, &[])
|
||||
}
|
||||
|
||||
pub(super) 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);
|
||||
|
|
@ -34,7 +24,7 @@ pub(super) fn encrypt_with_aad(
|
|||
&nonce,
|
||||
Payload {
|
||||
msg: plaintext,
|
||||
aad,
|
||||
aad: &[],
|
||||
},
|
||||
)
|
||||
.expect("ChaCha20-Poly1305 encryption is infallible")
|
||||
|
|
@ -45,16 +35,6 @@ pub(super) fn decrypt_with_key(
|
|||
cid: &[u8; 8],
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
decrypt_with_aad(key, cid, seq, ciphertext, &[])
|
||||
}
|
||||
|
||||
pub(super) 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);
|
||||
|
|
@ -64,7 +44,7 @@ pub(super) fn decrypt_with_aad(
|
|||
&nonce,
|
||||
Payload {
|
||||
msg: ciphertext,
|
||||
aad,
|
||||
aad: &[],
|
||||
},
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("decryption failed: {e:?}"))
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ pub struct SessionCrypto {
|
|||
|
||||
impl SessionCrypto {
|
||||
pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self {
|
||||
let salt = b"VNOX-LNEx-KDF-v2";
|
||||
let salt = b"VNOX-LNEx-KDF-v1";
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), shared_secret);
|
||||
|
||||
let mut keys = [0u8; 64];
|
||||
|
|
@ -42,22 +42,6 @@ impl SessionCrypto {
|
|||
cipher::decrypt_with_key(&self.c2s_key, &self.cid, seq, ciphertext)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn encrypt_c2s_frame(&self, seq: u64, plaintext: &[u8], header: &[u8]) -> Vec<u8> {
|
||||
cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, header)
|
||||
}
|
||||
pub fn encrypt_s2c_frame(&self, seq: u64, plaintext: &[u8], header: &[u8]) -> Vec<u8> {
|
||||
cipher::encrypt_with_aad(&self.s2c_key, &self.cid, seq, plaintext, header)
|
||||
}
|
||||
pub fn decrypt_c2s_frame(
|
||||
&self,
|
||||
seq: u64,
|
||||
ciphertext: &[u8],
|
||||
header: &[u8],
|
||||
) -> anyhow::Result<Vec<u8>> {
|
||||
cipher::decrypt_with_aad(&self.c2s_key, &self.cid, seq, ciphertext, header)
|
||||
}
|
||||
|
||||
pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) {
|
||||
let mut rng = rand::rng();
|
||||
let sk = EphemeralSecret::random_from_rng(&mut rng);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
#[repr(u16)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PacketId {
|
||||
WebhookErrorResult = 0x0206,
|
||||
MediaControl = 0x0180,
|
||||
MediaEvent = 0x0181,
|
||||
WebhookCreate = 0x0200,
|
||||
WebhookList = 0x0201,
|
||||
WebhookRotate = 0x0202,
|
||||
|
|
@ -15,7 +12,6 @@ pub enum PacketId {
|
|||
Session = 0x0003,
|
||||
Ping = 0x0004,
|
||||
Pong = 0x0005,
|
||||
VoiceSession = 0x0012,
|
||||
VoicePacket = 0x0010,
|
||||
VoiceState = 0x0011,
|
||||
ChatMessage = 0x0020,
|
||||
|
|
@ -69,7 +65,6 @@ pub enum PacketId {
|
|||
PresenceUpdate = 0x0140,
|
||||
PresenceSync = 0x0141,
|
||||
PresenceEvent = 0x0142,
|
||||
FriendEvent = 0x0158,
|
||||
FriendRequest = 0x0150,
|
||||
FriendAccept = 0x0151,
|
||||
FriendDecline = 0x0152,
|
||||
|
|
@ -85,9 +80,6 @@ pub enum PacketId {
|
|||
impl PacketId {
|
||||
pub fn from_u16(v: u16) -> Option<Self> {
|
||||
match v {
|
||||
0x0206 => Some(Self::WebhookErrorResult),
|
||||
0x0180 => Some(Self::MediaControl),
|
||||
0x0181 => Some(Self::MediaEvent),
|
||||
0x0200 => Some(Self::WebhookCreate),
|
||||
0x0201 => Some(Self::WebhookList),
|
||||
0x0202 => Some(Self::WebhookRotate),
|
||||
|
|
@ -99,7 +91,6 @@ impl PacketId {
|
|||
0x0003 => Some(Self::Session),
|
||||
0x0004 => Some(Self::Ping),
|
||||
0x0005 => Some(Self::Pong),
|
||||
0x0012 => Some(Self::VoiceSession),
|
||||
0x0010 => Some(Self::VoicePacket),
|
||||
0x0011 => Some(Self::VoiceState),
|
||||
0x0020 => Some(Self::ChatMessage),
|
||||
|
|
@ -153,7 +144,6 @@ impl PacketId {
|
|||
0x0140 => Some(Self::PresenceUpdate),
|
||||
0x0141 => Some(Self::PresenceSync),
|
||||
0x0142 => Some(Self::PresenceEvent),
|
||||
0x0158 => Some(Self::FriendEvent),
|
||||
0x0150 => Some(Self::FriendRequest),
|
||||
0x0151 => Some(Self::FriendAccept),
|
||||
0x0152 => Some(Self::FriendDecline),
|
||||
|
|
|
|||
|
|
@ -48,33 +48,13 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
let Some(session) = crate::domain::session::get(&ctx.state.sessions, session_id).await else {
|
||||
return Ok(());
|
||||
};
|
||||
if !ctx.state.rate_limiter.try_consume(session_id) {
|
||||
return error(ctx, "rate limited").await;
|
||||
}
|
||||
if payload.len() > 8192 {
|
||||
return error(
|
||||
ctx,
|
||||
"",
|
||||
ErrorCode::InvalidPacket,
|
||||
"webhook management payload too large",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "webhook management payload too large").await;
|
||||
}
|
||||
let req = WebhookRequest::decode(payload)?;
|
||||
let request_id = req.request_id.clone();
|
||||
if request_id.len() > 64
|
||||
|| !request_id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
{
|
||||
return error(
|
||||
ctx,
|
||||
"",
|
||||
ErrorCode::InvalidPacket,
|
||||
"invalid request identifier",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if !ctx.state.rate_limiter.try_consume(session_id) {
|
||||
return error(ctx, &request_id, ErrorCode::RateLimited, "rate limited").await;
|
||||
}
|
||||
let existing = if pid == PacketId::WebhookRotate || pid == PacketId::WebhookRevoke {
|
||||
ctx.state.storage.hook(&req.id).await?
|
||||
} else {
|
||||
|
|
@ -85,13 +65,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
.map(|h| h.channel_id.as_str())
|
||||
.unwrap_or(&req.channel_id);
|
||||
let Some(guild) = authorize(ctx.state, &session.user_id, channel).await? else {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::PermissionDenied,
|
||||
"permission denied",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "permission denied").await;
|
||||
};
|
||||
if pid == PacketId::WebhookList {
|
||||
let hooks = ctx
|
||||
|
|
@ -106,7 +80,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
ctx.stream,
|
||||
PacketId::WebhookListResult,
|
||||
ctx.seq,
|
||||
&to_payload(&WebhookListResult { hooks, request_id }),
|
||||
&to_payload(&WebhookListResult { hooks }),
|
||||
ctx.crypto,
|
||||
)
|
||||
.await;
|
||||
|
|
@ -117,25 +91,17 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
|| req.name.chars().count() > 64
|
||||
|| req.name.chars().any(char::is_control)
|
||||
{
|
||||
return error(ctx, &request_id, ErrorCode::InvalidPacket, "invalid name").await;
|
||||
return error(ctx, "invalid name").await;
|
||||
}
|
||||
if !matches!(
|
||||
(req.direction.as_str(), req.provider.as_str()),
|
||||
("incoming", "generic" | "github") | ("outgoing", "generic")
|
||||
) {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::InvalidPacket,
|
||||
"unsupported webhook type",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "unsupported webhook type").await;
|
||||
}
|
||||
if req.direction == "outgoing" && policy::endpoint(&req.endpoint).is_err() {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::InvalidPacket,
|
||||
"HTTPS public endpoint required; no credentials/query/fragment",
|
||||
)
|
||||
.await;
|
||||
|
|
@ -144,13 +110,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
secret = secrets::new_secret();
|
||||
let sealed = if req.direction == "outgoing" || req.provider == "github" {
|
||||
let Some(key) = ctx.state.webhooks.key() else {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::Internal,
|
||||
"webhook master key not configured",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "webhook master key not configured").await;
|
||||
};
|
||||
secrets::seal(key, &id, &secret)?
|
||||
} else {
|
||||
|
|
@ -175,24 +135,11 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
revoked_at: None,
|
||||
suspended_reason: None,
|
||||
};
|
||||
if let Err(problem) = ctx.state.storage.insert_hook(&h).await {
|
||||
let (code, message) = if problem.to_string() == "channel webhook limit reached" {
|
||||
(ErrorCode::RateLimited, "channel webhook limit reached")
|
||||
} else {
|
||||
(ErrorCode::Internal, "webhook creation failed")
|
||||
};
|
||||
return error(ctx, &request_id, code, message).await;
|
||||
}
|
||||
ctx.state.storage.insert_hook(&h).await?;
|
||||
h
|
||||
} else {
|
||||
let Some(mut h) = existing.filter(|h| h.revoked_at.is_none()) else {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::InvalidPacket,
|
||||
"webhook not found",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "webhook not found").await;
|
||||
};
|
||||
if pid == PacketId::WebhookRevoke {
|
||||
ctx.state.storage.revoke_hook(&h.id).await?;
|
||||
|
|
@ -201,13 +148,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
secret = secrets::new_secret();
|
||||
let sealed = if h.direction == "outgoing" || h.provider == "github" {
|
||||
let Some(key) = ctx.state.webhooks.key() else {
|
||||
return error(
|
||||
ctx,
|
||||
&request_id,
|
||||
ErrorCode::Internal,
|
||||
"webhook master key not configured",
|
||||
)
|
||||
.await;
|
||||
return error(ctx, "webhook master key not configured").await;
|
||||
};
|
||||
secrets::seal(key, &h.id, &secret)?
|
||||
} else {
|
||||
|
|
@ -228,25 +169,18 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
|
|||
&to_payload(&WebhookResult {
|
||||
hook: Some(info(&hook)),
|
||||
secret,
|
||||
request_id,
|
||||
}),
|
||||
ctx.crypto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
async fn error<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
ctx: &mut Ctx<'_, S>,
|
||||
request_id: &str,
|
||||
code: ErrorCode,
|
||||
msg: &str,
|
||||
) -> Result<()> {
|
||||
async fn error<S: AsyncRead + AsyncWrite + Unpin>(ctx: &mut Ctx<'_, S>, msg: &str) -> Result<()> {
|
||||
io::send_encrypted(
|
||||
ctx.stream,
|
||||
PacketId::WebhookErrorResult,
|
||||
PacketId::Error,
|
||||
ctx.seq,
|
||||
&to_payload(&WebhookErrorResult {
|
||||
request_id: request_id.into(),
|
||||
code: code as u32,
|
||||
&to_payload(&ErrorPayload {
|
||||
code: ErrorCode::PermissionDenied as u32,
|
||||
message: msg.into(),
|
||||
}),
|
||||
ctx.crypto,
|
||||
|
|
|
|||
|
|
@ -336,10 +336,9 @@ async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
|
|||
direction: "incoming".into(),
|
||||
provider: "generic".into(),
|
||||
endpoint: String::new(),
|
||||
request_id: "request-123".into(),
|
||||
};
|
||||
for (user, expected) in [
|
||||
("stranger", PacketId::WebhookErrorResult),
|
||||
("stranger", PacketId::Error),
|
||||
("owner", PacketId::WebhookResult),
|
||||
] {
|
||||
let session = session::create(&s.sessions, user.into(), user.into()).await;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ message Hello {
|
|||
string node_name = 4;
|
||||
bytes server_eph_pubkey = 5;
|
||||
bool private_mode = 6;
|
||||
bytes server_signature = 7;
|
||||
}
|
||||
|
||||
message Auth {
|
||||
|
|
@ -403,7 +402,6 @@ message WebhookRequest {
|
|||
string direction = 4; // incoming | outgoing
|
||||
string provider = 5; // generic | github (incoming only)
|
||||
string endpoint = 6; // outgoing HTTPS URL
|
||||
string request_id = 7;
|
||||
}
|
||||
message WebhookInfo {
|
||||
string id = 1;
|
||||
|
|
@ -416,46 +414,5 @@ message WebhookInfo {
|
|||
bool revoked = 8;
|
||||
string suspended_reason = 9;
|
||||
}
|
||||
message WebhookResult { WebhookInfo hook = 1; string secret = 2; string request_id = 3; }
|
||||
message WebhookListResult { repeated WebhookInfo hooks = 1; string request_id = 2; }
|
||||
message WebhookErrorResult { string request_id = 1; uint32 code = 2; string message = 3; }
|
||||
|
||||
// Authenticated signalling only; media uses DTLS/SRTP peer connections.
|
||||
message MediaControl {
|
||||
uint32 action = 1; // START1 STOP2 WATCH3 UNWATCH4 OFFER5 ANSWER6 ICE7
|
||||
string channel_id = 2;
|
||||
string share_id = 3;
|
||||
string target_session_id = 4;
|
||||
string body = 5;
|
||||
uint32 mline_index = 6;
|
||||
bool application_audio = 7;
|
||||
bool microphone = 8;
|
||||
}
|
||||
message MediaEvent {
|
||||
uint32 action = 1;
|
||||
string channel_id = 2;
|
||||
string share_id = 3;
|
||||
string target_session_id = 4;
|
||||
string body = 5;
|
||||
uint32 mline_index = 6;
|
||||
bool application_audio = 7;
|
||||
bool microphone = 8;
|
||||
string sender_session_id = 9;
|
||||
string publisher_user_id = 10;
|
||||
}
|
||||
|
||||
// Fresh credentials delivered only over the authenticated encrypted control session.
|
||||
message VoiceSession {
|
||||
bytes route_id = 1;
|
||||
bytes c2s_key = 2;
|
||||
bytes s2c_key = 3;
|
||||
string channel_id = 4;
|
||||
}
|
||||
message VoiceFrame {
|
||||
uint32 voice_seq = 1;
|
||||
uint32 timestamp = 2;
|
||||
string channel_id = 3;
|
||||
string sender_session_id = 4;
|
||||
bytes opus = 5;
|
||||
string sender_user_id = 6;
|
||||
}
|
||||
message WebhookResult { WebhookInfo hook = 1; string secret = 2; }
|
||||
message WebhookListResult { repeated WebhookInfo hooks = 1; }
|
||||
|
|
|
|||
|
|
@ -24,10 +24,3 @@ anyhow.workspace = true
|
|||
toml.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
chacha20poly1305.workspace = true
|
||||
hex.workspace = true
|
||||
prost.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
prost-build.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,4 +0,0 @@
|
|||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../protocol/lnex.proto");
|
||||
prost_build::compile_protos(&["../protocol/lnex.proto"], &["../protocol/"]).unwrap();
|
||||
}
|
||||
|
|
@ -1,7 +1,3 @@
|
|||
pub mod secure;
|
||||
pub mod wire {
|
||||
include!(concat!(env!("OUT_DIR"), "/lnex.rs"));
|
||||
}
|
||||
pub mod jitter;
|
||||
pub mod relay;
|
||||
pub mod runner;
|
||||
|
|
|
|||
|
|
@ -1,33 +1,141 @@
|
|||
use crate::{Config, MAX_UDP_PACKET, secure::Relay};
|
||||
use tokio::{net::UdpSocket, sync::broadcast};
|
||||
use tracing::info;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::broadcast;
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::relay;
|
||||
use crate::{
|
||||
Config, MAX_UDP_PACKET, PLAYOUT_INTERVAL_MS, VOICE_HDR_SIZE, VOICE_PACKET_ID, VoiceHeader,
|
||||
};
|
||||
|
||||
pub async fn run(config: Config) -> anyhow::Result<()> {
|
||||
let (_tx, rx) = broadcast::channel(1);
|
||||
let (_, rx) = broadcast::channel(1);
|
||||
run_bind(&config.node.name, &config.voice.bind, rx).await
|
||||
}
|
||||
/// Receives credentials only over the in-process gateway bridge. Standalone mode is fail-closed.
|
||||
|
||||
pub async fn run_bind(
|
||||
node_name: &str,
|
||||
bind: &str,
|
||||
mut events: broadcast::Receiver<String>,
|
||||
mut voice_member_rx: broadcast::Receiver<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
info!("VNOX Voice Node starting — node: {node_name}");
|
||||
info!("UDP bind: {bind}");
|
||||
|
||||
let socket = UdpSocket::bind(bind).await?;
|
||||
info!(node=node_name,address=%socket.local_addr()?,"authenticated UDP voice listening");
|
||||
let mut relay = Relay::default();
|
||||
let mut buffer = [0u8; MAX_UDP_PACKET + 1];
|
||||
let mut bridge_open = true;
|
||||
loop {
|
||||
tokio::select! {
|
||||
event=events.recv(),if bridge_open=>match event {
|
||||
Ok(value)=>if let Ok(event)=serde_json::from_str(&value){relay.event(&event);},
|
||||
Err(broadcast::error::RecvError::Lagged(_))=>relay.clear(),
|
||||
Err(broadcast::error::RecvError::Closed)=>{relay.clear();bridge_open=false;},
|
||||
},
|
||||
result=socket.recv_from(&mut buffer)=>{
|
||||
let (len,src)=result?;
|
||||
for (addr,packet) in relay.receive(&buffer[..len],src) {let _=socket.send_to(&packet,addr).await;}
|
||||
}
|
||||
info!("voice node listening on {bind}");
|
||||
|
||||
let channels = relay::new_channel_map();
|
||||
let user_map = relay::new_user_map();
|
||||
|
||||
let channels_cleanup = channels.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(15));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
relay::cleanup_stale(&channels_cleanup, Duration::from_secs(30)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let channels_events = channels.clone();
|
||||
let user_map_events = user_map.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(event_str) = voice_member_rx.recv().await {
|
||||
if let Ok(event) = serde_json::from_str::<serde_json::Value>(&event_str) {
|
||||
let event_type = event["type"].as_str().unwrap_or("");
|
||||
let channel_id = event["channel_id"].as_str().unwrap_or("");
|
||||
let user_id = event["user_id"].as_str().unwrap_or("");
|
||||
match event_type {
|
||||
"join" => {
|
||||
let endpoint_str = match event["endpoint"].as_str() {
|
||||
Some(s) => s,
|
||||
None => continue,
|
||||
};
|
||||
let addr = match endpoint_str.parse::<SocketAddr>() {
|
||||
Ok(a) => a,
|
||||
Err(_) => continue,
|
||||
};
|
||||
relay::add_user_mapping(&user_map_events, user_id.to_string(), addr).await;
|
||||
if let Ok(ch) = channel_id.parse::<u64>() {
|
||||
relay::touch_member(&channels_events, ch, addr).await;
|
||||
}
|
||||
}
|
||||
"leave" => {
|
||||
if let Some(addr) =
|
||||
relay::remove_user_mapping(&user_map_events, user_id).await
|
||||
{
|
||||
relay::remove_member_from_all(&channels_events, &addr).await;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let socket = Arc::new(socket);
|
||||
let socket_relay = socket.clone();
|
||||
let channels_playout = channels.clone();
|
||||
let epoch = Instant::now();
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_millis(PLAYOUT_INTERVAL_MS));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
let now_ms = epoch.elapsed().as_millis() as u64;
|
||||
relay::pop_and_relay(socket_relay.as_ref(), &channels_playout, now_ms).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut buf = vec![0u8; MAX_UDP_PACKET];
|
||||
|
||||
loop {
|
||||
let (len, src) = match socket.recv_from(&mut buf).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
error!("UDP recv error: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let data = &buf[..len];
|
||||
|
||||
let hdr = match VoiceHeader::parse(data) {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
warn!("short packet from {src} ({len} bytes), dropping");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if hdr.packet_id != VOICE_PACKET_ID {
|
||||
debug!(
|
||||
"non-voice packet 0x{:04X} from {src}, dropping",
|
||||
hdr.packet_id
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
relay::touch_member(&channels, hdr.channel_id, src).await;
|
||||
|
||||
let arrived_at = epoch.elapsed().as_millis() as u64;
|
||||
|
||||
debug!(
|
||||
"voice seq={} ch={} from {src} ({} bytes opus)",
|
||||
hdr.voice_seq,
|
||||
hdr.channel_id,
|
||||
len - VOICE_HDR_SIZE,
|
||||
);
|
||||
|
||||
relay::push_packet(
|
||||
&channels,
|
||||
hdr.channel_id,
|
||||
src,
|
||||
hdr.voice_seq,
|
||||
hdr.timestamp,
|
||||
data,
|
||||
arrived_at,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,294 +0,0 @@
|
|||
//! Authenticated per-session UDP transport. No address or room is learned from plaintext.
|
||||
use crate::wire::VoiceFrame;
|
||||
use chacha20poly1305::{
|
||||
ChaCha20Poly1305, KeyInit, Nonce,
|
||||
aead::{Aead, Payload},
|
||||
};
|
||||
use prost::Message;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
net::SocketAddr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
const HEADER: usize = 28;
|
||||
const MAX_SESSIONS: usize = 4096;
|
||||
#[derive(Default)]
|
||||
struct Replay {
|
||||
highest: Option<u64>,
|
||||
seen: u128,
|
||||
}
|
||||
impl Replay {
|
||||
fn accept(&mut self, seq: u64) -> bool {
|
||||
match self.highest {
|
||||
None => {
|
||||
self.highest = Some(seq);
|
||||
self.seen = 1;
|
||||
true
|
||||
}
|
||||
Some(high) if seq > high => {
|
||||
let gap = seq - high;
|
||||
self.seen = if gap >= 128 {
|
||||
1
|
||||
} else {
|
||||
(self.seen << gap) | 1
|
||||
};
|
||||
self.highest = Some(seq);
|
||||
true
|
||||
}
|
||||
Some(high) => {
|
||||
let gap = high - seq;
|
||||
if gap >= 128 || self.seen & (1u128 << gap) != 0 {
|
||||
return false;
|
||||
}
|
||||
self.seen |= 1u128 << gap;
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Member {
|
||||
session: String,
|
||||
user: String,
|
||||
channel: String,
|
||||
c2s: [u8; 32],
|
||||
s2c: [u8; 32],
|
||||
addr: Option<SocketAddr>,
|
||||
replay: Replay,
|
||||
out_seq: u64,
|
||||
window: Instant,
|
||||
count: u32,
|
||||
last: Instant,
|
||||
}
|
||||
impl Drop for Member {
|
||||
fn drop(&mut self) {
|
||||
self.c2s.fill(0);
|
||||
self.s2c.fill(0);
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Relay {
|
||||
members: HashMap<[u8; 16], Member>,
|
||||
}
|
||||
fn bytes<const N: usize>(event: &serde_json::Value, key: &str) -> Option<[u8; N]> {
|
||||
hex::decode(event[key].as_str()?).ok()?.try_into().ok()
|
||||
}
|
||||
fn nonce(seq: u64) -> [u8; 12] {
|
||||
let mut n = [0u8; 12];
|
||||
n[4..].copy_from_slice(&seq.to_be_bytes());
|
||||
n
|
||||
}
|
||||
fn encrypt(route: &[u8; 16], key: &[u8; 32], seq: u64, body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut header = [0u8; HEADER];
|
||||
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(route);
|
||||
header[20..].copy_from_slice(&seq.to_be_bytes());
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(key).ok()?;
|
||||
let n = Nonce::from(nonce(seq));
|
||||
let body = cipher
|
||||
.encrypt(
|
||||
&n,
|
||||
Payload {
|
||||
msg: body,
|
||||
aad: &header,
|
||||
},
|
||||
)
|
||||
.ok()?;
|
||||
let mut packet = header.to_vec();
|
||||
packet.extend_from_slice(&body);
|
||||
Some(packet)
|
||||
}
|
||||
impl Relay {
|
||||
pub fn clear(&mut self) {
|
||||
self.members.clear();
|
||||
}
|
||||
pub fn event(&mut self, event: &serde_json::Value) {
|
||||
let Some(session) = event["session_id"]
|
||||
.as_str()
|
||||
.filter(|s| !s.is_empty() && s.len() <= 128)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
match event["type"].as_str() {
|
||||
Some("leave") => {
|
||||
self.members.retain(|_, m| m.session != session);
|
||||
}
|
||||
Some("join") => {
|
||||
let (Some(route), Some(c2s), Some(s2c), Some(channel), Some(user)) = (
|
||||
bytes(event, "route_id"),
|
||||
bytes(event, "c2s_key"),
|
||||
bytes(event, "s2c_key"),
|
||||
event["channel_id"].as_str(),
|
||||
event["user_id"].as_str(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if channel.is_empty() || channel.len() > 128 || user.len() > 128 {
|
||||
return;
|
||||
}
|
||||
self.members.retain(|_, m| m.session != session);
|
||||
if self.members.len() >= MAX_SESSIONS {
|
||||
return;
|
||||
}
|
||||
self.members.insert(
|
||||
route,
|
||||
Member {
|
||||
session: session.into(),
|
||||
user: user.into(),
|
||||
channel: channel.into(),
|
||||
c2s,
|
||||
s2c,
|
||||
addr: None,
|
||||
replay: Replay::default(),
|
||||
out_seq: 0,
|
||||
window: Instant::now(),
|
||||
count: 0,
|
||||
last: Instant::now(),
|
||||
},
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Verify before updating replay state, endpoint or source attribution.
|
||||
pub fn receive(&mut self, packet: &[u8], src: SocketAddr) -> Vec<(SocketAddr, Vec<u8>)> {
|
||||
if packet.len() < HEADER + 16
|
||||
|| packet.len() > crate::MAX_UDP_PACKET
|
||||
|| packet[..4] != [0, 0x10, 0, 1]
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
let route: [u8; 16] = packet[4..20].try_into().unwrap();
|
||||
let seq = u64::from_be_bytes(packet[20..28].try_into().unwrap());
|
||||
let Some(member) = self.members.get_mut(&route) else {
|
||||
return vec![];
|
||||
};
|
||||
if member.window.elapsed() >= Duration::from_secs(1) {
|
||||
member.window = Instant::now();
|
||||
member.count = 0;
|
||||
}
|
||||
if member.count >= 120 {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&member.c2s).expect("key length");
|
||||
let n = Nonce::from(nonce(seq));
|
||||
let Ok(body) = cipher.decrypt(
|
||||
&n,
|
||||
Payload {
|
||||
msg: &packet[HEADER..],
|
||||
aad: &packet[..HEADER],
|
||||
},
|
||||
) else {
|
||||
return vec![];
|
||||
};
|
||||
let Ok(mut frame) = VoiceFrame::decode(body.as_slice()) else {
|
||||
return vec![];
|
||||
};
|
||||
if frame.channel_id != member.channel
|
||||
|| !frame.sender_session_id.is_empty()
|
||||
|| !frame.sender_user_id.is_empty()
|
||||
|| frame.opus.len() > 1275
|
||||
|| seq == u64::MAX
|
||||
|| !member.replay.accept(seq)
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
member.count += 1;
|
||||
member.addr = Some(src);
|
||||
member.last = Instant::now();
|
||||
if frame.opus.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
frame.sender_session_id = member.session.clone();
|
||||
frame.sender_user_id = member.user.clone();
|
||||
let channel = member.channel.clone();
|
||||
let body = frame.encode_to_vec();
|
||||
let mut output = Vec::new();
|
||||
for (target_route, target) in &mut self.members {
|
||||
if *target_route == route
|
||||
|| target.channel != channel
|
||||
|| target.last.elapsed() > Duration::from_secs(30)
|
||||
|| target.out_seq == u64::MAX
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(addr) = target.addr
|
||||
&& let Some(packet) = encrypt(target_route, &target.s2c, target.out_seq, &body)
|
||||
{
|
||||
target.out_seq += 1;
|
||||
if packet.len() <= crate::MAX_UDP_PACKET {
|
||||
output.push((addr, packet));
|
||||
}
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn event(session: &str, user: &str, route: u8, key: u8, channel: &str) -> serde_json::Value {
|
||||
serde_json::json!({"type":"join","session_id":session,"user_id":user,"route_id":hex::encode([route;16]),"c2s_key":hex::encode([key;32]),"s2c_key":hex::encode([key+1;32]),"channel_id":channel})
|
||||
}
|
||||
fn packet(route: u8, key: u8, seq: u64, opus: &[u8]) -> Vec<u8> {
|
||||
encrypt(
|
||||
&[route; 16],
|
||||
&[key; 32],
|
||||
seq,
|
||||
&VoiceFrame {
|
||||
voice_seq: seq as u32,
|
||||
timestamp: 0,
|
||||
channel_id: "voice-uuid".into(),
|
||||
sender_session_id: String::new(),
|
||||
sender_user_id: String::new(),
|
||||
opus: opus.into(),
|
||||
}
|
||||
.encode_to_vec(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn relay_authenticates_reencrypts_stamps_rejects_replay_and_revokes() {
|
||||
let mut relay = Relay::default();
|
||||
relay.event(&event("a", "alice", 1, 10, "voice-uuid"));
|
||||
relay.event(&event("b", "bob", 2, 20, "voice-uuid"));
|
||||
relay.event(&event("c", "other", 3, 30, "elsewhere"));
|
||||
let a = "127.0.0.1:10001".parse().unwrap();
|
||||
let b = "127.0.0.1:10002".parse().unwrap();
|
||||
assert!(relay.receive(&packet(2, 20, 0, &[]), b).is_empty());
|
||||
assert!(relay.receive(&packet(1, 11, 0, b"bad key"), a).is_empty());
|
||||
let good = packet(1, 10, 0, b"opus");
|
||||
let out = relay.receive(&good, a);
|
||||
assert_eq!(out.len(), 1);
|
||||
assert_eq!(out[0].0, b);
|
||||
let n = Nonce::from(nonce(0));
|
||||
let clear = ChaCha20Poly1305::new_from_slice(&[21; 32])
|
||||
.unwrap()
|
||||
.decrypt(
|
||||
&n,
|
||||
Payload {
|
||||
msg: &out[0].1[HEADER..],
|
||||
aad: &out[0].1[..HEADER],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let frame = VoiceFrame::decode(clear.as_slice()).unwrap();
|
||||
assert_eq!(frame.sender_session_id, "a");
|
||||
assert_eq!(frame.sender_user_id, "alice");
|
||||
assert_eq!(frame.opus, b"opus");
|
||||
assert!(relay.receive(&good, a).is_empty());
|
||||
relay.event(&serde_json::json!({"type":"leave","session_id":"a"}));
|
||||
assert!(relay.receive(&packet(1, 10, 1, b"opus"), a).is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn replay_window_allows_reordering_but_never_duplicates_or_old_packets() {
|
||||
let mut r = Replay::default();
|
||||
assert!(r.accept(100));
|
||||
assert!(r.accept(99));
|
||||
assert!(!r.accept(99));
|
||||
assert!(r.accept(200));
|
||||
assert!(!r.accept(1));
|
||||
assert!(r.accept(199));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue