diff --git a/.env.prod.example b/.env.prod.example index 61a2924..56efea7 100644 --- a/.env.prod.example +++ b/.env.prod.example @@ -53,3 +53,10 @@ EMAILJS_PRIVATE_KEY= # Image names and tag (for images built elsewhere, e.g. in CI and pulled from a registry) # IMAGE_PREFIX=ghcr.io/bradylab/data-visualizer # IMAGE_TAG=latest + +# Only when another web server owns ports 80/443 and does the HTTPS, such as cPanel's Apache (steps: deploy/cpanel/README.md). Leave unset otherwise +# WEB_HTTP_PUBLISH=127.0.0.1:8080 +# WEB_HTTPS_PUBLISH=127.0.0.1:8443 +# SITE_ADDRESS=http://data.example.org +# TRUSTED_PROXIES=private_ranges +# TRUST_PROXY=2 diff --git a/backend-express/package.json b/backend-express/package.json index 8a0e745..d0073bb 100644 --- a/backend-express/package.json +++ b/backend-express/package.json @@ -8,11 +8,12 @@ "build": "tsc", "start": "node dist/index.js", "dev": "tsx watch src/index.ts", - "format": "prettier --write --experimental-cli src/ && prettier --write --experimental-cli migrations/ && prettier --write --experimental-cli seeders/ && prettier --write --experimental-cli seeders-e2e/ && prettier --write --experimental-cli ../commons", + "format": "prettier --write --experimental-cli src/ && prettier --write --experimental-cli migrations/ && prettier --write --experimental-cli seeders/ && prettier --write --experimental-cli seeders-e2e/ && prettier --write --experimental-cli scripts/ && prettier --write --experimental-cli ../commons", "format:check": "prettier --check src/", "db:migrate": "node --import tsx node_modules/.bin/sequelize-cli db:migrate --config src/config.ts", "db:migrate:undo": "node --import tsx node_modules/.bin/sequelize-cli db:migrate:undo --config src/config.ts", "db:seed": "node --import tsx node_modules/.bin/sequelize-cli db:seed:all --config src/config.ts", + "admin:create": "node --import tsx scripts/create-admin.ts", "db:seed:e2e": "node --import tsx node_modules/.bin/sequelize-cli db:seed:all --config src/config.ts --seeders-path seeders-e2e", "e2e:start": "npm run db:migrate && npm run db:seed:e2e && tsx src/index.ts" }, diff --git a/backend-express/scripts/create-admin.ts b/backend-express/scripts/create-admin.ts new file mode 100644 index 0000000..42e328a --- /dev/null +++ b/backend-express/scripts/create-admin.ts @@ -0,0 +1,24 @@ +// Creates the first administrator of a production database (see src/services/adminBootstrap.ts). Run on the server, inside the backend container: +// docker compose -f docker-compose.prod.yml exec -e ADMIN_EMAIL=you@example.org -e ADMIN_NAME="Your Name" backend npm run admin:create +// Prints a temporary password once; it is not stored anywhere readable, so copy it from the terminal. Safe to run again: nothing happens if +// the user already exists. +import "dotenv/config"; +import "reflect-metadata"; +import { sequelize } from "@src/database.ts"; +import { createFirstAdmin } from "@src/services/adminBootstrap.ts"; + +try { + const result = await createFirstAdmin(); + if (result.created) { + console.log(`Created the administrator ${result.email}.`); + console.log(`Temporary password (shown only now): ${result.password}`); + console.log("Log in with it; the app then asks for a new password."); + } else { + console.log(`${result.email} already exists; nothing was changed.`); + } +} catch (err) { + console.error(err instanceof Error ? err.message : err); + process.exitCode = 1; +} finally { + await sequelize.close(); +} diff --git a/backend-express/src/services/adminBootstrap.ts b/backend-express/src/services/adminBootstrap.ts new file mode 100644 index 0000000..e4eae20 --- /dev/null +++ b/backend-express/src/services/adminBootstrap.ts @@ -0,0 +1,47 @@ +// Creates the first administrator of a production database. The development seeders are not run in production (they hold real people's +// emails), so without this there would be no way to log in the first time. Used by scripts/create-admin.ts (npm run admin:create) +import { UniqueConstraintError } from "sequelize"; +import { UserRoles, UserStatus } from "@commons/user.ts"; +import { Users } from "@src/models/user.ts"; +import { generatePassword, hashPassword } from "@src/utils/password.ts"; + +type Env = Record; + +/** What happened: the account that was created, with its one-time temporary password, or the account that was already there */ +export type FirstAdminResult = { created: true; email: string; password: string } | { created: false; email: string }; + +// One "@", no spaces, a dot in the domain: only to catch typos, the real check is that the person can log in +const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + +/** Reads ADMIN_EMAIL and ADMIN_NAME; throws an Error whose message says what is missing or wrong */ +export const adminInput = (env: Env = process.env) => { + const email = env.ADMIN_EMAIL?.trim(); + const name = env.ADMIN_NAME?.trim(); + if (!email || !name) throw new Error("Set ADMIN_EMAIL and ADMIN_NAME (the new administrator's email address and name)"); + if (!EMAIL_PATTERN.test(email)) throw new Error(`ADMIN_EMAIL "${email}" is not an email address`); + return { email, name }; +}; + +/** + * Creates one ADMIN in the INVITED state with a random temporary password, which the person must change at their first login. + * Does nothing (created: false) when a user with that email already exists, so running it again is harmless and never resets a password. + */ +export const createFirstAdmin = async (env: Env = process.env): Promise => { + const { email, name } = adminInput(env); + if (await Users.findOne({ where: { email } })) return { created: false, email }; + const password = generatePassword(); + try { + await Users.create({ + email, + name, + password: await hashPassword(password), + role: UserRoles.ADMIN, + status: UserStatus.INVITED, + } as Users); + } catch (err) { + // Two runs at the same moment: the other one won + if (err instanceof UniqueConstraintError) return { created: false, email }; + throw err; + } + return { created: true, email, password }; +}; diff --git a/backend-express/test/adminBootstrap.test.ts b/backend-express/test/adminBootstrap.test.ts new file mode 100644 index 0000000..ea900ea --- /dev/null +++ b/backend-express/test/adminBootstrap.test.ts @@ -0,0 +1,72 @@ +// Tests for creating the first administrator (services/adminBootstrap); the database calls are stubbed +import { test, afterEach, mock } from "node:test"; +import assert from "node:assert/strict"; +import { UniqueConstraintError } from "sequelize"; +import { UserRoles, UserStatus } from "@commons/user.ts"; +import { Users } from "@src/models/user.ts"; +import { adminInput, createFirstAdmin } from "@src/services/adminBootstrap.ts"; +import { verifyPassword } from "@src/services/auth.ts"; + +afterEach(() => mock.restoreAll()); + +const env = { ADMIN_EMAIL: " boss@example.org ", ADMIN_NAME: " The Boss " }; + +test("the email and name are required, trimmed, and the email must look like one", () => { + assert.deepEqual(adminInput(env), { email: "boss@example.org", name: "The Boss" }); + assert.throws(() => adminInput({}), /ADMIN_EMAIL and ADMIN_NAME/); + assert.throws(() => adminInput({ ADMIN_EMAIL: "boss@example.org" }), /ADMIN_EMAIL and ADMIN_NAME/); + assert.throws(() => adminInput({ ADMIN_EMAIL: " ", ADMIN_NAME: "x" }), /ADMIN_EMAIL and ADMIN_NAME/); + assert.throws(() => adminInput({ ADMIN_EMAIL: "not-an-email", ADMIN_NAME: "x" }), /not an email address/); +}); + +test("creates an INVITED admin whose stored password is the hash of the one it returns", async () => { + mock.method(Users, "findOne", async () => null); + const create = mock.method(Users, "create", async (values: unknown) => values as Users); + const result = await createFirstAdmin(env); + assert.ok(result.created); + assert.equal(result.email, "boss@example.org"); + assert.ok(result.password.length >= 16); + const stored = create.mock.calls[0]?.arguments[0] as unknown as Users; + assert.equal(stored.email, "boss@example.org"); + assert.equal(stored.name, "The Boss"); + assert.equal(stored.role, UserRoles.ADMIN); + assert.equal(stored.status, UserStatus.INVITED); + assert.notEqual(stored.password, result.password); + assert.ok(await verifyPassword(result.password, stored.password)); +}); + +test("each run makes a different password", async () => { + mock.method(Users, "findOne", async () => null); + mock.method(Users, "create", async (values: unknown) => values as Users); + const a = await createFirstAdmin(env); + const b = await createFirstAdmin(env); + assert.ok(a.created && b.created); + assert.notEqual(a.password, b.password); +}); + +test("an existing user with that email is left alone, whatever its role", async () => { + mock.method(Users, "findOne", async () => ({ email: "boss@example.org", role: UserRoles.EXTERNAL })); + const create = mock.method(Users, "create", async () => assert.fail("must not create")); + assert.deepEqual(await createFirstAdmin(env), { created: false, email: "boss@example.org" }); + assert.equal(create.mock.callCount(), 0); +}); + +test("losing a race to another run counts as already existing; other errors are not hidden", async () => { + mock.method(Users, "findOne", async () => null); + mock.method(Users, "create", async () => { + throw new UniqueConstraintError({}); + }); + assert.deepEqual(await createFirstAdmin(env), { created: false, email: "boss@example.org" }); + mock.restoreAll(); + mock.method(Users, "findOne", async () => null); + mock.method(Users, "create", async () => { + throw new Error("database down"); + }); + await assert.rejects(createFirstAdmin(env), /database down/); +}); + +test("without the settings nothing is looked up or created", async () => { + const find = mock.method(Users, "findOne", async () => null); + await assert.rejects(createFirstAdmin({}), /ADMIN_EMAIL/); + assert.equal(find.mock.callCount(), 0); +}); diff --git a/backend-express/tsconfig.json b/backend-express/tsconfig.json index fcdce36..66ed61f 100644 --- a/backend-express/tsconfig.json +++ b/backend-express/tsconfig.json @@ -51,5 +51,5 @@ "@src/*": ["./src/*"], } }, - "include": ["src/**/*", "test/**/*", "migrations/**/*", "seeders/**/*", "seeders-e2e/**/*", "../commons/**/*", "src/config.ts"] + "include": ["src/**/*", "test/**/*", "migrations/**/*", "seeders/**/*", "seeders-e2e/**/*", "scripts/**/*", "../commons/**/*", "src/config.ts"] } diff --git a/deploy/cpanel/README.md b/deploy/cpanel/README.md new file mode 100644 index 0000000..62cc949 --- /dev/null +++ b/deploy/cpanel/README.md @@ -0,0 +1,98 @@ +# Deploying on a cPanel/WHM server (AlmaLinux 9) + +cPanel's Apache owns ports 80 and 443 and does the HTTPS (AutoSSL). The Docker stack runs beside it: Caddy listens on 127.0.0.1:8080 in plain +HTTP, and Apache proxies the domain to it. Visitors -> Apache (TLS) -> Caddy (frontend files, routing) -> backend / Shiny / Postgres. +Everything is switched on by variables in `.env` (see the end of `.env.prod.example`); the compose file is the same as on any other server. +Run the commands as root. + +## 1. Domain in cPanel +1. Create the host name (e.g. `data.example.org`) as a subdomain or addon domain of a cPanel account; its DNS A record must point at this server. +2. In WHM > Manage AutoSSL (or the account's SSL/TLS Status), run AutoSSL for it so Apache has a certificate. Note the account's user name (``). +3. If WHM > ModSecurity is on, disable it for this domain (WHM > ModSecurity Tools > Domains): its default request-body limit (about 13 MB) breaks uploads. + +## 2. Install Docker + dnf install -y dnf-plugins-core + dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo + dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin + systemctl enable --now docker + docker run --rm hello-world +cPanel's nightly package updates (WHM > Update Preferences > Operating System Package Updates: Automatic) then keep Docker patched too. Kernel updates +still need a reboot: check `needs-restarting -r` now and then, or reboot in a quiet hour. +(`/tmp` being `noexec` does not matter: image builds run inside Docker.) + +## 3. Get the code and configure it + git clone https://github.com/BradyLab/data-visualizer /opt/data-visualizer && cd /opt/data-visualizer + cp .env.prod.example .env +Fill in `.env` as described in the file, plus these (15 GB server: leave room for cPanel's own services, about 2 GB): + + DOMAIN=data.example.org + WEB_HTTP_PUBLISH=127.0.0.1:8080 + WEB_HTTPS_PUBLISH=127.0.0.1:8443 + SITE_ADDRESS=http://data.example.org + TRUSTED_PROXIES=private_ranges + TRUST_PROXY=2 + PREPROCESS_MODE=auto + PREPROCESS_MEM_LIMIT=6g + SHINY_MEM_LIMIT=3g + SHINY_DUCKDB_MEMORY_LIMIT=1g + DATA_DIR=/home//dv-data # inside the cPanel account, so cPanel backups include it (step 6) + + mkdir -p /home//dv-data && chown 1000:1000 /home//dv-data + docker compose -f docker-compose.prod.yml up -d --build # or set IMAGE_PREFIX and run `docker compose ... pull` first + curl -s -H "Host: data.example.org" http://127.0.0.1:8080/health # answers through Caddy (it only answers for its own host name) + +## 4. Point Apache at it +Only the HTTPS vhost proxies to the app; the HTTP one just redirects to HTTPS (the include tells the app the visitor used HTTPS, which would be +false on port 80). + + d=/etc/apache2/conf.d/userdata/ssl/2_4//; mkdir -p "$d"; cp deploy/cpanel/apache-proxy.conf "$d/dv.conf" + /scripts/ensure_vhost_includes --user= # checks the config and rebuilds httpd.conf + systemctl restart httpd # (or: /scripts/restartsrv_httpd) + +Then turn on "Force HTTPS Redirect" for the domain (cPanel > Domains), so http:// goes to https://. +The folder names must be the cPanel user from `grep /etc/userdomains`, and the domain exactly as cPanel lists it. +Open https://data.example.org. If it shows the cPanel default page or a 503, check `curl -s -H "Host: " http://127.0.0.1:8080/health` first (the stack), +then `tail /var/log/apache2/error_log` (the proxy). +To test from the server itself, connect to the address the domain's vhost listens on (`httpd -S | grep `; behind NAT it is a private +address such as 10.0.2.15, NOT 127.0.0.1, which is the server host name's vhost): `curl -skI --resolve :443: https:///health`. +The visitor address check: log in wrongly a few times from two networks; the backend log (`docker compose -f docker-compose.prod.yml logs backend`) +must show each visitor's own address, not 172.x. If it shows 172.x for everybody, TRUST_PROXY or TRUSTED_PROXIES is not set. + +## 5. First admin and nightly updates +- First administrator (the development seeders do not run in production). Once the site opens, create one ADMIN with a temporary password: + + cd /opt/data-visualizer + docker compose -f docker-compose.prod.yml exec -e ADMIN_EMAIL=you@example.org -e ADMIN_NAME="Your Name" backend npm run admin:create + + It prints the password once: copy it, log in, and the app asks for a new one. Running it again changes nothing, so a lost password is not + recovered this way: use "Forgot password?" on the login page (needs EmailJS), or delete the user row in Postgres and run the command again. + Everyone else is invited from the app by this admin. +- Nightly image updates: the timer in `deploy/` (see the header of `data-visualizer-update.service`); nothing changes for cPanel. + +## 6. Backups +cPanel backs up each account's home folder, but not Docker volumes. So `DATA_DIR` (inside the home folder) is covered, and Postgres, which lives in +a Docker volume, is not. The fix is a nightly dump of the database into the home folder. + +1. Create `/etc/cron.d/dv-db-dump` with this single line (replace ``). It keeps one dump per weekday, so the last seven nights are kept: + + 30 1 * * * root umask 077; cd /opt/data-visualizer && docker compose -f docker-compose.prod.yml exec -T postgres pg_dump -U postgres data_visualizer | gzip > /home//dv-data/db-$(date +\%a).sql.gz + + `umask 077` makes the dump readable by root only. It contains password hashes, and root is who runs the cPanel backup. + +2. Skip the Parquet files, which can be rebuilt from the `.rds` files and would only make the backups bigger: + + echo "dv-data/parquet" >> /home//cpbackup-exclude.conf + +3. In WHM > Backup > Backup Configuration, check three things: + - The backup starts after 01:30, or it will contain the previous night's dump. + - This account is selected for backup. + - A remote destination is set (WHM > Backup > Additional Destinations: SFTP, S3, Backblaze B2, ...). A destination on this same server is lost along with the server. + +4. Restore test (do it once, before relying on it). Load a dump into a scratch database: + + cd /opt/data-visualizer + docker compose -f docker-compose.prod.yml exec -T postgres createdb -U postgres scratch + gunzip -c /home//dv-data/db-$(date +%a).sql.gz | docker compose -f docker-compose.prod.yml exec -T postgres psql -U postgres -d scratch + docker compose -f docker-compose.prod.yml exec -T postgres dropdb -U postgres scratch + +After a cPanel restore the files belong to the account's user again, so run `chown -R 1000:1000 /home//dv-data` and restart the stack. diff --git a/deploy/cpanel/apache-proxy.conf b/deploy/cpanel/apache-proxy.conf new file mode 100644 index 0000000..bae8717 --- /dev/null +++ b/deploy/cpanel/apache-proxy.conf @@ -0,0 +1,13 @@ +# Apache include that sends the whole site to the Caddy container (127.0.0.1:8080). Install it for the HTTPS vhost of the domain only (README.md, step 4): +# /etc/apache2/conf.d/userdata/ssl/2_4///dv.conf +# Not in the std (http) folder: that vhost only redirects to https, and this file says X-Forwarded-Proto is https. +# Needs nothing beyond mod_proxy and mod_proxy_http (upgrade=websocket works without mod_proxy_wstunnel on Apache 2.4.47 and newer). +ProxyPreserveHost On +ProxyRequests Off +# Caddy and the backend read this to know the visitor came in over HTTPS (it trusts it only from the proxies listed in TRUSTED_PROXIES) +RequestHeader set X-Forwarded-Proto "https" +# Multi-GB uploads: no body limit, and an hour before a quiet connection is cut (long downloads, Shiny websockets) +LimitRequestBody 0 +ProxyTimeout 3600 +ProxyPass / http://127.0.0.1:8080/ upgrade=websocket timeout=3600 retry=0 +ProxyPassReverse / http://127.0.0.1:8080/ diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index bdf9f7e..ef08413 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -25,12 +25,17 @@ services: context: . dockerfile: frontend/Dockerfile image: ${IMAGE_PREFIX:-data-visualizer}-web:${IMAGE_TAG:-latest} + # The defaults publish 80 and 443 to the world. Behind another web server (cPanel's Apache, see deploy/cpanel/README.md) .env moves them + # to loopback ports and turns Caddy's own HTTPS off ports: - - "80:80" - - "443:443" - - "443:443/udp" + - "${WEB_HTTP_PUBLISH:-80}:80" + - "${WEB_HTTPS_PUBLISH:-443}:443" + - "${WEB_HTTPS_PUBLISH:-443}:443/udp" environment: - DOMAIN: ${DOMAIN:?set DOMAIN in .env (see .env.prod.example)} + # Caddy's site address: the bare host name means automatic HTTPS; SITE_ADDRESS=http:// means plain HTTP (TLS done in front) + DOMAIN: ${SITE_ADDRESS:-${DOMAIN:?set DOMAIN in .env (see .env.prod.example)}} + # Proxies in front of Caddy whose X-Forwarded-For and -Proto Caddy believes (see the Caddyfile). Loopback only unless set + TRUSTED_PROXIES: ${TRUSTED_PROXIES:-127.0.0.1/32} volumes: # Certificates and Caddy's state: losing them only means getting new certificates - caddy-data:/data @@ -52,8 +57,8 @@ services: API_PORT: "3001" BACKEND_URL: https://${DOMAIN} FRONTEND_URL: https://${DOMAIN} - # One proxy (Caddy) in front: the login and websocket rate limits then see each client's own address - TRUST_PROXY: "1" + # One proxy (Caddy) in front: the login and websocket rate limits then see each client's own address. 2 when Apache is in front of Caddy + TRUST_PROXY: ${TRUST_PROXY:-1} DB_HOST: postgres DB_PORT: "5432" DB_NAME: data_visualizer diff --git a/frontend/Caddyfile b/frontend/Caddyfile index cd46bf9..f06e191 100644 --- a/frontend/Caddyfile +++ b/frontend/Caddyfile @@ -1,7 +1,15 @@ # Caddy in front of everything (the web service of docker-compose.prod.yml). # DOMAIN is the public host name, for example data.example.org: it must point at this server, and ports 80 and 443 must be open, so Caddy # can get and renew its HTTPS certificate on its own. Use DOMAIN=localhost to try the stack locally (Caddy then makes a local certificate). +# Behind another web server that does the HTTPS (cPanel's Apache): SITE_ADDRESS=http:// makes Caddy serve plain HTTP, and TRUSTED_PROXIES +# (private_ranges) makes it keep the X-Forwarded-For and -Proto that server sends instead of replacing them with its own address. # Not behind a CDN proxy such as Cloudflare's free plan: it caps request bodies at 100 MB and would break the multi-GB uploads. +{ + servers { + trusted_proxies static {$TRUSTED_PROXIES:127.0.0.1/32} + } +} + {$DOMAIN} { encode zstd gzip diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico index df36fcf..a11a22b 100644 Binary files a/frontend/public/favicon.ico and b/frontend/public/favicon.ico differ