Prototype2.2-n8n-Rechte-Problem

This commit is contained in:
2026-01-11 14:23:33 +01:00
parent 6d0cd58562
commit d5ebba844e
2 changed files with 253 additions and 196 deletions

View File

@@ -11,23 +11,19 @@ Usage:
bash install.sh [options]
Core options:
--ctid <id> Force CT ID (optional). If omitted, a customer-safe CTID is generated: (unix_time - 1000000000)
--ctid <id> Force CT ID (optional). If omitted, a customer-safe CTID is generated.
--cores <n> (default: 2)
--memory <mb> (default: 4096)
--swap <mb> (default: 512)
--disk <gb> (default: 50)
--bridge <vmbrX> (default: vmbr0)
--vlan <id> VLAN tag on net0 (default: 90)
--storage <storage> (default: local-zfs)
--ip <dhcp|CIDR> (default: dhcp)
--vlan <id> VLAN tag for net0 (default: 90)
--domain <domain> Base domain for FQDN (default: userman.de)
--privileged Create privileged CT (default: unprivileged)
--fqdn-suffix <domain> (default: userman.de) -> FQDN becomes sb-<time>.<domain>
--help Show help
Examples:
bash install.sh
bash install.sh --vlan 90 --ip dhcp
bash install.sh --ip 192.168.45.53/24 --vlan 90
EOF
}
@@ -38,11 +34,11 @@ MEMORY="4096"
SWAP="512"
DISK="50"
BRIDGE="vmbr0"
VLAN="90"
STORAGE="local-zfs"
IPCFG="dhcp"
VLAN="90"
DOMAIN="userman.de"
UNPRIV="1"
FQDN_SUFFIX="userman.de"
# ---------------------------
# Arg parsing
@@ -55,54 +51,50 @@ while [[ $# -gt 0 ]]; do
--swap) SWAP="${2:-}"; shift 2 ;;
--disk) DISK="${2:-}"; shift 2 ;;
--bridge) BRIDGE="${2:-}"; shift 2 ;;
--vlan) VLAN="${2:-}"; shift 2 ;;
--storage) STORAGE="${2:-}"; shift 2 ;;
--ip) IPCFG="${2:-}"; shift 2 ;;
--vlan) VLAN="${2:-}"; shift 2 ;;
--domain) DOMAIN="${2:-}"; shift 2 ;;
--fqdn-suffix) FQDN_SUFFIX="${2:-}"; shift 2 ;;
--privileged) UNPRIV="0"; shift 1 ;;
--help|-h) usage; exit 0 ;;
*) die "Unknown option: $1 (use --help)" ;;
esac
done
# Basic validation
is_int "$CORES" || die "--cores must be integer"
is_int "$MEMORY" || die "--memory must be integer"
is_int "$SWAP" || die "--swap must be integer"
is_int "$DISK" || die "--disk must be integer"
is_int "$VLAN" || die "--vlan must be integer"
# Validation
[[ "$CORES" =~ ^[0-9]+$ ]] || die "--cores must be integer"
[[ "$MEMORY" =~ ^[0-9]+$ ]] || die "--memory must be integer"
[[ "$SWAP" =~ ^[0-9]+$ ]] || die "--swap must be integer"
[[ "$DISK" =~ ^[0-9]+$ ]] || die "--disk must be integer"
[[ "$UNPRIV" == "0" || "$UNPRIV" == "1" ]] || die "internal: UNPRIV invalid"
[[ "$VLAN" =~ ^[0-9]+$ ]] || die "--vlan must be integer"
if [[ "$IPCFG" != "dhcp" ]]; then
[[ "$IPCFG" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$ ]] || die "--ip must be dhcp or CIDR (e.g. 192.168.45.53/24)"
[[ "$IPCFG" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$ ]] || die "--ip must be dhcp or CIDR (e.g. 192.168.45.171/24)"
fi
[[ -n "${DOMAIN}" ]] || die "--domain must not be empty"
info "Argument-Parsing OK"
# ---------------------------
# Preflight Proxmox
# ---------------------------
need_cmd pct pvesm pveam date
need_cmd pct pvesm pveam pvesh python3 grep date
pve_storage_exists "$STORAGE" || die "Storage not found: $STORAGE"
pve_bridge_exists "$BRIDGE" || die "Bridge not found: $BRIDGE"
pve_bridge_exists "$BRIDGE" || die "Bridge not found: $BRIDGE"
TEMPLATE="$(pve_template_ensure_debian12 "$STORAGE")"
info "Template OK: ${TEMPLATE}"
# Hostname based on unix time (as agreed)
UNIXTS="$(date +%s)"
CT_HOSTNAME="sb-${UNIXTS}"
FQDN="${CT_HOSTNAME}.${DOMAIN}"
# Hostname based on unix time (agreed)
CT_HOSTNAME="sb-$(date +%s)"
FQDN="${CT_HOSTNAME}.${FQDN_SUFFIX}"
# CTID selection
if [[ -n "$CTID" ]]; then
is_int "$CTID" || die "--ctid must be integer"
# nur lokal check (cluster-check war dir zu unzuverlässig)
if pct status "${CTID}" >/dev/null 2>&1; then
die "Forced CTID=${CTID} already exists on this node"
[[ "$CTID" =~ ^[0-9]+$ ]] || die "--ctid must be integer"
if pve_vmid_exists_cluster "$CTID"; then
die "Forced CTID=${CTID} already exists in cluster"
fi
else
CTID="$(pve_select_customer_ctid)"
@@ -124,7 +116,6 @@ FEATURES="nesting=1,keyctl=1,fuse=1"
info "Step 5: Create CT"
info "Creating CT ${CTID} (${CT_HOSTNAME}) from ${TEMPLATE}"
pct create "${CTID}" "${TEMPLATE}" \
--hostname "${CT_HOSTNAME}" \
--cores "${CORES}" \
@@ -152,15 +143,14 @@ info "CT_IP=${CT_IP}"
# ---------------------------
info "Step 6: Provisioning im CT (Docker + Locales + Base)"
# Base packages (include locales early, damit perl nicht meckert)
pct_exec "${CTID}" "export DEBIAN_FRONTEND=noninteractive; apt-get update -y"
pct_exec "${CTID}" "export DEBIAN_FRONTEND=noninteractive; apt-get install -y ca-certificates curl gnupg lsb-release locales"
# locales setzen (de_DE.UTF-8)
pct_exec "${CTID}" "sed -i 's/^# *de_DE.UTF-8 UTF-8/de_DE.UTF-8 UTF-8/' /etc/locale.gen || true"
pct_exec "${CTID}" "locale-gen >/dev/null"
pct_exec "${CTID}" "update-locale LANG=de_DE.UTF-8 LC_ALL=de_DE.UTF-8"
pct_exec "${CTID}" "printf 'LANG=de_DE.UTF-8\nLC_ALL=de_DE.UTF-8\n' > /etc/default/locale"
# Ensure locale exists (de_DE + en_US to be safe), then set default locale file.
pct_exec "${CTID}" "sed -i 's/^# \\(de_DE.UTF-8\\)/\\1/' /etc/locale.gen || true"
pct_exec "${CTID}" "sed -i 's/^# \\(en_US.UTF-8\\)/\\1/' /etc/locale.gen || true"
pct_exec "${CTID}" "locale-gen >/dev/null || true"
pct_exec "${CTID}" "update-locale LANG=de_DE.UTF-8 LC_ALL=de_DE.UTF-8 || true"
# Docker official repo (Debian 12 / bookworm)
pct_exec "${CTID}" "install -m 0755 -d /etc/apt/keyrings"
@@ -170,26 +160,22 @@ pct_exec "${CTID}" "echo \"deb [arch=\$(dpkg --print-architecture) signed-by=/et
pct_exec "${CTID}" "export DEBIAN_FRONTEND=noninteractive; apt-get update -y"
pct_exec "${CTID}" "export DEBIAN_FRONTEND=noninteractive; apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin"
# Create stack directories
pct_exec "${CTID}" "mkdir -p /opt/customer-stack/sql /opt/customer-stack/volumes/postgres/data /opt/customer-stack/volumes/n8n-data"
# Base directories
pct_exec "${CTID}" "mkdir -p /opt/customer-stack/volumes /opt/customer-stack/sql"
info "Step 6 OK: Docker + Compose Plugin installiert, Locales gesetzt, Basis-Verzeichnisse erstellt"
info "Next: Schritt 7 (finales docker-compose + Secrets + n8n/supabase up + Healthchecks)"
# ---------------------------
# Step 7: Stack finalisieren + Secrets + Up + Checks
# ---------------------------
info "Step 7: Stack finalisieren + Secrets + Up + Checks"
# secrets
# Generate secrets on host (safe, deterministic output), then write .env inside CT.
PG_DB="customer"
PG_USER="customer"
PG_PASSWORD="$(gen_hex 16)" # 32 hex chars
N8N_ENCRYPTION_KEY="$(gen_hex 32)" # 64 hex chars
PG_PASSWORD="$(_rand_b64url 24)"
N8N_ENCRYPTION_KEY="$(_rand_hex 32)"
# n8n URL config:
# intern bleibt http://CT_IP:5678
# extern geplant via OPNsense reverse proxy: https://FQDN
N8N_PORT="5678"
N8N_PROTOCOL="http"
N8N_HOST="${CT_IP}"
@@ -197,13 +183,13 @@ N8N_EDITOR_BASE_URL="https://${FQDN}/"
WEBHOOK_URL="https://${FQDN}/"
N8N_SECURE_COOKIE="false"
# Telemetrie / Background Calls aus
# Telemetry / background calls off
N8N_DIAGNOSTICS_ENABLED="false"
N8N_VERSION_NOTIFICATIONS_ENABLED="false"
N8N_TEMPLATES_ENABLED="false"
# write .env (in CT)
pct_exec "${CTID}" "cat > /opt/customer-stack/.env <<'ENV'
# Write env
pct exec "${CTID}" -- bash -lc "cat > /opt/customer-stack/.env <<'ENV'
PG_DB=${PG_DB}
PG_USER=${PG_USER}
PG_PASSWORD=${PG_PASSWORD}
@@ -217,19 +203,20 @@ N8N_SECURE_COOKIE=${N8N_SECURE_COOKIE}
N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
# Telemetrie/Background Calls aus (n8n docs)
N8N_DIAGNOSTICS_ENABLED=${N8N_DIAGNOSTICS_ENABLED}
N8N_VERSION_NOTIFICATIONS_ENABLED=${N8N_VERSION_NOTIFICATIONS_ENABLED}
N8N_TEMPLATES_ENABLED=${N8N_TEMPLATES_ENABLED}
ENV"
# init sql
pct_exec "${CTID}" "cat > /opt/customer-stack/sql/init_pgvector.sql <<'SQL'
# Write init SQL (pgvector)
pct exec "${CTID}" -- bash -lc "cat > /opt/customer-stack/sql/init_pgvector.sql <<'SQL'
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pgcrypto;
SQL"
# docker-compose.yml (in CT)
pct_exec "${CTID}" "cat > /opt/customer-stack/docker-compose.yml <<'YML'
# Write docker-compose.yml (final)
pct exec "${CTID}" -- bash -lc "cat > /opt/customer-stack/docker-compose.yml <<'YML'
services:
postgres:
image: pgvector/pgvector:pg16
@@ -243,7 +230,7 @@ services:
- ./volumes/postgres/data:/var/lib/postgresql/data
- ./sql:/docker-entrypoint-initdb.d:ro
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U \${PG_USER} -d \${PG_DB} || exit 1']
test: [\"CMD-SHELL\", \"pg_isready -U \${PG_USER} -d \${PG_DB} || exit 1\"]
interval: 10s
timeout: 5s
retries: 20
@@ -258,7 +245,8 @@ services:
postgres:
condition: service_healthy
ports:
- '\${N8N_PORT}:5678'
- \"\${N8N_PORT}:5678\"
user: \"1000:1000\"
environment:
N8N_PORT: 5678
N8N_PROTOCOL: \${N8N_PROTOCOL}
@@ -279,7 +267,7 @@ services:
N8N_ENCRYPTION_KEY: \${N8N_ENCRYPTION_KEY}
# Telemetrie/Background Calls aus
# Telemetry/Template/Versionschecks aus
N8N_DIAGNOSTICS_ENABLED: \${N8N_DIAGNOSTICS_ENABLED}
N8N_VERSION_NOTIFICATIONS_ENABLED: \${N8N_VERSION_NOTIFICATIONS_ENABLED}
N8N_TEMPLATES_ENABLED: \${N8N_TEMPLATES_ENABLED}
@@ -294,7 +282,12 @@ networks:
driver: bridge
YML"
# Deploy
# ---- IMPORTANT FIX: permissions BEFORE up ----
pct_exec "${CTID}" "mkdir -p /opt/customer-stack/volumes/n8n-data /opt/customer-stack/volumes/postgres/data"
pct_exec "${CTID}" "chown -R 1000:1000 /opt/customer-stack/volumes/n8n-data"
pct_exec "${CTID}" "chown -R 999:999 /opt/customer-stack/volumes/postgres/data || true"
# Pull + up
pct_exec "${CTID}" "cd /opt/customer-stack && docker compose pull"
pct_exec "${CTID}" "cd /opt/customer-stack && docker compose up -d"
pct_exec "${CTID}" "cd /opt/customer-stack && docker compose ps"
@@ -304,21 +297,16 @@ info "n8n intern: http://${CT_IP}:5678/"
info "n8n extern (geplant via OPNsense): https://${FQDN}"
info "Hinweis: Telemetrie/Template/Versionschecks sind deaktiviert (n8n docs)."
# ---------------------------
# JSON Output (NUR stdout)
# ---------------------------
# Damit kann n8n/SSH node direkt JSON parsen.
# Alles andere ist in stderr geloggt.
echo -n "{"
print_json_kv "ctid" "${CTID}"; echo -n ","
print_json_kv "hostname" "${CT_HOSTNAME}"; echo -n ","
print_json_kv "fqdn" "${FQDN}"; echo -n ","
print_json_kv "ip" "${CT_IP}"; echo -n ","
print_json_kv "n8n_internal_url" "http://${CT_IP}:5678/"; echo -n ","
print_json_kv "n8n_external_url" "https://${FQDN}/"; echo -n ","
print_json_kv "pg_db" "${PG_DB}"; echo -n ","
print_json_kv "pg_user" "${PG_USER}"; echo -n ","
print_json_kv "pg_password" "${PG_PASSWORD}"; echo -n ","
print_json_kv "n8n_encryption_key" "${N8N_ENCRYPTION_KEY}"
echo "}"
# Emit machine-readable JSON for automation (n8n can parse this)
emit_result_json \
"CTID=${CTID}" \
"CT_HOSTNAME=${CT_HOSTNAME}" \
"CT_IP=${CT_IP}" \
"VLAN=${VLAN}" \
"FQDN=${FQDN}" \
"N8N_INTERNAL_URL=http://${CT_IP}:5678/" \
"N8N_EXTERNAL_URL=https://${FQDN}/" \
"PG_DB=${PG_DB}" \
"PG_USER=${PG_USER}" \
"PG_PASSWORD=${PG_PASSWORD}" \
"N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}"

View File

@@ -1,24 +1,36 @@
#!/usr/bin/env bash
# libsupabase.sh
set -Eeuo pipefail
# ---------- logging (ALLES nach STDERR) ----------
# ---------------------------
# Logging / trap helpers
# ---------------------------
_ts() { date '+%F %T'; }
_log() {
local level="$1"; shift
# stderr, damit stdout sauber bleibt (für JSON am Ende)
echo "[$(_ts)] ${level}: $*" >&2
}
info() { _log "INFO" "$*"; }
warn() { _log "WARN" "$*"; }
err() { _log "ERROR" "$*"; }
_is_tty() { [[ -t 1 ]]; }
die() {
err "$*"
_color() {
local code="$1"; shift
if _is_tty; then printf "\033[%sm%s\033[0m" "$code" "$*"; else printf "%s" "$*"; fi
}
log() { echo "[$(_ts)] $*"; }
info() { log "$(_color '36' 'INFO:') $*"; }
warn() { log "$(_color '33' 'WARN:') $*"; }
err() { log "$(_color '31' 'ERROR:') $*"; }
die() { err "$*"; exit 1; }
on_error() {
local lineno="$1" cmd="$2" code="$3"
err "Failed at line ${lineno}: ${cmd} (exit=${code})"
exit 1
}
setup_traps() {
trap 'on_error "$LINENO" "$BASH_COMMAND" "$?"' ERR
}
need_cmd() {
local c
for c in "$@"; do
@@ -26,51 +38,13 @@ need_cmd() {
done
}
on_error() {
local lineno="$1" cmd="$2" code="$3"
err "Failed at line ${lineno}: ${cmd} (exit=${code})"
exit 1
}
# ---------------------------
# Proxmox helpers
# ---------------------------
setup_traps() {
trap 'on_error "${LINENO}" "${BASH_COMMAND}" "$?"' ERR
}
# ---------- helpers ----------
is_int() { [[ "${1:-}" =~ ^[0-9]+$ ]]; }
# pct exec wrapper
# - setzt Locale für apt/Perl stabil auf C.UTF-8 während Provisioning
pct_exec() {
local ctid="$1"; shift
need_cmd pct
# shellcheck disable=SC2029
pct exec "${ctid}" -- bash -lc "export LANG=C.UTF-8 LC_ALL=C.UTF-8; $*"
}
# wait for IP via pct (DHCP)
pct_wait_for_ip() {
local ctid="$1"
need_cmd pct awk grep
local i ip
for i in {1..60}; do
# pct exec ip addr ist zuverlässiger als pct config parsing
ip="$(pct exec "${ctid}" -- bash -lc "ip -4 -o addr show scope global | awk '{print \$4}' | head -n1 | cut -d/ -f1" 2>/dev/null || true)"
if [[ -n "${ip}" ]]; then
echo "${ip}"
return 0
fi
sleep 1
done
return 1
}
# Proxmox checks
pve_storage_exists() {
local st="$1"
need_cmd pvesm
pvesm status --storage "${st}" >/dev/null 2>&1
pvesm status --storage "$st" >/dev/null 2>&1
}
pve_bridge_exists() {
@@ -78,98 +52,193 @@ pve_bridge_exists() {
[[ -d "/sys/class/net/${br}/bridge" ]]
}
# Build net0 string (supports optional VLAN tag)
pve_build_net0() {
local bridge="$1"
local ipcfg="$2" # dhcp OR CIDR
local vlan="${3:-}" # optional integer
local net="name=eth0,bridge=${bridge}"
if [[ -n "${vlan}" ]]; then
is_int "${vlan}" || die "--vlan must be integer"
net="${net},tag=${vlan}"
fi
if [[ "${ipcfg}" == "dhcp" ]]; then
net="${net},ip=dhcp"
else
net="${net},ip=${ipcfg}"
fi
echo "${net}"
}
# Template ensure (stdout darf NUR den Template-Pfad liefern!)
# Ensure Debian 12 template. Return "storage:vztmpl/xxx.tar.zst"
pve_template_ensure_debian12() {
local preferred_store="$1"
local store="$1"
local tpl="debian-12-standard_12.12-1_amd64.tar.zst"
need_cmd pveam awk grep
local store="${preferred_store}"
# pveam kann oft nur "local"
if ! pveam list "${store}" >/dev/null 2>&1; then
# Some storages (like local-zfs) don't support templates in pveam
if ! pveam list "$store" >/dev/null 2>&1; then
warn "pveam storage '${store}' not available for templates; falling back to 'local'"
store="local"
fi
# update list
pveam update >/dev/null 2>&1 || true
pveam update >/dev/null
# download if missing
if ! pveam list "${store}" 2>/dev/null | awk '{print $2}' | grep -qx "${tpl}"; then
# If not available locally, download
if ! pveam list "$store" | awk '{print $2}' | grep -qx "$tpl"; then
info "Downloading CT template to ${store}: ${tpl}"
pveam download "${store}" "${tpl}" >/dev/null
pveam download "$store" "$tpl" >/dev/null
fi
echo "${store}:vztmpl/${tpl}"
}
# ---- CTID selection (customer-safe): (unix_time - 1_000_000_000) ----
# Keine Cluster-Abfrage mehr nötig. Nur lokale Node-Check, + increment falls belegt.
# Build net0 string with optional VLAN tag
pve_build_net0() {
local bridge="$1"
local ip="$2"
local vlan="${3:-}"
if [[ "$ip" == "dhcp" ]]; then
if [[ -n "$vlan" ]]; then
echo "name=eth0,bridge=${bridge},ip=dhcp,tag=${vlan}"
else
echo "name=eth0,bridge=${bridge},ip=dhcp"
fi
else
# static CIDR
if [[ -n "$vlan" ]]; then
echo "name=eth0,bridge=${bridge},ip=${ip},tag=${vlan}"
else
echo "name=eth0,bridge=${bridge},ip=${ip}"
fi
fi
}
pct_exec() {
local ctid="$1"; shift
# run a command inside CT with bash -lc
pct exec "$ctid" -- bash -lc "$*"
}
# Wait until CT has an IPv4 on eth0. Returns IP or empty.
pct_wait_for_ip() {
local ctid="$1"
local tries="${2:-60}"
local delay="${3:-1}"
local ip=""
while (( tries > 0 )); do
ip="$(pct exec "$ctid" -- bash -lc "ip -4 -o addr show dev eth0 2>/dev/null | awk '{print \$4}' | cut -d/ -f1 | head -n1" 2>/dev/null || true)"
if [[ -n "$ip" ]]; then
echo "$ip"
return 0
fi
sleep "$delay"
((tries--))
done
echo ""
return 1
}
# ---------------------------
# CTID strategy (your request)
# ---------------------------
# Customer-safe CTID:
# CTID = (unix_time - 1000000000)
# This is stable until 2038 and avoids collisions with typical low VMIDs.
customer_ctid_from_time() {
local now
now="$(date +%s)"
echo $(( now - 1000000000 ))
}
# Check if a VMID exists cluster-wide using pvesh.
# If pvesh fails (permissions/API), we still have a fallback.
pve_vmid_exists_cluster() {
local vmid="$1"
need_cmd pvesh python3
# pvesh returns JSON; we parse safely in python
local json
json="$(pvesh get /cluster/resources --type vm --output-format json 2>/dev/null || true)"
[[ -n "$json" ]] || return 1
python3 - "$vmid" <<'PY' 2>/dev/null
import sys, json
vmid = int(sys.argv[1])
data = json.load(sys.stdin)
for r in data:
if int(r.get("vmid", -1)) == vmid:
sys.exit(0)
sys.exit(1)
PY
}
# Select a CTID that does NOT exist cluster-wide.
pve_select_customer_ctid() {
need_cmd pct date
local ctid
ctid="$(customer_ctid_from_time)"
local base
base="$(($(date +%s) - 1000000000))"
# falls negative (sollte nicht passieren), fallback
if (( base < 100 )); then
base=100000
# If cluster check works, avoid collisions.
if pve_vmid_exists_cluster "$ctid"; then
# extremely unlikely, but add +1..+60 tries
local i
for i in $(seq 1 60); do
if ! pve_vmid_exists_cluster "$((ctid+i))"; then
echo "$((ctid+i))"
return 0
fi
done
die "CTID selection failed: all candidates busy"
fi
local ctid="${base}"
# nur lokal prüfen (pct list ist node-lokal)
while pct status "${ctid}" >/dev/null 2>&1; do
ctid="$((ctid + 1))"
done
echo "${ctid}"
echo "$ctid"
}
# Secrets ohne tr/head Pipes (kein Broken pipe)
gen_hex() {
local nbytes="$1"
is_int "${nbytes}" || die "gen_hex expects integer bytes"
need_cmd openssl
openssl rand -hex "${nbytes}"
# ---------------------------
# Secrets (no 'tr: broken pipe')
# ---------------------------
_rand_hex() {
local nbytes="${1:-32}"
if command -v openssl >/dev/null 2>&1; then
openssl rand -hex "$nbytes"
return 0
fi
if command -v python3 >/dev/null 2>&1; then
python3 - <<PY
import secrets
print(secrets.token_hex(${nbytes}))
PY
return 0
fi
# last resort: avoid pipefail by disabling locally
(
set +o pipefail
LC_ALL=C tr -dc 'a-f0-9' </dev/urandom | head -c $((nbytes*2))
)
}
_rand_b64url() {
local nbytes="${1:-32}"
if command -v python3 >/dev/null 2>&1; then
python3 - <<PY
import secrets
print(secrets.token_urlsafe(${nbytes}))
PY
return 0
fi
# fallback
(
set +o pipefail
LC_ALL=C tr -dc 'A-Za-z0-9_-'
) </dev/urandom | head -c $((nbytes*2))
}
# JSON escaper (minimal, reicht für unsere Werte)
json_escape() {
local s="${1:-}"
s="${s//\\/\\\\}"
s="${s//\"/\\\"}"
s="${s//$'\n'/\\n}"
s="${s//$'\r'/\\r}"
s="${s//$'\t'/\\t}"
echo -n "${s}"
python3 - <<'PY'
import json,sys
print(json.dumps(sys.stdin.read())[1:-1])
PY
}
# Print a JSON object (stdout). Use at the VERY end.
print_json_kv() {
# args: key value
local k="$1" v="$2"
echo -n "\"$(json_escape "$k")\":\"$(json_escape "$v")\""
emit_result_json() {
# Arguments are key=value pairs; prints a single JSON object
# Example: emit_result_json "CTID=123" "CT_IP=1.2.3.4"
python3 - "$@" <<'PY'
import sys, json
obj={}
for kv in sys.argv[1:]:
if "=" not in kv:
continue
k,v = kv.split("=",1)
obj[k]=v
print(json.dumps(obj, ensure_ascii=False))
PY
}