@onxdev/silentium 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/detect.rs ADDED
@@ -0,0 +1,248 @@
1
+ use anyhow::Result;
2
+
3
+ pub const VOICE_PORT_START: u16 = 50000;
4
+ pub const VOICE_PORT_END: u16 = 65535;
5
+
6
+ #[derive(Debug, Clone)]
7
+ pub struct Peer {
8
+ pub ip: String,
9
+ pub port: u16,
10
+ pub pid: u32,
11
+ pub process: String,
12
+ }
13
+
14
+ impl Peer {
15
+ pub fn is_voice(&self) -> bool {
16
+ (VOICE_PORT_START..=VOICE_PORT_END).contains(&self.port)
17
+ }
18
+ }
19
+
20
+ impl Peer {
21
+ pub fn endpoint(&self) -> String {
22
+ format!("{}:{}", self.ip, self.port)
23
+ }
24
+ }
25
+
26
+ /// PID do cliente Discord, se houver um rodando.
27
+ pub fn discord_running() -> Option<u32> {
28
+ #[cfg(target_os = "linux")]
29
+ {
30
+ let entries = std::fs::read_dir("/proc").ok()?;
31
+ for entry in entries.flatten() {
32
+ let name = entry.file_name();
33
+ let Some(pid) = name.to_string_lossy().parse::<u32>().ok() else {
34
+ continue;
35
+ };
36
+ let Ok(comm) = std::fs::read_to_string(entry.path().join("comm")) else {
37
+ continue;
38
+ };
39
+ if comm.to_ascii_lowercase().contains("discord") {
40
+ return Some(pid);
41
+ }
42
+ }
43
+ None
44
+ }
45
+ #[cfg(windows)]
46
+ {
47
+ let out = std::process::Command::new("powershell")
48
+ .args([
49
+ "-NoProfile",
50
+ "-NonInteractive",
51
+ "-Command",
52
+ "Get-Process Discord,DiscordPTB,DiscordCanary,DiscordDevelopment \
53
+ -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Id",
54
+ ])
55
+ .output()
56
+ .ok()?;
57
+ String::from_utf8_lossy(&out.stdout).trim().parse().ok()
58
+ }
59
+ #[cfg(not(any(windows, target_os = "linux")))]
60
+ {
61
+ None
62
+ }
63
+ }
64
+
65
+ pub fn voice_peers() -> Result<Vec<Peer>> {
66
+ #[cfg(windows)]
67
+ {
68
+ return windows::voice_peers();
69
+ }
70
+ #[cfg(target_os = "linux")]
71
+ {
72
+ linux::voice_peers()
73
+ }
74
+ #[cfg(not(any(windows, target_os = "linux")))]
75
+ {
76
+ anyhow::bail!("detecção local não implementada para esta plataforma")
77
+ }
78
+ }
79
+
80
+ #[cfg(target_os = "linux")]
81
+ mod linux {
82
+ use super::Peer;
83
+ use anyhow::{bail, Context, Result};
84
+ use std::process::Command;
85
+
86
+ pub fn voice_peers() -> Result<Vec<Peer>> {
87
+ let out = Command::new("ss")
88
+ .args(["-unp"])
89
+ .output()
90
+ .context("ss: iproute2 instalado?")?;
91
+ if !out.status.success() {
92
+ bail!("ss -unp falhou");
93
+ }
94
+ Ok(parse(&String::from_utf8_lossy(&out.stdout)))
95
+ }
96
+
97
+ fn parse(text: &str) -> Vec<Peer> {
98
+ let mut peers = Vec::new();
99
+ for line in text.lines() {
100
+ let cols: Vec<&str> = line.split_whitespace().collect();
101
+ if cols.len() < 4 {
102
+ continue;
103
+ }
104
+ let Some(owner) = cols.iter().find(|c| c.contains("users:((")) else {
105
+ continue;
106
+ };
107
+ if !owner.to_ascii_lowercase().contains("discord") {
108
+ continue;
109
+ }
110
+ let peer = cols[3];
111
+ if peer.starts_with("*") || peer.starts_with("0.0.0.0") || peer.starts_with("[::]") {
112
+ continue;
113
+ }
114
+ let (ip, port) = split_addr(peer);
115
+ let pid = owner
116
+ .split("pid=")
117
+ .nth(1)
118
+ .and_then(|rest| rest.split([',', ')']).next())
119
+ .and_then(|digits| digits.parse::<u32>().ok())
120
+ .unwrap_or(0);
121
+ peers.push(Peer {
122
+ ip,
123
+ port,
124
+ pid,
125
+ process: "Discord".to_string(),
126
+ });
127
+ }
128
+ peers.sort_by_key(|a| a.endpoint());
129
+ peers.dedup_by(|a, b| a.endpoint() == b.endpoint());
130
+ peers
131
+ }
132
+
133
+ fn split_addr(raw: &str) -> (String, u16) {
134
+ let trimmed = raw.trim_start_matches('[');
135
+ match trimmed.rsplit_once(':') {
136
+ Some((host, port)) => (
137
+ host.trim_end_matches(']').to_string(),
138
+ port.parse().unwrap_or(0),
139
+ ),
140
+ None => (trimmed.to_string(), 0),
141
+ }
142
+ }
143
+ }
144
+
145
+ #[cfg(windows)]
146
+ mod windows {
147
+ use super::Peer;
148
+ use anyhow::{bail, Context, Result};
149
+ use std::process::Command;
150
+
151
+ fn powershell(script: &str) -> Result<String> {
152
+ let out = Command::new("powershell")
153
+ .args(["-NoProfile", "-NonInteractive", "-Command", script])
154
+ .output()
155
+ .context("não consegui executar powershell")?;
156
+ if !out.status.success() {
157
+ bail!(
158
+ "powershell falhou: {}",
159
+ String::from_utf8_lossy(&out.stderr).trim()
160
+ );
161
+ }
162
+ Ok(String::from_utf8_lossy(&out.stdout).to_string())
163
+ }
164
+
165
+ pub fn voice_peers() -> Result<Vec<Peer>> {
166
+ let pids = powershell(
167
+ "Get-Process Discord,DiscordPTB,DiscordCanary,DiscordDevelopment -ErrorAction SilentlyContinue | \
168
+ ForEach-Object { $_.Id }",
169
+ )?;
170
+ let pids: Vec<u32> = pids
171
+ .split_whitespace()
172
+ .filter_map(|p| p.parse::<u32>().ok())
173
+ .collect();
174
+ if pids.is_empty() {
175
+ return Ok(Vec::new());
176
+ }
177
+
178
+ let table = powershell("netstat -ano -p UDP")?;
179
+ Ok(parse(&table, &pids))
180
+ }
181
+
182
+ fn parse(table: &str, discord_pids: &[u32]) -> Vec<Peer> {
183
+ let mut peers = Vec::new();
184
+ for line in table.lines() {
185
+ let cols: Vec<&str> = line.split_whitespace().collect();
186
+ if cols.len() < 4 || !cols[0].eq_ignore_ascii_case("UDP") {
187
+ continue;
188
+ }
189
+ let pid = cols[3].parse::<u32>().unwrap_or(0);
190
+ if !discord_pids.contains(&pid) {
191
+ continue;
192
+ }
193
+ let foreign = cols[2];
194
+ if foreign.contains(":*")
195
+ || foreign.starts_with("0.0.0.0")
196
+ || foreign.starts_with('[') && foreign.contains("]:*")
197
+ {
198
+ continue;
199
+ }
200
+ let (ip, port) = match foreign.rsplit_once(':') {
201
+ Some((host, port)) => (
202
+ host.trim_matches(|c| c == '[' || c == ']').to_string(),
203
+ port.parse().unwrap_or(0),
204
+ ),
205
+ None => continue,
206
+ };
207
+ if port == 0 {
208
+ continue;
209
+ }
210
+ peers.push(Peer {
211
+ ip,
212
+ port,
213
+ pid,
214
+ process: "Discord".to_string(),
215
+ });
216
+ }
217
+ peers.sort_by(|a, b| a.endpoint().cmp(&b.endpoint()));
218
+ peers.dedup_by(|a, b| a.endpoint() == b.endpoint());
219
+ peers
220
+ }
221
+ }
222
+
223
+ #[cfg(test)]
224
+ mod tests {
225
+ use super::Peer;
226
+
227
+ fn peer(port: u16) -> Peer {
228
+ Peer {
229
+ ip: "162.159.129.232".to_string(),
230
+ port,
231
+ pid: 1,
232
+ process: "Discord".to_string(),
233
+ }
234
+ }
235
+
236
+ #[test]
237
+ fn faixa_de_voz_e_reconhecida() {
238
+ assert!(peer(50002).is_voice());
239
+ assert!(peer(65535).is_voice());
240
+ assert!(!peer(443).is_voice());
241
+ assert!(!peer(49999).is_voice());
242
+ }
243
+
244
+ #[test]
245
+ fn endpoint_formatado() {
246
+ assert_eq!(peer(50002).endpoint(), "162.159.129.232:50002");
247
+ }
248
+ }
package/src/discord.rs ADDED
@@ -0,0 +1,273 @@
1
+ use anyhow::{anyhow, bail, Context, Result};
2
+ use serde::Deserialize;
3
+ use serde_json::{json, Value};
4
+ use std::thread::sleep;
5
+ use std::time::Duration;
6
+
7
+ const API: &str = "https://discord.com/api/v10";
8
+
9
+ #[derive(Debug, Deserialize)]
10
+ pub struct Me {
11
+ pub id: String,
12
+ pub username: String,
13
+ }
14
+
15
+ #[derive(Debug, Deserialize)]
16
+ pub struct User {
17
+ pub id: String,
18
+ pub username: String,
19
+ #[serde(default)]
20
+ pub bot: bool,
21
+ }
22
+
23
+ #[derive(Debug, Deserialize)]
24
+ pub struct Member {
25
+ pub user: User,
26
+ }
27
+
28
+ #[derive(Debug, Deserialize)]
29
+ pub struct VoiceState {
30
+ #[allow(dead_code)]
31
+ pub user_id: String,
32
+ pub channel_id: Option<String>,
33
+ #[serde(default)]
34
+ pub mute: bool,
35
+ #[serde(default)]
36
+ pub deaf: bool,
37
+ }
38
+
39
+ #[derive(Debug, Deserialize)]
40
+ pub struct InviteTarget {
41
+ pub guild: Option<InviteGuild>,
42
+ pub channel: Option<InviteChannel>,
43
+ }
44
+
45
+ #[derive(Debug, Deserialize)]
46
+ pub struct InviteGuild {
47
+ pub id: String,
48
+ pub name: String,
49
+ }
50
+
51
+ #[derive(Debug, Deserialize)]
52
+ pub struct InviteChannel {
53
+ pub id: String,
54
+ pub name: String,
55
+ }
56
+
57
+ pub struct Api {
58
+ agent: ureq::Agent,
59
+ header: String,
60
+ pub dry_run: bool,
61
+ pub delay_ms: u64,
62
+ }
63
+
64
+ impl Api {
65
+ pub fn new(token: String, dry_run: bool, delay_ms: u64, user_token: bool) -> Self {
66
+ let agent = ureq::AgentBuilder::new()
67
+ .timeout_connect(Duration::from_secs(10))
68
+ .timeout(Duration::from_secs(30))
69
+ .build();
70
+ let header = if user_token {
71
+ token
72
+ } else {
73
+ format!("Bot {token}")
74
+ };
75
+ Self {
76
+ agent,
77
+ header,
78
+ dry_run,
79
+ delay_ms,
80
+ }
81
+ }
82
+
83
+ fn auth(&self, req: ureq::Request) -> ureq::Request {
84
+ req.set("Authorization", &self.header)
85
+ .set("User-Agent", "Silentium/0.1 (local)")
86
+ .set("Content-Type", "application/json")
87
+ }
88
+
89
+ fn raw(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value> {
90
+ let url = format!("{API}{path}");
91
+ loop {
92
+ let req = self.auth(self.agent.request(method, &url));
93
+ let sent = match &body {
94
+ Some(payload) => req.send_json(payload.clone()),
95
+ None => req.call(),
96
+ };
97
+ match sent {
98
+ Ok(resp) => {
99
+ if resp.status() == 204 {
100
+ return Ok(Value::Null);
101
+ }
102
+ return resp.into_json::<Value>().context("resposta não-JSON");
103
+ }
104
+ Err(ureq::Error::Status(code, resp)) => {
105
+ let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
106
+ if code == 429 {
107
+ let wait = payload
108
+ .get("retry_after")
109
+ .and_then(Value::as_f64)
110
+ .unwrap_or(1.5);
111
+ sleep(Duration::from_millis((wait * 1000.0) as u64 + 120));
112
+ continue;
113
+ }
114
+ let msg = payload
115
+ .get("message")
116
+ .and_then(Value::as_str)
117
+ .unwrap_or("sem mensagem");
118
+ bail!("{method} {path} -> HTTP {code}: {msg}");
119
+ }
120
+ Err(err) => bail!("{method} {path} falhou: {err}"),
121
+ }
122
+ }
123
+ }
124
+
125
+ fn pause(&self) {
126
+ if self.delay_ms > 0 {
127
+ sleep(Duration::from_millis(self.delay_ms));
128
+ }
129
+ }
130
+
131
+ pub fn me(&self) -> Result<Me> {
132
+ let raw = self.raw("GET", "/users/@me", None)?;
133
+ serde_json::from_value(raw).context("payload de /users/@me inesperado")
134
+ }
135
+
136
+ pub fn resolve_invite(&self, invite: &str) -> Result<InviteTarget> {
137
+ let code = invite_code(invite)?;
138
+ let raw = self.raw("GET", &format!("/invites/{code}?with_counts=true"), None)?;
139
+ serde_json::from_value(raw).context("payload de /invites inesperado")
140
+ }
141
+
142
+ pub fn members(&self, guild: &str) -> Result<Vec<Member>> {
143
+ let mut out: Vec<Member> = Vec::new();
144
+ let mut after = String::from("0");
145
+ loop {
146
+ let page = self.raw(
147
+ "GET",
148
+ &format!("/guilds/{guild}/members?limit=1000&after={after}"),
149
+ None,
150
+ )?;
151
+ let batch: Vec<Member> =
152
+ serde_json::from_value(page).context("payload de /members inesperado")?;
153
+ let len = batch.len();
154
+ if let Some(last) = batch.last() {
155
+ after.clone_from(&last.user.id);
156
+ }
157
+ out.extend(batch);
158
+ if len < 1000 {
159
+ break;
160
+ }
161
+ self.pause();
162
+ }
163
+ Ok(out)
164
+ }
165
+
166
+ pub fn voice_state(&self, guild: &str, user: &str) -> Result<Option<VoiceState>> {
167
+ let url = format!("{API}/guilds/{guild}/voice-states/{user}");
168
+ let req = self
169
+ .agent
170
+ .get(&url)
171
+ .set("Authorization", &self.header)
172
+ .set("User-Agent", "Silentium/0.1 (local)");
173
+ match req.call() {
174
+ Ok(resp) => {
175
+ let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
176
+ Ok(serde_json::from_value::<VoiceState>(payload).ok())
177
+ }
178
+ Err(ureq::Error::Status(404, _)) => Ok(None),
179
+ Err(ureq::Error::Status(code, resp)) => {
180
+ let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
181
+ let msg = payload
182
+ .get("message")
183
+ .and_then(Value::as_str)
184
+ .unwrap_or("sem mensagem");
185
+ bail!("GET voice-states -> HTTP {code}: {msg}");
186
+ }
187
+ Err(err) => Err(anyhow!("GET voice-states falhou: {err}")),
188
+ }
189
+ }
190
+
191
+ pub fn patch_member(&self, guild: &str, user: &str, body: &Value) -> Result<()> {
192
+ if self.dry_run {
193
+ println!(" [dry-run] PATCH /guilds/{guild}/members/{user} {body}");
194
+ return Ok(());
195
+ }
196
+ self.raw(
197
+ "PATCH",
198
+ &format!("/guilds/{guild}/members/{user}"),
199
+ Some(body.clone()),
200
+ )?;
201
+ Ok(())
202
+ }
203
+
204
+ pub fn body_for(action: &str) -> Result<Value> {
205
+ Ok(match action {
206
+ "drop" => json!({ "channel_id": null }),
207
+ "mute" => json!({ "mute": true }),
208
+ "unmute" => json!({ "mute": false }),
209
+ "deafen" => json!({ "deaf": true }),
210
+ "undeafen" => json!({ "deaf": false }),
211
+ "restore" => json!({ "mute": false, "deaf": false }),
212
+ other => bail!("ação desconhecida: {other}"),
213
+ })
214
+ }
215
+ }
216
+
217
+ pub fn invite_code(raw: &str) -> Result<String> {
218
+ let trimmed = raw.trim().trim_end_matches('/');
219
+ let tail = trimmed.rsplit('/').next().unwrap_or(trimmed);
220
+ let code = tail.split(['?', '#']).next().unwrap_or(tail);
221
+ let valido = !code.is_empty() && code.len() <= 64 && !code.contains('.') && !code.contains(':');
222
+ if !valido {
223
+ bail!("convite inválido: {raw}");
224
+ }
225
+ Ok(code.to_string())
226
+ }
227
+
228
+ #[cfg(test)]
229
+ mod tests {
230
+ use super::{invite_code, Api};
231
+ use serde_json::json;
232
+
233
+ #[test]
234
+ fn extrai_codigo_de_varias_formas() {
235
+ for raw in [
236
+ "discord.gg/abc123",
237
+ "https://discord.gg/abc123",
238
+ "https://discord.gg/abc123/",
239
+ "https://discord.com/invite/abc123?event=1",
240
+ "abc123",
241
+ ] {
242
+ assert_eq!(invite_code(raw).unwrap(), "abc123", "entrada: {raw}");
243
+ }
244
+ }
245
+
246
+ #[test]
247
+ fn rejeita_convite_vazio() {
248
+ assert!(invite_code("https://discord.gg/").is_err());
249
+ assert!(invite_code("").is_err());
250
+ }
251
+
252
+ #[test]
253
+ fn corpo_do_drop_zera_canal() {
254
+ assert_eq!(
255
+ Api::body_for("drop").unwrap(),
256
+ json!({ "channel_id": null })
257
+ );
258
+ }
259
+
260
+ #[test]
261
+ fn corpo_do_restore_limpa_estado() {
262
+ assert_eq!(
263
+ Api::body_for("restore").unwrap(),
264
+ json!({ "mute": false, "deaf": false })
265
+ );
266
+ }
267
+
268
+ #[test]
269
+ fn acao_invalida_falha() {
270
+ assert!(Api::body_for("explodir").is_err());
271
+ assert!(Api::body_for("drop").is_ok());
272
+ }
273
+ }