fediverse-scripts/nginx_ua_block_pleroma_reje...

59 lines
1.5 KiB
Bash
Executable File

#!/bin/zsh
# Generates an nginx-map of User-Agents to block from the rejected domains in
# mrf_simple.
# Save the output to a file and include it in an nginx configuration file. Then
# add `if ($blockedagent) { return 403; }` to your server blocks.
# Version: 2019-08-17_2
function get_domains() # Outputs domains, separated by newline.
{
local instance="${1}"
local nodeinfo=$(curl -s "https://${instance}/nodeinfo/2.1.json")
local domains_json=$(jq -c '.metadata.federation.mrf_simple.reject' \
<<<"${nodeinfo}")
sed -e 's/\[//' -e 's/\]//' -e 's/"//g' -e 's/,/\n/g' <<<"${domains_json}"
}
function print_entry()
{
local domain="${1}"
# Filter out wildcard domains.
if ! [[ "${domain}" =~ "\*" ]]; then
domain=$(sed 's/\./\\./g' <<<${domain})
echo " ~*${domain} 1;"
fi
}
function main()
{
local instance="${1}"
if [[ -z "${instance}" ]]; then
echo "Usage: ${ZSH_ARGZERO} instance" >&2
echo " ${ZSH_ARGZERO} instance > /etc/nginx/useragents_fedi.rules"
return 1
fi
if ! command -v curl > /dev/null; then
echo "Error: curl not found. Please install it." >&2
return 2
fi
if ! command -v jq > /dev/null; then
echo "Error: jq not found. Please install it." >&2
return 2
fi
echo 'map $http_user_agent $blockedagent {'
echo " default 0;"
for domain in $(get_domains "${instance}"); do
print_entry "${domain}"
done
echo "}"
}
main "${1}"