Skip to content

Commit c57f83b

Browse files
Add project-local PostgreSQL on a random port, supervised by PM2
For VMs where the usual ports are already taken, the deployment can now run its own PostgreSQL inside the project instead of relying on a fixed host port. - scripts/postgres-local.sh: init a cluster under .postgres/ on a RANDOM free port (persisted in .postgres/port), create the role + database, and print the DATABASE_URL. Subcommands: init, start (foreground, for PM2), ctl-start/ctl-stop (used by deploy.sh), status. Refuses to run as root, as PostgreSQL requires. - ecosystem.config.cjs: supervises opencoperlock-postgres (ahead of the API) when a project-local cluster is present. - deploy.sh: brings the local cluster up for migrate/seed if it isn't already running (first install), then stops it so PM2 owns it; on redeploy it detects the running DB and migrates directly. - setup-wizard.sh: new database choice — project-local (random port, PM2-managed), system PostgreSQL, or an existing DATABASE_URL. Verified end to end as a non-root user: init picks a random port, the cluster starts, a TCP+password connection works, and all migrations apply. Docs + checklist updated; .postgres/ is gitignored.
1 parent 94151d7 commit c57f83b

7 files changed

Lines changed: 271 additions & 29 deletions

File tree

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ next-env.d.ts
2323
/data/
2424
storage/
2525
quarantine/
26+
# Project-local PostgreSQL cluster (created by scripts/postgres-local.sh)
27+
/.postgres/
2628

2729
# Prisma
2830
apps/api/prisma/*.db

‎TEST-CHECKLIST.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,21 @@ were hardened.
138138
- [ ] **Backward compatible**: a vault created before this change (no salt) still unlocks
139139
with its passphrase (uses the legacy salt). New vaults use a random per-vault salt.
140140

141+
## Project-local PostgreSQL on a random port (lot 6)
142+
143+
For hosts where ports are scarce: the wizard can run a dedicated PostgreSQL inside the
144+
project (`.postgres/`) on a random free port, supervised by PM2.
145+
146+
- [ ] **Wizard**: at the PostgreSQL step choose "Project-local DB". It picks a random free
147+
port, creates the cluster + role + database, and writes the generated `DATABASE_URL`
148+
(with that port) into `.env`.
149+
- [ ] **PM2**: `pm2 status` shows `opencoperlock-postgres` running alongside the api/web.
150+
- [ ] **Random port**: `cat .postgres/port` shows the chosen port; it also appears in the
151+
`DATABASE_URL` in `.env`. Nothing needed port 5432 to be free.
152+
- [ ] **Manual path**: `DB_NAME=… DB_USER=… ./scripts/postgres-local.sh init` prints a
153+
`DATABASE_URL`; `./scripts/deploy.sh` migrates/seeds (starting the cluster if needed),
154+
then `pm2 start ecosystem.config.cjs` runs everything.
155+
- [ ] **Survives reboot**: after `pm2 save && pm2 startup`, a reboot brings the database and
156+
app back up.
157+
141158
<!-- New features are appended below as they are built. -->

‎docs/DEPLOYMENT.md‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,24 @@ npm i -g pm2
146146
# (optional) clamav-daemon if you want antivirus scanning.
147147
```
148148

149+
### Database options
150+
151+
The wizard offers three ways to get a database, picked during setup:
152+
153+
1. **Project-local PostgreSQL (recommended on busy hosts).** A dedicated cluster is created
154+
inside the repo under `.postgres/`, listening on `127.0.0.1` on a **random free port**
155+
chosen at install time, and supervised by **PM2** alongside the app. Nothing needs port
156+
5432 (or any fixed port) to be free. Managed with `scripts/postgres-local.sh`.
157+
2. **System PostgreSQL.** A database + user are created on the host's PostgreSQL service.
158+
3. **Existing `DATABASE_URL`.** Point at a database you already run.
159+
160+
For the manual path, the project-local cluster can be created directly:
161+
162+
```bash
163+
DB_NAME=opencoperlock DB_USER=opencoperlock ./scripts/postgres-local.sh init # prints DATABASE_URL
164+
# put that DATABASE_URL in .env, then ./scripts/deploy.sh && pm2 start ecosystem.config.cjs
165+
```
166+
149167
### 2. Configure
150168

151169
```bash
@@ -156,7 +174,8 @@ cp .env.example .env
156174

157175
Edit `.env`:
158176

159-
- `DATABASE_URL` — point at your local Postgres.
177+
- `DATABASE_URL` — your database (for a project-local cluster this is generated for you,
178+
with the random port baked in).
160179
- `MASTER_KEY`, `SESSION_SECRET` — `openssl rand -base64 32` each.
161180
- `ADMIN_EMAIL` / `ADMIN_PASSWORD`.
162181
- `APP_URL` — your public site URL, e.g. `https://copper.forgenet.fr`.

‎ecosystem.config.cjs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,22 @@ function readEnv(file) {
4040

4141
const env = readEnv(path.join(root, '.env'));
4242

43+
// If a project-local PostgreSQL cluster exists (created by scripts/postgres-local.sh on a
44+
// random port), let PM2 supervise it too, ahead of the API.
45+
const hasLocalPostgres = fs.existsSync(path.join(root, '.postgres', 'data', 'PG_VERSION'));
46+
const localPostgresApp = {
47+
name: 'opencoperlock-postgres',
48+
cwd: root,
49+
script: 'scripts/postgres-local.sh',
50+
args: 'start',
51+
interpreter: 'bash',
52+
autorestart: true,
53+
max_restarts: 10,
54+
};
55+
4356
module.exports = {
4457
apps: [
58+
...(hasLocalPostgres ? [localPostgresApp] : []),
4559
{
4660
name: 'opencoperlock-api',
4761
cwd: path.join(root, 'apps/api'),

‎scripts/deploy.sh‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,39 @@ pnpm --filter @opencoperlock/api build
5656
echo "==> Building web (Next standalone)"
5757
pnpm --filter @opencoperlock/web build
5858

59+
# Make sure the database is reachable for migrate/seed. If it's a project-local cluster
60+
# that isn't running yet (first install), start it temporarily; on a redeploy it's already
61+
# up (PM2-managed) so we leave it alone.
62+
db_reachable() {
63+
local hp="${DATABASE_URL#*@}"; hp="${hp%%/*}"
64+
local host="${hp%%:*}"; local port="${hp##*:}"
65+
[[ "$port" == "$host" ]] && port=5432
66+
(exec 3<>"/dev/tcp/${host}/${port}") 2>/dev/null
67+
}
68+
STARTED_LOCAL_PG=false
69+
if ! db_reachable; then
70+
if [[ -f .postgres/data/PG_VERSION ]]; then
71+
echo "==> Starting project-local PostgreSQL for setup"
72+
./scripts/postgres-local.sh ctl-start
73+
STARTED_LOCAL_PG=true
74+
else
75+
echo "ERROR: the database in DATABASE_URL is not reachable, and no project-local" >&2
76+
echo " cluster exists (.postgres/). Start your database or re-run the wizard." >&2
77+
exit 1
78+
fi
79+
fi
80+
5981
echo "==> Applying database migrations"
6082
pnpm --filter @opencoperlock/api prisma:migrate
6183

6284
echo "==> Seeding first admin (idempotent)"
6385
pnpm --filter @opencoperlock/api db:seed
6486

87+
if [[ "$STARTED_LOCAL_PG" == true ]]; then
88+
echo "==> Stopping project-local PostgreSQL (PM2 will supervise it)"
89+
./scripts/postgres-local.sh ctl-stop
90+
fi
91+
6592
# Ensure storage directories exist and are writable by the current user.
6693
mkdir -p "${STORAGE_PATH:-$ROOT/data/storage}" "${QUARANTINE_PATH:-$ROOT/data/quarantine}"
6794

‎scripts/postgres-local.sh‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Manage a PROJECT-LOCAL PostgreSQL cluster, living entirely inside the repo under
4+
# `.postgres/`, listening on 127.0.0.1 on a RANDOM free port chosen at init time. This is
5+
# for hosts where the usual ports are already taken and you don't want a system-wide DB.
6+
#
7+
# ./scripts/postgres-local.sh init # create the cluster + role + database (prints DATABASE_URL)
8+
# ./scripts/postgres-local.sh start # run postgres in the foreground (used by PM2)
9+
# ./scripts/postgres-local.sh ctl-start # start in the background via pg_ctl (used by deploy.sh)
10+
# ./scripts/postgres-local.sh ctl-stop # stop a pg_ctl-started instance
11+
# ./scripts/postgres-local.sh status
12+
#
13+
# Credentials for `init` come from env: DB_NAME, DB_USER, DB_PASS (DB_PASS is generated if
14+
# unset). The port is persisted in `.postgres/port` and reused by every later command.
15+
set -euo pipefail
16+
17+
cd "$(dirname "$0")/.."
18+
ROOT="$(pwd)"
19+
20+
# PostgreSQL refuses to run as root, and the cluster should be owned by the app's run user.
21+
if [[ $EUID -eq 0 ]]; then
22+
echo "ERROR: run this as the unprivileged user that will own the database, not root." >&2
23+
echo " (The PM2 app user owns .postgres/; PostgreSQL will not start as root.)" >&2
24+
exit 1
25+
fi
26+
PGROOT="$ROOT/.postgres"
27+
DATA="$PGROOT/data"
28+
SOCK="$PGROOT/socket"
29+
PORT_FILE="$PGROOT/port"
30+
LOG="$PGROOT/postgres.log"
31+
32+
# Locate the PostgreSQL server binaries. They are on PATH on most systems; on Debian/Ubuntu
33+
# they live under /usr/lib/postgresql/<version>/bin.
34+
find_pg_bin() {
35+
if command -v initdb >/dev/null 2>&1; then echo ""; return; fi
36+
local d
37+
d="$(ls -d /usr/lib/postgresql/*/bin 2>/dev/null | sort -V | tail -1 || true)"
38+
[[ -n "$d" && -x "$d/initdb" ]] || {
39+
echo "ERROR: PostgreSQL server binaries (initdb) not found. Install the 'postgresql' package." >&2
40+
exit 1
41+
}
42+
echo "$d/"
43+
}
44+
PGBIN="$(find_pg_bin)"
45+
46+
# Pick a free TCP port on 127.0.0.1 in a high range, avoiding anything already listening.
47+
pick_free_port() {
48+
local p
49+
for _ in $(seq 1 100); do
50+
p=$(( (RANDOM << 2 ^ RANDOM) % 25000 + 30000 )) # 30000..54999, well-spread
51+
if ! (exec 3<>"/dev/tcp/127.0.0.1/$p") 2>/dev/null; then
52+
echo "$p"; return 0
53+
fi
54+
exec 3>&- 2>/dev/null || true
55+
done
56+
echo "ERROR: could not find a free port after 100 tries." >&2
57+
exit 1
58+
}
59+
60+
read_port() {
61+
[[ -f "$PORT_FILE" ]] || { echo "ERROR: $PORT_FILE missing — run 'init' first." >&2; exit 1; }
62+
cat "$PORT_FILE"
63+
}
64+
65+
cmd_init() {
66+
local DB_NAME="${DB_NAME:-opencoperlock}"
67+
local DB_USER="${DB_USER:-opencoperlock}"
68+
local DB_PASS="${DB_PASS:-$(openssl rand -hex 16)}"
69+
70+
mkdir -p "$PGROOT" "$SOCK"
71+
chmod 700 "$PGROOT"
72+
73+
if [[ ! -f "$DATA/PG_VERSION" ]]; then
74+
echo "==> Initialising cluster in $DATA" >&2
75+
# Superuser 'postgres'; local socket = trust, TCP = scram (the app uses a password).
76+
"${PGBIN}initdb" -D "$DATA" -U postgres -E UTF8 --auth-local=trust --auth-host=scram-sha-256 >/dev/null
77+
fi
78+
79+
local PORT
80+
if [[ -f "$PORT_FILE" ]]; then PORT="$(cat "$PORT_FILE")"; else PORT="$(pick_free_port)"; echo "$PORT" > "$PORT_FILE"; fi
81+
echo "==> Using port $PORT" >&2
82+
83+
# Start temporarily to provision the role + database, then stop.
84+
"${PGBIN}pg_ctl" -D "$DATA" -w -o "-p $PORT -k $SOCK -c listen_addresses=127.0.0.1" -l "$LOG" start >/dev/null
85+
trap '"${PGBIN}pg_ctl" -D "$DATA" -w stop >/dev/null 2>&1 || true' EXIT
86+
87+
"${PGBIN}psql" -h "$SOCK" -p "$PORT" -U postgres -d postgres -v ON_ERROR_STOP=1 >/dev/null <<SQL
88+
DO \$\$ BEGIN
89+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${DB_USER}') THEN
90+
CREATE ROLE "${DB_USER}" LOGIN PASSWORD '${DB_PASS}';
91+
ELSE
92+
ALTER ROLE "${DB_USER}" WITH PASSWORD '${DB_PASS}';
93+
END IF;
94+
END \$\$;
95+
SELECT 'CREATE DATABASE "${DB_NAME}" OWNER "${DB_USER}"'
96+
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${DB_NAME}')\gexec
97+
SQL
98+
99+
"${PGBIN}pg_ctl" -D "$DATA" -w stop >/dev/null
100+
trap - EXIT
101+
echo "==> Project-local PostgreSQL ready on 127.0.0.1:$PORT" >&2
102+
# Emit the connection string on stdout so callers (the wizard) can capture it.
103+
echo "postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:${PORT}/${DB_NAME}"
104+
}
105+
106+
cmd_start() {
107+
local PORT; PORT="$(read_port)"
108+
mkdir -p "$SOCK"
109+
# Foreground — PM2 supervises this process.
110+
exec "${PGBIN}postgres" -D "$DATA" -p "$PORT" -k "$SOCK" -c listen_addresses=127.0.0.1
111+
}
112+
113+
cmd_ctl_start() {
114+
local PORT; PORT="$(read_port)"
115+
mkdir -p "$SOCK"
116+
"${PGBIN}pg_ctl" -D "$DATA" -w -o "-p $PORT -k $SOCK -c listen_addresses=127.0.0.1" -l "$LOG" start
117+
}
118+
119+
cmd_ctl_stop() {
120+
"${PGBIN}pg_ctl" -D "$DATA" -w stop
121+
}
122+
123+
cmd_status() {
124+
"${PGBIN}pg_ctl" -D "$DATA" status || true
125+
}
126+
127+
case "${1:-}" in
128+
init) cmd_init ;;
129+
start) cmd_start ;;
130+
ctl-start) cmd_ctl_start ;;
131+
ctl-stop) cmd_ctl_stop ;;
132+
status) cmd_status ;;
133+
*) echo "Usage: $0 {init|start|ctl-start|ctl-stop|status}" >&2; exit 1 ;;
134+
esac

‎scripts/setup-wizard.sh‎

Lines changed: 57 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -125,21 +125,38 @@ done
125125

126126
# Database
127127
say ""; info "PostgreSQL"
128-
DB_MODE="$(ask 'Provision a local database for me? (yes) or use an existing DATABASE_URL (no)' 'yes')"
129-
DATABASE_URL=''; CREATE_DB=false
128+
say " 1) Project-local DB — runs inside the project on a random free port, supervised"
129+
say " by PM2. Best when the usual ports are already taken."
130+
say " 2) System PostgreSQL — create a database/user on the host's PostgreSQL service."
131+
say " 3) Existing DATABASE_URL — point at a database you already have."
132+
DB_CHOICE="$(ask 'Choose 1, 2 or 3' '1')"
133+
DATABASE_URL=''; DB_PROVISION='local'
130134
DB_NAME='opencoperlock'; DB_USER='opencoperlock'; DB_PASS=''
131-
if [[ "$DB_MODE" =~ ^[Yy] ]]; then
132-
CREATE_DB=true
133-
DB_NAME="$(ask 'Database name' 'opencoperlock')"
134-
DB_USER="$(ask 'Database user' 'opencoperlock')"
135-
# Restrict identifiers to a safe character set (they go into SQL).
136-
[[ "$DB_NAME" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database name (use letters, digits, underscore)."
137-
[[ "$DB_USER" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database user (use letters, digits, underscore)."
138-
DB_PASS="$(openssl rand -hex 16)"
139-
DATABASE_URL="postgresql://${DB_USER}:${DB_PASS}@localhost:5432/${DB_NAME}"
140-
else
141-
while [[ -z "$DATABASE_URL" ]]; do DATABASE_URL="$(ask 'Existing DATABASE_URL')"; done
142-
fi
135+
case "$DB_CHOICE" in
136+
1)
137+
DB_PROVISION='local'
138+
DB_NAME="$(ask 'Database name' 'opencoperlock')"
139+
DB_USER="$(ask 'Database user' 'opencoperlock')"
140+
[[ "$DB_NAME" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database name (letters, digits, underscore)."
141+
[[ "$DB_USER" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database user (letters, digits, underscore)."
142+
DB_PASS="$(openssl rand -hex 16)"
143+
# The port (and thus DATABASE_URL) is chosen at provisioning time (Step 3).
144+
;;
145+
2)
146+
DB_PROVISION='system'
147+
DB_NAME="$(ask 'Database name' 'opencoperlock')"
148+
DB_USER="$(ask 'Database user' 'opencoperlock')"
149+
[[ "$DB_NAME" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database name (letters, digits, underscore)."
150+
[[ "$DB_USER" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database user (letters, digits, underscore)."
151+
DB_PASS="$(openssl rand -hex 16)"
152+
DATABASE_URL="postgresql://${DB_USER}:${DB_PASS}@localhost:5432/${DB_NAME}"
153+
;;
154+
3)
155+
DB_PROVISION='existing'
156+
while [[ -z "$DATABASE_URL" ]]; do DATABASE_URL="$(ask 'Existing DATABASE_URL')"; done
157+
;;
158+
*) die "Invalid choice: $DB_CHOICE" ;;
159+
esac
143160

144161
# Storage
145162
say ""; info "Storage & limits"
@@ -177,7 +194,7 @@ say " Topology : $([[ $TOPO == 1 ]] && echo 'two subdomains' || { [[
177194
say " API URL (browser) : ${NEXT_PUBLIC_API_URL}"
178195
say " Web / API ports : ${WEB_PORT} / ${API_PORT}"
179196
say " Admin email : ${ADMIN_EMAIL}"
180-
say " Database : $([[ $CREATE_DB == true ]] && echo "create local '${DB_NAME}'" || echo 'existing (provided URL)')"
197+
say " Database : $(case $DB_PROVISION in local) echo "project-local '${DB_NAME}' (random port, PM2)";; system) echo "system PostgreSQL '${DB_NAME}'";; *) echo 'existing (provided URL)';; esac)"
181198
say " Storage path : ${STORAGE_PATH}"
182199
say " Per-user quota : ${QUOTA_GB} GiB Global cap: ${CAP_GB} GiB"
183200
say " ClamAV / VirusTotal : $([[ $CLAMAV_ENABLED == true ]] && echo on || echo off) / $([[ -n $VIRUSTOTAL_API_KEY ]] && echo set || echo off)"
@@ -228,11 +245,14 @@ if $CLAMAV_ENABLED && ! command -v clamdscan >/dev/null 2>&1; then
228245
fi
229246
fi
230247

231-
# PostgreSQL
232-
if $CREATE_DB && ! command -v psql >/dev/null 2>&1; then
233-
if [[ "$PKG" == apt ]] && ask_yn 'PostgreSQL not found. Install it?' 'Y'; then
248+
# PostgreSQL binaries (needed for system provisioning and for a project-local cluster).
249+
if [[ "$DB_PROVISION" != existing ]] && ! command -v initdb >/dev/null 2>&1 \
250+
&& ! ls /usr/lib/postgresql/*/bin/initdb >/dev/null 2>&1; then
251+
if [[ "$PKG" == apt ]] && ask_yn 'PostgreSQL is not installed. Install it?' 'Y'; then
234252
apt_install postgresql postgresql-contrib
235-
$SUDO systemctl enable --now postgresql
253+
# The project-local cluster does not use the system service; stop it to free port 5432
254+
# if the operator wants, but leave it as-is by default.
255+
[[ "$DB_PROVISION" == system ]] && $SUDO systemctl enable --now postgresql || true
236256
fi
237257
fi
238258

@@ -243,11 +263,18 @@ if $SETUP_TLS && ! command -v certbot >/dev/null 2>&1 && [[ "$PKG" == apt ]]; th
243263
# ─────────────────────────────────────────────────────────────────────────────
244264
# 3. DATABASE PROVISIONING
245265
# ─────────────────────────────────────────────────────────────────────────────
246-
if $CREATE_DB; then
247-
say ""; info "Step 3 / 8 — Creating PostgreSQL database & user"
248-
need_sudo
249-
# Create role if missing, set password, create db owned by it. Idempotent.
250-
$SUDO -u postgres psql -v ON_ERROR_STOP=1 <<SQL || die 'Database provisioning failed.'
266+
case "$DB_PROVISION" in
267+
local)
268+
say ""; info "Step 3 / 8 — Creating a project-local PostgreSQL (random port)"
269+
# postgres-local.sh must run as the unprivileged app user; it prints the DATABASE_URL.
270+
DATABASE_URL="$(DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASS="$DB_PASS" ./scripts/postgres-local.sh init)"
271+
[[ -n "$DATABASE_URL" ]] || die 'Project-local database provisioning failed.'
272+
ok "Project-local PostgreSQL ready (${DATABASE_URL##*@})"
273+
;;
274+
system)
275+
say ""; info "Step 3 / 8 — Creating PostgreSQL database & user on the system service"
276+
need_sudo
277+
$SUDO -u postgres psql -v ON_ERROR_STOP=1 <<SQL || die 'Database provisioning failed.'
251278
DO \$\$ BEGIN
252279
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${DB_USER}') THEN
253280
CREATE ROLE "${DB_USER}" LOGIN PASSWORD '${DB_PASS}';
@@ -258,10 +285,12 @@ END \$\$;
258285
SELECT 'CREATE DATABASE "${DB_NAME}" OWNER "${DB_USER}"'
259286
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${DB_NAME}')\gexec
260287
SQL
261-
ok "Database '${DB_NAME}' ready"
262-
else
263-
say ""; info "Step 3 / 8 — Using existing database (skipped provisioning)"
264-
fi
288+
ok "Database '${DB_NAME}' ready"
289+
;;
290+
*)
291+
say ""; info "Step 3 / 8 — Using existing database (skipped provisioning)"
292+
;;
293+
esac
265294

266295
# ─────────────────────────────────────────────────────────────────────────────
267296
# 4. STORAGE DIRECTORIES

0 commit comments

Comments
 (0)