#pApiAuth
Referência do nextxch-cli: comandos, cache de esquema, consultas jq & GitOps IaC
Com o nextxch-cli, você gerencia domínios, caixas de correio, listas de distribuição, aliases, chaves de API com escopo, rotas SMTP de saída (incl. substituições de TLS), aquecimento de IP, Reputation Shield e zonas DNS diretamente do seu terminal ou de pipelines de CI/CD (Ansible, GitLab CI, GitHub Actions) - com hot reload do cluster em 0 ms e sem reinicializações.
Pré-instalado no PATH de fábrica: o instalador .msi para Windows (C:\Program Files\nextxch\nextxch-cli.cmd), o pacote .deb para Debian/Ubuntu (/usr/bin/nextxch-cli), o install.sh (/usr/local/bin/nextxch-cli) e a imagem OCI registram o nextxch-cli automaticamente. Sempre passe as credenciais via NEXTXCH_API_KEY (ou NEXTXCH_TOKEN) para que segredos nunca apareçam nos argumentos do processo.
1. Invocação, variáveis de ambiente, autenticação & códigos de saída
Funciona de forma idêntica no próprio host de e-mail ou remotamente a partir de qualquer estação de trabalho de administração ou runner de CI via HTTPS.
# Linux / macOS / GitLab CI / GitHub Actions:
export NEXTXCH_URL="https://mail.firma.de"
export NEXTXCH_API_KEY="smk_01968f2a_..." # Alias: NEXTXCH_TOKEN
# PowerShell (Windows Server / Admin-Workstation):
$env:NEXTXCH_URL = "https://mail.firma.de"
$env:NEXTXCH_API_KEY = "smk_01968f2a_..."
# Docker-Host ohne lokalen Wrapper (direkt im Container):
docker exec -i nextxch nextxch-cli describe
# Interaktive Erst-Anmeldung vor dem ersten API-Key (fragt Passwort verdeckt ab, nur ohne 2FA):
nextxch-cli --url https://localhost --insecure -u admin@firma.de create ApiKey \
--set label="Ansible Prod" --set role=ServerAdmin --set allowedCidrs=10.0.0.0/8 --set expiresInDays=90
# Hilfe zu jedem Unterbefehl direkt im Terminal + definierte Exit-Codes für Skripte:
nextxch-cli --help
nextxch-cli help create
# Exit-Codes: 0 = Erfolg · 1 = HTTP-/Auth-/Server-Fehler · 2 = Ungültige CLI-Parameter / JSON
2. Descoberta de esquema (describe), consultas filtradas (query) & pipelines jq
Com --json, get imprime um único objeto JSON compacto, enquanto query transmite JSON delimitado por quebras de linha (NDJSON), pronto para jq ou PowerShell.
# Alle 12 verfügbaren Objekttypen oder die Felder eines einzelnen Typs anzeigen:
nextxch-cli describe
nextxch-cli describe Route
nextxch-cli describe TransactionalSend
# Einzelnes Objekt oder globale Singleton-Konfiguration lesen:
nextxch-cli get Domain firma.de
nextxch-cli get SmtpQueue --json | jq '{paused: .outboundQueuePaused, tls: .outboundTlsCertValidation}'
# Gefilterte Tabellen-Abfrage mit Spaltenprojektion:
nextxch-cli query Account --filter domain=firma.de,isActive=true --fields email,role,quotaMb,twoFactorEnabled
# NDJSON-Pipeline (Bash + jq): Alle aktiven Admin-Konten ohne 2FA auflisten:
nextxch-cli query Account --filter isActive=true --json \
| jq -r 'select(.role != "User" and .twoFactorEnabled == false) | "\(.email)\t\(.role)"'
# PowerShell-Pipeline auf Windows Server: Postfächer > 80 % Quota finden:
nextxch-cli query Account --json | ForEach-Object { $_ | ConvertFrom-Json } |
Where-Object { $_.quotaMb -gt 0 -and ($_.usedBytes / 1MB) -gt ($_.quotaMb * 0.8) } |
Select-Object email, quotaMb, @{N="UsedMB";E={[math]::Round($_.usedBytes/1MB,1)}}
3. Criar, alterar & excluir objetos (create, update, delete · @file.json & stdin)
Escalares, booleanos, números e arrays separados por vírgula são convertidos automaticamente via --set key=value; passe payloads JSON aninhados via --data @file.json ou stdin (-).
# 1. Domain mit Dual-DKIM (RSA-2048 + Ed25519) und 10 Jahren GoBD-Aufbewahrung anlegen:
nextxch-cli create Domain \
--set name=firma.de \
--set dkimSigningMode=Dual \
--set retentionLockMode=Compliance \
--set retentionDays=3650
# 2. Benutzerpostfach, Verteilerliste & Datenschutz-Alias anlegen:
nextxch-cli create Account/User --set email=buchhaltung@firma.de --set displayName="Buchhaltung" --set password='...' --set quotaMb=15360
nextxch-cli create Account/List --set email=rechnung@firma.de --set members=buchhaltung@firma.de,archiv@firma.de
nextxch-cli create Alias --set address=info@firma.de --set target=buchhaltung@firma.de --set description="Zentrale"
# 3. Scoped API-Key für Webshop/ERP (nur /api/v1/send, feste Absenderadresse & Subnetz-Filter):
nextxch-cli create ApiKey \
--set label="Shopware Produktion" \
--set role=User \
--set senderAddress=bestellung@firma.de \
--set defaultCategory=transactional \
--set allowedCidrs=10.20.0.0/16,198.51.100.12/32 \
--set expiresInDays=180
# 4. Ausgehende Route / TLS-Ausnahme für Partner-MX mit RemoteCertificateNameMismatch (Auto DNS-MX):
nextxch-cli create Route --set domain=neff.me --set tlsMode=StartTlsIgnoreCert --set description="Shared-MX TLS Override"
# 5. IP-Warming & Reputation Shield aktivieren oder JSON per Pipe (stdin) übergeben:
nextxch-cli update TransactionalSend --set preset=warming_28d
nextxch-cli update ReputationShield --set preset=recommended
echo '{"junkScoreThreshold":4.2,"clamAvEnabled":true}' | nextxch-cli update SpamGuard --data -
4. Verificações de DNS ao vivo, exportação de zona BIND & GitOps declarativo (snapshot & apply --dry-run)
Cada linha de um plano .ndjson descreve uma operação idempotente (upsert ou delete); comentários com # e // são suportados nativamente para revisões de código no Git.
# Öffentliche DNS-Einträge live gegen die konfigurierten DKIM/DMARC/TLSA-Werte prüfen & als BIND-Zone speichern:
nextxch-cli dns firma.de --live
nextxch-cli dns firma.de --bind --output firma.de.zone
# Aktuellen Serverzustand als versionierbaren NDJSON-Plan exportieren (ohne Geheimnisse für Git):
nextxch-cli snapshot Domain Account Alias Route TransactionalSend ReputationShield --output infra/mail-prod.ndjson
# Beispiel für deklarative Zeilen in infra/mail-prod.ndjson (inkl. Kommentaren & gezieltem Löschen):
# {"op":"upsert","type":"Domain","key":"firma.de","fields":{"name":"firma.de","dkimSigningMode":"Dual","retentionDays":3650}}
# {"op":"upsert","type":"Route","key":"neff.me","fields":{"domain":"neff.me","tlsMode":"StartTlsIgnoreCert","enabled":true}}
# {"op":"delete","type":"Alias","key":"alt-kampagne@firma.de"}
# CI/CD Pull-Request Check (verändert NICHTS in der Datenbank, Exit-Code != 0 bei Fehlern):
nextxch-cli apply --file infra/mail-prod.ndjson --dry-run
# Nach Freigabe idempotent auf Produktion anwenden:
nextxch-cli apply --file infra/mail-prod.ndjson
Configurações, valores padrão e boas práticas
| Configuração / local | Descrição | Valor padrão | Boa prática para produção |
|---|---|---|---|
Globale Flags & Umgebungsvariablen |
Controla a URL do servidor (--url / NEXTXCH_URL), a chave de API (--api-key, --token / NEXTXCH_API_KEY, NEXTXCH_TOKEN), autenticação Basic (-u/-p), modo JSON (--json), TLS de laboratório (--insecure / -k), cores (--no-color / NO_COLOR) e trace HTTP (--debug / NEXTXCH_DEBUG=1). | URL: http://localhost |
Sempre exporte NEXTXCH_URL + NEXTXCH_API_KEY e passe --json em scripts de automação; reserve --insecure (-k) estritamente para laboratórios locais de staging. |
describe [Type] (Schema & Offline-Cache) |
Lista todos os 12 tipos de objetos do servidor ou inspeciona cada campo, tipo e variante de enum de um objeto específico, armazenando o esquema em cache localmente por X-Nextxch-Schema-Version. | Lokaler XDG/AppData-Cache |
Execute nextxch-cli describe <Type> antes de criar scripts para novas políticas (por exemplo, nextxch-cli describe TransactionalSend); função mínima: ComplianceAuditor. |
get <Type> [IdOrName] [--json] |
Busca um único objeto de coleção por nome, e-mail, slug ou GUID, ou lê uma política global singleton ('singleton' é inferido automaticamente). | Kartenansicht / 1-Zeilen-JSON |
Para singletons, omita o ID: nextxch-cli get SpamGuard ou nextxch-cli get ReputationShield --json. |
query <Type> (Alias: list) |
Pesquisa coleções com filtros AND separados por vírgula (--filter k=v,k2=v2), projeção de colunas (--fields a,b,c) e --limit N. Emite NDJSON estrito (1 objeto JSON por linha) com --json. | Tabelle / NDJSON-Stream |
Ideal para auditorias de segurança: nextxch-cli query Account --json | jq -r 'select(.twoFactorEnabled==false) | .email' lista as contas sem 2FA. |
create <Type[/Variant]> & update <Type> (Alias: patch) |
Cria novos itens de coleção ou altera campos individuais em objetos/singletons existentes sem sobrescrever propriedades não alteradas (hot reload no cluster em 0 ms). | --set k=v · @file.json · stdin |
Passe campos escalares/de array via --set key=value (arrays separados por vírgula) e políticas aninhadas complexas via --data @policy.json ou stdin (--data -). |
delete <Type> <IdOrName> (Alias: rm) |
Desativa domínios/contas de forma segura (soft), exclui aliases secundários ou rotas personalizadas e revoga chaves de API com escopo imediatamente. | Schutz vor Selbstlöschung |
A proteção integrada contra bloqueio impede a exclusão da chave de API ou do principal de administrador atualmente autenticado. |
dns <Domain> [--live] [--bind] [-o Datei] |
Verifica MX, SPF, Dual-DKIM (RSA-2048 + Ed25519), DMARC, MTA-STS, DANE TLSA e BIMI ao vivo no DNS público ou exporta um arquivo de zona BIND conforme RFC 1035. | Advisor-Tabelle / BIND-Zone |
Logo após criar um domínio, execute nextxch-cli dns company.com --bind -o company.com.zone para importar todos os registros de forma limpa, sem erros de copiar e colar. |
snapshot & apply --dry-run (GitOps IaC) |
snapshot exporta o estado completo do servidor ou do locatário como operações NDJSON ordenadas; apply executa planos (com suporte a comentários # e //) de forma idempotente. | Atomarer Zeilen-Bericht |
Condicione sempre as implantações de CI/CD a nextxch-cli apply -f plan.ndjson --dry-run (sai com código 1 e diagnóstico exato por linha se alguma entrada for inválida). |
Sammlungen: Tenant, Domain, Account, Alias |
Gerencia locatários (ServerAdmin), domínios com geração automática de chaves Dual-DKIM, caixas de correio de usuários (Account/User), listas de distribuição (Account/List) e aliases (incl. isMasked). | Rolle: TenantAdmin+ |
Executar create Domain --set dkimSigningMode=Dual gera automática e imediatamente os dois pares de chaves RSA-2048 e Ed25519. |
Sammlungen: ApiKey & Route (OutboundRoute) |
ApiKey emite tokens smk_ imutáveis com escopo por função e CIDR (rotação via create + delete). Route gerencia smart hosts por domínio e substituições de certificado TLS. | ApiKey: TenantAdmin+ · Route: ServerAdmin |
Quando um MX parceiro falhar com RemoteCertificateNameMismatch, execute: nextxch-cli create Route --set domain=partner.com --set tlsMode=StartTlsIgnoreCert (targetHost vazio = Auto DNS-MX). |
Singletons: TransactionalSend & ReputationShield |
Controla o aquecimento de IP/domínio, categorias e cotas por provedor (TransactionalSend), além de listas de supressão, ARF FBL, cancelamento de inscrição RFC 8058 e circuit breakers (ReputationShield). | Presets per 1 Befehl |
Configuração rápida via presets: nextxch-cli update TransactionalSend --set preset=warming_28d e nextxch-cli update ReputationShield --set preset=recommended. |
Singletons: SpamGuard, SmtpQueue, TransportRules & Server |
Configura limites de spam & ClamAV (SpamGuard), workers da fila, smart host & política TLS (SmtpQueue), disclaimers & Fail2Ban (TransportRules) e serverHostName (Server). | Rolle: ServerAdmin |
Atualização do hostname sem downtime: nextxch-cli update Server --set serverHostName=mail.company.com atualiza EHLO, banners e Autodiscover ao vivo. |