Last active
November 13, 2024 09:53
-
-
Save kopiro/35d3f647166c588dfd7b3c274d7307b5 to your computer and use it in GitHub Desktop.
CORS HTTPS Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
backend="$1" | |
if [ -z "$backend" ]; then | |
echo "Please provide a backend URL" | |
return | |
fi | |
port="$2" | |
if [ -z "$port" ]; then | |
port=5555 | |
fi | |
ssl_dir="$HOME/.config/https-server" | |
ssl_cert_file="${ssl_dir}/localhost.crt" | |
ssl_key_file="${ssl_dir}/localhost.key" | |
if [ ! -f "${ssl_cert_file}" ] || [ ! -f "${ssl_key_file}" ]; then | |
echo "Generating certificates and saving it in ${ssl_cert_file}..." | |
mkdir -p "${ssl_dir}" | |
openssl req -x509 -out "${ssl_cert_file}" -keyout "${ssl_key_file}" \ | |
-newkey rsa:2048 -nodes -sha256 \ | |
-subj '/CN=localhost' -extensions EXT -config <( \ | |
printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") | |
echo "Adding certificate to trusted certs, please type your password:" | |
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${ssl_cert_file}" | |
fi | |
if [ ! -f "${ssl_cert_file}" ] || [ ! -f "${ssl_key_file}" ]; then | |
echo "Can't find certificate at ${ssl_cert_file} or key at ${ssl_key_file}" | |
return; | |
fi | |
cat <<EOF > /tmp/cors_proxy.conf | |
events {} | |
http { | |
server { | |
listen ${port} ssl; | |
ssl_certificate ${ssl_cert_file}; | |
ssl_certificate_key ${ssl_key_file}; | |
access_log /dev/stdout; | |
error_log /dev/stderr; | |
location / { | |
# Handle CORS preflight requests | |
if (\$request_method = OPTIONS) { | |
add_header 'Access-Control-Allow-Origin' '*'; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; | |
add_header 'Access-Control-Allow-Headers' '*'; | |
add_header 'Access-Control-Max-Age' 86400; | |
add_header 'Content-Length' 0; | |
add_header 'Content-Type' 'text/plain charset=UTF-8'; | |
return 204; | |
} | |
# Proxy all other requests | |
proxy_pass $backend; | |
add_header 'Access-Control-Allow-Origin' '*'; | |
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; | |
add_header 'Access-Control-Allow-Headers' '*'; | |
} | |
} | |
} | |
EOF | |
echo "Starting CORS proxy for '${backend}' at 'https://127.0.0.1:${port}'" | |
nginx -c /tmp/cors_proxy.conf -g 'daemon off;' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment