Merge pull request 'Slave/prod deploy' (#12) from slave/prod-deploy into master

Reviewed-on: #12
This commit was merged in pull request #12.
This commit is contained in:
2026-10-28 23:22:14 +00:00
15 changed files with 445 additions and 10 deletions
+4 -1
View File
@@ -16,6 +16,9 @@ FRONTEND_PORT=5173
NODE_ENV=development NODE_ENV=development
CLEARNET_DOMAIN=localhost
ONION_HOSTNAME=samplexxxxxxxxx.onion
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173 CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
ALTCHA_ENABLED=true ALTCHA_ENABLED=true
@@ -35,7 +38,7 @@ VALIDATION_UPLOAD_JSON_BODY_PADDING_BYTES=2097152 # 2MiB
VITE_API_BASE_URL=http://localhost:3000/api VITE_API_BASE_URL=http://localhost:3000/api
VITE_CLEARNET_SCHEME=http VITE_CLEARNET_SCHEME=http
VITE_CLEARNET_DOMAIN=localhost:5173 VITE_CLEARNET_DOMAIN=localhost:5173
VITE_ONION_HOSTNAME=abcdefghijklmnop.onion VITE_ONION_HOSTNAME=samplexxxxxxxxx.onion
VITE_ALTCHA_ENABLED=true VITE_ALTCHA_ENABLED=true
VITE_ALTCHA_MAX_NUMBER=250000 VITE_ALTCHA_MAX_NUMBER=250000
VITE_UPLOAD_MAX_QUEUE_SIZE=10 VITE_UPLOAD_MAX_QUEUE_SIZE=10
+2
View File
@@ -2,6 +2,8 @@
Self-hosted, privacy-focused image hosting. Images are metadata-stripped and encrypted in the browser before upload. Supports **zero-knowledge** viewer links and **hotlink** mode for embeds. Self-hosted, privacy-focused image hosting. Images are metadata-stripped and encrypted in the browser before upload. Supports **zero-knowledge** viewer links and **hotlink** mode for embeds.
For production deployment, see the [deployment guide](deploy/DEPLOYMENT_GUIDE.md).
## Development ## Development
### Start dev environment ### Start dev environment
+15
View File
@@ -0,0 +1,15 @@
FROM node:22.23.4-alpine
WORKDIR /backend
RUN apk add --no-cache curl
COPY package*.json .
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/main"]
+8
View File
@@ -35,4 +35,12 @@ describe('validate', () => {
expect(() => validate(validConfig({ ALTCHA_ENABLED: 'yes' }))).toThrow(); expect(() => validate(validConfig({ ALTCHA_ENABLED: 'yes' }))).toThrow();
expect(() => validate(validConfig({ POSTGRES_MIGRATIONS_RUN: '1' }))).toThrow(); expect(() => validate(validConfig({ POSTGRES_MIGRATIONS_RUN: '1' }))).toThrow();
}); });
it('does not require CORS_ORIGINS in production', () => {
const { CORS_ORIGINS: _removed, ...productionBase } = validConfig({
NODE_ENV: 'production'
});
expect(() => validate(productionBase)).not.toThrow();
});
}); });
+2 -1
View File
@@ -1,5 +1,5 @@
import { plainToClass } from 'class-transformer'; import { plainToClass } from 'class-transformer';
import { IsEnum, IsIn, IsNotEmpty, IsNumber, IsString, Max, Min, validateSync } from 'class-validator'; import { IsEnum, IsIn, IsNotEmpty, IsNumber, IsString, Max, Min, ValidateIf, validateSync } from 'class-validator';
import { BOOLEAN_STRING_VALUES } from '../consts/booleanStringValues'; import { BOOLEAN_STRING_VALUES } from '../consts/booleanStringValues';
import type { BooleanStringValue } from '../types/BooleanStringValue'; import type { BooleanStringValue } from '../types/BooleanStringValue';
import { NodeEnv } from '../types/NodeEnv'; import { NodeEnv } from '../types/NodeEnv';
@@ -41,6 +41,7 @@ class EnvironmentVariables {
@IsIn(BOOLEAN_STRING_VALUES) @IsIn(BOOLEAN_STRING_VALUES)
POSTGRES_MIGRATIONS_RUN: BooleanStringValue; POSTGRES_MIGRATIONS_RUN: BooleanStringValue;
@ValidateIf((config: EnvironmentVariables) => config.NODE_ENV === NodeEnv.Development)
@IsNotEmpty() @IsNotEmpty()
@IsString() @IsString()
CORS_ORIGINS: string; CORS_ORIGINS: string;
+10 -4
View File
@@ -8,6 +8,7 @@ import { altchaMiddleware } from './middlewares/altchaMiddleware';
import { AltchaService } from './modules/altcha/services/AltchaService'; import { AltchaService } from './modules/altcha/services/AltchaService';
import { Config } from './types/config/Config'; import { Config } from './types/config/Config';
import { HttpMethod } from './types/HttpMethod'; import { HttpMethod } from './types/HttpMethod';
import { NodeEnv } from './types/NodeEnv';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: false }); const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: false });
@@ -21,6 +22,7 @@ async function bootstrap() {
const { const {
port, port,
nodeEnv,
corsOrigins, corsOrigins,
validation: { validation: {
upload: { maxRequestBodyBytes } upload: { maxRequestBodyBytes }
@@ -52,10 +54,14 @@ async function bootstrap() {
}) })
); );
app.enableCors({ if (nodeEnv === NodeEnv.Development) {
origin: corsOrigins, app.enableCors({
credentials: true origin: corsOrigins,
}); credentials: true
});
}
app.set('trust proxy', 1);
await app.listen(port); await app.listen(port);
} }
@@ -1,4 +1,4 @@
import { Controller, Get, Header, Param, StreamableFile } from '@nestjs/common'; import { Controller, Get, Param, StreamableFile } from '@nestjs/common';
import { HotlinkImageParamsDto } from '../dto/HotlinkImageParamsDto'; import { HotlinkImageParamsDto } from '../dto/HotlinkImageParamsDto';
import { UploadService } from '../services/UploadService'; import { UploadService } from '../services/UploadService';
@@ -7,9 +7,6 @@ export class HotlinkImageController {
constructor(private readonly uploadService: UploadService) {} constructor(private readonly uploadService: UploadService) {}
@Get(':id/:secret') @Get(':id/:secret')
@Header('X-Content-Type-Options', 'nosniff')
@Header('Content-Security-Policy', 'sandbox')
@Header('Referrer-Policy', 'no-referrer')
async getImage(@Param() params: HotlinkImageParamsDto): Promise<StreamableFile> { async getImage(@Param() params: HotlinkImageParamsDto): Promise<StreamableFile> {
const { body, mimeType } = await this.uploadService.getHotlinkImage(params.id, params.secret); const { body, mimeType } = await this.uploadService.getHotlinkImage(params.id, params.secret);
+135
View File
@@ -0,0 +1,135 @@
# Deployment guide
## 1. Requirements
- Ubuntu 22.04+ or similar Linux with Docker Engine and the Compose plugin — follow [Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository). Tested and recommended on Ubuntu 22.04 LTS.
- A domain name pointing at your server (A records for apex and `www`)
## 2. Server setup
Deploy as **root** on the VPS. Docker Engine and Compose plugin must be installed — [Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository).
Verify:
```bash
docker compose version
```
## 3. Clone the repository
```bash
cd /root
git clone https://git.nobswebdev.com/nobswebdev/private_image.git private_image
cd private_image
```
## 4. Configure environment
```bash
cd /root/private_image
cp .env.example .env.prod
chmod 600 .env.prod
```
Edit `.env.prod`. Mandatory configuration:
| Variable | Production value |
| --- | --- |
| `COMPOSE_PROJECT_NAME` | `private_image_prod` |
| `POSTGRES_PASSWORD` | strong random password |
| `POSTGRES_MIGRATIONS_RUN` | `true` |
| `PGADMIN_DEFAULT_PASSWORD` | strong random password |
| `NODE_ENV` | `production` |
| `CLEARNET_DOMAIN` | `your-domain.com` |
| `ONION_HOSTNAME` | set after step 8 (Tor); use placeholder until then |
| `ALTCHA_HMAC_KEY` | strong random secret |
| `VITE_API_BASE_URL` | `/api` |
| `VITE_CLEARNET_SCHEME` | `https` |
| `VITE_CLEARNET_DOMAIN` | `your-domain.com` (same host as `CLEARNET_DOMAIN`) |
| `VITE_ONION_HOSTNAME` | same as `ONION_HOSTNAME` after step 8 |
Keep `VITE_VALIDATION_*` and `VITE_UPLOAD_*` aligned with backend `VALIDATION_*` caps in the same file.
## 5. Bootstrap TLS certificates
Nginx needs certificate files before it can start on port 443. For the **first** deploy, create a temporary self-signed pair (replaced after Let's Encrypt):
```bash
./deploy/scripts/bootstrap-certs.sh
```
After the stack is running, obtain real certificates (step 7).
## 6. Start the stack
```bash
./deploy/scripts/deploy.sh
```
Wait until `backend` and `nginx` are healthy:
```bash
docker compose --env-file .env.prod -f docker-compose.prod.yml ps
```
## 7. Issue Let's Encrypt certificates
Remove the temporary bootstrap certificates under `deploy/certs/live/` (Certbot cannot issue into the layout created by `bootstrap-certs.sh`):
```bash
rm -rf deploy/certs/live/*
```
Request the real certificate (apex + www):
```bash
./deploy/scripts/issue-certs.sh --email you@example.com
```
Reload nginx:
```bash
docker compose --env-file .env.prod -f docker-compose.prod.yml exec nginx nginx -s reload
```
### Automatic renewal
Open root's crontab:
```bash
crontab -e
```
Add a weekly job (`/root/private_image` is the standard deploy path):
```cron
0 3 * * 0 /root/private_image/deploy/scripts/renew-certs.sh >> /var/log/private_image-cert-renew.log 2>&1
```
Save and exit the editor. Optional — run once manually to verify:
```bash
/root/private_image/deploy/scripts/renew-certs.sh
```
## 8. Tor onion address
```bash
./deploy/scripts/show-onion.sh
```
Copy the hostname into `.env.prod` as `ONION_HOSTNAME` and `VITE_ONION_HOSTNAME`, then rebuild and recreate nginx (frontend share links and `Onion-Location` are baked at build / entrypoint):
```bash
docker compose --env-file .env.prod -f docker-compose.prod.yml up -d --build --force-recreate nginx
```
Tor Browser will then show ".onion available" when visitors open the clearnet site over HTTPS.
## 9. Updates
```bash
./deploy/scripts/update.sh
```
This pulls the latest code and rebuilds the stack (`deploy.sh`).
+95
View File
@@ -0,0 +1,95 @@
services:
postgres:
image: postgres:16
container_name: ${COMPOSE_PROJECT_NAME}_postgres
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- private_image.postgres.prod.data:/var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}']
interval: 5s
timeout: 5s
retries: 10
pgadmin:
image: dpage/pgadmin4:8
container_name: ${COMPOSE_PROJECT_NAME}_pgadmin
restart: unless-stopped
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
volumes:
- private_image.pgadmin.prod.data:/var/lib/pgadmin
depends_on:
postgres:
condition: service_healthy
backend:
build:
context: ./backend
dockerfile: Dockerfile.prod
container_name: ${COMPOSE_PROJECT_NAME}_backend
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
env_file:
- .env.prod
volumes:
- ./backend/uploads:/backend/uploads
healthcheck:
test: ['CMD-SHELL', 'curl -f http://backend:${BACKEND_PORT}/api/health-check/']
interval: 10s
timeout: 30s
retries: 10
start_period: 30s
nginx:
build:
context: .
dockerfile: nginx/Dockerfile.prod
args:
VITE_API_BASE_URL: ${VITE_API_BASE_URL}
VITE_CLEARNET_SCHEME: ${VITE_CLEARNET_SCHEME}
VITE_CLEARNET_DOMAIN: ${VITE_CLEARNET_DOMAIN}
VITE_ONION_HOSTNAME: ${VITE_ONION_HOSTNAME}
VITE_ALTCHA_ENABLED: ${VITE_ALTCHA_ENABLED}
VITE_ALTCHA_MAX_NUMBER: ${VITE_ALTCHA_MAX_NUMBER}
VITE_UPLOAD_MAX_QUEUE_SIZE: ${VITE_UPLOAD_MAX_QUEUE_SIZE}
VITE_VALIDATION_UPLOAD_MAX_VIEWS_MAX: ${VITE_VALIDATION_UPLOAD_MAX_VIEWS_MAX}
VITE_VALIDATION_UPLOAD_MAX_IMAGE_BYTES: ${VITE_VALIDATION_UPLOAD_MAX_IMAGE_BYTES}
container_name: ${COMPOSE_PROJECT_NAME}_nginx
restart: unless-stopped
env_file:
- .env.prod
ports:
- '80:80'
- '443:443'
volumes:
- ./deploy/certs:/etc/nginx/certs:ro
- ./deploy/certbot/www:/var/www/certbot:ro
depends_on:
backend:
condition: service_healthy
pgadmin:
condition: service_started
tor:
build:
context: ./deploy/tor
container_name: ${COMPOSE_PROJECT_NAME}_tor
restart: unless-stopped
volumes:
- private_image.tor.prod.data:/var/lib/tor
depends_on:
nginx:
condition: service_started
volumes:
private_image.postgres.prod.data:
private_image.pgadmin.prod.data:
private_image.tor.prod.data:
View File
+46
View File
@@ -0,0 +1,46 @@
FROM node:22.23.4-alpine AS frontend-builder
WORKDIR /frontend
COPY frontend/package*.json .
COPY frontend/patches ./patches
RUN npm ci
COPY frontend/ .
ARG VITE_API_BASE_URL
ARG VITE_CLEARNET_SCHEME
ARG VITE_CLEARNET_DOMAIN
ARG VITE_ONION_HOSTNAME
ARG VITE_ALTCHA_ENABLED
ARG VITE_ALTCHA_MAX_NUMBER
ARG VITE_UPLOAD_MAX_QUEUE_SIZE
ARG VITE_VALIDATION_UPLOAD_MAX_VIEWS_MAX
ARG VITE_VALIDATION_UPLOAD_MAX_IMAGE_BYTES
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL \
VITE_CLEARNET_SCHEME=$VITE_CLEARNET_SCHEME \
VITE_CLEARNET_DOMAIN=$VITE_CLEARNET_DOMAIN \
VITE_ONION_HOSTNAME=$VITE_ONION_HOSTNAME \
VITE_ALTCHA_ENABLED=$VITE_ALTCHA_ENABLED \
VITE_ALTCHA_MAX_NUMBER=$VITE_ALTCHA_MAX_NUMBER \
VITE_UPLOAD_MAX_QUEUE_SIZE=$VITE_UPLOAD_MAX_QUEUE_SIZE \
VITE_VALIDATION_UPLOAD_MAX_VIEWS_MAX=$VITE_VALIDATION_UPLOAD_MAX_VIEWS_MAX \
VITE_VALIDATION_UPLOAD_MAX_IMAGE_BYTES=$VITE_VALIDATION_UPLOAD_MAX_IMAGE_BYTES
RUN npm run build
FROM nginx:1.29.4-alpine
RUN apk add --no-cache gettext
COPY --from=frontend-builder /frontend/dist /usr/share/nginx/html
COPY nginx/conf.d/ /etc/nginx/templates/conf.d/
COPY nginx/snippets/private-image-locations.conf.template /etc/nginx/templates/snippets/
COPY nginx/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
+26
View File
@@ -0,0 +1,26 @@
server {
listen 80;
server_name ${CLEARNET_DOMAIN} www.${CLEARNET_DOMAIN};
access_log off;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name ${CLEARNET_DOMAIN} www.${CLEARNET_DOMAIN};
access_log off;
ssl_certificate /etc/nginx/certs/live/${CLEARNET_DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/nginx/certs/live/${CLEARNET_DOMAIN}/privkey.pem;
include /etc/nginx/snippets/private-image-locations.conf;
}
+8
View File
@@ -0,0 +1,8 @@
server {
listen 8080;
server_name _;
access_log off;
include /etc/nginx/snippets/private-image-locations.conf;
}
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
max_image_bytes="${VALIDATION_UPLOAD_MAX_IMAGE_BYTES:?}"
json_padding="${VALIDATION_UPLOAD_JSON_BODY_PADDING_BYTES:?}"
UPLOAD_MAX_REQUEST_BODY_BYTES=$(( (max_image_bytes * 4 + 2) / 3 + json_padding ))
export UPLOAD_MAX_REQUEST_BODY_BYTES BACKEND_PORT
render_locations() {
export ONION_LOCATION_HEADER="add_header Onion-Location \"http://${ONION_HOSTNAME}\$request_uri\" always;"
envsubst '${BACKEND_PORT} ${UPLOAD_MAX_REQUEST_BODY_BYTES} ${ONION_LOCATION_HEADER}' \
< /etc/nginx/templates/snippets/private-image-locations.conf.template \
> /etc/nginx/snippets/private-image-locations.conf
}
render_server() {
template_path="$1"
output_path="$2"
surface="$3"
if [ "$surface" = "clearnet" ]; then
export CLEARNET_DOMAIN
envsubst '${CLEARNET_DOMAIN}' \
< "$template_path" \
> "$output_path"
return
fi
cp "$template_path" "$output_path"
}
mkdir -p /etc/nginx/snippets
render_locations
render_server /etc/nginx/templates/conf.d/clearnet.conf.template /etc/nginx/conf.d/clearnet.conf clearnet
render_server /etc/nginx/templates/conf.d/onion.conf.template /etc/nginx/conf.d/onion.conf onion
exec nginx -g 'daemon off;'
@@ -0,0 +1,50 @@
location ^~ /i/ {
add_header Content-Security-Policy "sandbox" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control "private, no-store" always;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://backend:${BACKEND_PORT};
}
location /api {
client_max_body_size ${UPLOAD_MAX_REQUEST_BODY_BYTES};
add_header Cache-Control "no-store" always;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_pass http://backend:${BACKEND_PORT};
}
location /pgadmin {
proxy_set_header X-Script-Name /pgadmin;
proxy_set_header Host $host;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_header Set-Cookie;
proxy_pass http://pgadmin;
proxy_redirect off;
}
location / {
${ONION_LOCATION_HEADER}
add_header Referrer-Policy "no-referrer" always;
add_header Cache-Control "no-store" always;
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
}