Add automatic token generation for security

This commit is contained in:
Andreas Dueren
2025-06-16 12:36:46 -06:00
parent 2fa272436e
commit 63f67862d0

View File

@ -26,7 +26,11 @@ if [ ! -f "$CONFIG_PATH" ]; then
# Generate config as root first, then fix permissions
/app/pkg/mautrix-whatsapp -g -c "$CONFIG_PATH" -r "$REGISTRATION_PATH" || {
echo "=> Config generation failed, creating minimal config"
cat > "$CONFIG_PATH" << 'EOF'
# Generate secure random tokens
AS_TOKEN=$(openssl rand -hex 32)
HS_TOKEN=$(openssl rand -hex 32)
cat > "$CONFIG_PATH" << EOF
homeserver:
address: https://matrix.example.com
domain: example.com
@ -35,6 +39,8 @@ appservice:
address: https://example.com
hostname: 0.0.0.0
port: 29318
as_token: $AS_TOKEN
hs_token: $HS_TOKEN
database:
type: postgres
uri: postgres://user:pass@localhost/db
@ -51,11 +57,11 @@ logging:
filename: /app/data/mautrix-whatsapp.log
level: info
EOF
cat > "$REGISTRATION_PATH" << 'EOF'
cat > "$REGISTRATION_PATH" << EOF
id: whatsapp
url: https://example.com
as_token: generated_token
hs_token: generated_token
as_token: $AS_TOKEN
hs_token: $HS_TOKEN
rate_limited: false
sender_localpart: whatsappbot
namespaces:
@ -116,7 +122,7 @@ else
yq -i ".logging.level = \"info\"" "$CONFIG_PATH" 2>/dev/null || true
fi
# Fix homeserver domain configuration
# Fix homeserver domain configuration and tokens
if [ -n "${CLOUDRON_APP_DOMAIN:-}" ]; then
BASE_DOMAIN=$(echo "$CLOUDRON_APP_DOMAIN" | cut -d. -f2-)
CURRENT_DOMAIN=$(yq -r ".homeserver.domain // empty" "$CONFIG_PATH" 2>/dev/null)
@ -126,6 +132,32 @@ else
yq -i ".homeserver.domain = \"$BASE_DOMAIN\"" "$CONFIG_PATH"
yq -i ".appservice.address = \"https://$CLOUDRON_APP_DOMAIN\"" "$CONFIG_PATH"
fi
# Update registration file with correct URL
if [ -f "$REGISTRATION_PATH" ]; then
yq -i ".url = \"https://$CLOUDRON_APP_DOMAIN\"" "$REGISTRATION_PATH" 2>/dev/null || true
fi
fi
# Ensure tokens exist
if [ -f "$CONFIG_PATH" ] && [ -f "$REGISTRATION_PATH" ]; then
AS_TOKEN=$(yq -r ".as_token // empty" "$REGISTRATION_PATH" 2>/dev/null)
HS_TOKEN=$(yq -r ".hs_token // empty" "$REGISTRATION_PATH" 2>/dev/null)
# Generate tokens if missing
if [ -z "$AS_TOKEN" ] || [ "$AS_TOKEN" = "generated_token" ]; then
AS_TOKEN=$(openssl rand -hex 32)
echo "=> Generating new as_token"
yq -i ".as_token = \"$AS_TOKEN\"" "$REGISTRATION_PATH" 2>/dev/null || true
yq -i ".appservice.as_token = \"$AS_TOKEN\"" "$CONFIG_PATH" 2>/dev/null || true
fi
if [ -z "$HS_TOKEN" ] || [ "$HS_TOKEN" = "generated_token" ]; then
HS_TOKEN=$(openssl rand -hex 32)
echo "=> Generating new hs_token"
yq -i ".hs_token = \"$HS_TOKEN\"" "$REGISTRATION_PATH" 2>/dev/null || true
yq -i ".appservice.hs_token = \"$HS_TOKEN\"" "$CONFIG_PATH" 2>/dev/null || true
fi
fi
fi
fi