Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Synology Bitwarden_rs Websocket setup without SSH
#!/bin/bash
LOC_DIR="/etc/nginx"
if [ ! -f $LOC_DIR/ws.locations ]; then
echo """
location /notifications/hub {
proxy_pass http://localhost:$3;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
}
location /notifications/hub/negotiate {
proxy_pass http://localhost:$2;
}
""" >> $LOC_DIR/ws.locations
fi
if ! grep -q "ws.locations" /etc/nginx/app.d/server.ReverseProxy.conf; then
sed -i "/$1;/ a\ include $LOC_DIR/ws.locations;" /etc/nginx/app.d/server.ReverseProxy.conf
if nginx -t 2>/dev/null; then synoservicecfg --reload nginx; else exit 1; fi
fi

Synology Bitwarden_rs Websocket Setup

Below steps allow you to setup Websocket support for your Bitwarden_rs installation running on Synology Diskstation. You can do all steps using the GUI so there is no SSH Access needed.

Prerequisites

  • Working HTTPS Reverse proxy Setup (Control Panel -> Application Portal -> Reverse Proxy)
  • Set Enviourment Variable WEBSOCKET_ENABLED=true in your Bitwarden container and expose the container port 3012 to a local port, in my case 5556.

Upload script

  1. Download enable_ws.sh
  2. Upload the script "enable_ws.sh" onto your Diskstation. I would recommand putting it in your Bitwarden directory. In my case /volume1/docker/bitwarden

Create scheduled Task

Control Panel -> Task Scheduler -> Create -> Scheduled Task -> User-defined Script

Make sure to amend the command according to your setup.

  • /volume1/docker/bitwarden/enable_ws.sh = Full path to previously uploaded script
  • vault.example.com = Hostname of your Bitwarden_rs as configured in the Reverse Proxy
  • 5555 = Exposed ROCKET_PORT by Docker (The same as in your Reverse Proxy setup)
  • 5556 = Exposed WEBSOCKET_PORT by Docker

Run Command (My example):

bash /volume1/docker/bitwarden/enable_ws.sh vault.example.com 5555 5556

  General Settings
      Task -> Enable BW WS
      User -> root
      Enabled -> Tick
  Schedule
      Run on the following days -> Daily
      Frequency -> Every hour
  Task Settings:
      (Optional) Enable Notifications
      Run Command: <Paste Command Crafted Above> 

Save and run the new task by selecting Run. Login into your Webvault and confirm in your web browsers developer console that the connection to wss:// succeded.

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

Hello,
I found your solution for WebSocket notification in Bitwarden_RS.
I'm going to implement your solution, and I've got a question.
Why did you create a schedule task every hour ? Is there a reason for this value ?

Thanks in advance.

@nstanke

This comment has been minimized.

Copy link
Owner Author

@nstanke nstanke commented Apr 3, 2021

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

Ok ! That's a good explanation 😃
Thank you very much.
I don't made many modifications in DSM UI Reverse-proxy, but some day a lot 😄.
So I'm going to set the same value.

Thanks again

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

@nstanke
Hello again,
I run the script, and it had done what it supposed to do. But websocket doesn't work...
The command I ran :

./Bitwarden_RS__Enable_Websocket.sh may-domaine-name.tld 882 30120

882 is the port for the UI to be joined.
30120 is the websocket port I set in my docker-compose :
image

The ws.locations file is well created :
image

And the /etc/nginx/app.d/server.ReverseProxy.conf file is well edited :
image

But, the websocket connexion failed : (MS Edge)
image

What's going wrong ?

PS : here the reverse-proxy config for my bitwarden domaine name :
image
image

Thanks for your help.

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

Firefox gave me this :
image

@nstanke

This comment has been minimized.

Copy link
Owner Author

@nstanke nstanke commented Apr 3, 2021

Hi MilesTEG1,

it seems that your websocket port mapping is not consistent. 30120 -> 3012. Maybe you could try:

bash Bitwarden_RS__Enable_Websocket.sh may-domaine-name.tld 882 3012

In order for the change to take affect I'd delete /etc/nginx/ws.locations first before re-running the scheduled task. - You could also change the exposed docker port to 30120.

-Norman

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

Hi nstanke,
I was thinking about my router witch is configured to only let pass the 443 and 80 port and severals other ports needed for some synology's services.
Do I need to open the 30120 ports ?
I may have to verify the firewall of my router and nas too...
After I'll try what ou proposed.

You could also change the exposed docker port to 30120.
What do you meen ? It's already exposed, no ? see the excerpt of my docker-compose.yml file :

I'll get back after doing some tests :)
Thanks for your help.

@nstanke

This comment has been minimized.

Copy link
Owner Author

@nstanke nstanke commented Apr 3, 2021

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Apr 3, 2021

Hi,
I finally succeed to have the websocket working :
image
No more warning in bitwarden's log :
image

The Firewalls (NAS & Router) were a dead-end : it didn't solve anything...
I tried to change the websocket port in my docker-compose file to the default port 3012 as you suggested... But it didn't work at the time...
I put the nas IP adress on the reverse-proxy interface, and I modiy the script like this :

  • put the IP adresse instead of localhost
  • add some backslash before " character
    image

As I made a big amount of attempt, I would like to be sure the ws.locations file is autmatically removed, I change the condition.
And I like to know where the script is, I put some echo ligne to write some text for a log file when I run it periodicaly.

Here the script I made with some comments of my own (I'm sorry, my comments are in french 😅
It is probably not optimized at all 😅

Thank you very much for your help !!

The script :

#!/bin/bash
##==============================================================================================
##                                                                                            ##
##                          Script Bitwarden_RS__Enable_Websocket.sh                          ##
##                                                                                            ##
##          Source : https://gist.github.com/nstanke/3949ae1c4706854d8f166d1fb3dadc81         ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##   Ce script pemet de router ce qui ne peut pas être fait avec le reverse-proxy             ##
##   de DSM (Synology) pour faire fonctionner les notifications Websocket                     ##
##   Doc. Bitwarden_RS :                                                                      ##
##        Route the /notifications/hub endpoint to the WebSocket server, by default           ##
##        at port 3012, making sure to pass the Connection and Upgrade headers.               ##
##        (Note the port can be changed with WEBSOCKET_PORT variable)                         ##
##        https://github.com/dani-garcia/bitwarden_rs/wiki/Enabling-WebSocket-notifications   ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##                             Principe de Tâche planifier à créer                            ##
##                                                                                            ##
## Il faut lancer régulièrement le script car toutes modifications faites dans l'interface    ##
## graphique du Reverse-Proxy de DSM va modifier le fichier de configuration. Il en va de     ##
## même lorsque le NAS redémarre.                                                             ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##        /!\    Il faut modifier l'adresse IP en ligne 89 et 95 par l'IP du NAS    /!\       ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
## Paramètres de lancement du script :                                                        ##
## bash /volume1/docker/bitwarden/enable_ws.sh vault.example.com 5555 5556                    ##
##                                                                                            ##
## -- vault.example.com = Nom de domaine de Bitwarden_rs (celui du Reverse Proxy de DSM)      ##
## -- 5555 = Port exposé ROCKET_PORT par Docker (Identique à celui du Reverse Proxy de DSM)   ##
## -- 5556 = Port exposé WEBSOCKET_PORT par Docker                                            ##
##                                                                                            ##
##==============================================================================================

##===========================================================================================================
##                                                                                                         ##
## Ma commande à lancer :                                                                                  ##
## bash /volume1//docker/_Scripts-DOCKER/Bitwarden_RS__Enable_Websocket.sh mon-ndd-a-moi.tld 8001 3012     ##
##                                                                                                         ##
##===========================================================================================================

LOC_DIR="/etc/nginx"
part1=0
part2=0
# declare -r nb_param=$#                           # Nombre d'argument(s) fourni(s) au script.
# declare -r param_1="$1"                          # 1er argument fourni
# declare -r param_2="$2"                          # 1er argument fourni
# declare -r param_3="$3"                          # 1er argument fourni

echo -e "\n$(date "+%R:%S - ") Script Bitwarden_RS__Enable_Websocket.sh pour activer les Notifications Websockets"
echo "$(date "+%R:%S - ") Exécution des commandes..."

f_affiche_parametre() {
    echo "                       bash /volume1/docker/bitwarden/enable_ws.sh vault.example.com 5555 5556 "
    echo "                           -- vault.example.com = Nom de domaine de Bitwarden_rs (celui du Reverse Proxy de DSM) "
    echo "                           -- 5555 = Port exposé ROCKET_PORT par Docker (Identique à celui du Reverse Proxy de DSM)"
    echo "                           -- 5556 = Port exposé WEBSOCKET_PORT par Docker"
}

if [ ! $# -eq 3 ]; then
    if [ $# -eq 0 ]; then
        # Aucun paramètre n'a été fourni. On va afficher la liste de ce qui peut être utilisé.
        echo "$(date "+%R:%S - ") Aucun paramètre fourni ! Revoir l'appel du script :"
        f_affiche_parametre
    else
        echo "$(date "+%R:%S - ") Le nombre de paramètres fournis n'est pas correct ! Revoir l'appel du script :"
        f_affiche_parametre
    fi
    echo -e "$(date "+%R:%S - ") ECHEC de lancement du script !!!!!!!!!\n"
    exit
fi


#############################################################################################################
## Début de la partie de création/modification de fichiers
##
if [ -f $LOC_DIR/ws.locations ]; then
  rm /etc/nginx/ws.locations
  part1=1
fi
echo """
location /notifications/hub {
    proxy_pass http://192.168.2.200:$3;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \"upgrade\";
}

location /notifications/hub/negotiate {
    proxy_pass http://192.168.2.200:$2;
}
""" >> $LOC_DIR/ws.locations

if [ $part1 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- 1ère étape du script : le fichier existait déjà, il a été supprimé."
fi
echo "$(date "+%R:%S - ")    -- 1ère étape du script : écriture du fichier $LOC_DIR/ws.locations ."


if ! grep -q "ws.locations" /etc/nginx/app.d/server.ReverseProxy.conf; then
    sed -i "/$1;/ a\ include $LOC_DIR/ws.locations;" /etc/nginx/app.d/server.ReverseProxy.conf
    if nginx -t 2>/dev/null; then synoservicecfg --reload nginx; else exit 1; fi

    echo "$(date "+%R:%S - ")    -- Étape finale du script atteinte : Écriture dans le fichier server.ReverseProxy.conf."
    part2=1
fi
##
## Fin de la partie de création/modification de fichiers
#############################################################################################################



echo "$(date "+%R:%S - ")    -- Vérification du fichier créé lors de la 1ère étape du script (qu'elle ait été exécuté maintenant ou précédemment) :"
echo "cat /etc/nginx/ws.locations"
cat /etc/nginx/ws.locations
if [ ! $part2 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- 2ème étape du script inutile donc non exécutée : la modification du fichier server.ReverseProxy.conf a déjà été effectuée lors d'une précédente exécution"
fi
echo "$(date "+%R:%S - ") Script Bitwarden_RS__Enable_Websocket.sh terminé"

exit
@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Jun 2, 2021

Hi @nstanke.
I just upgrade my DSM to the DSM7 RC.
And I'm having some problems with the script to add the inlcude of ws.locations into the server.ReverseProxy.conf file.

This file is no more in /etc/nginx/app.d/ folder, it's in the /etc/nginx/sites-enabled/ folder.
And for information, this folder is a link to another :
image
The file inside this folder (linked), is not linked again :
image

Another thing that has changed, is the synoservicecfg witch is no more available. Now it must be synosystemctl :
synosystemctl reload nginx

That's for the changes.
Now, here's the section for my domaine name on the new server.ReverseProxy.conf file :

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name my-domaine-name.tld ;

    if ( $host !~ "(^my-domaine-name.tld$)" ) { return 404; }

    include /usr/syno/etc/www/certificate/ReverseProxy_XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX/cert.conf*;

    include /usr/syno/etc/security-profile/tls-profile/config/ReverseProxy_XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX.conf*;

    add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload" always;

    proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;

    location / {

        proxy_connect_timeout 300;

        proxy_read_timeout 300;

        proxy_send_timeout 300;

        proxy_intercept_errors off;

        proxy_http_version 1.1;

        proxy_set_header        Upgrade            $http_upgrade;

        proxy_set_header        Connection            $connection_upgrade;

        proxy_set_header        X-Real-IP            $remote_addr;

        proxy_set_header        Host            $http_host;

        proxy_set_header        X-Forwarded-For            $proxy_add_x_forwarded_for;

        proxy_set_header        X-Forwarded-Proto            $scheme;

        proxy_pass http://192.168.2.200:882;

    }

    error_page 403 404 500 502 503 504 /dsm_error_page;

    location /dsm_error_page {
        internal;
        root /usr/syno/share/nginx;
        rewrite (.*) /error.html break;
        allow all;
    }

The line : sed -i "/$1;/ a\ include $LOC_DIR/ws.locations.vw;" /etc/nginx/sites-enabled/server.ReverseProxy.conf doesn't work anymore...
And I don't know hos to fix it...
Can you help me ?
Thanks in advance :)

@Autonomous120

This comment has been minimized.

Copy link

@Autonomous120 Autonomous120 commented Jun 25, 2021

@MilesTEG1 The same issue in DSM 6.2.4-25556

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Jun 28, 2021

hello,
Oh, DSM 6.2.4-25556 changed the file's location too !!

I managed to have a working script.
I put it here, but I must warn you that there is many comments in french, and many echo commands in order to have a log file after the execution.

You only have to change the IP_NAS variable with your value.
The domaine name, and the ports are to be given by arguments at script launch.

#!/bin/bash
##==============================================================================================
##                                                                                            ##
##                       Script vaultwarden__Enable_Websocket-DSM_7.sh                        ##
##                                                                                            ##
##          Source : https://gist.github.com/nstanke/3949ae1c4706854d8f166d1fb3dadc81         ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##   Ce script pemet de router ce qui ne peut pas être fait avec le reverse-proxy             ##
##   de DSM (Synology) pour faire fonctionner les notifications Websocket                     ##
##   Doc. vaultwarden :                                                                       ##
##        Route the /notifications/hub endpoint to the WebSocket server, by default           ##
##        at port 3012, making sure to pass the Connection and Upgrade headers.               ##
##        (Note the port can be changed with WEBSOCKET_PORT variable)                         ##
##        https://github.com/dani-garcia/vaultwarden/wiki/Enabling-WebSocket-notifications    ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##                             Principe de Tâche planifier à créer                            ##
##                                                                                            ##
## Il faut lancer régulièrement le script car toutes modifications faites dans l'interface    ##
## graphique du Reverse-Proxy de DSM va modifier le fichier de configuration. Il en va de     ##
## même lorsque le NAS redémarre.                                                             ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##        /!\    Il faut modifier l'adresse IP en ligne 47 par l'IP du NAS    /!\             ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
## Paramètres de lancement du script :                                                        ##
## bash /volume1/docker/bitwarden/enable_ws.sh vault.example.com 5555 5556                    ##
##                                                                                            ##
## -- vault.example.com = Nom de domaine de vaultwarden (celui du Reverse Proxy de DSM)       ##
## -- 5555 = Port exposé ROCKET_PORT par Docker (Identique à celui du Reverse Proxy de DSM)   ##
## -- 5556 = Port exposé WEBSOCKET_PORT par Docker                                            ##
##                                                                                            ##
##==============================================================================================

LOC_DIR="/etc/nginx"
part1=0
part2=0
MY_DOMAIN=$1
PORT_ACCES=$2
PORT_CONT=$3
IP_NAS="192.168.2.200"

echo -e "\n$(date "+%R:%S - ") Script vaultwarden__Enable_Websocket.sh pour activer les Notifications Websockets"

f_affiche_parametre() {
  echo "          bash /volume1/docker/_Scripts-DOCKER/vaultwarden__Enable_Websocket.sh vault.example.com 5555 5556 "
  echo "                           -- vault.example.com = Nom de domaine de vaultwarden (celui du Reverse Proxy de DSM) "
  echo "                           -- 5555 = Port exposé ROCKET_PORT par Docker (Identique à celui du Reverse Proxy de DSM)"
  echo "                           -- 5556 = Port exposé WEBSOCKET_PORT par Docker"
}

if [ ! $# -eq 3 ]; then
  if [ $# -eq 0 ]; then
    # Aucun paramètre n'a été fourni. On va afficher la liste de ce qui peut être utilisé.
    echo "$(date "+%R:%S - ") Aucun paramètre fourni ! Revoir l'appel du script :"
    f_affiche_parametre
  else
    echo "$(date "+%R:%S - ") Le nombre de paramètres fournis n'est pas correct ! Revoir l'appel du script :"
    f_affiche_parametre
  fi
  echo -e "$(date "+%R:%S - ") ECHEC de lancement du script !!!!!!!!!\n"
  exit 1
fi

echo "$(date "+%R:%S - ") Exécution des commandes..."


#############################################################################################################
## Début de la partie de création/modification de fichiers
##
if [ -f $LOC_DIR/websocket.locations.vaultwarden ]; then
  rm $LOC_DIR/websocket.locations.vaultwarden
  part1=1
fi
echo """
location /notifications/hub {
    proxy_pass http://$IP_NAS:$PORT_CONT;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \"upgrade\";
}

location /notifications/hub/negotiate {
    proxy_pass http://$IP_NAS:$PORT_ACCES;
}
""" >>$LOC_DIR/websocket.locations.vaultwarden

# Note : avec DSM7, le chemin d'accès du fichier server.ReverseProxy.conf a changé
#         DSM6.2  = /etc/nginx/app.d/server.ReverseProxy.conf
#         DSM7    = /etc/nginx/sites-enabled/server.ReverseProxy.conf
if ! grep -q "websocket.locations.vaultwarden" /etc/nginx/sites-enabled/server.ReverseProxy.conf; then

  # Commandes fonctionnelles avec DSM6.2.x, mais plus avec DSM 7.0 (RC)
  #sed -i "/$1;/ a\ include $LOC_DIR/websocket.locations.vaultwarden;" /etc/nginx/app.d/server.ReverseProxy.conf
  #if nginx -t 2>/dev/null; then synoservicecfg --reload nginx; else exit 1; fi

  # Commande fonctionnelles avec DSM 7 (RC)
  sed -r "s#^([[:blank:]]*server_name[[:blank:]]*${MY_DOMAIN}[[:blank:]]*;[[:blank:]]*)\$#\1\n\n\tinclude ${LOC_DIR}/websocket.locations.vaultwarden;#" /etc/nginx/sites-enabled/server.ReverseProxy.conf > /etc/nginx/sites-enabled/server.ReverseProxy.conf.new
  mv /etc/nginx/sites-enabled/server.ReverseProxy.conf.new /etc/nginx/sites-enabled/server.ReverseProxy.conf

  if nginx -t 2>/dev/null; then synosystemctl reload nginx; else exit 1; fi

  part2=1 # Variable pour indiquer que cette partie a été exécutée

fi
##
## Fin de la partie de création/modification de fichiers
#############################################################################################################

if [ $part1 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- Le fichier $LOC_DIR/websocket.locations.vaultwarden existait déjà, il a été supprimé puis recréé."
else
  echo "$(date "+%R:%S - ")    -- Le fichier $LOC_DIR/websocket.locations.vaultwarden n'existait pas, il a été créé."
fi
if [ $part2 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- !!!!!! --->  La modification dans le fichier /etc/nginx/sites-enabled/server.ReverseProxy.conf n'existait pas. Elle a été écrite."
  echo "$(date "+%R:%S - ")    -- !!!!!! --->  Le fichier /etc/nginx/sites-enabled/server.ReverseProxy.conf a du être réinitialisé après un reboot ou lors d'une modification du reverse-proxy dans DSM."
else
  echo "$(date "+%R:%S - ")    -- La modification du fichier /etc/nginx/sites-enabled/server.ReverseProxy.conf a déjà été effectuée lors d'une précédente exécution. Aucune modification n'est donc nécessaire."
fi

echo "$(date "+%R:%S - ") Script vaultwarden__Enable_Websocket.sh terminé"

exit
@nstanke

This comment has been minimized.

Copy link
Owner Author

@nstanke nstanke commented Jun 28, 2021

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Jun 28, 2021

I forget to tell that I run DSM 7 RC on my Synology :)

@Autonomous120

This comment has been minimized.

Copy link

@Autonomous120 Autonomous120 commented Jun 30, 2021

@MilesTEG1
Sorry dude. The server.ReverseProxy.conf still locate in /etc/nginx/app.d/ when running at DSM 6.2.4-25556. I just put enable_ws.sh file into the folder which contains a whitespace and cause the script interrupted then received an error code 127. The issue has been fixed by modifying the path, thanks.

@xedoc64

This comment has been minimized.

Copy link

@xedoc64 xedoc64 commented Jul 2, 2021

Hi,

i can't get it working to add the needed include in /etc/nginx/app.d/server.ReverseProxy.conf. It seems that the sed does nothing (or the grep is failing). This happens with the original script as well with the new one from MilesTEG1. Does someone have a hint for me?

@xedoc64

This comment has been minimized.

Copy link

@xedoc64 xedoc64 commented Jul 2, 2021

Damn it, now its working. It really depends in which folder the script is stored. I didn't had any spaces or special chars in the folder name but it seems that there where permissions which leaded into the error.

@RonV42

This comment has been minimized.

Copy link

@RonV42 RonV42 commented Jul 15, 2021

I translated the French to English, also I had to cleanup from the old method after the DSM 7 upgrade. Disabled the cron job. When into the proxy settings for Vaultwarden made one change (port number) saved, then made the change back (original port number) and saved. This reset the files back to default. After that this shell script worked like a champ in DSM 7. Validated the syntax of the cron job and restarted.

#!/bin/bash
##==============================================================================================
##                                                                                            ##
##                       Script vaultwarden__Enable_Websocket-DSM_7.sh                        ##
##                                                                                            ##
##          Source : https://gist.github.com/nstanke/3949ae1c4706854d8f166d1fb3dadc81         ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##   This script allows you to route what cannot be done with the reverse-proxy               ##
##   from DSM (Synology) to make Websocket notifications work                                 ##
##   Doc. vaultwarden :                                                                       ##
##        Route the /notifications/hub endpoint to the WebSocket server, by default           ##
##        at port 3012, making sure to pass the Connection and Upgrade headers.               ##
##        (Note the port can be changed with WEBSOCKET_PORT variable)                         ##
##        https://github.com/dani-garcia/vaultwarden/wiki/Enabling-WebSocket-notifications    ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##                            Principle of Task schedule to create                            ##
##                                                                                            ##
## It is necessary to run the script regularly because all changes made in the interface      ##
## DSM Reverse-Proxy graph will modify the configuration file. The same applies to            ##
## even when the NAS reboots.                                                                 ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
##        /!\      The online IP address 47 must be changed to the NAS IP     /!\             ##
##                                                                                            ##
##==============================================================================================
##                                                                                            ##
## Script launch parameters :                                                                 ##
## bash /volume1/docker/bitwarden/enable_ws.sh vault.example.com 5555 5556                    ##
##                                                                                            ##
## -- vault.example.com = Vaultwarden domain name (that of DSM's Reverse Proxy)               ##
## -- 5555 = Port exposed ROCKET_PORT by Docker (Same as DSM Reverse Proxy)                   ##
## -- 5556 = Port exposed WEBSOCKET_PORT by Docker                                            ##
##                                                                                            ##
##==============================================================================================

LOC_DIR="/etc/nginx"
part1=0
part2=0
MY_DOMAIN=$1
PORT_ACCES=$2
PORT_CONT=$3
IP_NAS="192.168.10.200"

echo -e "\n$(date "+%R:%S - ") Script vaultwarden__Enable_Websocket.sh to enable Websockets Notifications"

f_affiche_parametre() {
  echo "          bash /volume1/docker/_Scripts-DOCKER/vaultwarden__Enable_Websocket.sh vault.example.com 5555 5556 "
  echo "                           -- vault.example.com = Vaultwarden domain name (that of DSM's Reverse Proxy) "
  echo "                           -- 5555 = Port exposed ROCKET_PORT by Docker (Same as DSM Reverse Proxy)"
  echo "                           -- 5556 = Port exposed WEBSOCKET_PORT by Docker"
}

if [ ! $# -eq 3 ]; then
  if [ $# -eq 0 ]; then
    # No parameters were provided. We will display the list of what can be used.
    echo "$(date "+%R:%S - ") No parameters provided! Review the script call :"
    f_affiche_parametre
  else
    echo "$(date "+%R:%S - ") The number of parameters provided is not correct! Review the script call :"
    f_affiche_parametre
  fi
  echo -e "$(date "+%R:%S - ") Failed to launch !!!!!!!!! script\n"
  exit 1
fi

echo "$(date "+%R:%S - ") Executing commands..."


#############################################################################################################
## Start of file creation/editing part
##
if [ -f $LOC_DIR/websocket.locations.vaultwarden ]; then
  rm $LOC_DIR/websocket.locations.vaultwarden
  part1=1
fi
echo """
location /notifications/hub {
    proxy_pass http://$IP_NAS:$PORT_CONT;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \"upgrade\";
}

location /notifications/hub/negotiate {
    proxy_pass http://$IP_NAS:$PORT_ACCES;
}
""" >>$LOC_DIR/websocket.locations.vaultwarden


# Note : with DSM7, the path of the server file. ReverseProxy.conf has changed 
#         DSM6.2  = /etc/nginx/app.d/server.ReverseProxy.conf
#         DSM7    = /etc/nginx/sites-enabled/server.ReverseProxy.conf
if ! grep -q "websocket.locations.vaultwarden" /etc/nginx/sites-enabled/server.ReverseProxy.conf; then

  # Functional commands with DSM6.2.x, but no longer with DSM 7.0 (RC)
  #sed -i "/$1;/ a\ include $LOC_DIR/websocket.locations.vaultwarden;" /etc/nginx/app.d/server.ReverseProxy.conf
  #if nginx -t 2>/dev/null; then synoservicecfg --reload nginx; else exit 1; fi

  # Functional commands with DSM 7 (RC)
  sed -r "s#^([[:blank:]]*server_name[[:blank:]]*${MY_DOMAIN}[[:blank:]]*;[[:blank:]]*)\$#\1\n\n\tinclude ${LOC_DIR}/websocket.locations.vaultwarden;#" /etc/nginx/sites-enabled/server.ReverseProxy.conf > /etc/nginx/sites-enabled/server.ReverseProxy.conf.new
  mv /etc/nginx/sites-enabled/server.ReverseProxy.conf.new /etc/nginx/sites-enabled/server.ReverseProxy.conf

  if nginx -t 2>/dev/null; then synosystemctl reload nginx; else exit 1; fi

  part2=1 # Variable to indicate that this part has been executed

fi
##
## End of file creation/editing part
#############################################################################################################

if [ $part1 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- The file $LOC_DIR/websocket.locations.vaultwarden already existed, it was deleted and then recreated."
else
  echo "$(date "+%R:%S - ")    -- The file $LOC_DIR/websocket.locations.vaultwarden did not exist, it was created."
fi
if [ $part2 -eq 1 ]; then
  echo "$(date "+%R:%S - ")    -- !!!!!! --->  The change in the /etc/nginx/sites-enabled/server file. ReverseProxy.conf did not exist. It was written."
  echo "$(date "+%R:%S - ")    -- !!!!!! --->  The /etc/nginx/sites-enabled/server file. ReverseProxy.conf had to be reset after a reboot or when changing the reverse-proxy in DSM."
else
  echo "$(date "+%R:%S - ")    -- Editing the /etc/nginx/sites-enabled/server file. ReverseProxy.conf was already performed during a previous run. No changes are therefore necessary."
fi

echo "$(date "+%R:%S - ") Script vaultwarden__Enable_Websocket.sh Finished"

exit

@coalfield

This comment has been minimized.

Copy link

@coalfield coalfield commented Jul 15, 2021

Thanks for doing this @MilesTEG1 @RonV42. I too am on DSM 7 but would like to make the changes required manually if possible, only so if anything goes wrong in future I have understand what I am doing.

What is the end result of the script? Trying to look at the code so far it looks like

It creates a file in /etc/nginx/ called websocket.locations.vaultwarden containing

location /notifications/hub {
    proxy_pass http://IP:WS-PORT;
    proxy_set_header Upgrade \$http_upgrade;
    proxy_set_header Connection \"upgrade\";
}

location /notifications/hub/negotiate {
    proxy_pass http://IP:BW-PORT;
}

And then adds

include /etc/nginx/websocket.locations.vaultwarden;

this file to /etc/nginx/sites-enabled/server.ReverseProxy.conf

EDIT:

Ran the script as I think I know what it was doing from the above, noting I had to sudo su after SSHing in to get permissions.
Works absolutely perfectly. Thank you!

@RonV42

This comment has been minimized.

Copy link

@RonV42 RonV42 commented Jul 16, 2021

@coalfield Your coments were correct on the process the script takes and the outputs. I also did what you did to verify. I put pauses into the script, verifyed the actions to files, and confirmed that it was making the right edits to the server.ReverseProxy.conf file. It's good to have a fallback if something does happen in the future.

@MilesTEG1

This comment has been minimized.

Copy link

@MilesTEG1 MilesTEG1 commented Jul 18, 2021

@RonV42 👍 Well done for the translation.
You should edit this line :

##        /!\      The online IP address 47 must be changed to the NAS IP     /!\             ##

to :

##        /!\      The online IP address in line 47 must be changed to the NAS IP     /!\     ##

😃

@SirDanc3lot

This comment has been minimized.

Copy link

@SirDanc3lot SirDanc3lot commented Oct 21, 2021

Hi there and thanks for all the research!

Just to be sure and before anything else; If the internal container ROCKET_PORT is 1111, the local mapped port is 2222, and the WAN port is 3333, so the reversed proxy is doing HTTPS://WANIP:3333->HTTP://LANIP:2222, i should be using the command : bash /volume1/docker/vaultwarden/enable_ws.sh mynas.mydomain.com 3333 3012?
(all three WAN/LAN/Docker port numbers for the WEBSOCKET_PORT are the same: 3012 in my config)

If so, then perhaps someone may know why i'm getting this error in my vaultwarden.log:
2021-10-22 00:30:38.655][vaultwarden::api::notifications][ERROR]
###########################################################
'/notifications/hub' should be proxied to the websocket server or notifications won't work.
Go to the Wiki for more info, or disable WebSockets setting WEBSOCKET_ENABLED=false.
###########################################################################################

And although it 'seems' to work, as the developer console of firefox gives: "Information: WebSocket connected to wss://mynas.mydomain,com:3333/notifications", changing an item in the Firefox extension or in the iOS app, syncs immediately to the webvault, but not the reverse. Neither does it livesync from extension to iOS or vice versa. only after manual sync...

I checked for /etc/nginx/websocket.locations.vaultwarden and if /etc/nginx/websocket.locations.vaultwarden gets added to /etc/nginx/sites-enabled/server.ReverseProxy.conf and its all there...

Thanks in advance for any feedback!

@SirDanc3lot

This comment has been minimized.

Copy link

@SirDanc3lot SirDanc3lot commented Oct 22, 2021

OK after more trial and error debugging: the Firefox extention was connected via local LAN IP address. Switched to domainname and it works flawlessly! both on LAN and on WAN. Only thing that doesnt work is iOS app receiving. Sending is instant though. So the log error seems to be iOS related and only push towards iOS (15.0.2). Probably a bug on either side.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment