caddy-cli-manager 1.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +140 -0
  3. package/bin/cli.js +496 -0
  4. package/package.json +9 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 William Moreschi
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 ADDED
@@ -0,0 +1,140 @@
1
+ # Caddy CLI Manager
2
+
3
+ CLI simples para gerenciar o **Caddyfile** de forma rápida e interativa, com zero dependências externas.
4
+
5
+ Ideal para quem trabalha com múltiplos projetos locais e precisa criar/remover domínios com frequência.
6
+
7
+ ## 🎥 Preview
8
+
9
+ <p align="center">
10
+ <img src="./docs/preview.gif" alt="preview" />
11
+ </p>
12
+
13
+ ## ⚡ Zero dependências
14
+
15
+ Este projeto foi desenvolvido utilizando apenas módulos nativos do Node.js.
16
+
17
+ Isso significa:
18
+
19
+ - 🚀 Instalação rápida
20
+ - 🔒 Mais segurança (sem dependências externas)
21
+ - 🧩 Fácil manutenção
22
+ - 💡 Código simples e direto
23
+
24
+ ## ⚠️ Requisitos
25
+
26
+ Este CLI foi desenvolvido para uso com o Caddy.
27
+
28
+ Certifique-se de ter o Caddy instalado antes de utilizar a ferramenta.
29
+
30
+ ### Instalação do Caddy
31
+
32
+ - 🌐 Guia oficial: https://caddyserver.com/docs/install
33
+
34
+ ### Windows (winget)
35
+
36
+ ```bash
37
+ winget install -e --id CaddyServer.Caddy
38
+ ```
39
+
40
+ ### WSL / Linux
41
+
42
+ ```bash
43
+ sudo apt install caddy
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 📦 Instalação
49
+
50
+ ```bash
51
+ npm install -g caddy-cli-manager
52
+ ```
53
+
54
+ ---
55
+
56
+ ## 🚀 Uso
57
+
58
+ ```bash
59
+ caddy-cli
60
+ ```
61
+
62
+ ---
63
+
64
+ ## ⚙️ Primeira execução
65
+
66
+ Na primeira vez, o CLI irá solicitar o caminho do seu `Caddyfile`.
67
+
68
+ Exemplos:
69
+
70
+ ```bash
71
+ C:\caddy\Caddyfile
72
+ ```
73
+
74
+ ou (WSL/Linux):
75
+
76
+ ```bash
77
+ /mnt/c/caddy/Caddyfile
78
+ ```
79
+
80
+ O caminho será salvo automaticamente em:
81
+
82
+ ```bash
83
+ ~/.caddy-cli.json
84
+ ```
85
+
86
+ ---
87
+
88
+ ## ✨ Funcionalidades
89
+
90
+ - ➕ Adicionar domínio
91
+ - 📄 Listar domínios
92
+ - ❌ Remover domínio
93
+ - ⚠️ Validação de porta e domínio
94
+ - 💾 Persistência de configuração
95
+
96
+ ---
97
+
98
+ ## 🔧 Opções
99
+
100
+ ### Definir caminho manualmente
101
+
102
+ ```bash
103
+ caddy-cli --file /caminho/Caddyfile
104
+ ```
105
+
106
+ ---
107
+
108
+ ### Resetar configuração
109
+
110
+ ```bash
111
+ caddy-cli --reset
112
+ ```
113
+
114
+ ---
115
+
116
+ ### Usar variável de ambiente
117
+
118
+ ```bash
119
+ CADDYFILE=/caminho/Caddyfile caddy-cli
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 💡 Observações
125
+
126
+ - Funciona em **Windows, Linux e WSL**
127
+ - Caminhos do Windows são automaticamente convertidos no WSL
128
+ - O arquivo de configuração é salvo globalmente (por usuário)
129
+
130
+ ---
131
+
132
+ ## 🧠 Motivação
133
+
134
+ Este CLI foi criado para facilitar o gerenciamento de domínios locais usando o Caddy, evitando edição manual do arquivo.
135
+
136
+ ---
137
+
138
+ ## 📄 Licença
139
+
140
+ MIT
package/bin/cli.js ADDED
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env node
2
+
3
+ const os = require("os");
4
+ const fs = require("fs");
5
+ const readline = require("readline");
6
+ const path = require("path");
7
+
8
+ const configPath = path.join(os.homedir(), ".caddy-cli.json");
9
+
10
+ let filePath;
11
+
12
+ const rl = readline.createInterface({
13
+ input: process.stdin,
14
+ output: process.stdout,
15
+ });
16
+
17
+ const commonPorts = ["80", "443"];
18
+
19
+ function normalizePath(input) {
20
+ // Detecta caminho Windows tipo C:\...
21
+ if (/^[a-zA-Z]:\\/.test(input)) {
22
+ const drive = input[0].toLowerCase();
23
+ const rest = input.slice(2).replace(/\\/g, "/");
24
+ return `/mnt/${drive}${rest}`;
25
+ }
26
+
27
+ return input;
28
+ }
29
+
30
+ function askProtocol() {
31
+ return new Promise((resolve) => {
32
+ console.log("\nEscolha o protocolo:");
33
+ console.log("[1] http");
34
+ console.log("[2] https");
35
+
36
+ rl.question("Digite o número: ", (answer) => {
37
+ if (["1", "http"].includes(answer.toLowerCase())) return resolve("http");
38
+ if (["2", "https"].includes(answer.toLowerCase()))
39
+ return resolve("https");
40
+
41
+ console.log("❌ Opção inválida. Tente novamente.");
42
+ resolve(askProtocol());
43
+ });
44
+ });
45
+ }
46
+
47
+ function askDomain() {
48
+ return new Promise((resolve) => {
49
+ rl.question("Digite o Domínio: ", (domain) => {
50
+ const result = isValidDomain(domain);
51
+ if (result === true) return resolve(domain);
52
+ console.log(result);
53
+ resolve(askDomain());
54
+ });
55
+ });
56
+ }
57
+
58
+ function askPort() {
59
+ return new Promise((resolve) => {
60
+ rl.question("Digite a Porta: ", async (port) => {
61
+ const result = isValidPort(port);
62
+
63
+ if (result !== true) {
64
+ console.log(result);
65
+ return resolve(askPort());
66
+ }
67
+
68
+ // ⚠️ Se for porta comum, pede confirmação
69
+ if (commonPorts.includes(port)) {
70
+ const confirmed = await confirmPort(port);
71
+
72
+ if (!confirmed) {
73
+ return resolve(askPort()); // refaz pergunta
74
+ }
75
+ }
76
+
77
+ resolve(port);
78
+ });
79
+ });
80
+ }
81
+
82
+ function isValidDomain(domain) {
83
+ if (!domain.trim()) return "❌ Domínio não pode ser vazio";
84
+
85
+ if (domain.includes(" ")) return "❌ Domínio não pode ter espaços";
86
+
87
+ const regex = /^[a-zA-Z0-9.-]+$/;
88
+
89
+ if (!regex.test(domain)) {
90
+ return "❌ Domínio contém caracteres inválidos";
91
+ }
92
+
93
+ return true;
94
+ }
95
+
96
+ function isValidPort(port) {
97
+ if (!port.trim()) return "❌ Porta não pode ser vazia";
98
+
99
+ if (!/^\d+$/.test(port)) {
100
+ return "❌ Porta deve conter apenas números";
101
+ }
102
+
103
+ const portNumber = Number(port);
104
+
105
+ if (portNumber < 1 || portNumber > 65535) {
106
+ return "❌ Porta deve estar entre 1 e 65535";
107
+ }
108
+
109
+ return true;
110
+ }
111
+
112
+ function confirmPort(port) {
113
+ return new Promise((resolve) => {
114
+ function ask() {
115
+ rl.question(
116
+ `⚠️ Porta ${port} é comum (80/443). Deseja continuar? (S/n): `,
117
+ (answer) => {
118
+ const value = answer.trim().toLowerCase();
119
+
120
+ // Enter vazio = SIM
121
+ if (value === "" || value === "s") return resolve(true);
122
+
123
+ if (value === "n") return resolve(false);
124
+
125
+ console.log("❌ Digite apenas S, N ou Enter");
126
+ ask(); // loop até resposta válida
127
+ },
128
+ );
129
+ }
130
+
131
+ ask();
132
+ });
133
+ }
134
+
135
+ function domainExists(domain) {
136
+ if (!fs.existsSync(filePath)) return false;
137
+
138
+ const content = fs.readFileSync(filePath, "utf-8");
139
+
140
+ return content.includes(domain);
141
+ }
142
+
143
+ function confirmOverwrite(domain) {
144
+ return new Promise((resolve) => {
145
+ function ask() {
146
+ rl.question(
147
+ `⚠️ O domínio "${domain}" já existe. Deseja sobrescrever? (S/n): `,
148
+ (answer) => {
149
+ const value = answer.trim().toLowerCase();
150
+
151
+ if (value === "" || value === "s") return resolve(true);
152
+ if (value === "n") return resolve(false);
153
+
154
+ console.log("❌ Digite apenas S, N ou Enter");
155
+ ask();
156
+ },
157
+ );
158
+ }
159
+
160
+ ask();
161
+ });
162
+ }
163
+
164
+ function removeDomainBlock(domain) {
165
+ if (!fs.existsSync(filePath)) return;
166
+
167
+ let content = fs.readFileSync(filePath, "utf-8");
168
+
169
+ // Regex que pega o bloco completo do domínio
170
+ const regex = new RegExp(`((http[s]?:\\/\\/)?${domain}\\s*\\{[^}]*\\})`, "g");
171
+
172
+ content = content.replace(regex, "").trim() + "\n";
173
+
174
+ fs.writeFileSync(filePath, content);
175
+ }
176
+
177
+ async function addDomainFlow() {
178
+ const protocol = await askProtocol();
179
+ const domain = await askDomain();
180
+
181
+ let shouldRemove = false;
182
+
183
+ if (domainExists(domain)) {
184
+ const overwrite = await confirmOverwrite(domain);
185
+
186
+ if (!overwrite) {
187
+ console.log("❌ Operação cancelada. Informe outro domínio.");
188
+ return;
189
+ }
190
+
191
+ shouldRemove = true;
192
+ }
193
+
194
+ const port = await askPort();
195
+
196
+ const block = `\n${protocol}://${domain} {\n reverse_proxy localhost:${port}\n}\n`;
197
+
198
+ if (shouldRemove) {
199
+ removeDomainBlock(domain);
200
+ }
201
+
202
+ fs.appendFileSync(filePath, block);
203
+
204
+ console.log("\n✅ Domínio adicionado com sucesso!");
205
+ }
206
+
207
+ function listDomains() {
208
+ if (!fs.existsSync(filePath)) {
209
+ console.log("📭 Nenhum domínio configurado.");
210
+ return;
211
+ }
212
+
213
+ const content = fs.readFileSync(filePath, "utf-8");
214
+
215
+ const matches = content.match(
216
+ /(http[s]?:\/\/)?([a-zA-Z0-9.-]+)\s*\{[^}]*reverse_proxy\s+localhost:(\d+)/g,
217
+ );
218
+
219
+ if (!matches) {
220
+ console.log("📭 Nenhum domínio encontrado.");
221
+ return;
222
+ }
223
+
224
+ console.log("\n📋 Domínios configurados:\n");
225
+
226
+ matches.forEach((match, index) => {
227
+ const domainMatch = match.match(/([a-zA-Z0-9.-]+)\s*\{/);
228
+ const portMatch = match.match(/localhost:(\d+)/);
229
+
230
+ const domain = domainMatch?.[1];
231
+ const port = portMatch?.[1];
232
+
233
+ console.log(`${index + 1} - ${domain} → ${port}`);
234
+ });
235
+ }
236
+
237
+ async function removeDomainFlow() {
238
+ const domains = getDomains();
239
+
240
+ if (domains.length === 0) {
241
+ console.log("📭 Nenhum domínio configurado.");
242
+ return;
243
+ }
244
+
245
+ printDomains(domains);
246
+
247
+ function ask() {
248
+ return new Promise((resolve) => {
249
+ rl.question(
250
+ "\nDigite o número do domínio para remover (ou 0 para cancelar): ",
251
+ (answer) => {
252
+ const value = answer.trim().toLowerCase();
253
+
254
+ if (value === "0") {
255
+ console.log("↩️ Cancelado.");
256
+ return resolve(null);
257
+ }
258
+
259
+ if (!/^\d+$/.test(value)) {
260
+ console.log("❌ Digite apenas números");
261
+ return resolve(ask());
262
+ }
263
+
264
+ const index = Number(value) - 1;
265
+
266
+ if (!domains[index]) {
267
+ console.log("❌ Número inválido");
268
+ return resolve(ask());
269
+ }
270
+
271
+ resolve(domains[index]);
272
+ },
273
+ );
274
+ });
275
+ }
276
+
277
+ const selected = await ask();
278
+
279
+ if (!selected) return;
280
+
281
+ // confirmação antes de remover
282
+ const confirm = await confirmDelete(selected.domain);
283
+
284
+ if (!confirm) {
285
+ console.log("❌ Remoção cancelada.");
286
+ return;
287
+ }
288
+
289
+ removeDomainBlock(selected.domain);
290
+
291
+ console.log(`🗑️ Domínio "${selected.domain}" removido com sucesso!`);
292
+ }
293
+
294
+ function confirmDelete(domain) {
295
+ return new Promise((resolve) => {
296
+ function ask() {
297
+ rl.question(
298
+ `Tem certeza que deseja remover "${domain}"? (S/n): `,
299
+ (answer) => {
300
+ const value = answer.trim().toLowerCase();
301
+
302
+ if (value === "" || value === "s") return resolve(true);
303
+ if (value === "n") return resolve(false);
304
+
305
+ console.log("❌ Digite apenas S, N ou Enter");
306
+ ask();
307
+ },
308
+ );
309
+ }
310
+
311
+ ask();
312
+ });
313
+ }
314
+
315
+ function printDomains(domains) {
316
+ console.log("\n📋 Domínios configurados:\n");
317
+
318
+ domains.forEach((item, index) => {
319
+ console.log(`${index + 1} - ${item.domain} → ${item.port}`);
320
+ });
321
+ }
322
+
323
+ function getDomains() {
324
+ if (!fs.existsSync(filePath)) return [];
325
+
326
+ const content = fs.readFileSync(filePath, "utf-8");
327
+
328
+ const regex =
329
+ /(http[s]?:\/\/)?([a-zA-Z0-9.-]+)\s*\{[^}]*reverse_proxy\s+localhost:(\d+)/g;
330
+
331
+ const domains = [];
332
+ let match;
333
+
334
+ while ((match = regex.exec(content)) !== null) {
335
+ domains.push({
336
+ fullMatch: match[0],
337
+ domain: match[2],
338
+ port: match[3],
339
+ });
340
+ }
341
+
342
+ return domains;
343
+ }
344
+
345
+ function showMenu() {
346
+ return new Promise((resolve) => {
347
+ console.log("\n=== Caddy Manager ===");
348
+ console.log("[1] Adicionar domínio");
349
+ console.log("[2] Listar domínios");
350
+ console.log("[3] Remover domínio");
351
+ console.log("[0] Sair");
352
+
353
+ rl.question("Escolha uma opção: ", (answer) => {
354
+ resolve(answer.trim());
355
+ });
356
+ });
357
+ }
358
+
359
+ function getCaddyfilePath() {
360
+ // 1. Passou a flag
361
+ const argPath = getArgValue("--file");
362
+ if (argPath) {
363
+ const resolved = path.resolve(argPath);
364
+
365
+ if (!fs.existsSync(resolved)) {
366
+ console.log("❌ Caminho passado em --file não existe.");
367
+ process.exit();
368
+ }
369
+
370
+ return resolved;
371
+ }
372
+
373
+ // 2. ENV tem prioridade
374
+ if (process.env.CADDYFILE) {
375
+ return process.env.CADDYFILE;
376
+ }
377
+
378
+ // 3. Config salvo
379
+ if (fs.existsSync(configPath)) {
380
+ try {
381
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
382
+ if (config.caddyfile && fs.existsSync(config.caddyfile)) {
383
+ return config.caddyfile;
384
+ }
385
+ } catch {
386
+ console.log("⚠️ Configuração inválida, recriando...");
387
+ }
388
+ }
389
+
390
+ return null;
391
+ }
392
+
393
+ function askCaddyfilePath() {
394
+ return new Promise((resolve) => {
395
+ function ask() {
396
+ console.log("Exemplo: C:\\caddy\\Caddyfile");
397
+ rl.question("Informe o caminho do seu Caddyfile: ", (input) => {
398
+ const raw = input.trim();
399
+
400
+ if (!raw) {
401
+ console.log("❌ Caminho não pode ser vazio");
402
+ return ask();
403
+ }
404
+
405
+ const normalized = normalizePath(raw);
406
+ const file = path.resolve(normalized);
407
+
408
+ if (!fs.existsSync(file)) {
409
+ console.log("❌ Arquivo não encontrado");
410
+ return ask();
411
+ }
412
+
413
+ resolve(file);
414
+ });
415
+ }
416
+
417
+ ask();
418
+ });
419
+ }
420
+
421
+ if (process.argv.includes("--reset")) {
422
+ if (fs.existsSync(configPath)) {
423
+ fs.unlinkSync(configPath);
424
+ console.log("🔄 Configuração resetada.");
425
+ } else {
426
+ console.log("ℹ️ Nenhuma configuração para resetar.");
427
+ }
428
+
429
+ process.exit(); // 👈 importante
430
+ }
431
+
432
+ function saveConfig(filePath) {
433
+ fs.writeFileSync(
434
+ configPath,
435
+ JSON.stringify({ caddyfile: filePath }, null, 2),
436
+ );
437
+ }
438
+
439
+ function getArgValue(flag) {
440
+ const index = process.argv.indexOf(flag);
441
+ if (index !== -1 && process.argv[index + 1]) {
442
+ return process.argv[index + 1];
443
+ }
444
+ return null;
445
+ }
446
+
447
+ async function init() {
448
+ filePath = getCaddyfilePath();
449
+
450
+ if (!filePath) {
451
+ console.log("⚙️ Configuração inicial necessária\n");
452
+
453
+ const path = await askCaddyfilePath();
454
+
455
+ saveConfig(path);
456
+
457
+ filePath = path;
458
+
459
+ console.log("✅ Caminho salvo com sucesso!\n");
460
+ console.log(`⚙️ Config salvo em: ${configPath}\n`);
461
+ }
462
+
463
+ console.log(`📁 Usando Caddyfile em: ${filePath}\n`);
464
+ }
465
+
466
+ async function main() {
467
+ await init(); // 👈 importante
468
+
469
+ while (true) {
470
+ const option = await showMenu();
471
+
472
+ switch (option) {
473
+ case "1":
474
+ await addDomainFlow();
475
+ break;
476
+
477
+ case "2":
478
+ listDomains();
479
+ break;
480
+
481
+ case "3":
482
+ await removeDomainFlow();
483
+ break;
484
+
485
+ case "0":
486
+ console.log("👋 Saindo...");
487
+ rl.close();
488
+ return;
489
+
490
+ default:
491
+ console.log("❌ Opção inválida. Use 1, 2, 3 ou 0.");
492
+ }
493
+ }
494
+ }
495
+
496
+ main();
package/package.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "caddy-cli-manager",
3
+ "version": "1.0.0",
4
+ "description": "CLI para gerenciar Caddyfile facilmente",
5
+ "bin": {
6
+ "caddy-cli": "./bin/cli.js"
7
+ },
8
+ "type": "commonjs"
9
+ }