Skip to content

Ditto⚓︎

A different way of running on nostr, Ditto helps you host your own community, without needing to develop a nostr app yourself.

Troubleshooting⚓︎

Jumping into new rabbit holes means learning new information and testing it, often needing to troubleshoot. This journey is no different.

I have already tried to run Ditto a couple of times, restarting now from scratch a third time. The first time, I tried to follow the doc without any deviations. I tested a few changes in version two, but I kept getting a 502 nginx error.

This latest try, I documented the entire process here, modifying a few options. I don't get a 502 error, but the connection times out.

I hope this may be useful to people who know how this works to help me discover the issue that's preventing it from running. What's obvious in developers' eyes is often hard to see for newbies.

When we get it to work, I hope the process helps others run one as well, and learn from my mistakes on what not to do.

These steps will likely work if using Linux or MacOS (Sorry, no Windows)

Doubts and questions I have in the process are highlighted in cyan, often below the issue.

Resource: Ditto Installation Docs

Terminal⚓︎

If you are reading this and don't know how to use a terminal, I won't go through the details on how to use it. It can seem daunting, but it's like going into a digital library catalog and looking up information. You must, however, learn what to type in order to look it up. A lot of the time it's only a copy and paste process from installation docs like the one above, but if you run into issues, it helps to know what you are typing.

You can often locate it by searching "Terminal" and clicking on it.

It will open up an almost empty screen but for your home directory (user name followed by your computer's name). The location will change based on what you are doing, so keep an eye on where you are, so you can install items in the proper place.

yourusername@yourcomputer ~ %

It's also not without help. Most of the time it guides you on what you're doing right, or at the very least, it doesn't show an error message if something was done correctly. For errors, it often suggests how to fix them. Some errors sound scarier than they are, sometimes they are sucess messages, so read carefully.

It does not understand typos. It is as if you were trying to speak a different language and the terminal did not understand you. It asks you to speak again, without the typos.

Passwords

It's a good idea to paste your password when requested, instead of typing it in, because the terminal will not show you the passwords as you type.

Hit enter

Always hit enter after you type or paste a command or password.

What you need...⚓︎

When starting to learn something new, always choose the recommended option

Ditto docs recommends VPS with Ubuntu.


  1. domain name

  2. VPS plan (Ubuntu) - If you have ever hosted a website, then you likely know that hosting providers offer VPS plans, your server in the cloud, so it can run 24/7. Once subscribed to a plan, it will give you the following:

    • IP address for your server (using 111.111.11.11 here as an example, please replace with your own)

    • SSH port of access (often 22 or replace with what your provider gives you)

    • Root (admin) password

Your hosting provider should have a tutorial on how to point your domain name to your server's IP address.

It will looking similar to this:

Record Host Value
A Record @ 111.111.11.11 (example, enter your own)
CNAME Record www yourdomain.ending

To check if your records point your website's domain to your IP you can enter:

dig yourwebsite.com ANY +noall + answer

recommended

password manager

you will need to keep track of a few passwords. Password managers can help both save them and generate new ones for you. Choose long strong passwords with numbers, a mixture of uppercase and lowercase letters, and special characters.


warnings exist for a reason, preventing future mistakes

My hosting provider had a security warning on running a VPS from a root user. I'm documenting the steps to their security recommendations here.

Of course, going through best practices may also create additional steps or issues to solve, and, something in my initial setup, may be what's contributing to the 502 error.

secure your VPS⚓︎

remove root user & set up a custom one

log in to your server (first time)⚓︎

ssh root@111.111.11.11 -p22
message from terminal
The authenticity of host '111.111.11.11 (111.111.11.11)' cannot be established. 
RSA key fingerprint is SHA256:+.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/)? 

enter yes
yes
you'll get a message like this one
Permanently added '111.111.11.11' (RSA) to the list of known hosts.
Connection closed by 111.111.11.11 port 22 

you're back in your home directory
yourname@yourcomputer ~ %

new credentials⚓︎

log in again
ssh root@111.111.11.11 -p22
enter the password your service provider gave you
root@111.111.11.11 s password:
message from terminal
Welcome to Ubuntu

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

New release '' available.
Run 'do-release-upgrade' to upgrade to it.

Last login: date and time
[] [server1.yourdomain.ending ~] # 

create a new user⚓︎

choose what your name you're going to use to access your server (yourusername).

useradd -m -s /bin/bash -c "Admin"  yourusername 

set a new password⚓︎

passwd yourusername 
message from terminal, after entering a password and retyping it
passwd: password updated successfully
[] [server1.yourdomain.ending ~] # 

give admin rights⚓︎

usermod -aG sudo yourusername
if you don't get an error message, after hitting enter, and it looks like this, you're ok
[] [server1.yourdomain.com ~] # 

test if it works⚓︎

switch to your username
sudo su - yourusername
notice the directory change
yourusername@server1:~$
run this command as a test
sudo ls -la /root
you'll get a similar list and its details, after entering yourusername's password
total 21
drwx------   
drwxr-xr-x  
-rw-------  .bash_history
-rw-r--r--  
drwx------  cache
-rw-r--r--  profile

disable root⚓︎

open config file
sudo nano /etc/ssh/sshd_config

it will open a new window, look for PermitRootLogin (using the up and down arrows)
# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.
...
#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
set PermitRootLogin to no. Make sure there is no hashtag infront of it, unlike the other options. Hashtags are used to make comments that the program ignores.
# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.
...
#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

change the SSH port⚓︎

In the same window you have open, remove the hashtag from port 22 and add another port of your preference (the example here is 2140)

find port 22
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

remove the hashtag from Port 22 and add another port of your preference
Port 22
Port 2140
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
Save with Ctrl + O

you'll see the following message highlighted in the bottom bar
File Name to Write: /etc/ssh/sshd_config

hit enter

Exit with Ctrl + X

Try one of the following three commands, if you get a command not found error, try a different one.

sudo /etc/init.d/sshd restart
sudo service sshd restart
sudo restart ssh

when you are able to log out and log back in again with your custom port, make sure to enter the config file again and add a hashtag to comment out port 22

#Port 22
Port 2140
#AddressFamily any
#ListenAddress 0.0.0.0
#Lis

SSH keys⚓︎

These keys (long strings of characters) authenticate you to your server. Generate new keys with the following, but don't do this if you already have keys in use to authenticate to this server or you may overwrite them.

ssh-keygen -t rsa

press enter to accept their recommended directory path
Generating public/private rsa key pair.
Enter file in which to save the key (/recommended-path):
enter a strong password
Enter passphrase (empty for no passphrase):
you'll get a similar message to this, along with randomart
Your identification has been saved in
Your public key has been saved in
The keys randomart image is

check if your keys exist, listed as id_rsa and id_rsa.pub
ls -la ~/.ssh/

deeper dive on passwords for SSH keys

copy your SSH keys to the server⚓︎

ssh-copy-id -p 2140 yourusername@111.111.11.11
message from terminal
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/route/id_rsa.pub"
The authenticity of host '[111.111.11.11]:yourcustomport ([111.111.11.11]:yourcustomport)' cannot be established.
RSA key fingerprint is SHA256:
Are you sure you want to continue connecting (yes/no)?
yes
enter your password
yourusername@111.111.11.11 password:
success message
Number of key(s) added: 1

Now try loggin into the machine with: 
and check to make sure that only the key(s) you wanted were added.

Log in with your custom settings⚓︎

exit twice to get back to your home folder
exit

log back in

ssh yourusername@111.111.11.11 -p2140
you'll get a message like this one
Welcome to Ubuntu

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

New release '' available.
Run 'do-release-upgrade' to upgrade to it.

Last login: date and time
[] [server1.yourdomain.ending ~] # 

check if your key has been saved
nano ~/.ssh/authorized_keys
you should see your key in a new window
ssh-rsa ...

exit with Ctrl + X


ufw (uncomplicated firewall)⚓︎

ubuntu should already have ufw installed

ufw status
you should see this message
Status: inactive

if it's not installed:

apt install ufw

setup firewall⚓︎

sudo ufw default deny incoming
message from terminal
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

let your server access the internet
sudo ufw default allow outgoing
message from terminal
Default outgoing policy changed to 'allow'
(be sure to update your rules accordingly)

allow your custom port
sudo ufw default allow 2140
allow http
sudo ufw default allow http/tcp
allow port for ssl certifificate
sudo ufw default allow 443
allow port for database
sudo ufw default allow 5432

if changing the access port for the server makes it more secure, could the database port be customized too? would it improve security or could it block some connections?

Leaving as is, 5432.

configured ports list⚓︎

this command will list the ports you have configured

sudo ufw status

enable ufw⚓︎

So far, the ufw has been disabled. As long as the port you use to access the server is allowed, you should be ok to log back in.

However, you can test if you can log in by opening a separate terminal window, without closing the one you are in.

Once you are sure of your settings:

ufw enable
message from terminal
Command may disrupt existing ssh connections. Proceed with operation (y|n)
y
check if it's running
systemctl status ufw

it should be green and active
 ufw.service - Uncomplicated firewall
     Loaded: loaded (/.../ufw.service; enabled; vendor preset: e>
     Active: active 
     ...
Close with Ctrl + C

deeper dive on configuring firewall rules with UFW


finally, Ditto install docs⚓︎

Resource: Ditto Installation Docs

1. System setup⚓︎

1.a. Install updates⚓︎

sudo apt update
message terminal gives
Hit:1 http://us.archive.ubuntu.com/ubuntu focal InRelease
Get:2 http://us.archive.ubuntu.com/ubuntu focal-updates InRelease [128 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security InRelease [128 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu focal-backports InRelease [128 kB]
Get:5 http://security.ubuntu.com/ubuntu focal-security/main i386 Packages [807 kB]
Get:6 http://us.archive.ubuntu.com/ubuntu focal-updates/main i386 Packages [1024 kB]
Get:7 http://us.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [3534 kB]
...
All packages are up to date.
sudo apt upgrade

message terminal gives
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Calculating upgrade... Done
The following NEW packages will be installed:
...
Do you want to continue? [Y/n]
Y

You should see a progress bar at the bottom. In my case, it prepped and unpacked a long list of files, including some errors of "couldn't resolve device".

1.b. Install system dependencies⚓︎

sudo apt install git curl unzip nginx postgresql-contrib certbot python3-certbot-nginx
message from terminal
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following packages were automatically installed and are no longer required:
  linux-image-5.4.0-26-generic linux-modules-5.4.0-26-generic
  linux-modules-extra-5.4.0-26-generic
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
...
Do you want to continue? [Y/n]
Y

You should see a progress bar at the bottom, and another long list of files.

1.c. Install deno⚓︎

curl -fsSL https://deno.land/x/install/install.sh | sudo DENO_INSTALL=/usr/local sh -s v1.45.2
message from terminal
INSTALL=/usr/local sh -s v1.45.2
######################################################################## 100.0%
Archive:  /usr/local/bin/deno.zip
  inflating: /usr/local/bin/deno     
Deno was installed successfully to /usr/local/bin/deno
Run 'deno --help' to get started

1.d. Create the Ditto user⚓︎

notes

Since the program, the user, and the database are all named ditto, I had a hard time distinguishing them to learn more about the commands in this process.

That also gave me some doubts on which password to use, and where, so I could have made a mistake somewhere. In two instances it seemed like it may need a password but, if I tried to type one, it would do so in plain text, which doesn't seem right.

sudo adduser ditto

enter password for ditto user and retype it
Adding user `ditto' ...
Adding new group `ditto' (1001) ...
Adding new user `ditto' (1001) with group `ditto' ...
Creating home directory `/home/ditto' ...
Copying files from `/etc/skel' ...
New password: 
Retype password:
success message
passwd: password updated successfully
Changing the user information for ditto
Enter the new value, or press ENTER for the default
hit enter after each one, except the name, don't need to fill it in
Full Name []: ditto 
  Room Number []: 
  Work Phone []: 
  Home Phone []: 
  Other []:
Is the information correct? [Y/n] Y

2. Install Ditto⚓︎

2.a. Download source code⚓︎

sudo git clone https://gitlab.com/soapbox-pub/ditto /opt/ditto
message from terminal
Cloning into '/opt/ditto'...
warning: redirecting to https://gitlab.com/soapbox-pub/ditto.git/
remote: Enumerating objects: 13338, done.
remote: Counting objects: 100% (916/916), done.
remote: Compressing objects: 100% (333/333), done.
remote: Total 13338 (delta 645), reused 816 (delta 582), pack-reused 12422 (from 1)
Receiving objects: 100% (13338/13338), 3.59 MiB | 20.11 MiB/s, done.
Resolving deltas: 100% (9586/9586), done.

sudo chown -R ditto:ditto /opt/ditto

No message appears.

navigate to the ditto directory
cd /opt/ditto
notice the change in location
yourusername@server1:/opt/ditto$

become ditto

sudo su ditto
no message appears.

2.b. Configure Ditto⚓︎

create an .env file

deno task setup
Setting up this screen is one of the most confusing in the entire process. I am not sure I've added the correct information.

Task setup deno run -A scripts/setup.ts

Hello! Welcome to the Ditto setup tool. We will ask you a few questions to generate a .env file for you.

- Ditto docs: https://docs.soapbox.pub/ditto/
- Press Ctrl+D to exit at any time.

  Generated secret key

? What is the domain of your instance? (eg ditto.pub) [localhost:4036]

I had a hard time typing a website out, it had a bug (all three times I ran it) that showed what I was typing repeated multiple times, and it wouldn't delete the extra ones. So I just hit enter, and it kept

localhost:4036

Is the 4036 an independent port, like the database port, or should it be the custom port used to access the server?

Should the IP be left as is, or exchanged for the server's IP?

I am guessing that the localhost:4036 needs to be updated in the .env file to either:

serverIP:customport

or

server@domain:customport

I have also tried it with the localhost IP.

just hit enter, it will select postgres
Which database do you want to use?
> postgres
  sqlite
hit enter
? Postgres host localhost

I left it as localhost, but since it is a VPS I don't know if I need to try * or something else , nor where to modify it after leaving it as is.

hit enter
? Postgres port 5432
hit enter
? Postgres user ditto
hit enter
? Postgres password ditto

If I enter a real password here, it shows in plain text, so I don't know if that's what it's requesting. I am guessing it is the name of the user that we need to enter (ditto). Is it?

hit enter
? Postgres database dittodb

I changed the name from ditto to dittodb, to try to distinguish between the user and its database, but then, as I went through the rest of the steps, I kept getting errors of either user does not exist or database doesn't exist. I'm not sure I set it up properly. Maybe there's a reason they're all ditto.

media uploads⚓︎

hit enter
How do you want to upload files? 
> nostrbuild
  blossom
  s3
  ipfs
  local
hit enter
? nostr.build endpoint [https://nostr.build/api/v2/upload/files]
message from terminal
Writing to .env file...
Done

troubleshooting postgresql⚓︎

learning more about the database adjusting config files to allow connection to VPS, in case that solves for the error

source: 3) CURSO VPS - Instalando PostgresQL en Ubuntu y configurar el acceso remoto


log in as yourusername to postgres database

navigate to /opt/ditto, if not there already
cd /opt/ditto

if requested, enter ditto password, then exit (as you are logged in as ditto)

if requested yourusername password, continue

sudo -u postgres psql
message from terminal
psql (12.20 (Ubuntu 12.20-0ubuntu0.20.04.1))
Type "help" for help.

postgres=#
find config file
SHOW config_file;
message from terminal
 config_file               
-----------------------------------------
 /etc/postgresql/12/main/postgresql.conf
(1 row)

postgres=#
quit
\q
copy file route from above
sudo nano /etc/postgresql/12/main/postgresql.conf

original (very long) config file window
# -----------------------------
# PostgreSQL configuration file
# -----------------------------
#
# This file consists of lines of the form:
#
#   name = value
#
# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
# "#" anywhere on a line.  The complete list of parameter names and allowed
# values can be found in the PostgreSQL documentation.
#
# The commented-out settings shown in this file represent the default values.
# Re-commenting a setting is NOT sufficient to revert it to the default value;
# you need to reload the server.
#
# This file is read on server startup and when the server receives a SIGHUP
# signal.  If you edit the file on a running system, you have to SIGHUP the
# server for the changes to take effect, run "pg_ctl reload", or execute
# "SELECT pg_reload_conf()".  Some parameters, which are marked below,
# require a server shutdown and restart to take effect.
#
# Any parameter can also be given as a command-line option to the server, e.g.,
# "postgres -c log_connections=on".  Some parameters can be changed at run time
# with the "SET" SQL command.
#
# Memory units:  B  = bytes            Time units:  us  = microseconds
#                kB = kilobytes                     ms  = milliseconds
#                MB = megabytes                     s   = seconds
#                GB = gigabytes                     min = minutes
#                TB = terabytes                     h   = hours
#                                                   d   = days


#------------------------------------------------------------------------------
# FILE LOCATIONS
#------------------------------------------------------------------------------

# The default values of these variables are driven from the -D command-line
# option or PGDATA environment variable, represented here as ConfigDir.

data_directory = '/var/lib/postgresql/12/main'          # use data in another directory
                                        # (change requires restart)
hba_file = '/etc/postgresql/12/main/pg_hba.conf'        # host-based authentication file
                                        # (change requires restart)
ident_file = '/etc/postgresql/12/main/pg_ident.conf'    # ident configuration file
                                        # (change requires restart)

# If external_pid_file is not explicitly set, no extra PID file is written.
external_pid_file = '/var/run/postgresql/12-main.pid'                   # write an extra PID >
                                        # (change requires restart)

#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

#listen_addresses = 'localhost'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
port = 5432                             # (change requires restart)
max_connections = 100                   # (change requires restart)
#superuser_reserved_connections = 3     # (change requires restart)
unix_socket_directories = '/var/run/postgresql' # comma-separated list of directories
                                        # (change requires restart)
#unix_socket_group = ''                 # (change requires restart)
#unix_socket_permissions = 0777         # begin with 0 to use octal notation
                                        # (change requires restart)
#bonjour = off                          # advertise server via Bonjour
                                        # (change requires restart)
#bonjour_name = ''                      # defaults to the computer name
                                        # (change requires restart)

# - TCP settings -
# see "man 7 tcp" for details

#tcp_keepalives_idle = 0                # TCP_KEEPIDLE, in seconds;
                                        # 0 selects the system default
#tcp_keepalives_interval = 0            # TCP_KEEPINTVL, in seconds;
                                        # 0 selects the system default
#tcp_keepalives_count = 0               # TCP_KEEPCNT;
                                        # 0 selects the system default
#tcp_user_timeout = 0                   # TCP_USER_TIMEOUT, in milliseconds;
                                        # 0 selects the system default

# - Authentication -

#authentication_timeout = 1min          # 1s-600s
#password_encryption = md5              # md5 or scram-sha-256
#db_user_namespace = off

# GSSAPI using Kerberos
#krb_server_keyfile = 'FILE:${sysconfdir}/krb5.keytab'
#krb_caseins_users = off

# - SSL -


ssl = on
#ssl_ca_file = ''
ssl_cert_file = 'cert'
#ssl_crl_file = ''
ssl_key_file = 'key'
#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
#ssl_prefer_server_ciphers = on
#ssl_ecdh_curve = 'prime256v1'
#ssl_min_protocol_version = 'TLSv1'
#ssl_max_protocol_version = ''
#ssl_dh_params_file = ''
#ssl_passphrase_command = ''
#ssl_passphrase_command_supports_reload = off


#------------------------------------------------------------------------------
# RESOURCE USAGE (except WAL)
#------------------------------------------------------------------------------

# - Memory -

shared_buffers = 128MB                  # min 128kB
                                        # (change requires restart)
#huge_pages = try                       # on, off, or try
                                        # (change requires restart)
#temp_buffers = 8MB                     # min 800kB
#max_prepared_transactions = 0          # zero disables the feature
                                        # (change requires restart)
# Caution: it is not advisable to set max_prepared_transactions nonzero unless
# you actively intend to use prepared transactions.
#work_mem = 4MB                         # min 64kB
#maintenance_work_mem = 64MB            # min 1MB
#autovacuum_work_mem = -1               # min 1MB, or -1 to use maintenance_work_mem
#max_stack_depth = 2MB                  # min 100kB
#shared_memory_type = mmap              # the default is the first option
                                        # supported by the operating system:
                                        #   mmap
                                        #   sysv
                                        #   windows
                                        # (change requires restart)
dynamic_shared_memory_type = posix      # the default is the first option
                                        # supported by the operating system:
                                        #   posix
                                        #   sysv
                                        #   windows
                                        #   mmap
                                        # (change requires restart)

# - Disk -

#temp_file_limit = -1                   # limits per-process temp file space
                                        # in kB, or -1 for no limit

# - Kernel Resources -

#max_files_per_process = 1000           # min 25
                                        # (change requires restart)

# - Cost-Based Vacuum Delay -

#vacuum_cost_delay = 0                  # 0-100 milliseconds (0 disables)
#vacuum_cost_page_hit = 1               # 0-10000 credits
#vacuum_cost_page_miss = 10             # 0-10000 credits
#vacuum_cost_page_dirty = 20            # 0-10000 credits
#vacuum_cost_limit = 200                # 1-10000 credits

# - Background Writer -

#bgwriter_delay = 200ms                 # 10-10000ms between rounds
#bgwriter_lru_maxpages = 100            # max buffers written/round, 0 disables
#bgwriter_lru_multiplier = 2.0          # 0-10.0 multiplier on buffers scanned/round
#bgwriter_flush_after = 512kB           # measured in pages, 0 disables

# - Asynchronous Behavior -

#effective_io_concurrency = 1           # 1-1000; 0 disables prefetching
#max_worker_processes = 8               # (change requires restart)
#max_parallel_maintenance_workers = 2   # limited by max_parallel_workers
#max_parallel_workers_per_gather = 2    # limited by max_parallel_workers
#parallel_leader_participation = on
#max_parallel_workers = 8               # number of max_worker_processes that
                                        # can be used in parallel operations
#old_snapshot_threshold = -1            # 1min-60d; -1 disables; 0 is immediate
                                        # (change requires restart)
#backend_flush_after = 0                # measured in pages, 0 disables



#------------------------------------------------------------------------------
# WRITE-AHEAD LOG
#------------------------------------------------------------------------------

# - Settings -

#wal_level = replica                    # minimal, replica, or logical
                                        # (change requires restart)
#fsync = on                             # flush data to disk for crash safety
                                        # (turning this off can cause
                                        # unrecoverable data corruption)
#synchronous_commit = on                # synchronization level;
                                        # off, local, remote_write, remote_apply, or on
#wal_sync_method = fsync                # the default is the first option
                                        # supported by the operating system:
                                        #   open_datasync
                                        #   fdatasync (default on Linux and FreeBSD)
                                        #   fsync
                                        #   fsync_writethrough
                                        #   open_sync
#full_page_writes = on                  # recover from partial page writes
#wal_compression = off                  # enable compression of full-page writes
#wal_log_hints = off                    # also do full page writes of non-critical updates
                                        # (change requires restart)
#wal_init_zero = on                     # zero-fill new WAL files
#wal_recycle = on                       # recycle WAL files
#wal_buffers = -1                       # min 32kB, -1 sets based on shared_buffers
                                        # (change requires restart)
#wal_writer_delay = 200ms               # 1-10000 milliseconds
#wal_writer_flush_after = 1MB           # measured in pages, 0 disables

#commit_delay = 0                       # range 0-100000, in microseconds
#commit_siblings = 5                    # range 1-1000

# - Checkpoints -

#checkpoint_timeout = 5min              # range 30s-1d
max_wal_size = 1GB
min_wal_size = 80MB
#checkpoint_completion_target = 0.5     # checkpoint target duration, 0.0 - 1.0
#checkpoint_flush_after = 256kB         # measured in pages, 0 disables
#checkpoint_warning = 30s               # 0 disables

# - Archiving -

#archive_mode = off             # enables archiving; off, on, or always
                                # (change requires restart)
#archive_command = ''           # command to use to archive a logfile segment
                                # placeholders: %p = path of file to archive
                                #               %f = file name only
                                # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/ser>
#archive_timeout = 0            # force a logfile segment switch after this
                                # number of seconds; 0 disables

# - Archive Recovery -

# These are only used in recovery mode.

#restore_command = ''           # command to use to restore an archived logfile segment
                                # placeholders: %p = path of file to restore
                                #               %f = file name only
                                # e.g. 'cp /mnt/server/archivedir/%f %p'
                                # (change requires restart)
#archive_cleanup_command = ''   # command to execute at every restartpoint
#recovery_end_command = ''      # command to execute at completion of recovery

# - Recovery Target -

# Set these only when performing a targeted recovery.

#recovery_target = ''           # 'immediate' to end recovery as soon as a
                                # consistent state is reached
                                # (change requires restart)
#recovery_target_name = ''      # the named restore point to which recovery will proceed
                                # (change requires restart)
#recovery_target_time = ''      # the time stamp up to which recovery will proceed
                                # (change requires restart)
#recovery_target_xid = ''       # the transaction ID up to which recovery will proceed
                                # (change requires restart)
#recovery_target_lsn = ''       # the WAL LSN up to which recovery will proceed
                                # (change requires restart)
#recovery_target_inclusive = on # Specifies whether to stop:
                                # just after the specified recovery target (on)
                                # just before the recovery target (off)
                                # (change requires restart)
#recovery_target_timeline = 'latest'    # 'current', 'latest', or timeline ID
                                # (change requires restart)
#recovery_target_action = 'pause'       # 'pause', 'promote', 'shutdown'
                                # (change requires restart)



#------------------------------------------------------------------------------
# REPLICATION
#------------------------------------------------------------------------------

# - Sending Servers -

# Set these on the master and on any standby that will send replication data.

#max_wal_senders = 10           # max number of walsender processes
                                # (change requires restart)
#wal_keep_segments = 0          # in logfile segments; 0 disables
#wal_sender_timeout = 60s       # in milliseconds; 0 disables

#max_replication_slots = 10     # max number of replication slots
                                # (change requires restart)
#track_commit_timestamp = off   # collect timestamp of transaction commit
                                # (change requires restart)

# - Master Server -

# These settings are ignored on a standby server.

#synchronous_standby_names = '' # standby servers that provide sync rep
                                # method to choose sync standbys, number of sync standbys,
                                # and comma-separated list of application_name
                                # from standby(s); '*' = all
#vacuum_defer_cleanup_age = 0   # number of xacts by which cleanup is delayed

# - Standby Servers -

# These settings are ignored on a master server.

#primary_conninfo = ''                  # connection string to sending server
                                        # (change requires restart)
#primary_slot_name = ''                 # replication slot on sending server
                                        # (change requires restart)
#promote_trigger_file = ''              # file name whose presence ends recovery
#hot_standby = on                       # "off" disallows queries during recovery
                                        # (change requires restart)
#max_standby_archive_delay = 30s        # max delay before canceling queries
                                        # when reading WAL from archive;
                                        # -1 allows indefinite delay
#max_standby_streaming_delay = 30s      # max delay before canceling queries
                                        # when reading streaming WAL;
                                        # -1 allows indefinite delay
#wal_receiver_status_interval = 10s     # send replies at least this often
                                        # 0 disables
#hot_standby_feedback = off             # send info from standby to prevent
                                        # query conflicts
#wal_receiver_timeout = 60s             # time that receiver waits for
                                        # communication from master
                                        # in milliseconds; 0 disables
#wal_retrieve_retry_interval = 5s       # time to wait before retrying to
                                        # retrieve WAL after a failed attempt
#recovery_min_apply_delay = 0           # minimum delay for applying changes during recovery

# - Subscribers -

# These settings are ignored on a publisher.

#max_logical_replication_workers = 4    # taken from max_worker_processes
                                        # (change requires restart)
#max_sync_workers_per_subscription = 2  # taken from max_logical_replication_workers


#------------------------------------------------------------------------------
# QUERY TUNING
#------------------------------------------------------------------------------

# - Planner Method Configuration -

#enable_bitmapscan = on
#enable_hashagg = on
#enable_hashjoin = on
#enable_indexscan = on
#enable_indexonlyscan = on
#enable_material = on
#enable_mergejoin = on
#enable_nestloop = on
#enable_parallel_append = on
#enable_seqscan = on
#enable_sort = on
#enable_tidscan = on
#enable_partitionwise_join = off
#enable_partitionwise_aggregate = off
#enable_parallel_hash = on
#enable_partition_pruning = on

# - Planner Cost Constants -


#seq_page_cost = 1.0                    # measured on an arbitrary scale
#random_page_cost = 4.0                 # same scale as above
#cpu_tuple_cost = 0.01                  # same scale as above
#cpu_index_tuple_cost = 0.005           # same scale as above
#cpu_operator_cost = 0.0025             # same scale as above
#parallel_tuple_cost = 0.1              # same scale as above
#parallel_setup_cost = 1000.0   # same scale as above

#jit_above_cost = 100000                # perform JIT compilation if available
                                        # and query more expensive than this;
                                        # -1 disables
#jit_inline_above_cost = 500000         # inline small functions if query is
                                        # more expensive than this; -1 disables
#jit_optimize_above_cost = 500000       # use expensive JIT optimizations if
                                        # query is more expensive than this;
                                        # -1 disables

#min_parallel_table_scan_size = 8MB
#min_parallel_index_scan_size = 512kB
#effective_cache_size = 4GB

# - Genetic Query Optimizer -

#geqo = on
#geqo_threshold = 12
#geqo_effort = 5                        # range 1-10
#geqo_pool_size = 0                     # selects default based on effort
#geqo_generations = 0                   # selects default based on effort
#geqo_selection_bias = 2.0              # range 1.5-2.0
#geqo_seed = 0.0                        # range 0.0-1.0

# - Other Planner Options -

#default_statistics_target = 100        # range 1-10000
#constraint_exclusion = partition       # on, off, or partition
#cursor_tuple_fraction = 0.1            # range 0.0-1.0
#from_collapse_limit = 8
#join_collapse_limit = 8                # 1 disables collapsing of explicit
                                        # JOIN clauses
#force_parallel_mode = off
#jit = on                               # allow JIT compilation
#plan_cache_mode = auto                 # auto, force_generic_plan or
                                        # force_custom_plan


#------------------------------------------------------------------------------
# REPORTING AND LOGGING
#------------------------------------------------------------------------------

# - Where to Log -

#log_destination = 'stderr'             # Valid values are combinations of
                                        # stderr, csvlog, syslog, and eventlog,
                                        # depending on platform.  csvlog
                                        # requires logging_collector to be on.

# This is used when logging to stderr:
#logging_collector = off                # Enable capturing of stderr and csvlog
                                        # into log files. Required to be on for
                                        # csvlogs.
                                        # (change requires restart)

# These are only used if logging_collector is on:
#log_directory = 'log'                  # directory where log files are written,
                                        # can be absolute or relative to PGDATA
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'        # log file name pattern,
                                        # can include strftime() escapes
#log_file_mode = 0600                   # creation mode for log files,
                                        # begin with 0 to use octal notation
#log_truncate_on_rotation = off         # If on, an existing log file with the
                                        # same name as the new log file will be
                                        # truncated rather than appended to.
                                        # But such truncation only occurs on
                                        # time-driven rotation, not on restarts
                                        # or size-driven rotation.  Default is
                                        # off, meaning append to existing files
                                        # in all cases.
#log_rotation_age = 1d                  # Automatic rotation of logfiles will
                                        # happen after that time.  0 disables.
#log_rotation_size = 10MB               # Automatic rotation of logfiles will
                                        # happen after that much log output.
                                        # 0 disables.

# These are relevant when logging to syslog:
#syslog_facility = 'LOCAL0'
#syslog_ident = 'postgres'
#syslog_sequence_numbers = on
#syslog_split_messages = on

# This is only relevant when logging to eventlog (win32):
# (change requires restart)
#event_source = 'PostgreSQL'

# - When to Log -

#log_min_messages = warning             # values in order of decreasing detail:
                                        #   debug5
                                        #   debug4
                                        #   debug3
                                        #   debug2
                                        #   debug1
                                        #   info
                                        #   notice
                                        #   warning
                                        #   error
                                        #   log
                                        #   fatal
                                        #   panic

#log_min_error_statement = error        # values in order of decreasing detail:
                                        #   debug5
                                        #   debug4
                                        #   debug3
                                        #   debug2
                                        #   debug1
                                        #   info
                                        #   notice
                                        #   warning
                                        #   error
                                        #   log
                                        #   fatal
                                        #   panic (effectively off)

#log_min_duration_statement = -1        # -1 is disabled, 0 logs all statements
                                        # and their durations, > 0 logs only
                                        # statements running at least this number
                                        # of milliseconds

#log_transaction_sample_rate = 0.0      # Fraction of transactions whose statements
                                        # are logged regardless of their duration. 1.0 logs a>
                                        # statements from all transactions, 0.0 never logs.

# - What to Log -

#debug_print_parse = off
#debug_print_rewritten = off
#debug_print_plan = off
#debug_pretty_print = on
#log_checkpoints = off
#log_connections = off
#log_disconnections = off
#log_duration = off
#log_error_verbosity = default          # terse, default, or verbose messages
#log_hostname = off
log_line_prefix = '%m [%p] %q%u@%d '            # special values:
                                        #   %a = application name
                                        #   %u = user name
                                        #   %d = database name
                                        #   %r = remote host and port
                                        #   %h = remote host
                                        #   %p = process ID
                                        #   %t = timestamp without milliseconds
                                        #   %m = timestamp with milliseconds
                                        #   %n = timestamp with milliseconds (as a Unix epoch)
                                        #   %i = command tag
                                        #   %e = SQL state
                                        #   %c = session ID
                                        #   %l = session line number
                                        #   %s = session start timestamp
                                        #   %v = virtual transaction ID
                                        #   %x = transaction ID (0 if none)
                                        #   %q = stop here in non-session
                                        #        processes
                                        #   %% = '%'
                                        # e.g. '<%u%%%d> '
#log_lock_waits = off                   # log lock waits >= deadlock_timeout
#log_statement = 'none'                 # none, ddl, mod, all
#log_replication_commands = off
#log_temp_files = -1                    # log temporary files equal or larger
                                        # than the specified size in kilobytes;
                                        # -1 disables, 0 logs all temp files
log_timezone = 'Etc/UTC'

#------------------------------------------------------------------------------
# PROCESS TITLE
#------------------------------------------------------------------------------

cluster_name = '12/main'                        # added to process titles if nonempty
                                        # (change requires restart)
#update_process_title = on


#------------------------------------------------------------------------------
# STATISTICS
#------------------------------------------------------------------------------

# - Query and Index Statistics Collector -

#track_activities = on
#track_counts = on
#track_io_timing = off
#track_functions = none                 # none, pl, all
#track_activity_query_size = 1024       # (change requires restart)
stats_temp_directory = '/var/run/postgresql/12-main.pg_stat_tmp'


# - Monitoring -

#log_parser_stats = off
#log_planner_stats = off
#log_executor_stats = off
#log_statement_stats = off


#------------------------------------------------------------------------------
# AUTOVACUUM
#------------------------------------------------------------------------------

#autovacuum = on                        # Enable autovacuum subprocess?  'on'
                                        # requires track_counts to also be on.
#log_autovacuum_min_duration = -1       # -1 disables, 0 logs all actions and
                                        # their durations, > 0 logs only
                                        # actions running at least this number
                                        # of milliseconds.
#autovacuum_max_workers = 3             # max number of autovacuum subprocesses
                                        # (change requires restart)
#autovacuum_naptime = 1min              # time between autovacuum runs
#autovacuum_vacuum_threshold = 50       # min number of row updates before
                                        # vacuum
#autovacuum_analyze_threshold = 50      # min number of row updates before
                                        # analyze
#autovacuum_vacuum_scale_factor = 0.2   # fraction of table size before vacuum
#autovacuum_analyze_scale_factor = 0.1  # fraction of table size before analyze
#autovacuum_freeze_max_age = 200000000  # maximum XID age before forced vacuum
                                        # (change requires restart)
#autovacuum_multixact_freeze_max_age = 400000000        # maximum multixact age
                                        # before forced vacuum
                                        # (change requires restart)
#autovacuum_vacuum_cost_delay = 2ms     # default vacuum cost delay for
                                        # autovacuum, in milliseconds;
                                        # -1 means use vacuum_cost_delay
#autovacuum_vacuum_cost_limit = -1      # default vacuum cost limit for
                                        # autovacuum, -1 means use
                                        # vacuum_cost_limit



#------------------------------------------------------------------------------
# CLIENT CONNECTION DEFAULTS
#------------------------------------------------------------------------------

# - Statement Behavior -

#client_min_messages = notice           # values in order of decreasing detail:
                                        #   debug5
                                        #   debug4
                                        #   debug3
                                        #   debug2
                                        #   debug1
                                        #   log
                                        #   notice
                                        #   warning
                                        #   error
#search_path = '"$user", public'        # schema names
#row_security = on
#default_tablespace = ''                # a tablespace name, '' uses the default
#temp_tablespaces = ''                  # a list of tablespace names, '' uses
                                        # only default tablespace
#default_table_access_method = 'heap'
#check_function_bodies = on
#default_transaction_isolation = 'read committed'
#default_transaction_read_only = off
#default_transaction_deferrable = off
#session_replication_role = 'origin'
#statement_timeout = 0                  # in milliseconds, 0 is disabled
#lock_timeout = 0                       # in milliseconds, 0 is disabled
#idle_in_transaction_session_timeout = 0        # in milliseconds, 0 is disabled
#vacuum_freeze_min_age = 50000000
#vacuum_freeze_table_age = 150000000
#vacuum_multixact_freeze_min_age = 5000000
#vacuum_multixact_freeze_table_age = 150000000
#vacuum_cleanup_index_scale_factor = 0.1        # fraction of total number of tuples
                                                # before index cleanup, 0 always performs
                                                # index cleanup
#bytea_output = 'hex'                   # hex, escape
#xmlbinary = 'base64'
#xmloption = 'content'
#gin_fuzzy_search_limit = 0
#gin_pending_list_limit = 4MB


# - Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'Etc/UTC'
#timezone_abbreviations = 'Default'     # Select the set of available time zone
                                        # abbreviations.  Currently, there are
                                        #   Default
                                        #   Australia (historical usage)
                                        #   India
                                        # You can create your own file in
                                        # share/timezonesets/.
#extra_float_digits = 1                 # min -15, max 3; any value >0 actually
                                        # selects precise output mode
#client_encoding = sql_ascii            # actually, defaults to database
                                        # encoding

# These settings are initialized by initdb, but they can be changed.
lc_messages = 'en_US'                   # locale for system error message
                                        # strings
lc_monetary = 'en_US'                   # locale for monetary formatting
lc_numeric = 'en_US'                    # locale for number formatting
lc_time = 'en_US'                               # locale for time formatting

# default configuration for text search
default_text_search_config = 'pg_catalog.english'

# - Shared Library Preloading -

#shared_preload_libraries = ''  # (change requires restart)
#local_preload_libraries = ''
#session_preload_libraries = ''
#jit_provider = 'llvmjit'               # JIT library to use

# - Other Defaults -

#dynamic_library_path = '$libdir'


#------------------------------------------------------------------------------
# LOCK MANAGEMENT
#------------------------------------------------------------------------------

#deadlock_timeout = 1s
#max_locks_per_transaction = 64         # min 10
                                        # (change requires restart)
#max_pred_locks_per_transaction = 64    # min 10
                                        # (change requires restart)
#max_pred_locks_per_relation = -2       # negative values mean
                                        # (max_pred_locks_per_transaction
                                        #  / -max_pred_locks_per_relation) - 1
#max_pred_locks_per_page = 2            # min 0


#------------------------------------------------------------------------------
# VERSION AND PLATFORM COMPATIBILITY
#------------------------------------------------------------------------------

# - Previous PostgreSQL Versions -

#array_nulls = on
#backslash_quote = safe_encoding        # on, off, or safe_encoding
#escape_string_warning = on
#lo_compat_privileges = off
#operator_precedence_warning = off
#quote_all_identifiers = off
#standard_conforming_strings = on
#synchronize_seqscans = on

# - Other Platforms and Clients -

#transform_null_equals = off


#------------------------------------------------------------------------------
# ERROR HANDLING
#------------------------------------------------------------------------------

#exit_on_error = off                    # terminate session on any error?
#restart_after_crash = on               # reinitialize after backend crash?
#data_sync_retry = off                  # retry or panic on failure to fsync
                                        # data?
                                        # (change requires restart)


#------------------------------------------------------------------------------
# CONFIG FILE INCLUDES
#------------------------------------------------------------------------------

# These options allow settings to be loaded from files other than the
# default postgresql.conf.  Note that these are directives, not variable
# assignments, so they can usefully be given more than once.

include_dir = 'conf.d'                  # include files ending in '.conf' from
                                        # a directory, e.g., 'conf.d'
#include_if_exists = '...'              # include file only if it exists
#include = '...'                        # include file


#------------------------------------------------------------------------------
# CUSTOMIZED OPTIONS
#------------------------------------------------------------------------------

# Add settings for extensions here
end of original config file

changes made to config file:

before
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

#listen_addresses = 'localhost'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
                                        # (change requires restart)
port = 5432                             # (change requires restart)
max_connections = 100                   # (change requires restart)
after: added non-commented line for listen_addresses with * instead of localhost
#------------------------------------------------------------------------------
# CONNECTIONS AND AUTHENTICATION
#------------------------------------------------------------------------------

# - Connection Settings -

#listen_addresses = 'localhost'         # what IP address(es) to listen on;
                                        # comma-separated list of addresses;
                                        # defaults to 'localhost'; use '*' for all
listen_addresses = '*'         
                                        # (change requires restart)
port = 5432                             # (change requires restart)
max_connections = 100                   # (change requires restart)

save changes Ctrl + O, then enter exit config window with Ctrl + X

restart for changes to be applied
sudo systemctl restart postgresql

check if ditto is running

systemctl status ditto

not running, same error


Modifying the PostgreSQL Client Authentication Configuration File

Route copied from config file

again from /opt/ditto NOT as ditto user
sudo nano /etc/postgresql/12/main/pg_hba.conf
PostgreSQL Client Authentication Configuration File window
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# Refer to the "Client Authentication" section in the PostgreSQL
# documentation for a complete description of this file.  A short
# synopsis follows.
#
# This file controls: which hosts are allowed to connect, how clients
# are authenticated, which PostgreSQL user names they can use, which
# databases they can access.  Records take one of these forms:
#
# local         DATABASE  USER  METHOD  [OPTIONS]
# host          DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostssl       DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostnossl     DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostgssenc    DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
# hostnogssenc  DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
#
# (The uppercase items must be replaced by actual values.)
#
# The first field is the connection type: "local" is a Unix-domain
# socket, "host" is either a plain or SSL-encrypted TCP/IP socket,
# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a
# non-SSL TCP/IP socket.  Similarly, "hostgssenc" uses a
# GSSAPI-encrypted TCP/IP socket, while "hostnogssenc" uses a
# non-GSSAPI socket.
#
# DATABASE can be "all", "sameuser", "samerole", "replication", a
# database name, or a comma-separated list thereof. The "all"
# keyword does not match "replication". Access to replication
# must be enabled in a separate record (see example below).
#
# USER can be "all", a user name, a group name prefixed with "+", or a
# comma-separated list thereof.  In both the DATABASE and USER fields
# you can also write a file name prefixed with "@" to include names
# from a separate file.
#
# ADDRESS specifies the set of hosts the record matches.  It can be a
# host name, or it is made up of an IP address and a CIDR mask that is
# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that
# specifies the number of significant bits in the mask.  A host name
# that starts with a dot (.) matches a suffix of the actual host name.
# Alternatively, you can write an IP address and netmask in separate
# columns to specify the set of hosts.  Instead of a CIDR-address, you
# can write "samehost" to match any of the server's own IP addresses,
# or "samenet" to match any address in any subnet that the server is
# directly connected to.
#
# METHOD can be "trust", "reject", "md5", "password", "scram-sha-256",
# "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert".
# Note that "password" sends passwords in clear text; "md5" or
# "scram-sha-256" are preferred since they send encrypted passwords.
#
# OPTIONS are a set of options for the authentication in the format
# NAME=VALUE.  The available options depend on the different
# authentication methods -- refer to the "Client Authentication"
# section in the documentation for a list of which options are
# available for which authentication methods.
#
# Database and user names containing spaces, commas, quotes and other
# special characters must be quoted.  Quoting one of the keywords
# "all", "sameuser", "samerole" or "replication" makes the name lose
# its special character, and just match a database or username with
# that name.
#
# This file is read on server startup and when the server receives a
# SIGHUP signal.  If you edit the file on a running system, you have to
# SIGHUP the server for the changes to take effect, run "pg_ctl reload",
# or execute "SELECT pg_reload_conf()".
#
# Put your actual configuration here
# ----------------------------------
#
#
# If you want to allow non-local connections, you need to add more
# "host" records.  In that case you will also need to make PostgreSQL
# listen on a non-local interface via the listen_addresses
# configuration parameter, or via the -i or -h command line switches.




# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

change IPv4 localhost IP to 0.0.0.0/0
# IPv4 local connections:
host    all             all             0.0.0.0/0            md5
save changes Ctrl + O, then enter exit config window with Ctrl + X

restart for changes to be applied
sudo systemctl restart postgresql

check if ditto is running

systemctl status ditto
same error
 ditto.service - Ditto
     Loaded: loaded (/etc/systemd/system/ditto.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since 
    Process: 64502 ExecStart=/usr/local/bin/deno task start (code=exited, status=1/FAILURE)
   Main PID: 64502 (code=exited, status=1/FAILURE)

same error


list of ditto files

from /opt/ditto
ls
message from terminal
CHANGELOG.md  LICENSE    data       deno.lock         docs      installation  scripts  static
Dockerfile    README.md  deno.json  ditto-planet.png  fixtures  public        src

log in as ditto to ditto database

navigate to /opt/ditto, if not there already
cd /opt/ditto
log in as ditto, if not already
sudo su ditto
enter your server user password
[sudo] password for yourserverusername:
sudo -u postgres
message from terminal
usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user]
            [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p
            prompt] [-T timeout] [-u user] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p
            prompt] [-T timeout] [-u user] file ...
psql
message from terminal
psql (12.20 (Ubuntu 12.20-0ubuntu0.20.04.1))
Type "help" for help.

ditto=> help
You are using psql, the command-line interface to PostgreSQL.
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit
ditto=>
list databases
\l
message from terminal
 List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges   
-----------+----------+----------+---------+-------+-----------------------
 ditto     | ditto    | LATIN1   | en_US   | en_US | 
 dittodb   | ditto    | LATIN1   | en_US   | en_US | 
 postgres  | postgres | LATIN1   | en_US   | en_US | 
 template0 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | LATIN1   | en_US   | en_US | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
(5 rows)

I'm guessing there should only be one database listed above, and that ditto should point to it in a database config file somewhere.

quit
\quit

2.c. Add Soapbox⚓︎

deno task soapbox
a very very long list of files gets installed
Task soapbox curl -O https://dl.soapbox.pub/main/soapbox.zip && mkdir -p public && mv soapbox.zip public/ && cd public/ && unzip soapbox.zip && rm soapbox.zip
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 20.8M  100 20.8M    0     0  9666k      0  0:00:02  0:00:02 --:--:-- 9662k
Archive:  soapbox.zip
  inflating: report.html             
   creating: packs/
  inflating: packs/audio.worker-PmTdibbe.js  
  inflating: packs/memory.worker-BoRe3qDz.js 
  ...
  inflating: sw.js                   
  inflating: sw.js.map               
  inflating: index.html              
  inflating: 404.html  

to stop being the ditto user, if you type exit just once, it doesn't change the directory location, you're still in /opt/ditto, but, I assume, you do stop being the ditto user.

enter exit only once
exit

2.d. Provision the database⚓︎

create postgress user and database (from within /opt/ditto)

sudo -u postgres createuser -P ditto
enter ditto user password
Enter password for new role:
Retype:

I entered the existing ditto user password, should it have been a password for a second ditto user?

sudo -u postgres createdb ditto -O dittodb
sudo -u ditto psql dittodb
message from terminal
psql (version (Ubuntu)
Type "help" for help.

ditto=> ALTER USER ditto WITH PASSWORD 'added new database password';

The option above saves the password in plaintext.

Unsure on this one, as the docs point out to use a previously entered password, so it could be the one for the second ditto user, or maybe it is to fill in the database password where I just left the word ditto previously. Or perhaps the second ditto user and the database password are the same. I added what I'd like the database password to be.

close database
\q

2.e Start Ditto⚓︎

from within the /opt/ditto folder
sudo cp /opt/ditto/installation/ditto.service /etc/systemd/system/ditto.service

no message appeared.

to reload
sudo systemctl daemon-reload
enable ditto to run automatically
sudo systemctl enable --now ditto
message from terminal
Created symlink /etc/systemd/system/multi-user.target.wants/ditto.service  /etc/systemd/system/ditto.service.

check if ditto is running

systemctl status ditto

stop process with Ctrl + C

It fails here, but I haven't updated the .env file yet.

3. Getting online⚓︎

3.a. Configure Nginx⚓︎

correct location
sudo cp /opt/ditto/installation/ditto.conf /etc/nginx/sites-enabled/ditto.conf

open config file window to replace example.com with your domain

sudo nano /etc/nginx/sites-enabled/ditto.conf
original conf file for reference
# Nginx configuration for Ditto.
#
# Edit this file to change occurences of "example.com" to your own domain.

upstream ditto {
  server 127.0.0.1:4036;
}

server {
  listen 80;
  listen [::]:80;
  location /.well-known/acme-challenge/ { allow all; }
  location / { return 301 https://$host$request_uri; }
}

server {
  server_name example.com;

  keepalive_timeout 70;
  sendfile on;
  client_max_body_size 100m;
  ignore_invalid_headers off;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;

  root /opt/ditto/public;

  location /packs {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header Strict-Transport-Security "max-age=31536000" always;
    root /opt/ditto/public;
  }

  location ~ ^/(instance|sw\.js$|sw\.js\.map$) {
    root /opt/ditto/public;
    try_files $uri =404;
  }

  location /metrics {
    allow 127.0.0.1;
    deny all;
    proxy_pass http://ditto;
  }

location / {
    proxy_pass http://ditto;
  }
}
updated file
# Nginx configuration for Ditto.
#
# Edit this file to change occurences of "example.com" to your own domain.

upstream ditto {
  server 111.111.11.11:2140;
}

server {
  listen 80;
  listen [::]:80;
  location /.well-known/acme-challenge/ { allow all; }
  location / { return 301 https://$host$request_uri; }
}

server {
  server_name owndomain.com;

  keepalive_timeout 70;
  sendfile on;
  client_max_body_size 100m;
  ignore_invalid_headers off;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;

  root /opt/ditto/public;

  location /packs {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header Strict-Transport-Security "max-age=31536000" always;
    root /opt/ditto/public;
  }

  location ~ ^/(instance|sw\.js$|sw\.js\.map$) {
    root /opt/ditto/public;

    try_files $uri =404;
  }

  location /metrics {
    allow 111.111.11.11;
    # changed to server IP
    deny all;
    proxy_pass http://ditto;
  }

location / {
    proxy_pass http://ditto;
  }
}

after changes

If you make any other changes to the .env file, make sure to restart nginx. If you get any errors, the latest change you made is likely to be wrong.

sudo systemctl restart nginx

3.b.i. Setting up nginx to serve local uploads⚓︎

There's an extra step here if you didn't choose nostr.build for image uploads.


3.b. Obtain an SSL certificate⚓︎

navigate back to your server's home folder (username@server) repeating the following command twice
cd ..

sudo certbot --nginx
If your env file has no syntax errors, it will ask you for a contact email:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel):
agree to the terms of service
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.4-April-3-2024.pdf. You must agree in
order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

share your email address
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N
it will display your domain name, hit enter
Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: your domain name
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):
choose your option
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you are confident your site works on HTTPS. 
You can undo this
change by editing your web server s configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
chose to redirect all traffic to https, not sure if all traffic to ditto arrives so

success message with analyze link
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://yourdomain

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=yourdomain
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   ...
   Your cert will expire on. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le
visit the analyze link above
A grade 
for 
certificate
protocol support 
key exchange 
cipher strength

HTTP request failed
Server supports TLS 1.3
Trusted Yes

It expires in over 2 years

Qualys SSL labs documentation page

restart nginx

sudo systemctl restart nginx

The previous two times I got a 502 error. Right now I'm getting a connection that has timed out.

check again if ditto is running

if checked from server home folder

check status
systemctl status ditto
stop process with Ctrl + C

it's not running, here's the error message
 ditto.service - Ditto
     Loaded: loaded (/etc/systemd/system/ditto.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since date & time
    Process: 64502 ExecStart=/usr/local/bin/deno task start (code=exited, status=1/FAIL>
   Main PID: 64502 (code=exited, status=1/FAILURE)

if checked from within /opt/ditto

check status
systemctl status ditto
stop process with Ctrl + C

it's not running, here's the error message
 ditto.service - Ditto
     Loaded: loaded (/etc/systemd/system/ditto.service; enabled; vendor preset:>
     Active: failed (Result: exit-code) since date a>
    Process: 64502 ExecStart=/usr/local/bin/deno task start (code=exited, statu>
   Main PID: 64502 (code=exited, status=1/FAILURE)

date time server1.yourdomain.com systemd[1]: ditto.service: Scheduled>
date time server1.yourdomain.com systemd[1]: Stopped Ditto.
date time server1.yourdomain.com systemd[1]: ditto.service: Start req>
date time server1.yourdomain.com systemd[1]: ditto.service: Failed wi>
date time server1.yourdomain.com systemd[1]: Failed to start Ditto.
stop process with Ctrl + C

files in error message⚓︎

opening both files mentioned in the message above

sudo nano /etc/systemd/system/ditto.service

message from terminal
[Unit]
Description=Ditto
Wants=network-online.target
After=network-online.target

[Service]
Type=simple
User=ditto
WorkingDirectory=/opt/ditto
ExecStart=/usr/local/bin/deno task start
Restart=on-failure

[Install]
WantedBy=multi-user.target
Ctrl + C to close

sudo nano /usr/local/bin/deno 

Getting a lot of non-parsed characters and a few mentions of fatal errors, but nothing specific that would point to a possible fix. I'll review later in more detail.


restart from scratch⚓︎

Learning about tech means learning to make mistakes and trying again.

If you reinstall the server software to try this process again from scratch, on the same server IP, you will get a scary warning like this one:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
Don't worry, you can fix it by removing your old key from the server's IP:

ssh-keygen -R 111.111.11.11

source: How to Fix Warning Remote Host Identification Has Changed