@onxdev/silentium 0.0.0-stage → 0.2.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/Cargo.toml ADDED
@@ -0,0 +1,37 @@
1
+ [package]
2
+ name = "silentium"
3
+ version = "0.2.0"
4
+ edition = "2021"
5
+ rust-version = "1.75"
6
+ description = "Discord voice kill switch: drop/mute/deafen every call participant, plus local voice-traffic shaping"
7
+ license = "MIT"
8
+ authors = ["onx90s"]
9
+ repository = "https://github.com/onx90s/silentium"
10
+ homepage = "https://github.com/onx90s/silentium"
11
+ readme = "README.md"
12
+ keywords = ["discord", "voice", "firewall", "qos", "cli"]
13
+ categories = ["command-line-utilities", "network-programming"]
14
+
15
+ [[bin]]
16
+ name = "silentium"
17
+ path = "src/main.rs"
18
+
19
+ [dependencies]
20
+ anyhow = "1"
21
+ clap = { version = "4", features = ["derive", "env"] }
22
+ ctrlc = "3"
23
+ serde = { version = "1", features = ["derive"] }
24
+ serde_json = "1"
25
+ sha2 = "0.10"
26
+
27
+ [target.'cfg(windows)'.dependencies]
28
+ ureq = { version = "2.12", default-features = false, features = ["json", "native-tls", "gzip"] }
29
+
30
+ [target.'cfg(unix)'.dependencies]
31
+ ureq = { version = "2.12", default-features = false, features = ["json", "tls", "gzip"] }
32
+
33
+ [profile.release]
34
+ lto = "thin"
35
+ codegen-units = 1
36
+ strip = true
37
+ opt-level = 3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 onx90s
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,315 @@
1
- # Temporary Holding Version
1
+ # Silentium
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```
4
+ ██████╗ ██╗ ██╗ ██████╗ ███╗ ██╗ ████████╗ ██╗ ██╗ ██╗ ███╗ ███╗
5
+ ██╔═══╝ ██║ ██║ ██╔═══╝ ████╗ ██║ ╚══██╔══╝ ██║ ██║ ██║ ████╗ ████║
6
+ ██████╗ ██║ ██║ █████╗ ██╔██╗ ██║ ██║ ██║ ██║ ██║ ██╔████╔██║
7
+ ╚═══██║ ██║ ██║ ██╔══╝ ██║╚██╗██║ ██║ ██║ ██║ ██║ ██║╚██╔╝██║
8
+ ██████║ ██║ ██████╗ ██████╗ ██║ ╚████║ ██║ ██║ ╚██████╔╝ ██║ ╚═╝ ██║
9
+ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
10
+ ```
11
+
12
+ **Kill switch de voz para Discord.** Detecta a call ativa pelos sockets locais do cliente e corta, limita, muta ou derruba — sem plugin, sem injeção, sem tocar no aplicativo.
13
+
14
+ [![release](https://img.shields.io/github/v/release/onx90s/silentium?color=6c8cff)](https://github.com/onx90s/silentium/releases)
15
+ [![npm](https://img.shields.io/npm/v/@onxdev/silentium?label=npm&color=cb3837)](https://www.npmjs.com/package/@onxdev/silentium)
16
+ [![ci](https://img.shields.io/github/actions/workflow/status/onx90s/silentium/ci.yml?label=ci)](https://github.com/onx90s/silentium/actions)
17
+ [![license](https://img.shields.io/badge/license-MIT-8fbcbb)](#licença)
18
+ ![platforms](https://img.shields.io/badge/plataformas-linux%20·%20windows%20·%20macos-9aa0a6)
19
+
20
+ ---
21
+
22
+ ## O que é
23
+
24
+ Silentium é uma CLI em Rust que trata a voz do Discord como infraestrutura: você escolhe o escopo — todos na call, um canal, um usuário — e aplica uma ação.
25
+
26
+ | camada | o que faz | precisa de |
27
+ |---|---|---|
28
+ | **detecção local** | descobre se existe call ativa e onde, lendo os sockets UDP do processo Discord | nada |
29
+ | **controle de voz** | derruba, muta, ensurdece, restaura e vigia entrada de participantes via REST | token com permissões de moderação |
30
+ | **shaping de rede** | corta ou limita só o tráfego do Discord, o resto da máquina segue intacto | root (Linux) / Administrador (Windows) |
31
+
32
+ O binário é pequeno, sem runtime, sem dependência de Node ou Python. `npm install -g @onxdev/silentium` existe só como transporte do binário.
33
+
34
+ ## Como funciona
35
+
36
+ **1. Detecção sem API.** O Discord negocia mídia em UDP na faixa **50000–65535**. Silentium lê a tabela de sockets do sistema, filtra o que pertence ao processo Discord e separa tráfego de mídia (faixa de voz) de tráfego de gateway/QUIC (443). Nenhum token é usado nesse caminho — `silentium detect` funciona offline.
37
+
38
+ **2. Controle via REST v10.** Com token de bot (`Authorization: Bot <token>`) ou token de usuário (`--user-token`), o comando faz `PATCH /guilds/{guild}/members/{user}` com um destes corpos:
39
+
40
+ ```json
41
+ { "channel_id": null } // derruba da call
42
+ { "mute": true } // muta no servidor
43
+ { "deaf": true } // ensurdece no servidor
44
+ { "mute": false, "deaf": false } // restaura
45
+ ```
46
+
47
+ Permissões exigidas no servidor: `MOVE_MEMBERS`, `MUTE_MEMBERS`, `DEAFEN_MEMBERS`.
48
+
49
+ **3. Shaping no sistema.** No Linux, `iptables` com match por dono do socket e `tc`/`netem` para banda, perda e latência. No Windows, regras de firewall por caminho do `Discord.exe` e política `New-NetQosPolicy` na faixa de voz. Sempre restrito ao tráfego do Discord.
50
+
51
+ ## Instalação
52
+
53
+ ### npm (recomendado)
54
+
55
+ ```bash
56
+ npm install -g @onxdev/silentium
57
+ silentium
58
+ ```
59
+
60
+ O `postinstall` baixa o binário pré-compilado para a sua plataforma direto dos releases, confere o SHA-256 e coloca em `node_modules/@onxdev/silentium/vendor/`. Sem Rust instalado, sem compilação. Se o download falhar e houver Rust na máquina, ele compila na hora.
61
+
62
+ Linux, macOS e Windows usam exatamente o mesmo comando. Precisa de Node 18+ apenas para instalar; o binário em si não tem runtime.
63
+
64
+ Sem instalar nada globalmente:
65
+
66
+ ```bash
67
+ npx @onxdev/silentium
68
+ ```
69
+
70
+ > O nome `silentium` no npm pertence a outro projeto (uma solução de mensageria). Este CLI é publicado sob o escopo `@onx90s`, e o comando continua sendo `silentium`.
71
+
72
+ ### Cargo
73
+
74
+ ```bash
75
+ cargo install --git https://github.com/onx90s/silentium --locked
76
+ ```
77
+
78
+ ### Binário direto
79
+
80
+ ```bash
81
+ # Linux x86_64
82
+ curl -fsSL https://github.com/onx90s/silentium/releases/latest/download/silentium-linux-x64.tar.gz \
83
+ | tar -xz -C ~/.local/bin
84
+ chmod +x ~/.local/bin/silentium
85
+ ```
86
+
87
+ Assets disponíveis: `silentium-linux-x64`, `silentium-linux-arm64`, `silentium-darwin-x64`, `silentium-darwin-arm64`, `silentium-windows-x64.zip`, sempre com `SHASUMS256.txt` ao lado.
88
+
89
+ ## Primeiro uso
90
+
91
+ Rodar sem argumento abre a tela inicial: banner, diagnóstico do sistema e menu.
92
+
93
+ ```bash
94
+ silentium
95
+ ```
96
+
97
+ ```
98
+ sistema linux-x86_64 · uid 1000
99
+ discord ● rodando — pid 4213
100
+ call ● ativa — 2 socket(s) de mídia (50002, 50004)
101
+ token ● definido (MTQ3…)
102
+ guild ● 123456789012345678
103
+ firewall ○ sem privilégio — net só com sudo
104
+ ```
105
+
106
+ Depois, dois caminhos:
107
+
108
+ ```bash
109
+ # só detecção, zero credencial
110
+ silentium detect
111
+
112
+ # controle de voz: aponte o convite da call, sem precisar de IDs
113
+ export DISCORD_TOKEN="seu_token_de_bot"
114
+ silentium voice list --invite discord.gg/abc123
115
+ silentium voice drop --invite discord.gg/abc123
116
+ ```
117
+
118
+ `--invite` resolve o convite em guild + canal automaticamente. IDs explícitos também valem:
119
+
120
+ ```bash
121
+ silentium voice mute --guild 123456789012345678 --channel 987654321098765432
122
+ ```
123
+
124
+ ## Comandos
125
+
126
+ ### Globais
127
+
128
+ | flag | padrão | função |
129
+ |---|---|---|
130
+ | `--token` | `$DISCORD_TOKEN` | token de bot, ou de usuário com `--user-token` |
131
+ | `--user-token` | — | trata o token como de usuário (sem prefixo `Bot `) |
132
+ | `--guild` | `$GUILD_ID` | ID do servidor |
133
+ | `--delay-ms` | `150` | intervalo entre chamadas REST |
134
+ | `--dry-run` | — | mostra o que faria, sem executar |
135
+
136
+ ### `silentium detect`
137
+
138
+ Lista sockets do Discord. Sem token. Marca o que cai na faixa de voz.
139
+
140
+ ```bash
141
+ silentium detect
142
+ ```
143
+
144
+ ### `silentium whoami` / `silentium resolve`
145
+
146
+ ```bash
147
+ silentium whoami # valida o token
148
+ silentium resolve discord.gg/abc123 # convite -> guild + canal
149
+ ```
150
+
151
+ ### `silentium voice <ação>`
152
+
153
+ Ações: `list`, `drop`, `mute`, `unmute`, `deafen`, `undeafen`, `restore`.
154
+
155
+ ```bash
156
+ silentium voice list # quem está em voz
157
+ silentium voice drop # derruba todos
158
+ silentium voice mute --channel 987654321098765432 # muta um canal
159
+ silentium voice restore # desfaz mute e deafen
160
+ silentium voice drop --user 111111111111111111 # alvo único
161
+ ```
162
+
163
+ Filtros comuns a todas as ações:
164
+
165
+ | flag | efeito |
166
+ |---|---|
167
+ | `--guild <id>` | servidor |
168
+ | `--channel <id>` | restringe a um canal de voz |
169
+ | `--user <id>` | alvo específico, repetível |
170
+ | `--invite <link>` | extrai guild e canal do convite |
171
+
172
+ ### `silentium voice guard`
173
+
174
+ Vigia o canal e aplica a ação em quem entrar.
175
+
176
+ ```bash
177
+ silentium voice guard --invite discord.gg/abc123 --action drop --interval 2
178
+ ```
179
+
180
+ ### `silentium net <subcomando>`
181
+
182
+ | comando | efeito |
183
+ |---|---|
184
+ | `throttle --kbps 8` | limita a banda do áudio (8 degrada, 2 mata) |
185
+ | `throttle --loss 30 --latency 400` | perda e latência no UDP de voz (Linux) |
186
+ | `clear` | remove todo o shaping |
187
+ | `block` | corta a internet **só do Discord**, por processo |
188
+ | `unblock` | desfaz o bloqueio |
189
+ | `auto` | detecta call ativa e corta; restaura no `Enter`/`Ctrl-C` |
190
+
191
+ ```bash
192
+ sudo silentium net auto --seconds 30
193
+ sudo silentium net throttle --kbps 4 --loss 40
194
+ ```
195
+
196
+ ## Receitas
197
+
198
+ Cortar a call por 30 segundos, sem pensar em IDs:
199
+
200
+ ```bash
201
+ sudo silentium net auto --seconds 30
202
+ ```
203
+
204
+ Silenciar um participante específico, sem sair do servidor:
205
+
206
+ ```bash
207
+ silentium voice mute --invite discord.gg/abc123 --user 987654321098765432
208
+ silentium voice unmute --invite discord.gg/abc123 --user 987654321098765432
209
+ ```
210
+
211
+ Receber ninguém: vigia o canal e derruba quem entrar.
212
+
213
+ ```bash
214
+ silentium voice guard --invite discord.gg/abc123 --action drop
215
+ ```
216
+
217
+ Silêncio total numa máquina compartilhada: corta o Discord, resto navega normal.
218
+
219
+ ```bash
220
+ sudo silentium net block # até Enter/Ctrl-C
221
+ sudo silentium net block --seconds 120
222
+ ```
223
+
224
+ ## Atualização
225
+
226
+ O CLI consulta a última release do GitHub uma vez a cada 6 horas (cache em `~/.cache/silentium/update.json`) e avisa na tela inicial:
227
+
228
+ ```
229
+ atualização disponível: v0.2.0 (você tem v0.1.0)
230
+ ```
231
+
232
+ Aí é só escolher `u` no menu, ou rodar direto:
233
+
234
+ ```bash
235
+ silentium update --check # só informa
236
+ silentium update # baixa, confere o SHA-256 e troca o binário
237
+ ```
238
+
239
+ Como ele se atualiza depende de como foi instalado: pacote npm → `npm install -g @onxdev/silentium@<versão>`; binário solto → baixa o asset da release, valida o checksum e substitui o executável no lugar (no Windows via renomear, já que o arquivo em uso não pode ser sobrescrito).
240
+
241
+ ## Permissões
242
+
243
+ | operação | Linux | Windows |
244
+ |---|---|---|
245
+ | `detect` | `iproute2` (`ss`) | PowerShell (`netstat`) |
246
+ | `voice *` | token + permissões no servidor | idem |
247
+ | `net block` | root, `iptables` | Administrador, firewall |
248
+ | `net throttle` | root, `iptables` + `tc`/`netem` | Administrador, `New-NetQosPolicy` (só banda) |
249
+ | `net throttle --loss/--latency` | Linux apenas | ignorado com aviso |
250
+
251
+ No Windows a pilha nativa de QoS só limita banda; perda e latência são exclusivas do Linux.
252
+
253
+ ## Plataformas
254
+
255
+ | | detect | voice | net block | net throttle |
256
+ |---|---|---|---|---|
257
+ | Linux x86_64 / arm64 | ✅ | ✅ | ✅ | ✅ |
258
+ | Windows x86_64 | ✅ | ✅ | ✅ | banda |
259
+ | macOS x86_64 / arm64 | ⚠️ `detect` usa `ss`, indisponível | ✅ | — | — |
260
+
261
+ O controle de voz é independente de plataforma: é REST.
262
+
263
+ ## Construindo do código
264
+
265
+ ```bash
266
+ git clone https://github.com/onx90s/silentium
267
+ cd silentium
268
+ cargo build --release # target/release/silentium
269
+ cargo test
270
+ ```
271
+
272
+ Toolchain: stable, edição 2021, MSRV 1.75. Sem dependência nativa: `clap`, `serde`, `ureq`, `anyhow`, `ctrlc`.
273
+
274
+ ## Estrutura do repositório
275
+
276
+ ```
277
+ src/
278
+ main.rs dispatch, guard, janela de restauração
279
+ cli.rs superfície de argumentos (clap)
280
+ ui.rs tela inicial: banner, diagnóstico, menu
281
+ detect.rs sockets do Discord (ss / netstat)
282
+ discord.rs REST v10: membros, voice states, convites
283
+ net.rs iptables + tc (Linux) / firewall + QoS (Windows)
284
+ npm/
285
+ lib.js resolução de plataforma, download, verificação
286
+ install.js postinstall com fallback para cargo
287
+ bin/ shim que executa o binário nativo
288
+ ```
289
+
290
+ ## Limites
291
+
292
+ - Ações de moderação são registradas no audit log do servidor: `drop`, `mute` e `deafen` ficam atribuídos ao token que as executou.
293
+ - `net block` depende de privilégio elevado. Sem ele, o comando informa e sai sem aplicar nada.
294
+ - A detecção lê sockets do próprio sistema: com Discord rodando em Flatpak ou sandbox, `ss` pode não expor o dono do socket.
295
+ - Token de usuário viola os termos do Discord. Use token de bot em servidor que você administra.
296
+
297
+ ## Licença
298
+
299
+ MIT. Veja [LICENSE](LICENSE).
300
+
301
+ ---
302
+
303
+ ## English
304
+
305
+ **Silentium** is a voice kill switch for Discord, written in Rust. It detects an active call by inspecting the client's local UDP sockets (50000–65535), then drops, mutes, deafens or restores participants through the REST v10 API, or shapes the machine's network so only Discord traffic is cut.
306
+
307
+ ```bash
308
+ npm install -g @onxdev/silentium
309
+ silentium # banner, local diagnosis, interactive menu
310
+ silentium detect # no credentials needed
311
+ ```
312
+
313
+ Requires Node 18+ only for installation; the CLI itself is a native binary. Voice actions need a bot token with `MOVE_MEMBERS`, `MUTE_MEMBERS`, `DEAFEN_MEMBERS`. Network shaping needs root on Linux (iptables/tc) or Administrator on Windows (firewall/QoS).
314
+
315
+ Star the repo if it saved a call.
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ // javascript — npm/bin/silentium.js — executa o binário nativo, instalando sob demanda
3
+ "use strict";
4
+
5
+ const { spawn } = require("node:child_process");
6
+ const lib = require("../lib.js");
7
+
8
+ async function main() {
9
+ let binary = lib.resolveBinary();
10
+
11
+ if (!binary) {
12
+ console.error("[silentium] primeira execução: preparando o binário…");
13
+ try {
14
+ binary = await lib.ensureBinary();
15
+ } catch (err) {
16
+ console.error(`[silentium] não consegui preparar o binário: ${err.message}`);
17
+ console.error(`[silentium] releases: https://github.com/${lib.REPO}/releases`);
18
+ console.error("[silentium] alternative: cargo install --git https://github.com/" + lib.REPO);
19
+ process.exit(1);
20
+ }
21
+ }
22
+
23
+ const child = spawn(binary, process.argv.slice(2), {
24
+ stdio: "inherit",
25
+ env: process.env,
26
+ });
27
+
28
+ child.on("error", (err) => {
29
+ console.error(`[silentium] falha ao executar o binário: ${err.message}`);
30
+ process.exit(1);
31
+ });
32
+
33
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
34
+ process.on(signal, () => {
35
+ if (!child.killed) child.kill(signal);
36
+ });
37
+ }
38
+
39
+ child.on("exit", (code, signal) => {
40
+ if (signal) process.kill(process.pid, signal);
41
+ process.exit(code === null ? 1 : code);
42
+ });
43
+ }
44
+
45
+ main();
package/npm/install.js ADDED
@@ -0,0 +1,31 @@
1
+ // javascript — npm/install.js — postinstall best-effort: nunca derruba a instalação
2
+ "use strict";
3
+
4
+ const lib = require("./lib.js");
5
+
6
+ async function main() {
7
+ if (process.env.SILENTIUM_SKIP_DOWNLOAD === "1") {
8
+ console.log("[silentium] SILENTIUM_SKIP_DOWNLOAD=1: download pulado");
9
+ return;
10
+ }
11
+
12
+ const existing = lib.resolveBinary();
13
+ if (existing) {
14
+ console.log(`[silentium] binário presente: ${existing}`);
15
+ return;
16
+ }
17
+
18
+ try {
19
+ await lib.ensureBinary();
20
+ } catch (err) {
21
+ // O shim do CLI tenta de novo no primeiro uso: aqui nunca falhamos o install.
22
+ console.warn(`[silentium] aviso: ${err.message}`);
23
+ console.warn("[silentium] o binário será baixado ou compilado no primeiro `silentium`");
24
+ if (process.env.SILENTIUM_STRICT === "1") throw err;
25
+ }
26
+ }
27
+
28
+ main().catch((err) => {
29
+ console.warn(`[silentium] aviso: ${err.message}`);
30
+ if (process.env.SILENTIUM_STRICT === "1") process.exit(1);
31
+ });
package/npm/lib.js ADDED
@@ -0,0 +1,220 @@
1
+ // javascript — npm/lib.js — plataforma, download do release e resolução do binário
2
+ "use strict";
3
+
4
+ const fs = require("node:fs");
5
+ const os = require("node:os");
6
+ const path = require("node:path");
7
+ const crypto = require("node:crypto");
8
+ const https = require("node:https");
9
+ const { execFileSync } = require("node:child_process");
10
+
11
+ const REPO = "onx90s/silentium";
12
+ const PKG_ROOT = path.join(__dirname, "..");
13
+ const VENDOR = path.join(__dirname, "vendor");
14
+
15
+ function packageVersion() {
16
+ const pkg = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, "package.json"), "utf8"));
17
+ return pkg.version;
18
+ }
19
+
20
+ function platformTag() {
21
+ const platform = process.platform;
22
+ const arch = process.arch;
23
+ if (platform === "linux" && (arch === "x64" || arch === "arm64")) return { platform: "linux", arch };
24
+ if (platform === "darwin" && (arch === "x64" || arch === "arm64")) return { platform: "darwin", arch };
25
+ if (platform === "win32" && arch === "x64") return { platform: "windows", arch };
26
+ return null;
27
+ }
28
+
29
+ function isMusl() {
30
+ if (process.platform !== "linux") return false;
31
+ try {
32
+ const report = process.report && process.report.getReport();
33
+ return Boolean(report) && !report.header.glibcVersionRuntime;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function binaryName() {
40
+ return process.platform === "win32" ? "silentium.exe" : "silentium";
41
+ }
42
+
43
+ function assetName(tag) {
44
+ const ext = tag.platform === "windows" ? "zip" : "tar.gz";
45
+ return `silentium-${tag.platform}-${tag.arch}.${ext}`;
46
+ }
47
+
48
+ function vendorBinary() {
49
+ return path.join(VENDOR, binaryName());
50
+ }
51
+
52
+ function localBuildBinary() {
53
+ const name = binaryName();
54
+ const candidates = [
55
+ path.join(PKG_ROOT, "target", "release", name),
56
+ path.join(PKG_ROOT, "..", "target", "release", name),
57
+ ];
58
+ return candidates.find((p) => fs.existsSync(p)) || null;
59
+ }
60
+
61
+ // Ordem: SILENTIUM_BINARY -> vendor/ -> build local do cargo.
62
+ function resolveBinary() {
63
+ const override = process.env.SILENTIUM_BINARY;
64
+ if (override && fs.existsSync(override)) return override;
65
+ const vendored = vendorBinary();
66
+ if (fs.existsSync(vendored)) return vendored;
67
+ const built = localBuildBinary();
68
+ if (built) return built;
69
+ return null;
70
+ }
71
+
72
+ function download(url, destination, redirects = 0) {
73
+ return new Promise((resolve, reject) => {
74
+ if (redirects > 5) return reject(new Error("redirects demais"));
75
+ https
76
+ .get(url, { headers: { "user-agent": `silentium-npm/${packageVersion()}` } }, (res) => {
77
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
78
+ res.resume();
79
+ return resolve(download(res.headers.location, destination, redirects + 1));
80
+ }
81
+ if (res.statusCode !== 200) {
82
+ res.resume();
83
+ return reject(new Error(`HTTP ${res.statusCode} em ${url}`));
84
+ }
85
+ const file = fs.createWriteStream(destination);
86
+ res.pipe(file);
87
+ file.on("finish", () => file.close(() => resolve(destination)));
88
+ file.on("error", reject);
89
+ })
90
+ .on("error", reject);
91
+ });
92
+ }
93
+
94
+ async function fetchText(url) {
95
+ const tmp = path.join(os.tmpdir(), `silentium-${process.pid}-${Date.now()}.txt`);
96
+ await download(url, tmp);
97
+ const text = fs.readFileSync(tmp, "utf8");
98
+ fs.rmSync(tmp, { force: true });
99
+ return text;
100
+ }
101
+
102
+ function sha256(file) {
103
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
104
+ }
105
+
106
+ function extract(archive, tag, into) {
107
+ if (tag.platform === "windows") {
108
+ execFileSync(
109
+ "powershell",
110
+ ["-NoProfile", "-NonInteractive", "-Command", `Expand-Archive -Path '${archive}' -DestinationPath '${into}' -Force`],
111
+ { stdio: "inherit" }
112
+ );
113
+ } else {
114
+ execFileSync("tar", ["-xzf", archive, "-C", into], { stdio: "inherit" });
115
+ }
116
+ }
117
+
118
+ async function downloadRelease(tag) {
119
+ const version = packageVersion();
120
+ const base = `https://github.com/${REPO}/releases/download/v${version}`;
121
+ const asset = assetName(tag);
122
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "silentium-"));
123
+ const archive = path.join(tmpDir, asset);
124
+
125
+ await download(`${base}/${asset}`, archive);
126
+
127
+ let expected = null;
128
+ try {
129
+ const sums = await fetchText(`${base}/SHASUMS256.txt`);
130
+ const line = sums.split("\n").find((l) => l.trim().endsWith(asset));
131
+ if (line) expected = line.trim().split(/\s+/)[0];
132
+ } catch {
133
+ // release sem checksums: segue, mas avisa
134
+ }
135
+
136
+ if (expected) {
137
+ const actual = sha256(archive);
138
+ if (actual !== expected) {
139
+ fs.rmSync(tmpDir, { recursive: true, force: true });
140
+ throw new Error(`checksum não bate: esperado ${expected}, obtido ${actual}`);
141
+ }
142
+ } else {
143
+ console.warn("[silentium] aviso: SHASUMS256.txt ausente no release, pulando verificação");
144
+ }
145
+
146
+ extract(archive, tag, tmpDir);
147
+ const candidates = [
148
+ path.join(tmpDir, binaryName()),
149
+ path.join(tmpDir, "silentium", binaryName()),
150
+ ];
151
+ const found = candidates.find((p) => fs.existsSync(p));
152
+ if (!found) {
153
+ fs.rmSync(tmpDir, { recursive: true, force: true });
154
+ throw new Error("binário não encontrado dentro do arquivo baixado");
155
+ }
156
+
157
+ fs.mkdirSync(VENDOR, { recursive: true });
158
+ const target = vendorBinary();
159
+ fs.copyFileSync(found, target);
160
+ if (process.platform !== "win32") fs.chmodSync(target, 0o755);
161
+ fs.rmSync(tmpDir, { recursive: true, force: true });
162
+ return target;
163
+ }
164
+
165
+ function buildFromSource() {
166
+ const cargoToml = path.join(PKG_ROOT, "Cargo.toml");
167
+ if (!fs.existsSync(cargoToml)) {
168
+ throw new Error("sem Cargo.toml: este pacote não traz código-fonte para compilar");
169
+ }
170
+ execFileSync("cargo", ["build", "--release", "--locked"], {
171
+ cwd: PKG_ROOT,
172
+ stdio: "inherit",
173
+ });
174
+ const built = localBuildBinary();
175
+ if (!built) throw new Error("cargo terminou sem produzir o binário");
176
+ fs.mkdirSync(VENDOR, { recursive: true });
177
+ const target = vendorBinary();
178
+ fs.copyFileSync(built, target);
179
+ if (process.platform !== "win32") fs.chmodSync(target, 0o755);
180
+ return target;
181
+ }
182
+
183
+ // Instala o binário se ainda não estiver presente: release -> cargo.
184
+ async function ensureBinary({ quiet = false } = {}) {
185
+ const existing = resolveBinary();
186
+ if (existing) return existing;
187
+
188
+ const tag = platformTag();
189
+ if (tag && !isMusl()) {
190
+ try {
191
+ const target = await downloadRelease(tag);
192
+ if (!quiet) console.log(`[silentium] binário instalado: ${target}`);
193
+ return target;
194
+ } catch (err) {
195
+ if (!quiet) console.warn(`[silentium] download falhou (${err.message}); tentando compilar`);
196
+ }
197
+ } else if (!quiet) {
198
+ console.warn(`[silentium] sem binário pronto para ${process.platform}/${process.arch}; compilando`);
199
+ }
200
+
201
+ const target = buildFromSource();
202
+ if (!quiet) console.log(`[silentium] binário compilado: ${target}`);
203
+ return target;
204
+ }
205
+
206
+ module.exports = {
207
+ ensureBinary,
208
+ REPO,
209
+ PKG_ROOT,
210
+ VENDOR,
211
+ packageVersion,
212
+ platformTag,
213
+ assetName,
214
+ binaryName,
215
+ vendorBinary,
216
+ resolveBinary,
217
+ downloadRelease,
218
+ buildFromSource,
219
+ isMusl,
220
+ };