Capítulo 13 Clientes, groupware & CLI Admin: #pApiAuth

Referencia de nextxch-cli: comandos, caché de esquemas, consultas jq & IaC GitOps

Con nextxch-cli gestiona dominios, buzones, listas de distribución, alias, claves de API con ámbito, rutas SMTP salientes (incl. excepciones TLS), calentamiento de IP, Reputation Shield y zonas DNS directamente desde su terminal o desde pipelines de CI/CD (Ansible, GitLab CI, GitHub Actions), con recarga en caliente del clúster en 0 ms y sin reinicios.

Consejo operativo y nota de arquitectura

Preinstalado en el PATH de serie: el instalador .msi de Windows (C:\Program Files\nextxch\nextxch-cli.cmd), el paquete .deb de Debian/Ubuntu (/usr/bin/nextxch-cli), install.sh (/usr/local/bin/nextxch-cli) y la imagen OCI registran nextxch-cli automáticamente. Pase siempre las credenciales mediante NEXTXCH_API_KEY (o NEXTXCH_TOKEN) para que los secretos nunca aparezcan en los argumentos del proceso.

1. Invocación, variables de entorno, autenticación & códigos de salida

Funciona de forma idéntica en el propio host de correo o de forma remota desde cualquier estación de trabajo de administración o runner de CI a través de HTTPS.

Referencia / configuración
# 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. Descubrimiento del esquema (describe), consultas filtradas (query) & pipelines jq

Con --json, get imprime un único objeto JSON compacto, mientras que query transmite JSON delimitado por saltos de línea (NDJSON), listo para jq o PowerShell.

Referencia / configuración
# 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. Crear, modificar y eliminar objetos (create, update, delete · @file.json & stdin)

Los escalares, booleanos, números y arrays separados por comas se convierten automáticamente con --set key=value; las cargas JSON anidadas se pasan con --data @file.json o por stdin (-).

Referencia / configuración
# 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. Comprobaciones DNS en vivo, exportación de zona BIND & GitOps declarativo (snapshot & apply --dry-run)

Cada línea de un plan .ndjson describe una operación idempotente (upsert o delete); los comentarios # y // se admiten de forma nativa para las revisiones de código en Git.

Referencia / configuración
# Ö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

Configuración, valores predeterminados y buenas prácticas

Ajuste / ubicación Descripción Valor predeterminado Buena práctica de producción
Globale Flags & Umgebungsvariablen Controla la URL del servidor (--url / NEXTXCH_URL), la clave de API (--api-key, --token / NEXTXCH_API_KEY, NEXTXCH_TOKEN), la autenticación Basic (-u/-p), el modo JSON (--json), TLS de laboratorio (--insecure / -k), los colores (--no-color / NO_COLOR) y la traza HTTP (--debug / NEXTXCH_DEBUG=1). URL: http://localhost Exporte siempre NEXTXCH_URL + NEXTXCH_API_KEY y pase --json en los scripts de automatización; reserve --insecure (-k) estrictamente para laboratorios locales de staging.
describe [Type] (Schema & Offline-Cache) Enumera los 12 tipos de objetos del servidor o inspecciona cada campo, tipo y variante de enum de un objeto concreto, y almacena el esquema en caché local según X-Nextxch-Schema-Version. Lokaler XDG/AppData-Cache Ejecute nextxch-cli describe <Type> antes de crear scripts para nuevas políticas (p. ej., nextxch-cli describe TransactionalSend); rol mínimo: ComplianceAuditor.
get <Type> [IdOrName] [--json] Obtiene un único objeto de colección por nombre, correo electrónico, slug o GUID, o lee una política global singleton ('singleton' se deduce automáticamente). Kartenansicht / 1-Zeilen-JSON Para los singletons, omita el ID: nextxch-cli get SpamGuard o nextxch-cli get ReputationShield --json.
query <Type> (Alias: list) Busca en colecciones con filtros AND separados por comas (--filter k=v,k2=v2), proyección de columnas (--fields a,b,c) y --limit N. Con --json emite NDJSON estricto (1 objeto JSON por línea). Tabelle / NDJSON-Stream Ideal para auditorías de seguridad: nextxch-cli query Account --json | jq -r 'select(.twoFactorEnabled==false) | .email' enumera las cuentas sin 2FA.
create <Type[/Variant]> & update <Type> (Alias: patch) Crea nuevos elementos de colección o modifica campos individuales de objetos/singletons existentes sin sobrescribir las propiedades no modificadas (recarga en caliente del clúster en 0 ms). --set k=v · @file.json · stdin Pase los campos escalares/de array mediante --set key=value (arrays separados por comas) y las políticas anidadas complejas mediante --data @policy.json o stdin (--data -).
delete <Type> <IdOrName> (Alias: rm) Desactiva de forma segura (soft) dominios/cuentas, elimina alias secundarios o rutas personalizadas y revoca de inmediato las claves de API con ámbito. Schutz vor Selbstlöschung Una protección integrada contra bloqueos impide eliminar la clave de API o el principal de administrador con el que se ha autenticado actualmente.
dns <Domain> [--live] [--bind] [-o Datei] Verifica en vivo MX, SPF, Dual-DKIM (RSA-2048 + Ed25519), DMARC, MTA-STS, DANE TLSA y BIMI contra el DNS público o exporta un archivo de zona BIND según RFC 1035. Advisor-Tabelle / BIND-Zone Justo después de crear un dominio, ejecute nextxch-cli dns company.com --bind -o company.com.zone para importar todos los registros limpiamente, sin errores tipográficos de copiar y pegar.
snapshot & apply --dry-run (GitOps IaC) snapshot exporta el estado completo del servidor o del inquilino como operaciones NDJSON ordenadas; apply ejecuta planes (admite comentarios # y //) de forma idempotente. Atomarer Zeilen-Bericht Condicione siempre los despliegues de CI/CD a nextxch-cli apply -f plan.ndjson --dry-run (sale con 1 y diagnósticos exactos por línea si alguna entrada no es válida).
Sammlungen: Tenant, Domain, Account, Alias Gestiona inquilinos (ServerAdmin), dominios con generación automática de claves Dual-DKIM, buzones de usuario (Account/User), listas de distribución (Account/List) y alias (incl. isMasked). Rolle: TenantAdmin+ Ejecutar create Domain --set dkimSigningMode=Dual genera de inmediato y automáticamente los dos pares de claves, RSA-2048 y Ed25519.
Sammlungen: ApiKey & Route (OutboundRoute) ApiKey emite tokens smk_ inmutables limitados por rol y CIDR (rotación mediante create + delete). Route gestiona smart hosts por dominio y excepciones de certificados TLS. ApiKey: TenantAdmin+ · Route: ServerAdmin Cuando el MX de un socio falla con RemoteCertificateNameMismatch, ejecute: nextxch-cli create Route --set domain=partner.com --set tlsMode=StartTlsIgnoreCert (targetHost vacío = Auto DNS-MX).
Singletons: TransactionalSend & ReputationShield Controla el calentamiento de IP/dominio, las categorías y las cuotas por proveedor (TransactionalSend), junto con listas de supresión, FBL ARF, baja según RFC 8058 y cortacircuitos (ReputationShield). Presets per 1 Befehl Configuración rápida mediante presets: nextxch-cli update TransactionalSend --set preset=warming_28d y nextxch-cli update ReputationShield --set preset=recommended.
Singletons: SpamGuard, SmtpQueue, TransportRules & Server Configura umbrales de spam y ClamAV (SpamGuard), workers de la cola, smart host y política TLS (SmtpQueue), avisos legales y Fail2Ban (TransportRules), y serverHostName (Server). Rolle: ServerAdmin Actualización del nombre de host sin tiempo de inactividad: nextxch-cli update Server --set serverHostName=mail.company.com actualiza en vivo EHLO, banners y Autodiscover.