@alexfgregio/kortex 0.0.0-stage → 1.13.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/README.md +63 -2
- package/compose/.env.example +24 -0
- package/compose/docker-compose.yml +58 -0
- package/dist/commands/backup.js +20 -0
- package/dist/commands/init.js +90 -0
- package/dist/commands/misc.js +15 -0
- package/dist/commands/rollback.js +38 -0
- package/dist/commands/uninstall.js +78 -0
- package/dist/commands/update.js +38 -0
- package/dist/context.js +7 -0
- package/dist/docker.js +52 -0
- package/dist/env.js +61 -0
- package/dist/health.js +26 -0
- package/dist/index.js +148 -0
- package/dist/runner.js +42 -0
- package/dist/secrets.js +24 -0
- package/dist/state.js +17 -0
- package/package.json +25 -4
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @alexfgregio/kortex
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CLI para instalar e operar o [Kortex](https://hub.docker.com/r/alexfgregio/kortex) pelo Docker: instala,
|
|
4
|
+
atualiza, salva e restaura uma instância sem copiar arquivos à mão. Funciona no Linux, no Mac e no Windows.
|
|
5
|
+
|
|
6
|
+
Este pacote **não contém o Kortex**: só orquestra o `docker compose`. A imagem `alexfgregio/kortex` é privada;
|
|
7
|
+
você precisa do **token de leitura do Docker Hub** que o mantenedor entrega (o `init` pede o `docker login`
|
|
8
|
+
sozinho quando o download é negado).
|
|
9
|
+
|
|
10
|
+
## Requisitos
|
|
11
|
+
|
|
12
|
+
- Node >= 20
|
|
13
|
+
- Docker com o plugin Compose v2 (`docker compose version`)
|
|
14
|
+
- Uma chave do Gemini (opcional na instalação): <https://aistudio.google.com/apikey>
|
|
15
|
+
|
|
16
|
+
## Instalar
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @alexfgregio/kortex init kortex
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
O `init` pergunta o usuário (e-mail) e a senha do administrador (o que você digita aparece na tela; Enter gera uma senha), a porta e o endereço, e então:
|
|
23
|
+
|
|
24
|
+
1. gera a senha do banco, a chave-mestra e, se você não digitou, a senha do administrador (10+ caracteres e diferente do usuário);
|
|
25
|
+
2. escreve `docker-compose.yml` e `.env` (só o dono lê) na pasta;
|
|
26
|
+
3. baixa as imagens, sobe tudo e espera o `/api/health`;
|
|
27
|
+
4. mostra a URL, o usuário e a senha do administrador **uma única vez**, num bloco no fim, e tira a senha do `.env`.
|
|
28
|
+
|
|
29
|
+
Para scripts: `kortex init pasta --yes --email admin@empresa.com --url https://kortex.empresa.com`
|
|
30
|
+
(`--google-api-key-stdin` lê a chave do Gemini pela entrada padrão).
|
|
31
|
+
|
|
32
|
+
## Comandos
|
|
33
|
+
|
|
34
|
+
Rode na pasta da instalação (a que tem o `docker-compose.yml` e o `.env`).
|
|
35
|
+
|
|
36
|
+
| Comando | O que faz |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `kortex status` | Contêineres e saúde |
|
|
39
|
+
| `kortex update [versão]` | Backup → troca a versão → baixa → sobe → espera ficar saudável |
|
|
40
|
+
| `kortex backup` | Dump em `backups/kortex-AAAA-MM-DD-HHMMSS.dump` |
|
|
41
|
+
| `kortex rollback` | Restaura o backup do último `update` e volta a versão anterior |
|
|
42
|
+
| `kortex logs [-f]` | Log do app |
|
|
43
|
+
| `kortex start` / `kortex stop` | Sobe ou para os contêineres |
|
|
44
|
+
| `kortex uninstall [--purge] [--yes]` | Remove os contêineres e mantém banco, `.env` e backups. `--purge` apaga também o banco, as imagens e os arquivos da instalação (pede o nome da pasta). `--yes` não pergunta; sem terminal e sem `--yes`, não faz nada |
|
|
45
|
+
|
|
46
|
+
## Quem já está em produção
|
|
47
|
+
|
|
48
|
+
Funciona na pasta criada pelo guia manual, sem mudar o nome do projeto nem o volume do banco. Em produção,
|
|
49
|
+
fixe a versão da CLI:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx @alexfgregio/kortex@1.13.0 update
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Sem versão, o `update` vai para a versão da própria CLI. O `rollback` apaga o que foi gravado depois do
|
|
56
|
+
backup; o volume não é apagado.
|
|
57
|
+
|
|
58
|
+
## Sem Node
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
docker compose -f oci://docker.io/alexfgregio/kortex-compose:1.13.0 up -d
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
(com o `.env` na pasta; veja `compose/.env.example`, que vem neste pacote).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Versão da imagem. Em produção, fixe a versão (ex.: 1.13.0) em vez de latest.
|
|
2
|
+
KORTEX_VERSION=latest
|
|
3
|
+
|
|
4
|
+
# Chave do Gemini (https://aistudio.google.com/apikey): modelo e embeddings.
|
|
5
|
+
GOOGLE_API_KEY=
|
|
6
|
+
KORTEX_MODEL=gemini-3.8-flash
|
|
7
|
+
|
|
8
|
+
# Senha do banco: só letras e números (ela entra numa URL de conexão).
|
|
9
|
+
# Vale só na primeira subida; depois, mudar aqui não muda a senha do banco.
|
|
10
|
+
KORTEX_DB_PASSWORD=
|
|
11
|
+
|
|
12
|
+
# Administrador criado na primeira subida (só se ainda não houver usuários). Senha com 10+ caracteres.
|
|
13
|
+
KORTEX_ADMIN_EMAIL=admin@exemplo.com
|
|
14
|
+
KORTEX_ADMIN_PASSWORD=
|
|
15
|
+
|
|
16
|
+
# Chave-mestra que cifra as chaves dos provedores (docker compose run --rm app kortex-web secret-key).
|
|
17
|
+
KORTEX_SECRET_KEY=
|
|
18
|
+
|
|
19
|
+
# Porta publicada na máquina.
|
|
20
|
+
KORTEX_PORT=8080
|
|
21
|
+
|
|
22
|
+
# Endereço que o navegador usa. Testando na máquina: http://localhost:8080. Num servidor com HTTPS na
|
|
23
|
+
# frente: https://kortex.suaempresa.com (liga o cookie seguro e o HSTS).
|
|
24
|
+
KORTEX_PUBLIC_URL=http://localhost:8080
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Kortex a partir da imagem do Docker Hub. Preencha o .env (veja .env.example) e rode: docker compose up -d
|
|
2
|
+
# Esta é a fonte única do compose de produção: ela é publicada como artefato OCI
|
|
3
|
+
# (alexfgregio/kortex-compose) e embutida na CLI `kortex`.
|
|
4
|
+
services:
|
|
5
|
+
postgres:
|
|
6
|
+
image: pgvector/pgvector:pg17
|
|
7
|
+
restart: unless-stopped
|
|
8
|
+
environment:
|
|
9
|
+
POSTGRES_USER: kortex
|
|
10
|
+
POSTGRES_PASSWORD: ${KORTEX_DB_PASSWORD:?defina KORTEX_DB_PASSWORD no .env}
|
|
11
|
+
POSTGRES_DB: kortex
|
|
12
|
+
volumes:
|
|
13
|
+
- kortex-pgdata:/var/lib/postgresql/data
|
|
14
|
+
healthcheck:
|
|
15
|
+
test: ["CMD-SHELL", "pg_isready -U kortex -d kortex"]
|
|
16
|
+
interval: 5s
|
|
17
|
+
timeout: 3s
|
|
18
|
+
retries: 10
|
|
19
|
+
|
|
20
|
+
app:
|
|
21
|
+
image: alexfgregio/kortex:${KORTEX_VERSION:-latest}
|
|
22
|
+
restart: unless-stopped
|
|
23
|
+
depends_on:
|
|
24
|
+
postgres:
|
|
25
|
+
condition: service_healthy
|
|
26
|
+
ports:
|
|
27
|
+
- target: 8080
|
|
28
|
+
published: "${KORTEX_PORT:-8080}"
|
|
29
|
+
# Sem env_file: as variáveis vêm do .env da pasta (interpolação), então o mesmo arquivo serve
|
|
30
|
+
# para `docker compose up` e para `docker compose -f oci://… up`.
|
|
31
|
+
environment:
|
|
32
|
+
KORTEX_DATABASE_URL: postgresql://kortex:${KORTEX_DB_PASSWORD}@postgres:5432/kortex
|
|
33
|
+
GOOGLE_API_KEY: ${GOOGLE_API_KEY:-}
|
|
34
|
+
KORTEX_PUBLIC_URL: ${KORTEX_PUBLIC_URL:-http://localhost:8080}
|
|
35
|
+
KORTEX_ADMIN_EMAIL: ${KORTEX_ADMIN_EMAIL:-}
|
|
36
|
+
KORTEX_ADMIN_PASSWORD: ${KORTEX_ADMIN_PASSWORD:-}
|
|
37
|
+
KORTEX_SECRET_KEY: ${KORTEX_SECRET_KEY:-}
|
|
38
|
+
KORTEX_SECRET_KEYS_OLD: ${KORTEX_SECRET_KEYS_OLD:-}
|
|
39
|
+
KORTEX_ALLOW_PRIVATE_PROVIDERS: ${KORTEX_ALLOW_PRIVATE_PROVIDERS:-false}
|
|
40
|
+
KORTEX_TRUSTED_PROXIES: ${KORTEX_TRUSTED_PROXIES:-127.0.0.1}
|
|
41
|
+
KORTEX_UI_ENABLED: ${KORTEX_UI_ENABLED:-true}
|
|
42
|
+
KORTEX_MODEL: ${KORTEX_MODEL:-gemini-3.8-flash}
|
|
43
|
+
KORTEX_TEACH_LIMIT_PER_DAY: ${KORTEX_TEACH_LIMIT_PER_DAY:-50}
|
|
44
|
+
KORTEX_RATE_LIMIT_PER_MINUTE: ${KORTEX_RATE_LIMIT_PER_MINUTE:-60}
|
|
45
|
+
KORTEX_ATTACHMENT_MAX_BYTES: ${KORTEX_ATTACHMENT_MAX_BYTES:-10485760}
|
|
46
|
+
KORTEX_MODEL_TIMEOUT_SECONDS: ${KORTEX_MODEL_TIMEOUT_SECONDS:-30}
|
|
47
|
+
KORTEX_TOOL_TIMEOUT_SECONDS: ${KORTEX_TOOL_TIMEOUT_SECONDS:-15}
|
|
48
|
+
KORTEX_TOOL_MAX_CALLS: ${KORTEX_TOOL_MAX_CALLS:-8}
|
|
49
|
+
KORTEX_TOOL_RESULT_MAX_CHARS: ${KORTEX_TOOL_RESULT_MAX_CHARS:-8000}
|
|
50
|
+
KORTEX_TOOL_AUDIT_RETENTION_DAYS: ${KORTEX_TOOL_AUDIT_RETENTION_DAYS:-180}
|
|
51
|
+
KORTEX_GROUNDED_HISTORY_TURNS: ${KORTEX_GROUNDED_HISTORY_TURNS:-6}
|
|
52
|
+
KORTEX_RELEVANCE_THRESHOLD:
|
|
53
|
+
KORTEX_TEACH_PREFIXES:
|
|
54
|
+
KORTEX_API_KEYS:
|
|
55
|
+
KORTEX_CONFIG:
|
|
56
|
+
|
|
57
|
+
volumes:
|
|
58
|
+
kortex-pgdata:
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { CliError } from "../docker.js";
|
|
4
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
5
|
+
export function stamp(d) {
|
|
6
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
7
|
+
}
|
|
8
|
+
/** pg_dump no formato custom, copiado byte a byte (o `>` do PowerShell 5.1 corromperia o dump). */
|
|
9
|
+
export async function backup(ctx) {
|
|
10
|
+
const dir = join(ctx.cwd, "backups");
|
|
11
|
+
mkdirSync(dir, { recursive: true });
|
|
12
|
+
const path = join(dir, `kortex-${stamp(ctx.now())}.dump`);
|
|
13
|
+
const res = await ctx.docker.compose(["exec", "-T", "postgres", "pg_dump", "-U", "kortex", "-d", "kortex", "-Fc"], { toFile: path });
|
|
14
|
+
if (res.code !== 0) {
|
|
15
|
+
rmSync(path, { force: true });
|
|
16
|
+
throw new CliError(`O backup falhou (o Postgres está de pé?):\n${res.stderr.trim()}`);
|
|
17
|
+
}
|
|
18
|
+
ctx.io.out(`Backup salvo em ${path}`);
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { envPath } from "../context.js";
|
|
4
|
+
import { CliError } from "../docker.js";
|
|
5
|
+
import { clearEnv, setEnv, writeEnvFile } from "../env.js";
|
|
6
|
+
import { generateAdminPassword, generateDbPassword, validateAdminPassword } from "../secrets.js";
|
|
7
|
+
const MAX_PASSWORD_TRIES = 5;
|
|
8
|
+
/** Pede a senha com o texto visível; Enter gera uma. Repete até a senha valer para o app. */
|
|
9
|
+
async function askAdminPassword(ctx, email) {
|
|
10
|
+
for (let i = 0; i < MAX_PASSWORD_TRIES; i++) {
|
|
11
|
+
const typed = await ctx.io.ask("Senha do administrador (visível; Enter para gerar uma)", { fallback: "" });
|
|
12
|
+
if (!typed)
|
|
13
|
+
return generateAdminPassword();
|
|
14
|
+
const problem = validateAdminPassword(typed, email);
|
|
15
|
+
if (!problem)
|
|
16
|
+
return typed;
|
|
17
|
+
ctx.io.out(problem);
|
|
18
|
+
}
|
|
19
|
+
throw new CliError("Senha do administrador inválida demais vezes. Rode o init de novo.");
|
|
20
|
+
}
|
|
21
|
+
export async function init(ctx, opts) {
|
|
22
|
+
if (existsSync(envPath(ctx))) {
|
|
23
|
+
throw new CliError(`Já existe um .env em ${ctx.cwd}. Para atualizar essa instalação use: kortex update`);
|
|
24
|
+
}
|
|
25
|
+
await ctx.docker.requireCompose();
|
|
26
|
+
const email = opts.email ??
|
|
27
|
+
(opts.yes ? "" : await ctx.io.ask("E-mail do administrador", { fallback: "admin@exemplo.com" }));
|
|
28
|
+
if (!email)
|
|
29
|
+
throw new CliError("Informe o e-mail do administrador com --email.");
|
|
30
|
+
const port = opts.port ?? (opts.yes ? "8080" : await ctx.io.ask("Porta", { fallback: "8080" }));
|
|
31
|
+
const url = opts.url ??
|
|
32
|
+
(opts.yes
|
|
33
|
+
? `http://localhost:${port}`
|
|
34
|
+
: await ctx.io.ask("Endereço que o navegador usa", { fallback: `http://localhost:${port}` }));
|
|
35
|
+
let googleKey = "";
|
|
36
|
+
if (opts.googleKeyStdin)
|
|
37
|
+
googleKey = (await ctx.io.readStdin()).trim();
|
|
38
|
+
else if (!opts.yes) {
|
|
39
|
+
googleKey = await ctx.io.ask("GOOGLE_API_KEY (Enter para configurar depois na tela Provedores)", {
|
|
40
|
+
secret: true,
|
|
41
|
+
fallback: "",
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const adminPassword = opts.yes ? generateAdminPassword() : await askAdminPassword(ctx, email);
|
|
45
|
+
let env = readFileSync(join(ctx.bundleDir, ".env.example"), "utf8");
|
|
46
|
+
for (const [key, value] of Object.entries({
|
|
47
|
+
KORTEX_VERSION: ctx.version,
|
|
48
|
+
GOOGLE_API_KEY: googleKey,
|
|
49
|
+
KORTEX_DB_PASSWORD: generateDbPassword(),
|
|
50
|
+
KORTEX_ADMIN_EMAIL: email,
|
|
51
|
+
KORTEX_ADMIN_PASSWORD: adminPassword,
|
|
52
|
+
KORTEX_PORT: port,
|
|
53
|
+
KORTEX_PUBLIC_URL: url,
|
|
54
|
+
})) {
|
|
55
|
+
env = setEnv(env, key, value);
|
|
56
|
+
}
|
|
57
|
+
mkdirSync(ctx.cwd, { recursive: true });
|
|
58
|
+
copyFileSync(join(ctx.bundleDir, "docker-compose.yml"), join(ctx.cwd, "docker-compose.yml"));
|
|
59
|
+
writeEnvFile(envPath(ctx), env);
|
|
60
|
+
ctx.io.out(`Arquivos escritos em ${ctx.cwd} (docker-compose.yml e .env).`);
|
|
61
|
+
ctx.io.out("Baixando as imagens...");
|
|
62
|
+
await ctx.docker.pull();
|
|
63
|
+
const secretKey = await ctx.docker.secretKey();
|
|
64
|
+
if (secretKey) {
|
|
65
|
+
env = setEnv(env, "KORTEX_SECRET_KEY", secretKey);
|
|
66
|
+
writeEnvFile(envPath(ctx), env);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
ctx.io.err("Aviso: não consegui gerar a KORTEX_SECRET_KEY; o cadastro de provedores fica desligado. " +
|
|
70
|
+
"Gere depois com: docker compose run --rm app kortex-web secret-key");
|
|
71
|
+
}
|
|
72
|
+
await ctx.docker.up();
|
|
73
|
+
ctx.io.out("Aguardando o Kortex ficar saudável (a primeira subida migra o banco)...");
|
|
74
|
+
const base = `http://127.0.0.1:${port}`;
|
|
75
|
+
const health = await ctx.health(`${base}/api/health`);
|
|
76
|
+
if (!health.ready) {
|
|
77
|
+
throw new CliError("O Kortex não ficou saudável a tempo. A senha do admin continua no .env. Veja: kortex logs");
|
|
78
|
+
}
|
|
79
|
+
const bar = "=".repeat(60);
|
|
80
|
+
ctx.io.out(`\n${bar}`);
|
|
81
|
+
ctx.io.out(` Kortex no ar: ${url}`);
|
|
82
|
+
ctx.io.out(` usuário: ${email}`);
|
|
83
|
+
ctx.io.out(` senha: ${adminPassword}`);
|
|
84
|
+
ctx.io.out(" (aparece só agora; troque a senha na tela Usuários)");
|
|
85
|
+
ctx.io.out(bar);
|
|
86
|
+
if (health.aiProvider === false) {
|
|
87
|
+
ctx.io.out(" Falta um provedor de IA: use Provedores → Comece em um clique, ou GOOGLE_API_KEY no .env.");
|
|
88
|
+
}
|
|
89
|
+
writeEnvFile(envPath(ctx), clearEnv(env, "KORTEX_ADMIN_PASSWORD"));
|
|
90
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { healthUrl } from "../context.js";
|
|
2
|
+
import { CliError } from "../docker.js";
|
|
3
|
+
async function inherit(ctx, args) {
|
|
4
|
+
const res = await ctx.docker.compose(args, { inherit: true });
|
|
5
|
+
if (res.code !== 0)
|
|
6
|
+
throw new CliError(`docker compose ${args[0]} falhou (código ${res.code}).`);
|
|
7
|
+
}
|
|
8
|
+
export async function status(ctx) {
|
|
9
|
+
await inherit(ctx, ["ps"]);
|
|
10
|
+
const h = await ctx.health(healthUrl(ctx));
|
|
11
|
+
ctx.io.out(h.ready ? `Saúde: ${h.status}` : "Saúde: o app não respondeu em /api/health");
|
|
12
|
+
}
|
|
13
|
+
export const logs = (ctx, follow) => inherit(ctx, follow ? ["logs", "-f", "--tail", "200", "app"] : ["logs", "--tail", "200", "app"]);
|
|
14
|
+
export const start = (ctx) => inherit(ctx, ["up", "-d"]);
|
|
15
|
+
export const stop = (ctx) => inherit(ctx, ["stop"]);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { envPath, healthUrl } from "../context.js";
|
|
3
|
+
import { CliError } from "../docker.js";
|
|
4
|
+
import { readEnvFile, setEnv, writeEnvFile } from "../env.js";
|
|
5
|
+
import { readState } from "../state.js";
|
|
6
|
+
/** Restaura o backup do último `update` e volta a versão anterior, sem apagar o volume. */
|
|
7
|
+
export async function rollback(ctx) {
|
|
8
|
+
const state = readState(ctx.cwd);
|
|
9
|
+
if (!state) {
|
|
10
|
+
ctx.io.out("Não há atualização registrada; nada para desfazer.");
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
if (!existsSync(state.backup))
|
|
14
|
+
throw new CliError(`O backup ${state.backup} não existe mais.`);
|
|
15
|
+
ctx.io.out(`Voltando para a ${state.versaoAnterior}. Tudo gravado depois do backup será perdido.`);
|
|
16
|
+
await ctx.docker.compose(["stop", "app"]);
|
|
17
|
+
const db = await ctx.docker.compose(["up", "-d", "--wait", "postgres"]);
|
|
18
|
+
if (db.code !== 0)
|
|
19
|
+
throw new CliError(`Não consegui subir o Postgres:\n${db.stderr.trim()}`);
|
|
20
|
+
// O --clean só apaga o que está no dump: tabelas criadas por uma migração nova ficariam e a
|
|
21
|
+
// migração falharia ao rodar de novo. Recriar o schema equivale a restaurar num banco limpo
|
|
22
|
+
// (o dump traz a extensão vector de volta).
|
|
23
|
+
const reset = await ctx.docker.compose([
|
|
24
|
+
"exec", "-T", "postgres", "psql", "-U", "kortex", "-d", "kortex", "-v", "ON_ERROR_STOP=1",
|
|
25
|
+
"-c", "DROP SCHEMA public CASCADE; CREATE SCHEMA public;",
|
|
26
|
+
]);
|
|
27
|
+
if (reset.code !== 0)
|
|
28
|
+
throw new CliError(`Não consegui limpar o banco antes de restaurar:\n${reset.stderr.trim()}`);
|
|
29
|
+
const restore = await ctx.docker.compose(["exec", "-T", "postgres", "pg_restore", "-U", "kortex", "-d", "kortex", "--clean", "--if-exists"], { fromFile: state.backup });
|
|
30
|
+
if (restore.code !== 0)
|
|
31
|
+
throw new CliError(`O pg_restore falhou:\n${restore.stderr.trim()}`);
|
|
32
|
+
writeEnvFile(envPath(ctx), setEnv(readEnvFile(envPath(ctx)), "KORTEX_VERSION", state.versaoAnterior));
|
|
33
|
+
await ctx.docker.up();
|
|
34
|
+
const health = await ctx.health(healthUrl(ctx));
|
|
35
|
+
if (!health.ready)
|
|
36
|
+
throw new CliError("Restaurei o backup, mas o app não ficou saudável. Veja: kortex logs");
|
|
37
|
+
ctx.io.out(`Restaurado: versão ${state.versaoAnterior} com os dados de ${state.quando}.`);
|
|
38
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { existsSync, readdirSync, rmSync, rmdirSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { CliError } from "../docker.js";
|
|
4
|
+
/** O que o `init` cria na pasta; qualquer outro arquivo é da pessoa e fica. */
|
|
5
|
+
const INSTALL_FILES = ["docker-compose.yml", ".env", ".kortex", "backups"];
|
|
6
|
+
const isYes = (answer) => /^(s|sim|y|yes)$/i.test(answer.trim());
|
|
7
|
+
/**
|
|
8
|
+
* Todas as perguntas vêm antes de qualquer comando do Docker. Sem terminal, `ask` devolve o padrão
|
|
9
|
+
* ("n"), então o comando não faz nada.
|
|
10
|
+
*/
|
|
11
|
+
async function confirm(ctx, purge) {
|
|
12
|
+
const folder = basename(ctx.cwd);
|
|
13
|
+
const ok = await ctx.io.ask(`Remover os contêineres do Kortex em ${ctx.cwd}?`, { fallback: "n" });
|
|
14
|
+
if (!isYes(ok)) {
|
|
15
|
+
ctx.io.out("Nada foi alterado.");
|
|
16
|
+
return "no";
|
|
17
|
+
}
|
|
18
|
+
let wipe = purge;
|
|
19
|
+
if (!wipe) {
|
|
20
|
+
const data = await ctx.io.ask("Apagar também os dados (banco, imagens, .env e backups)? Não tem volta. (s/n)", { fallback: "n" });
|
|
21
|
+
wipe = isYes(data);
|
|
22
|
+
}
|
|
23
|
+
if (wipe) {
|
|
24
|
+
const typed = await ctx.io.ask(`Para apagar os dados, digite o nome da pasta (${folder})`, { fallback: "" });
|
|
25
|
+
if (typed.trim() !== folder) {
|
|
26
|
+
throw new CliError(`O nome da pasta não confere (esperado: ${folder}). Nada foi apagado.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return wipe ? "wipe" : "keep";
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* No Windows não dá para apagar a pasta que é o diretório atual do próprio processo (EBUSY), então
|
|
33
|
+
* sai dela antes. Se ainda assim falhar, a pasta vazia fica e a pessoa é avisada: os dados já foram.
|
|
34
|
+
*/
|
|
35
|
+
function removeFolderIfEmpty(ctx) {
|
|
36
|
+
if (readdirSync(ctx.cwd).length > 0)
|
|
37
|
+
return;
|
|
38
|
+
try {
|
|
39
|
+
process.chdir(dirname(ctx.cwd));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// worker sem chdir (testes) ou pasta já inacessível: tenta apagar mesmo assim
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
rmdirSync(ctx.cwd);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
ctx.io.err(`Não consegui apagar a pasta vazia ${ctx.cwd}; apague à mão se quiser.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export async function uninstall(ctx, opts) {
|
|
52
|
+
if (!existsSync(join(ctx.cwd, "docker-compose.yml"))) {
|
|
53
|
+
throw new CliError(`Não achei docker-compose.yml em ${ctx.cwd}. Rode o comando na pasta da instalação.`);
|
|
54
|
+
}
|
|
55
|
+
let wipe = Boolean(opts.purge);
|
|
56
|
+
if (!opts.yes) {
|
|
57
|
+
const answer = await confirm(ctx, wipe);
|
|
58
|
+
if (answer === "no")
|
|
59
|
+
return;
|
|
60
|
+
wipe = answer === "wipe";
|
|
61
|
+
}
|
|
62
|
+
const args = wipe ? ["down", "-v", "--rmi", "all", "--remove-orphans"] : ["down", "--remove-orphans"];
|
|
63
|
+
const res = await ctx.docker.compose(args);
|
|
64
|
+
if (res.code !== 0) {
|
|
65
|
+
throw new CliError(`docker compose down falhou:\n${(res.stderr || res.stdout).trim()}`);
|
|
66
|
+
}
|
|
67
|
+
if (wipe) {
|
|
68
|
+
for (const name of INSTALL_FILES)
|
|
69
|
+
rmSync(join(ctx.cwd, name), { recursive: true, force: true });
|
|
70
|
+
removeFolderIfEmpty(ctx);
|
|
71
|
+
ctx.io.out("Kortex desinstalado e dados apagados.");
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
ctx.io.out("Contêineres removidos. Os dados continuam no volume, no .env e em backups/.");
|
|
75
|
+
ctx.io.out("Para subir de novo: kortex start. Para apagar tudo: kortex uninstall --purge");
|
|
76
|
+
}
|
|
77
|
+
ctx.io.out("Para remover a CLI: npm uninstall -g @alexfgregio/kortex");
|
|
78
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { envPath, healthUrl } from "../context.js";
|
|
3
|
+
import { CliError } from "../docker.js";
|
|
4
|
+
import { getEnv, readEnvFile, setEnv, writeEnvFile } from "../env.js";
|
|
5
|
+
import { writeState } from "../state.js";
|
|
6
|
+
import { backup } from "./backup.js";
|
|
7
|
+
/** Backup → troca KORTEX_VERSION → pull → up → health. Sem backup, nada muda. */
|
|
8
|
+
export async function update(ctx, version) {
|
|
9
|
+
if (!existsSync(envPath(ctx))) {
|
|
10
|
+
throw new CliError("Não achei o .env nesta pasta. Rode o comando na pasta da instalação.");
|
|
11
|
+
}
|
|
12
|
+
const target = version ?? ctx.version;
|
|
13
|
+
const before = readEnvFile(envPath(ctx));
|
|
14
|
+
const previous = getEnv(before, "KORTEX_VERSION") || "latest";
|
|
15
|
+
const backupPath = await backup(ctx);
|
|
16
|
+
writeEnvFile(envPath(ctx), setEnv(before, "KORTEX_VERSION", target));
|
|
17
|
+
try {
|
|
18
|
+
await ctx.docker.pull();
|
|
19
|
+
await ctx.docker.up();
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
writeEnvFile(envPath(ctx), before);
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
// Só registra depois que a versão trocou de fato: o rollback não pode ler um update que não houve.
|
|
26
|
+
writeState(ctx.cwd, {
|
|
27
|
+
versaoAnterior: previous,
|
|
28
|
+
versaoNova: target,
|
|
29
|
+
backup: backupPath,
|
|
30
|
+
quando: ctx.now().toISOString(),
|
|
31
|
+
});
|
|
32
|
+
ctx.io.out(`Aguardando o Kortex ${target} ficar saudável...`);
|
|
33
|
+
const health = await ctx.health(healthUrl(ctx));
|
|
34
|
+
if (!health.ready) {
|
|
35
|
+
throw new CliError(`O Kortex ${target} não ficou saudável a tempo. Para voltar à ${previous} e restaurar o backup: kortex rollback`);
|
|
36
|
+
}
|
|
37
|
+
ctx.io.out(`Atualizado de ${previous} para ${target}.`);
|
|
38
|
+
}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { getEnv, readEnvFile } from "./env.js";
|
|
3
|
+
export const envPath = (ctx) => join(ctx.cwd, ".env");
|
|
4
|
+
export function healthUrl(ctx) {
|
|
5
|
+
const port = getEnv(readEnvFile(envPath(ctx)), "KORTEX_PORT") || "8080";
|
|
6
|
+
return `http://127.0.0.1:${port}/api/health`;
|
|
7
|
+
}
|
package/dist/docker.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export const DOCKERHUB_USER = "alexfgregio";
|
|
2
|
+
export class CliError extends Error {
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Chamadas ao `docker compose` na pasta da instalação. Nunca passa -p/--project-name: o nome do
|
|
6
|
+
* projeto (e do volume do banco) continua o da pasta, como numa instalação feita pelo guia manual.
|
|
7
|
+
*/
|
|
8
|
+
export class Docker {
|
|
9
|
+
runner;
|
|
10
|
+
cwd;
|
|
11
|
+
constructor(runner, cwd) {
|
|
12
|
+
this.runner = runner;
|
|
13
|
+
this.cwd = cwd;
|
|
14
|
+
}
|
|
15
|
+
compose(args, opts = {}) {
|
|
16
|
+
return this.runner.run("docker", ["compose", ...args], { cwd: this.cwd, ...opts });
|
|
17
|
+
}
|
|
18
|
+
async requireCompose() {
|
|
19
|
+
// Sem cwd: no `init` a pasta ainda não existe (e não deve ser criada se o Docker faltar).
|
|
20
|
+
const res = await this.runner.run("docker", ["compose", "version"]);
|
|
21
|
+
if (res.code !== 0) {
|
|
22
|
+
throw new CliError("Não encontrei o Docker com o plugin Compose v2 (docker compose version falhou). " +
|
|
23
|
+
"Instale o Docker e tente de novo.");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Baixa as imagens; se o acesso for negado, faz `docker login` e tenta de novo uma vez. */
|
|
27
|
+
async pull() {
|
|
28
|
+
let res = await this.compose(["pull"]);
|
|
29
|
+
if (res.code !== 0 && /denied|unauthorized/i.test(res.stdout + res.stderr)) {
|
|
30
|
+
const login = await this.runner.run("docker", ["login", "-u", DOCKERHUB_USER], {
|
|
31
|
+
cwd: this.cwd,
|
|
32
|
+
inherit: true,
|
|
33
|
+
});
|
|
34
|
+
if (login.code !== 0)
|
|
35
|
+
throw new CliError("O docker login falhou. Peça um token de leitura ao mantenedor.");
|
|
36
|
+
res = await this.compose(["pull"]);
|
|
37
|
+
}
|
|
38
|
+
if (res.code !== 0)
|
|
39
|
+
throw new CliError(`docker compose pull falhou:\n${(res.stderr || res.stdout).trim()}`);
|
|
40
|
+
}
|
|
41
|
+
async up(services = []) {
|
|
42
|
+
const res = await this.compose(["up", "-d", ...services]);
|
|
43
|
+
if (res.code !== 0)
|
|
44
|
+
throw new CliError(`docker compose up falhou:\n${(res.stderr || res.stdout).trim()}`);
|
|
45
|
+
}
|
|
46
|
+
/** A chave-mestra é gerada pelo próprio app, para não duplicar o formato aqui. */
|
|
47
|
+
async secretKey() {
|
|
48
|
+
const res = await this.compose(["run", "--rm", "--no-deps", "app", "kortex-web", "secret-key"]);
|
|
49
|
+
const key = res.stdout.trim().split(/\r?\n/).pop()?.trim() ?? "";
|
|
50
|
+
return res.code === 0 && key ? key : null;
|
|
51
|
+
}
|
|
52
|
+
}
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* O .env é tratado como lista de linhas: trocar uma chave não mexe em comentários, ordem
|
|
4
|
+
* nem em variáveis que o operador acrescentou.
|
|
5
|
+
*/
|
|
6
|
+
export function quoteValue(value) {
|
|
7
|
+
return /[\s#"'$\\]/.test(value) ? `"${value.replace(/(["\\$])/g, "\\$1")}"` : value;
|
|
8
|
+
}
|
|
9
|
+
function unquote(raw) {
|
|
10
|
+
const v = raw.trim();
|
|
11
|
+
if (v.length >= 2 && v.startsWith('"') && v.endsWith('"')) {
|
|
12
|
+
return v.slice(1, -1).replace(/\\(["\\$])/g, "$1");
|
|
13
|
+
}
|
|
14
|
+
if (v.length >= 2 && v.startsWith("'") && v.endsWith("'"))
|
|
15
|
+
return v.slice(1, -1);
|
|
16
|
+
return v;
|
|
17
|
+
}
|
|
18
|
+
function keyOf(line) {
|
|
19
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
|
20
|
+
return m?.[1] ?? null;
|
|
21
|
+
}
|
|
22
|
+
export function getEnv(text, key) {
|
|
23
|
+
let found;
|
|
24
|
+
for (const line of text.split(/\r?\n/)) {
|
|
25
|
+
if (keyOf(line) === key)
|
|
26
|
+
found = unquote(line.slice(line.indexOf("=") + 1));
|
|
27
|
+
}
|
|
28
|
+
return found;
|
|
29
|
+
}
|
|
30
|
+
export function setEnv(text, key, value) {
|
|
31
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
32
|
+
const lines = text.split(/\r?\n/);
|
|
33
|
+
const rendered = `${key}=${quoteValue(value)}`;
|
|
34
|
+
let replaced = false;
|
|
35
|
+
const out = lines.map((line) => {
|
|
36
|
+
if (keyOf(line) === key) {
|
|
37
|
+
replaced = true;
|
|
38
|
+
return rendered;
|
|
39
|
+
}
|
|
40
|
+
return line;
|
|
41
|
+
});
|
|
42
|
+
if (!replaced) {
|
|
43
|
+
if (out.length > 0 && out[out.length - 1] === "")
|
|
44
|
+
out.splice(out.length - 1, 0, rendered);
|
|
45
|
+
else
|
|
46
|
+
out.push(rendered);
|
|
47
|
+
}
|
|
48
|
+
return out.join(eol);
|
|
49
|
+
}
|
|
50
|
+
export function clearEnv(text, key) {
|
|
51
|
+
return setEnv(text, key, "");
|
|
52
|
+
}
|
|
53
|
+
export function readEnvFile(path) {
|
|
54
|
+
return existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
55
|
+
}
|
|
56
|
+
/** Escreve o .env com permissão só do dono (no Windows o chmod é ignorado). */
|
|
57
|
+
export function writeEnvFile(path, text) {
|
|
58
|
+
writeFileSync(path, text, { encoding: "utf8", mode: 0o600 });
|
|
59
|
+
if (process.platform !== "win32")
|
|
60
|
+
chmodSync(path, 0o600);
|
|
61
|
+
}
|
package/dist/health.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Espera o /api/health: pronto é HTTP 200 com status "ok" ou "degraded" (sem provedor de IA). */
|
|
2
|
+
export async function waitForHealth(url, opts = {}) {
|
|
3
|
+
const doFetch = opts.fetch ?? ((u) => fetch(u, { signal: AbortSignal.timeout(3000) }));
|
|
4
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
5
|
+
const now = opts.now ?? Date.now;
|
|
6
|
+
const deadline = now() + (opts.timeoutMs ?? 180_000);
|
|
7
|
+
const interval = opts.intervalMs ?? 3000;
|
|
8
|
+
let last = { ready: false };
|
|
9
|
+
for (;;) {
|
|
10
|
+
try {
|
|
11
|
+
const res = await doFetch(url);
|
|
12
|
+
if (res.ok) {
|
|
13
|
+
const body = (await res.json());
|
|
14
|
+
last = { ready: body.status === "ok" || body.status === "degraded", status: body.status, aiProvider: body.ai_provider };
|
|
15
|
+
if (last.ready)
|
|
16
|
+
return last;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// o app ainda está subindo
|
|
21
|
+
}
|
|
22
|
+
if (now() >= deadline)
|
|
23
|
+
return last;
|
|
24
|
+
await sleep(interval);
|
|
25
|
+
}
|
|
26
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import { Writable } from "node:stream";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
import { backup } from "./commands/backup.js";
|
|
9
|
+
import { init } from "./commands/init.js";
|
|
10
|
+
import { logs, start, status, stop } from "./commands/misc.js";
|
|
11
|
+
import { rollback } from "./commands/rollback.js";
|
|
12
|
+
import { uninstall } from "./commands/uninstall.js";
|
|
13
|
+
import { update } from "./commands/update.js";
|
|
14
|
+
import { CliError, Docker } from "./docker.js";
|
|
15
|
+
import { waitForHealth } from "./health.js";
|
|
16
|
+
import { realRunner } from "./runner.js";
|
|
17
|
+
const HELP = `kortex: instala e opera o Kortex pelo Docker.
|
|
18
|
+
|
|
19
|
+
Uso: kortex <comando> [opções]
|
|
20
|
+
|
|
21
|
+
Comandos:
|
|
22
|
+
init [pasta] Instala numa pasta nova: gera o .env, baixa, sobe e mostra a senha do admin
|
|
23
|
+
status Contêineres e saúde (/api/health)
|
|
24
|
+
update [versão] Backup, troca a versão, baixa, sobe e espera ficar saudável
|
|
25
|
+
backup Dump do banco em backups/kortex-AAAA-MM-DD-HHMMSS.dump
|
|
26
|
+
rollback Restaura o backup do último update e volta a versão anterior
|
|
27
|
+
logs [-f] Log do app
|
|
28
|
+
start | stop Sobe ou para os contêineres
|
|
29
|
+
uninstall Remove os contêineres e mantém os dados (--purge apaga banco, imagens e arquivos)
|
|
30
|
+
|
|
31
|
+
Opções do init: --email, --url, --port, --google-api-key-stdin, --yes
|
|
32
|
+
(pergunta usuário e senha do admin com o texto visível; Enter na senha gera uma)
|
|
33
|
+
Opções do uninstall: --purge, --yes (--yes não pergunta nada; sem terminal e sem --yes, não faz nada)
|
|
34
|
+
Rode os comandos na pasta da instalação (a que tem o docker-compose.yml e o .env).`;
|
|
35
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
36
|
+
function realIo() {
|
|
37
|
+
return {
|
|
38
|
+
out: (m) => console.log(m),
|
|
39
|
+
err: (m) => console.error(m),
|
|
40
|
+
async ask(question, opts = {}) {
|
|
41
|
+
const tty = Boolean(process.stdin.isTTY);
|
|
42
|
+
let muted = false;
|
|
43
|
+
const output = new Writable({
|
|
44
|
+
write(chunk, enc, cb) {
|
|
45
|
+
if (!muted)
|
|
46
|
+
process.stdout.write(chunk, enc);
|
|
47
|
+
cb();
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
const rl = createInterface({ input: process.stdin, output, terminal: tty });
|
|
51
|
+
const suffix = opts.fallback ? ` [${opts.fallback}]` : "";
|
|
52
|
+
process.stdout.write(`${question}${suffix}: `);
|
|
53
|
+
muted = Boolean(opts.secret);
|
|
54
|
+
const answer = await new Promise((res) => rl.question("", res));
|
|
55
|
+
muted = false;
|
|
56
|
+
rl.close();
|
|
57
|
+
if (opts.secret)
|
|
58
|
+
process.stdout.write("\n");
|
|
59
|
+
return answer.trim() || opts.fallback || "";
|
|
60
|
+
},
|
|
61
|
+
async readStdin() {
|
|
62
|
+
const chunks = [];
|
|
63
|
+
for await (const chunk of process.stdin)
|
|
64
|
+
chunks.push(chunk);
|
|
65
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
async function main(argv) {
|
|
70
|
+
const { values, positionals } = parseArgs({
|
|
71
|
+
args: argv,
|
|
72
|
+
allowPositionals: true,
|
|
73
|
+
options: {
|
|
74
|
+
email: { type: "string" },
|
|
75
|
+
url: { type: "string" },
|
|
76
|
+
port: { type: "string" },
|
|
77
|
+
"google-api-key-stdin": { type: "boolean" },
|
|
78
|
+
yes: { type: "boolean", short: "y" },
|
|
79
|
+
purge: { type: "boolean" },
|
|
80
|
+
follow: { type: "boolean", short: "f" },
|
|
81
|
+
help: { type: "boolean", short: "h" },
|
|
82
|
+
version: { type: "boolean", short: "v" },
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
|
86
|
+
const [command, arg] = positionals;
|
|
87
|
+
if (values.version) {
|
|
88
|
+
console.log(pkg.version);
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
if (values.help || !command) {
|
|
92
|
+
console.log(HELP);
|
|
93
|
+
return command || values.help ? 0 : 1;
|
|
94
|
+
}
|
|
95
|
+
const cwd = resolve(command === "init" && arg ? arg : process.cwd());
|
|
96
|
+
const ctx = {
|
|
97
|
+
cwd,
|
|
98
|
+
docker: new Docker(realRunner, cwd),
|
|
99
|
+
io: realIo(),
|
|
100
|
+
version: pkg.version,
|
|
101
|
+
bundleDir: join(here, "..", "compose"),
|
|
102
|
+
now: () => new Date(),
|
|
103
|
+
health: (url) => waitForHealth(url),
|
|
104
|
+
};
|
|
105
|
+
switch (command) {
|
|
106
|
+
case "init":
|
|
107
|
+
await init(ctx, {
|
|
108
|
+
email: values.email,
|
|
109
|
+
url: values.url,
|
|
110
|
+
port: values.port,
|
|
111
|
+
googleKeyStdin: values["google-api-key-stdin"],
|
|
112
|
+
yes: values.yes,
|
|
113
|
+
});
|
|
114
|
+
break;
|
|
115
|
+
case "status":
|
|
116
|
+
await status(ctx);
|
|
117
|
+
break;
|
|
118
|
+
case "update":
|
|
119
|
+
await update(ctx, arg);
|
|
120
|
+
break;
|
|
121
|
+
case "backup":
|
|
122
|
+
await backup(ctx);
|
|
123
|
+
break;
|
|
124
|
+
case "rollback":
|
|
125
|
+
await rollback(ctx);
|
|
126
|
+
break;
|
|
127
|
+
case "logs":
|
|
128
|
+
await logs(ctx, Boolean(values.follow));
|
|
129
|
+
break;
|
|
130
|
+
case "start":
|
|
131
|
+
await start(ctx);
|
|
132
|
+
break;
|
|
133
|
+
case "stop":
|
|
134
|
+
await stop(ctx);
|
|
135
|
+
break;
|
|
136
|
+
case "uninstall":
|
|
137
|
+
await uninstall(ctx, { purge: values.purge, yes: values.yes });
|
|
138
|
+
break;
|
|
139
|
+
default:
|
|
140
|
+
console.error(`Comando desconhecido: ${command}\n\n${HELP}`);
|
|
141
|
+
return 1;
|
|
142
|
+
}
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
145
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
146
|
+
console.error(err instanceof CliError ? err.message : err);
|
|
147
|
+
process.exit(1);
|
|
148
|
+
});
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
3
|
+
import { once } from "node:events";
|
|
4
|
+
export const realRunner = {
|
|
5
|
+
async run(cmd, args, opts = {}) {
|
|
6
|
+
const child = spawn(cmd, args, {
|
|
7
|
+
cwd: opts.cwd,
|
|
8
|
+
stdio: opts.inherit ? "inherit" : ["pipe", "pipe", "pipe"],
|
|
9
|
+
});
|
|
10
|
+
let stdout = "";
|
|
11
|
+
let stderr = "";
|
|
12
|
+
let fileDone = Promise.resolve();
|
|
13
|
+
if (!opts.inherit) {
|
|
14
|
+
if (opts.toFile) {
|
|
15
|
+
const out = createWriteStream(opts.toFile);
|
|
16
|
+
child.stdout?.pipe(out);
|
|
17
|
+
fileDone = once(out, "close");
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
child.stdout?.on("data", (chunk) => (stdout += chunk.toString("utf8")));
|
|
21
|
+
}
|
|
22
|
+
child.stderr?.on("data", (chunk) => (stderr += chunk.toString("utf8")));
|
|
23
|
+
if (opts.fromFile) {
|
|
24
|
+
const input = createReadStream(opts.fromFile);
|
|
25
|
+
input.on("error", () => child.stdin?.end());
|
|
26
|
+
input.pipe(child.stdin);
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
child.stdin?.end();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const code = await new Promise((resolve) => {
|
|
33
|
+
child.on("error", (err) => {
|
|
34
|
+
stderr += String(err);
|
|
35
|
+
resolve(127);
|
|
36
|
+
});
|
|
37
|
+
child.on("close", (c) => resolve(c ?? 1));
|
|
38
|
+
});
|
|
39
|
+
await fileDone;
|
|
40
|
+
return { code, stdout, stderr };
|
|
41
|
+
},
|
|
42
|
+
};
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { randomInt } from "node:crypto";
|
|
2
|
+
const ALNUM = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
|
|
3
|
+
/** Só letras e números: a senha do banco entra numa URL de conexão. */
|
|
4
|
+
export function randomAlnum(length) {
|
|
5
|
+
let out = "";
|
|
6
|
+
for (let i = 0; i < length; i++)
|
|
7
|
+
out += ALNUM[randomInt(ALNUM.length)];
|
|
8
|
+
return out;
|
|
9
|
+
}
|
|
10
|
+
export const generateDbPassword = () => randomAlnum(32);
|
|
11
|
+
export const generateAdminPassword = () => randomAlnum(20);
|
|
12
|
+
export const MIN_ADMIN_PASSWORD = 10;
|
|
13
|
+
/**
|
|
14
|
+
* Mesma regra do app para o primeiro admin (apps/api/src/kortex_api/auth/passwords.py): se a CLI
|
|
15
|
+
* aceitasse mais, o app ignoraria a senha e subiria sem administrador. Devolve o motivo ou null.
|
|
16
|
+
*/
|
|
17
|
+
export function validateAdminPassword(password, user) {
|
|
18
|
+
if (password.length < MIN_ADMIN_PASSWORD) {
|
|
19
|
+
return `A senha precisa ter pelo menos ${MIN_ADMIN_PASSWORD} caracteres.`;
|
|
20
|
+
}
|
|
21
|
+
if (password.toLowerCase() === user.toLowerCase())
|
|
22
|
+
return "A senha não pode ser igual ao usuário.";
|
|
23
|
+
return null;
|
|
24
|
+
}
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
const file = (dir) => join(dir, ".kortex", "estado.json");
|
|
4
|
+
export function readState(dir) {
|
|
5
|
+
if (!existsSync(file(dir)))
|
|
6
|
+
return null;
|
|
7
|
+
try {
|
|
8
|
+
return JSON.parse(readFileSync(file(dir), "utf8"));
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function writeState(dir, state) {
|
|
15
|
+
mkdirSync(join(dir, ".kortex"), { recursive: true });
|
|
16
|
+
writeFileSync(file(dir), JSON.stringify(state, null, 2) + "\n", "utf8");
|
|
17
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexfgregio/kortex",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.13.0",
|
|
4
|
+
"description": "CLI do Kortex: instala, atualiza, salva e restaura uma instância pelo Docker (init, update, backup, rollback).",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": { "kortex": "dist/index.js" },
|
|
8
|
+
"files": ["dist", "compose", "README.md"],
|
|
9
|
+
"engines": { "node": ">=20" },
|
|
10
|
+
"publishConfig": { "access": "public" },
|
|
11
|
+
"scripts": {
|
|
12
|
+
"bundle-compose": "node scripts/copy-compose.mjs",
|
|
13
|
+
"build": "node scripts/copy-compose.mjs && tsc -p tsconfig.build.json",
|
|
14
|
+
"lint": "eslint .",
|
|
15
|
+
"typecheck": "tsc --noEmit",
|
|
16
|
+
"test": "node scripts/copy-compose.mjs && vitest run"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@eslint/js": "^10.0.1",
|
|
20
|
+
"@types/node": "^24.19.2",
|
|
21
|
+
"eslint": "^10.13.0",
|
|
22
|
+
"globals": "^17.13.0",
|
|
23
|
+
"typescript": "^5.9.3",
|
|
24
|
+
"typescript-eslint": "^8.72.0",
|
|
25
|
+
"vitest": "^5.0.5"
|
|
26
|
+
}
|
|
27
|
+
}
|