# Deploying Colayer on AlmaLinux 9

This guide sets up Colayer on a single AlmaLinux 9 server:

- PostgreSQL 16 for the database.
- The Next.js app running as a systemd service.
- nginx in front with a free HTTPS certificate.
- Daily backups.

Run the commands as a user with `sudo` unless a step says otherwise.

**What you need:**

- A server with at least 2 GB of memory, or 1 GB plus the swap file in step 1.
- A domain name such as `intra.yourcompany.com`.
- SMTP credentials for sending sign-in codes.
- The code in a git repository the server can reach (see step 4).

Uploaded files are stored on the server's disk, so the app has to run as a long-lived process on a real server. Serverless hosts such as Vercel won't work without moving uploads to object storage first.

---

## 1. Update the system and install the basics

```bash
sudo dnf update -y
sudo dnf install -y git nginx tar
```

`npm run build` needs about 2 GB of memory. On a smaller server, add swap:

```bash
sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile
sudo mkswap /swapfile && sudo swapon /swapfile
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab
```

## 2. Install Node.js 22

```bash
sudo dnf module reset -y nodejs
sudo dnf module enable -y nodejs:22
sudo dnf install -y nodejs
node -v   # should print v22.x
```

If the `nodejs:22` stream isn't available on your AlmaLinux version, use NodeSource instead:

```bash
curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
sudo dnf install -y nodejs
```

## 3. Install PostgreSQL 16 and create the database

```bash
sudo dnf module reset -y postgresql
sudo dnf module enable -y postgresql:16
sudo dnf install -y postgresql-server postgresql
sudo postgresql-setup --initdb
sudo systemctl enable --now postgresql
```

**Allow password logins over localhost.** AlmaLinux uses `ident` authentication by default, which rejects the app with "Ident authentication failed". Switch local TCP connections to password authentication:

```bash
sudo sed -i -E 's/^(host\s+all\s+all\s+(127\.0\.0\.1\/32|::1\/128)\s+)ident/\1scram-sha-256/' /var/lib/pgsql/data/pg_hba.conf
sudo systemctl restart postgresql
```

**Create the database user and database.** Generate a strong password first:

```bash
openssl rand -base64 24
sudo -u postgres psql
```

```sql
CREATE USER intra WITH PASSWORD 'paste-the-password-here';
CREATE DATABASE intra_cotrav OWNER intra;
\q
```

PostgreSQL only listens on `localhost` by default. Keep it that way: the database should never be reachable from the internet.

## 4. Create the app user and get the code

```bash
sudo useradd --create-home --shell /bin/bash intra
sudo -iu intra
mkdir -p ~/uploads ~/backups
```

If the repository is private, give the server read-only access to it with a deploy key:

```bash
ssh-keygen -t ed25519 -C "intra-server" -f ~/.ssh/id_ed25519 -N ""
cat ~/.ssh/id_ed25519.pub
```

On GitHub, go to the repository's **Settings → Deploy keys → Add deploy key**. Paste the key and leave "Allow write access" unchecked. GitLab and Bitbucket have the same feature. Then clone the code:

```bash
git clone git@github.com:YOUR-USERNAME/intra-cotrav.git ~/app
cd ~/app
```

## 5. Configure the app

Still as the `intra` user, create `~/app/.env`:

```bash
nano .env
```

```
DATABASE_URL="postgresql://intra:paste-the-password-here@127.0.0.1:5432/intra_cotrav"

UPLOAD_DIR="/home/intra/uploads"
MAX_UPLOAD_MB=25

# Only people with an email at this domain can sign themselves up.
# Admins can still add anyone from the People page.
ALLOWED_EMAIL_DOMAIN="yourcompany.com"

SMTP_HOST="smtp.yourprovider.com"
SMTP_PORT=587
SMTP_SECURE=false          # true when using port 465
SMTP_USER="..."
SMTP_PASS="..."
MAIL_FROM="Colayer <no-reply@yourcompany.com>"

# Push notifications (see below for how to generate these)
VAPID_PUBLIC_KEY="..."
VAPID_PRIVATE_KEY="..."
VAPID_SUBJECT="mailto:it@yourcompany.com"
```

```bash
chmod 600 .env
```

**Use a dedicated sending credential for SMTP.** That means an app password, Amazon SES SMTP credentials or a send-only API key, never a personal mailbox password. Without `SMTP_HOST`, the app refuses to send sign-in codes in production.

- **Port 587** (`SMTP_SECURE=false`): the app requires the connection to be upgraded to TLS before it sends the password or any email, and refuses to send otherwise.
- **Port 465** (`SMTP_SECURE=true`): the connection is encrypted from the start.
- **Port 25:** don't use it. Many hosts block it, and it's meant for server-to-server mail.

For Gmail or Google Workspace, use `smtp.gmail.com` on port 587 with an [app password](https://myaccount.google.com/apppasswords). That requires 2-step verification on the sending account.

**Generate the push notification keys** on the server, once, after step 6's `npm ci`:

```bash
cd ~/app
npx web-push generate-vapid-keys
```

Copy the public and private key it prints into `VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY`, and set `VAPID_SUBJECT` to a contact address for your IT team (push services use it if something goes wrong).

- **Use these keys only on this server.** Don't reuse the keys from your development `.env`.
- **Keep the private key secret.** Anyone who has it can send notifications to your users' browsers.
- **Keep the same keys from then on.** If they change, everyone's browser subscription stops working and people have to turn notifications on again.

Without these keys the app runs normally, but push notifications are off and admins see a note on the Notifications page.

## 6. Install, create the tables and build

```bash
npm ci                      # installs packages and generates the Prisma client
npx prisma migrate deploy   # creates every table from prisma/migrations
npm run build
exit                        # back to your sudo user
```

**Never run `npm run db:seed` on the server.** It wipes the data and creates demo accounts whose passwords are published in the README. For the same reason, never run `prisma migrate dev` or `prisma migrate reset` there.

## 7. Run the app as a service

Create `/etc/systemd/system/intra.service`:

```ini
[Unit]
Description=Colayer intranet
After=network.target postgresql.service

[Service]
User=intra
WorkingDirectory=/home/intra/app
Environment=NODE_ENV=production
Environment=PORT=3000
Environment=HOSTNAME=127.0.0.1
ExecStart=/usr/bin/npm start
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now intra
sudo systemctl status intra          # should say "active (running)"
curl -I http://127.0.0.1:3000/login  # should return 200
```

To see the app's logs, run `journalctl -u intra -f`.

## 8. Put nginx in front of the app

Create `/etc/nginx/conf.d/intra.conf`:

```nginx
server {
    listen 80;
    server_name intra.yourcompany.com;

    # Must be larger than MAX_UPLOAD_MB
    client_max_body_size 30M;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        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;
    }
}
```

Keep the `X-Real-IP` line. Sign-in rate limits (see below) count attempts per visitor IP address, and they read it from this header. That's also why the app listens only on `127.0.0.1` (step 7): if it were reachable directly, a visitor could set the header themselves and get around the per-IP limits.

**Allow nginx through SELinux.** SELinux stops nginx from connecting to the app by default, which shows up as "502 Bad Gateway":

```bash
sudo setsebool -P httpd_can_network_connect 1
```

```bash
sudo nginx -t
sudo systemctl enable --now nginx
```

## 9. Open the firewall

```bash
sudo systemctl enable --now firewalld
sudo firewall-cmd --permanent --add-service=http --add-service=https --add-service=ssh
sudo firewall-cmd --reload
```

Only open these services. Never open port 3000 (the app) or 5432 (PostgreSQL); everything goes through nginx.

## 10. Turn on HTTPS

First point your domain's DNS A record at the server's IP address. Then:

```bash
sudo dnf install -y epel-release
sudo dnf install -y certbot python3-certbot-nginx
sudo certbot --nginx -d intra.yourcompany.com
sudo systemctl enable --now certbot-renew.timer   # renews the certificate automatically
```

HTTPS is required. In production the login cookie is only sent over HTTPS, so sign-in fails on plain HTTP.

## 11. Create the first admin

Open `https://intra.yourcompany.com/signup` and register. The first account on an empty database becomes the admin. Add everyone else from **People → Add person**, which gives each person a temporary password that they change at their first sign-in.

## 12. Set up daily backups

As the `intra` user, store the database password so backups can run unattended:

```bash
sudo -iu intra
echo "127.0.0.1:5432:intra_cotrav:intra:paste-the-password-here" > ~/.pgpass
chmod 600 ~/.pgpass
crontab -e
```

Add these lines. The database is backed up at 02:00 and the uploads at 02:30, and backups older than 14 days are deleted:

```
0 2 * * * pg_dump -Fc -h 127.0.0.1 -U intra intra_cotrav > ~/backups/db-$(date +\%F).dump
30 2 * * * tar -czf ~/backups/uploads-$(date +\%F).tgz -C ~ uploads && find ~/backups -mtime +14 -delete
```

The database and the uploads folder belong together, because database records point at files on disk. Copy both off the server regularly.

**To restore:**

```bash
pg_restore --clean -h 127.0.0.1 -U intra -d intra_cotrav ~/backups/db-2026-12-01.dump
tar -xzf ~/backups/uploads-2026-12-01.tgz -C ~
sudo systemctl restart intra
```

---

## Deploying updates

```bash
sudo -iu intra
cd ~/app
git pull
npm ci
npx prisma migrate deploy   # applies any new migrations; safe to run every time
npm run build
exit
sudo systemctl restart intra
```

## Sign-in rate limits

These limits are built in and need no setup:

| What | Limit | Counted per |
| --- | --- | --- |
| Wrong passwords | 8 per 15 minutes | account, from any IP |
| Wrong passwords | 20 per 15 minutes | IP address |
| Sign-in code emails | 10 per 15 minutes | IP address |
| Sign-in code emails | 1 per 30 seconds, 6 per hour | account |
| Wrong codes | 5 per code, 20 per 15 minutes | code, IP address |
| New sign-ups | 10 per hour | IP address |

A successful sign-in clears that account's count of wrong passwords. While an account's password sign-in is locked, its owner can still sign in with an email code.

The counters are kept in the app's memory, so `sudo systemctl restart intra` clears them all. That's also how to unlock someone early. Keeping them in memory is fine for a single server. If you ever run several copies of the app behind a load balancer, the counters need to move to the database or Redis.

People sharing one office internet connection share one IP address. If a large office regularly hits the per-IP limits, raise them in `src/lib/rate-limit.ts`.

## Push notifications

People turn notifications on per browser: on the **Notifications** page, or from the prompt on the timeline. They then get a system notification for replies, mentions, shares, team invites and Sem type reviews, even when Colayer isn't open. Clicking it opens the right page.

- **The server sends pushes out to the browser makers' push services:** Google (`fcm.googleapis.com`), Mozilla (`updates.push.services.mozilla.com`), Apple (`web.push.apple.com`) and Microsoft (`*.notify.windows.com`). If your server's outgoing traffic is filtered, allow HTTPS (port 443) to these hosts. The app refuses to send to any other address.
- **Message content is end-to-end encrypted.** The push services can't read it. The notification itself shows who did what and the first line of the post, including on a locked screen.
- **Signing out stops pushes to that browser,** and so does an admin resetting someone's password. Each subscription belongs to the sign-in session it was made in.
- **iPhone and iPad:** push only works after adding Colayer to the Home Screen (Safari → Share → **Add to Home Screen**), then turning notifications on from the app opened there. This needs iOS 16.4 or later.
- **HTTPS is required.** Browsers only allow push on secure sites (step 10).

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `502 Bad Gateway` | SELinux is blocking nginx. Run `sudo setsebool -P httpd_can_network_connect 1`. If that doesn't fix it, check that the app is running with `systemctl status intra`. |
| `Ident authentication failed for user "intra"` | The `pg_hba.conf` change in step 3 is missing. Apply it, then run `sudo systemctl restart postgresql`. |
| The build stops with `Killed` | Not enough memory. Add swap (step 1). |
| Sign-in does nothing, or you're signed out immediately | The site isn't served over HTTPS (step 10). |
| Sign-in code emails don't arrive | Check `journalctl -u intra` for the error. Some hosts block outgoing port 587; try port 465 with `SMTP_SECURE=true`. |
| Email fails with `Invalid login: 535` | The mail server rejected the username or password. For Gmail, use an app password, not the account password. |
| Email fails with `STARTTLS` or `TLS` in the error | The mail server didn't offer encryption on port 587. Check the host and port, or use port 465 with `SMTP_SECURE=true`. |
| "Too many attempts" for many people at once | Everyone may share one office IP address, or nginx isn't sending `X-Real-IP`. Check the nginx config, then run `sudo systemctl restart intra` to clear the counters. |
| No **Turn on** button for notifications | The VAPID keys aren't set. Add them to `.env` and run `sudo systemctl restart intra`. |
| Notifications turned on, but none arrive | Check `journalctl -u intra` for "Push failed". Make sure outgoing HTTPS to the push services is allowed. Also check the operating system's notification settings for the browser, and Focus or Do Not Disturb. |
| `413 Request Entity Too Large` on upload | Raise `client_max_body_size` in the nginx config, then run `sudo systemctl reload nginx`. |
| Upload fails with a permission error | Make sure `/home/intra/uploads` exists and belongs to `intra` by running `sudo chown -R intra:intra /home/intra/uploads`. |

## Connecting to the production database

From the server:

```bash
sudo -iu intra
psql -h 127.0.0.1 -U intra intra_cotrav
```

From a desktop tool such as DataGrip, connect through SSH instead of opening port 5432. Set the data source's **SSH/SSL** tab to your server, then use host `127.0.0.1`, port `5432`, database `intra_cotrav` and user `intra`.
