8000 GitHub - hamzasgd/DbBackup: πŸ€–πŸ—„οΈ The agent-ready, self-hosted database backup platform β€” MySQL, MariaDB & PostgreSQL over SSH tunnels, AES-256-GCM encryption at rest (local / S3 / Google Drive), passkeys, heartbeat monitoring, audit logs, alerts & a built-in MCP server for AI agents. Β· GitHub
[go: up one dir, main page]

Skip to content
hamzasgdPublic

About

πŸ€–πŸ—„οΈ The agent-ready, self-hosted database backup platform β€” MySQL, MariaDB & PostgreSQL over SSH tunnels, AES-256-GCM encryption at rest (local / S3 / Google Drive), passkeys, heartbeat monitoring, audit logs, alerts & a built-in MCP server for AI agents.

Topics

Resources

Security policy

Stars

7 stars

Watchers

0 watching

Forks

Repository files navigation

DbBackup Logo

DbBackup

The agent-ready, self-hosted database backup platform.
Back up, restore and migrate MySQL, MariaDB and PostgreSQL (plus MongoDB and Redis backups) β€” over SSH tunnels, encrypted at rest,
monitored around the clock β€” and drive it all from your AI agent via built-in MCP.

XERJ Corpus Hub contributor


⚠️ USE AT YOUR OWN RISK β€” NO WARRANTY, NO RESPONSIBILITY

This software is provided "AS IS" without warranty of any kind. The authors are NOT responsible β€” under any circumstances β€” for any data loss, data corruption, data leakage, failed backups, failed restores, broken databases, downtime, lost profits, or any other damage arising from the use of this software. This includes situations involving the software's security features β€” see TERMS_OF_SERVICE.md (you accept these terms by using the software).

You are the operator. DbBackup is self-hosted software that you deploy and manage. Before trusting it with production data:

  • Never rely on it as your only backup β€” keep an independent backup strategy.
  • Verify backups and test restores regularly (a backup you haven't restored is not a backup).
  • Secure your own infrastructure β€” server, encryption keys, and third-party accounts are your responsibility.

The project takes security seriously (see SECURITY.md) β€” but security features reduce risk, they do not guarantee outcomes, and they create no liability for the authors. See the LICENSE for the full MIT disclaimer.

πŸ“„ Legal: Terms of Service Β· Security Policy & vulnerability reporting Β· Incident response runbook Β· License


✨ Features

πŸ€– AI Agents (MCP) β€” built in

  • Model Context Protocol server at /mcp (Streamable HTTP, JSON-RPC 2.0) β€” connect Claude Desktop, Claude Code, Cursor, Windsurf, VS Code, Cline, Zed, Goose, ZCode, Kiro, Codex CLI, Gemini CLI or Trae
  • Scoped API keys (dbbk_mcp_…, SHA-256-hashed at rest, shown once, instant revocation, optional expiry): read βŠ‚ write βŠ‚ admin, enforced per tool
  • Agent tools: list connections, test connectivity, list/get backups, trigger backups, verify, heartbeat status, storage usage, activity log, delete (admin) β€” restore deliberately not exposed
  • Every call audited (key, tool, outcome, duration, IP) with live usage tracking; ready-made per-agent config snippets with copy buttons in Settings β†’ AI/MCP
  • Rate-limited endpoint (120 req/min)

Core

  • Multi-Engine Support β€” MySQL, MariaDB, and PostgreSQL via native CLI tools (mysqldump, mariadb-dump, pg_dump, pg_restore)
  • MongoDB & Redis β€” MongoDB backup and restore (mongodump / mongorestore); Redis RDB snapshot backups (redis-cli --rdb). Redis restore is manual (it needs a server restart), and migration, sync and export cover the SQL engines only
  • Backup & Restore β€” Multiple output formats: compressed SQL, plain SQL, custom (.dump), directory, and tar
  • Write protection β€” Mark a connection as write-protected (like termination protection on a cloud database): DbBackup then refuses every write into it β€” restores, Compare & Sync, migrations, sync β€” and the connection can't be deleted, checked on the server and again by the background jobs right before they write. Backups, Compare and using it as a source keep working; restore drills use a separate temporary database
  • Compare & Sync (MySQL/MariaDB) β€” Bring a copy up to date by copying only what changed, from any provider to any provider: it only needs to read the source and write the target. Each table is split into chunks along its primary key and both servers checksum their own chunks (128-bit, so only checksums cross the network); in a chunk that differs, rows missing on the target are added, changed rows replaced and rows only on the target deleted. The source is read in one consistent snapshot. Compare is read-only and reports per table; Sync needs the target database name typed back, never runs with source and target being the same database, creates tables missing on the target, leaves tables that exist only on the target alone, and skips (and reports) tables whose columns differ or that have no primary key. Every run still reads all rows on both sides; it saves network and writes, not reading
  • Run on the SSH server (MySQL/MariaDB, opt-in per backup, restore and schedule) β€” Instead of running mysqldump/mysql on the DbBackup server through the SSH tunnel, run them on the connection's SSH server, next to the database: only the gzip-compressed data crosses the internet, and every query round trip stays local to that server. Much faster for distant databases (e.g. RDS behind a jump host). Needs the MySQL client and gzip on the SSH server and an SSH login allowed to run commands (a key limited with restrict,port-forwarding can only use the default). The password goes to a private option file in a mktemp -d directory (never a command line) that is removed when the command ends
  • Safe restores β€” A Restores panel shows every restore with its step (download, decrypt, restore), how much of the backup has been read, speed and time left, and how it ended (with the error). Restoring into the database a backup was taken from (the same connection, or another connection to the same host and database) needs the database name typed back; a second restore into a database that is already being restored is refused; a restore cut off by an app restart is marked failed instead of silently re-run
  • Scheduled Backups β€” Cron-based automation (hourly, daily, weekly, monthly, or custom cron expressions)
  • Cross-Engine Migration β€” Migrate data between databases of different types (e.g., MySQL β†’ PostgreSQL)
  • Data Export β€” Export individual tables as JSON, CSV, or SQL
  • Retention Policies β€” Age + "keep last N" rules per schedule, daily global sweep, and an on-demand Purge Now button
  • Safe Connection Deletion β€” Delete a connection while keeping its backup history & files (or clean everything)

Storage & Encryption

  • Local Disk β€” Backups stored with owner-only (0700) permissions; never served publicly
  • Amazon S3 / S3-compatible β€” AWS S3, DigitalOcean Spaces, MinIO, Backblaze B2, with a bucket-privacy probe on Test Connection (warns if the bucket is publicly accessible)
  • Google Drive β€” OAuth refresh-token uploads into a DbBackups folder, quota-aware
  • πŸ” Encrypted Backups at Rest β€” Optional AES-256-GCM encryption (.enc) with a user passphrase. Plaintext is hashed, encrypted, decrypted back and hash-verified before the plaintext is deleted β€” a corrupt encrypted copy can never replace good data. Downloads/restores/verification decrypt transparently; passphrase rotation keeps old backups readable (history + current-passphrase confirmation)

Monitoring & Alerts

  • DB Heartbeat β€” Per-connection SELECT 1 health checks every 5 minutes (SSH-tunnel aware) with uptime %, latency, 7-day history, and down/recovery alerts
  • Storage Threshold Alerts β€” Email/Slack when local disk, Google Drive quota, or your S3 budget crosses a threshold (default 80%); live usage bars on the Storage page
  • Login Alerts β€” Email/Slack on every sign-in and wrong-password attempt (device + IP)
  • Activity Logs β€” Complete audit trail of every action: logins, connections, backups, restores, storage changes, passkeys, sessions β€” with IP and device
  • Real-Time Progress β€” SSE for live backup/restore/migration progress
  • Backup Verification β€” SHA-256 integrity checks with one-click verify

Security & Access

  • Passkey (WebAuthn) Login β€” Passwordless sign-in with Touch ID / Face ID / Windows Hello / security keys
  • Login Lockout β€” 3 failed password attempts from one IP blocks that address for 15 minutes (tunable) with an email/Slack alert; a cross-IP brute-force detector catches VPN/proxy hopping (consolidated alert instead of a grief-able account lock) and per-attempt failure emails are throttled
  • Active Session Management β€” See every logged-in device (browser, OS, IP, login time) and revoke individually or all at once
  • Password Change Lockdown β€” Optional 2-hour sign-in cool-down after a password change (bank-style anti-takeover)
  • Credential Encryption β€” All stored credentials and SSH keys encrypted with AES-256-GCM; versioned keys with rotation support
  • KMS Kill Switch β€” Optional AWS KMS-wrapped master key: the encryption key never touches the server disk; revoking IAM/KMS makes stolen ciphertext permanently undecryptable
  • SSH Keys Out of the DB β€” Reference a server-side key file instead of storing the PEM in the database
  • SSH Tunnels β€” Connect to private databases through bastion hosts
  • Database access gateway β€” Give developers their own MySQL/MariaDB login with only the rights you choose (read only, read and write, or picked rights; whole database or some tables; an end date). They connect DBeaver, DbGate or mysql to DbBackup over TLS β€” no SSH and no database password for them β€” and every query is logged. Turn it off or remove it in one click (see Database access gateway)
  • JWT + refresh rotation, rate limiting, secret redaction in logs, Helmet/CORS, SSL/TLS enforcement, secure memory handling

Integrations

  • Email Notifications β€” SMTP alerts on success, failure, retention, heartbeat, storage, and login events
  • Slack Notifications β€” Webhook alerts for all of the above

UI/UX

  • Responsive Dashboard β€” Mobile-friendly layout with collapsible sidebar
  • Loading Skeletons β€” Smooth loading states across all pages
  • Confirmation Dialogs β€” Styled confirmation prompts for destructive actions

πŸ› οΈ Tech Stack

Layer Technology
Frontend React 19, Vite 8, TypeScript, Tailwind CSS v4, React Router v7, Zustand, TanStack Query, React Hook Form, Zod, Lucide Icons
Backend Node.js, Express.js 4, TypeScript, tsx (dev)
Database PostgreSQL 16 via Prisma ORM 5
Queue BullMQ 6 + Redis 7 (via ioredis 6)
Auth JWT (access + refresh tokens), bcryptjs, WebAuthn passkeys (@simplewebauthn)
Encryption AES-256-GCM (Node.js crypto), Key Manager with rotation support, Cloud KMS providers (AWS, Azure, GCP, Vault)
SSH ssh2 library
Storage Local filesystem + AWS S3 SDK v3 + Google Drive (REST)
Notifications Nodemailer (SMTP) + Slack webhooks
Logging Winston + Morgan

πŸ“ Project Structure

DbBackup/
β”œβ”€β”€ package.json                # npm workspaces root
β”œβ”€β”€ docker-compose.yml          # PostgreSQL 16 + Redis 7
β”‚
β”œβ”€β”€ client/                     # React + Vite frontend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ layout/         # Sidebar, DashboardLayout, ProtectedRoute
β”‚   β”‚   β”‚   └── ui/             # Button, Card, Modal, Badge, Input, Select, Skeleton, ConfirmDialog, Toaster
β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth/           # Login, Register
β”‚   β”‚   β”‚   β”œβ”€β”€ dashboard/      # Dashboard overview
β”‚   β”‚   β”‚   β”œβ”€β”€ connections/    # Manage database connections
β”‚   β”‚   β”‚   β”œβ”€β”€ backups/        # Backup list, trigger, verify, download
β”‚   β”‚   β”‚   β”œβ”€β”€ schedules/      # Scheduled backup management
β”‚   β”‚   β”‚   β”œβ”€β”€ migrations/     # Cross-engine migration (modular components)
β”‚   β”‚   β”‚   └── settings/       # Notifications, Storage, Retention, Audit
β”‚   β”‚   β”œβ”€β”€ services/           # API service layer (axios)
β”‚   β”‚   β”œβ”€β”€ hooks/              # useProgressSSE (SSE hook)
β”‚   β”‚   β”œβ”€β”€ store/              # Zustand stores (auth, toast)
β”‚   β”‚   └── lib/                # Axios client (with refresh queue), cn(), formatBytes, etc.
β”‚   └── public/                 # Static assets (favicon, icons)
β”‚
└── server/                     # Express.js backend
    β”œβ”€β”€ prisma/
    β”‚   └── schema.prisma       # User, Connection, Backup, Schedule, Migration, AuditLog, CredentialAccessLog
    └── src/
        β”œβ”€β”€ controllers/        # Auth, Backup, Connection, Export, Migration, Notification, Restore, Schedule, SSE, Storage
        β”œβ”€β”€ services/
        β”‚   β”œβ”€β”€ engines/        # MySQL, MariaDB, PostgreSQL, MongoDB, Redis engine adapters + ConnectionFactory
        β”‚   β”œβ”€β”€ crypto/         # Key rotation, CryptoProvider interface, KMS providers (AWS, Azure, GCP, Vault)
        β”‚   β”œβ”€β”€ migrations/     # Cross-engine migration: executors, schema builder, type mapper
        β”‚   β”œβ”€β”€ security/      # Credential audit, rate limiting, secure credentials, connection validator
        β”‚   β”œβ”€β”€ sync/           # CDC trackers, conflict resolver, sync types
        β”‚   β”œβ”€β”€ crypto.service.ts
        β”‚   β”œβ”€β”€ ssh.service.ts
        β”‚   β”œβ”€β”€ token.service.ts
        β”‚   β”œβ”€β”€ notification.service.ts
        β”‚   β”œβ”€β”€ storage.service.ts
        β”‚   β”œβ”€β”€ retention.service.ts
        β”‚   β”œβ”€β”€ sse.service.ts
        β”‚   β”œβ”€β”€ export.service.ts
        β”‚   └── verification.service.ts
        β”œβ”€β”€ routes/             # Express route definitions
        β”œβ”€β”€ middleware/         # Auth guard, error handler, rate limiters, 404
        β”œβ”€β”€ queue/              # BullMQ queues & workers
        β”‚   β”œβ”€β”€ backup.queue.ts
        β”‚   β”œβ”€β”€ migration.queue.ts
        β”‚   β”œβ”€β”€ schedule.queue.ts
        β”‚   └── sync/          # Modular sync queue (handlers, validation, sanitation, execution, utils)
        └── config/             # Prisma client, Redis, Winston logger

πŸ“‹ Prerequisites

  • Node.js β‰₯ 20 (22 LTS recommended; the Docker image uses Node 22)
  • Docker & Docker Compose (for PostgreSQL and Redis)
  • Database CLI tools installed on the host:
    • MySQL / MariaDB: mysqldump, mysql, mariadb-dump, mariadb
    • PostgreSQL: pg_dump, pg_restore, psql
    • MongoDB (optional): mongodump, mongorestore (MongoDB Database Tools 100.x)
    • Redis (optional): redis-cli
    • Cross-Engine Migrations: pgloader (required for MySQL to PostgreSQL migrations)

πŸš€ Getting Started

1. Clone the repository

git clone https://github.com/hamzasgd/DbBackup.git
cd DbBackup

2. Start infrastructure

docker compose up -d

This starts PostgreSQL on port 5433 and Redis on port 6379.

Note: Port 5433 is used to avoid conflicts with a local PostgreSQL on 5432. Change it in docker-compose.yml if needed.

3. Install dependencies

npm run install:all

4. Configure environment

cp server/.env.example server/.env

Edit server/.env with your values:

DATABASE_URL="postgresql://dbbackup:dbbackup_secret@localhost:5433/dbbackup?schema=public"
JWT_ACCESS_SECRET=<random-string>
JWT_REFRESH_SECRET=<different-random-string>
ENCRYPTION_KEY=<64-hex-char-string>

Generate secrets:

openssl rand -hex 32

5. Run database migrations

cd server
npx prisma migrate dev
npx prisma generate
cd ..

6. Start the application

npm run dev

This starts both the API server and the React frontend concurrently.

Service URL
Frontend http://localhost:5173
API http://localhost:3001/api
Prisma Studio cd server && npx prisma studio

7. Create your account

Open http://localhost:5173 and register your first user.


πŸ—„οΈ Supported Backup Formats

Engine Format Extension CLI Tool
MySQL / MariaDB Compressed SQL .sql.gz mysqldump / mariadb-dump
MySQL / MariaDB Plain SQL .sql mysqldump / mariadb-dump
PostgreSQL Compressed SQL .sql.gz pg_dump + gzip
PostgreSQL Plain SQL .sql pg_dump
PostgreSQL Custom .dump pg_dump -Fc
PostgreSQL Tar .tar pg_dump -Ft
PostgreSQL Directory folder pg_dump -Fd (parallel)
MongoDB Gzipped archive .archive.gz mongodump --archive --gzip
Redis RDB snapshot .rdb redis-cli --rdb

βš™οΈ Environment Variables

Key variables (full annotated list in server/.env.example):

Variable Description Default
PORT API server port 3001
DATABASE_URL PostgreSQL connection string β€”
JWT_ACCESS_SECRET / JWT_REFRESH_SECRET Token signing secrets β€”
ENCRYPTION_KEY Legacy encryption key (still decrypts existing rows) β€”
ENCRYPTION_KEY_PRIMARY + ENCRYPTION_KEY_V1... Versioned keys for rotation β€”
KMS_WRAPPED_MASTER_KEY Kill-switch mode: master key wrapped by AWS KMS, unwrapped in memory at boot β€” never on disk β€”
AWS_KMS_KEY_ID / AWS_REGION KMS settings for the above β€”
REDIS_HOST / REDIS_PORT / REDIS_PASSWORD Redis (queues) localhost:6379
BACKUP_STORAGE_PATH Local backup dir β€” keep it outside the web root, 0700 (enforced by the app) ./backups
HEARTBEAT_INTERVAL_MINUTES DB heartbeat check interval 5
STORAGE_ALERT_THRESHOLD_PERCENT Storage usage alert threshold 80
S3_STORAGE_BUDGET_GB S3 budget for threshold alerts (S3 has no quota) β€”
PASSWORD_CHANGE_LOCKDOWN_HOURS Sign-in lock after password change (0 disables) 2
PASSKEY_RP_ID / PASSKEY_EXTRA_ORIGINS WebAuthn relying-party config (auto-derived if unset) β€”
DEFAULT_RETENTION_DAYS / DEFAULT_RETENTION_COUNT Fallback retention for schedule-less connections 30 / off
RETENTION_SWEEP_CRON Daily global retention sweep 30 3 * * *
CLIENT_URL Frontend URL (CORS) http://localhost:5173
DB_GATEWAY_PORT Port of the database access gateway (unset = off) β€”
DB_GATEWAY_TLS_CERT / DB_GATEWAY_TLS_KEY Certificate (full chain) and key for the gateway β€”
DB_GATEWAY_PUBLIC_HOST Host name shown to people for connecting host of FRONTEND_URL
DB_GATEWAY_LOG_MAX_MB The most the query log takes up; past it the oldest statements go (0 = no limit) 1000
DB_GATEWAY_MAX_CONNECTIONS The most gateway connections at once (logged in or not) 500
DB_GATEWAY_TRUST_PRIVATE_NETWORK Let the gateway give a database the password when it is not vouched for (no SSL CA, no SSH tunnel) false
DB_GATEWAY_ADVERTISED_VERSION The version every client is greeted with 8.0.40

Storage backends (S3 / Google Drive), notification channels, and the backup encryption passphrase are configured in the app's Settings UI β€” not env vars β€” and are stored encrypted in the database.


πŸ” Security & Data Safety β€” read this before production

  1. Backup encryption is passphrase-based. If you lose the passphrase and the app database, encrypted backups are unrecoverable by design. Keep an offline copy of the passphrase.
  2. Never rely on DbBackup as your only backup. Keep an independent copy of critical data and periodically test restores.
  3. KMS kill switch protects credentials: if the KMS key/IAM is revoked, stored credentials cannot be decrypted anywhere β€” but backup files encrypted with your passphrase remain recoverable with the passphrase.
  4. Lock down the host: backups directory must never be web-accessible (see the nginx notes in .env.example), and the backup encryption passphrase should differ from your login password.

Despite all of this, security features reduce risk β€” they do not guarantee outcomes, and they create no liability for the authors. See TERMS_OF_SERVICE.md and SECURITY.md.

Database TLS (SSL) settings

Connection settings What happens
SSL off Driver and CLI defaults (unchanged)
SSL on, no CA certificate Encryption is required, but the server certificate is not verified. Test Connection shows a warning.
SSL on + CA certificate Encryption required and the certificate is verified against the CA, including the host name
+ client certificate and key Sent for mutual TLS

These settings apply to everything: backups and restores (pg_dump, psql, pg_restore, mysqldump, mariadb-dump, mysql, mongodump), migrations, exports, sync and verification. Paste your provider's CA certificate (for example the AWS RDS or DigitalOcean CA bundle) into the connection to get full verification. Through an SSH tunnel, PostgreSQL still checks the real host name; MySQL/MariaDB clients can only check the certificate chain there, and the tunnel is protected by its pinned host key.

SSH host keys

The first successful connection through an SSH tunnel pins the server's host key fingerprint (SHA256:…, shown in the connection's settings). Every later connection must present the same key, otherwise it is refused before any database traffic is sent. If the SSH server was reinstalled or its key rotated, confirm the new fingerprint with its admin (ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub on the server), then click Forget SSH host key. Changing the SSH host or port also clears the pin.

Disaster recovery: what to keep off this server

If the DbBackup server is lost, you need these to get your backups back:

  1. The encryption key(s) from server/.env: ENCRYPTION_KEY / ENCRYPTION_KEY_PRIMARY / ENCRYPTION_KEY_V* (or, with the KMS option, KMS_WRAPPED_MASTER_KEY plus access to the KMS key). Every saved connection password, SSH key and storage credential is encrypted with them. Store a copy in a password manager or vault, not next to the backups.

  2. The backup encryption passphrase, if backup encryption is on (Settings β†’ Storage). Without it, .enc backups cannot be decrypted.

  3. A regular dump of the app's own PostgreSQL database (connections, schedules, backup history, users). Example cron job on the server:

    # /etc/cron.d/dbbackup-appdb β€” daily at 02:15, keep 14 days, then copy off-site
    15 2 * * * dbbackup pg_dump "$DATABASE_URL" -Fc -f /var/backups/dbbackup-app-$(date +\%F).dump && find /var/backups -name 'dbbackup-app-*.dump' -mtime +14 -delete

    Copy /var/backups to another machine or bucket (for example rclone sync or aws s3 sync). The dump contains only encrypted credentials, so it is useless without item 1, and item 1 is useless without it: keep them in different places.

  4. The backup files themselves: use S3 or Google Drive storage, or copy the local backup directory off-site.

To recover on a new server: install DbBackup, put the same encryption key(s) in server/.env, restore the app database with pg_restore -d "$DATABASE_URL" --clean dbbackup-app-YYYY-MM-DD.dump, run npx prisma migrate deploy, and start the app. Test this once on a spare machine before you need it.

Uptime monitoring

GET /health checks the app database, Redis and the queue workers. It returns 200 with "status": "ok" when all are fine and 503 with the failing check otherwise:

{ "status": "ok", "uptimeSeconds": 8123, "checks": { "database": { "ok": true, "latencyMs": 2 }, "redis": { "ok": true, "latencyMs": 1 }, "workers": { "ok": true } } }

The app's own alerts (email, Slack, …) cannot fire if the server itself is down, so add an external monitor: in UptimeRobot, Better Stack or similar (free plans are enough), create an HTTP(S) monitor for https://your-dbbackup-host/health that alerts on any non-200 status, checked every 1–5 minutes. The endpoint needs no login and returns no secrets.

Authentication & sessions

  • The refresh token is delivered in an httpOnly, SameSite=Strict cookie scoped to /api/auth β€” never readable by JavaScript and never sent cross-site. The SPA only holds the short-lived (15 min) access token. Refresh and logout also require a custom X-DBBK-CSRF header that browsers send only same-origin (CSRF defence).
  • Changing your password and "revoke all sessions" bump a per-user token version, so every outstanding access token stops working immediately β€” not after its 15-minute expiry.
  • JWTs are verified with a pinned algorithm (HS256).

After deploying this version everyone is signed out once (the refresh token moved into a cookie) β€” just log in again.

Reverse proxy and client IP

Set TRUST_PROXY to the exact number of proxy hops in front of the app: 1 for a single nginx, 2 for Cloudflare + nginx, or an IP/subnet. Rate limiting, login lockout and audit logs all use req.ip; a wrong hop count lets a client spoof it with X-Forwarded-For and evade the lockout. Don't expose the Node port directly to the internet when TRUST_PROXY is on.

SSH key files

If a connection reads its SSH key from a file (sshPrivateKeyPath), set SSH_KEY_DIR so those paths are confined to one directory. Without it the server would read whatever absolute path the connection names. Important if more than one person can create connections.

Docker default password

docker-compose.yml ships a default app-database password (dbbackup). Set DB_PASSWORD in your .env before docker compose up β€” don't run production on the default.

Super admin

A role column (USER / ADMIN) controls who manages the SaaS itself. The earliest-created user is promoted automatically by a migration (that's the owner β€” registration locks after them); optionally set ADMIN_EMAIL to promote (or hand the role to) a different account at startup β€” idempotent, audit-logged.

Admins get a Super Admin page in the app (/admin): platform-wide stats (users, connections, backups, storage), a searchable/suspendable user list, and a read-only support view of any user's connections, backups, MCP keys and recent activity. Server-side, requireAdmin guards /api/admin/* behind authenticate, a stricter rate limit, and per-request role re-checks (a suspended or demoted admin loses access on their next request).

What the admin can and cannot see β€” deliberate guardrails:

  • βœ… User profiles, connection metadata (name/type/host/db), backup file names, sizes and statuses, MCP key names/prefixes/usage
  • ❌ Database passwords, SSH/TLS private keys, backup filePath/storageKey, MCP key hashes β€” masked or omitted at the API
  • ❌ No user deletion, no password resets, no role-granting UI (role changes only via migration/ADMIN_EMAIL)

Every admin action is audit-logged (ADMIN_VIEW_USER, ADMIN_SUSPEND, ADMIN_REACTIVATE, ADMIN_ACCESS_DENIED, ADMIN_PROMOTED).

Database access gateway

The Database access page gives a person their own login to a MySQL or MariaDB database, like a small Teleport or Warpgate built into DbBackup:

  • They connect any MySQL client (DBeaver, DbGate, mysql) to DbBackup's gateway with the user and password shown once when the access is created. TLS is required. They get no SSH access and never see the database's own credentials.
  • Clients are greeted with a fixed version (DB_GATEWAY_ADVERTISED_VERSION), never the database's own: they get it before they log in.
  • DbBackup creates a database user for each access with exactly the chosen rights (e.g. SELECT only, or only some tables) and logs in as it, through the connection's SSH tunnel when it has one. The rights are enforced by the database itself; the gateway also refuses switching users, replication and server commands, and does not allow LOAD DATA LOCAL.
  • The text of every query and prepared statement they send is logged with the session (who, from where, which client), read in the character set the session uses, with the values sent for a prepared statement (as bytes), the commands that change the session, and the database a login picks. Long leading comments are left out, so that they cannot hide the statement. The log is kept DB_GATEWAY_LOG_DAYS days and up to DB_GATEWAY_LOG_MAX_MB (1000 MB): past that, its oldest statements go.
  • Turning an access off, changing its rights, a new password or its end date ends its open sessions at once, also for a login still in progress. Removing it also drops its database user, so a connection with accesses on it cannot be deleted until they are removed. Suspending an account ends the access it gave.
  • Write rights cannot be given on a write-protected connection, nor on the target of a running live sync (anything written there would be overwritten). When protection or a live sync is turned on later, accesses with write rights pause (within 30 seconds) until it is off again.
  • A whole-database grant covers that database only. In MySQL's GRANT ... ON db.*, _ and % are wildcards, so DbBackup escapes them: shop_db does not also cover shop-db.
  • With the "Everything in this database" preset, views, triggers, routines and events a person creates keep their database user as their definer. After the access is removed these stop working ("definer does not exist") until they are changed or removed on the database.
  • The connection's database user must be allowed to create users and to give the chosen rights (CREATE USER and the rights WITH GRANT OPTION, e.g. root).

To turn it on, set in server/.env and restart DbBackup:

DB_GATEWAY_PORT=3307
DB_GATEWAY_TLS_CERT=/www/server/panel/vhost/cert/dbbackup.example.com/fullchain.pem
DB_GATEWAY_TLS_KEY=/www/server/panel/vhost/cert/dbbackup.example.com/privkey.pem

(the paths above are where aaPanel keeps a site's Let's Encrypt certificate; renewals are picked up without a restart). Then allow the port in the server's firewall. Failed logins are limited per address (10 in 15 minutes; per IPv6 block; 20 at the most per window, parallel attempts included), and at most DB_GATEWAY_MAX_CONNECTIONS connections (500 by default) are open at once, logged in or not. A session is ended after 100 commands the gateway refuses. These limits go by the address of each client's own connection: do not put the gateway behind a TCP proxy that hides client addresses, or every client counts as one.

When the gateway cannot reach or log in to the database, the person gets a reference number and the reason is in the server log. One case to know about: MySQL 8 asks for the password itself the first time it sees a user. The gateway gives it only to a database that is vouched for: reached through the connection's SSH tunnel, or over SSL with the connection's CA set. Over a plain connection, or over SSL without a CA, anyone on the way could answer in the database's place and read the password, so there the login is refused. Set the CA or use the tunnel, or, on a network you know is private, set DB_GATEWAY_TRUST_PRIVATE_NETWORK=true.

Storage quotas & connection limits

Every user gets a storage quota β€” 1 GB free by default (null = unlimited). It counts the user's COMPLETED backups across all providers (local disk, S3, Google Drive); retention cleanup frees space automatically.

Users also get a connection limit β€” 5 free by default (null = unlimited). Creating the (N+1)th connection is rejected with 403, and config-bundle imports that would exceed the limit fail atomically before creating anything.

Backups are also capped by a max retention period β€” 30 days free by default (null = unlimited, admin presets: 7/14/30/60/90/180/365). Schedules above the cap are rejected at save time (403), the daily sweep clamps existing schedules to the cap, and bundle imports with longer retentions are rejected up front β€” backups are never deleted sooner than a bundle promised.

  • Over quota: new backups are rejected β€” instantly on the API when already over, and in the backup worker once the dump size is known (covering manual, scheduled and MCP-triggered backups). The dump is discarded and the backup is marked FAILED with a clear message; quota failures do not retry.
  • Near-limit alert: at the same threshold as storage alerts (default 80%, STORAGE_ALERT_THRESHOLD_PERCENT), throttled to once per 24h, delivered through every configured notification channel.
  • Admin control: Super Admin β†’ user detail β†’ Storage quota, Connection limit and Max retention period editors (set a value or Unlimit). Changes are audit-logged (ADMIN_SET_QUOTA, ADMIN_SET_CONNECTION_LIMIT, ADMIN_SET_RETENTION_LIMIT).

Securing your environment file (.env)

An env file always holds some plaintext bootstrap secrets β€” that's unavoidable β€” but you can shrink the blast radius:

  1. Permissions & ownership β€” only the app user may read it:
    chmod 600 /www/wwwroot/dbbackup.hamza.codes/DbBackup/server/.env
    chown <app-user>:<app-user> .../.env
    The app audits this at boot and warns in the logs when the file is group/world readable.
  2. Fewer secrets in the file β€” JWT_ACCESS_SECRET / JWT_REFRESH_SECRET are optional: when unset they are derived from the master encryption key. Delete those two lines from .env (note: existing sessions re-login once after the switch).
  3. Master key off the disk β€” set up the KMS kill switch (KMS_WRAPPED_MASTER_KEY, see server/.env.example): the credential-encryption master key lives only in AWS KMS and process memory. With JWT secrets derived from it, a stolen .env + stolen database no longer decrypt anything.
  4. What still must stay in .env: the app's own DATABASE_URL (Postgres for DbBackup), Redis, port β€” treat the server itself as the perimeter for these; rotate them in INCIDENT_RESPONSE.md if in doubt.
  5. Never commit it (already gitignored), never copy it into backups/notes, and avoid editing it over unencrypted channels.

πŸ“‘ API Endpoints

Authentication

Method Endpoint Description
POST /api/auth/register Create a new account
POST /api/auth/login Login and receive tokens
POST /api/auth/logout Revoke refresh token
POST /api/auth/refresh Refresh access token
GET /api/auth/me Get current user
POST /api/auth/change-password Change password (starts the sign-in cool-down)
GET /api/auth/sessions List active sessions (device, IP, login time)
DELETE /api/auth/sessions/:id Revoke one session
DELETE /api/auth/sessions Revoke all sessions (log out everywhere)
GET /api/auth/passkey/list List registered passkeys
POST /api/auth/passkey/register/options + /verify Register a passkey
DELETE /api/auth/passkey/:id Remove a passkey
POST /api/auth/passkey/login/options + /verify Passwordless passkey login

Connections

Method Endpoint Description
GET /api/connections List all connections
POST /api/connections Create a new connection
PUT /api/connections/:id Update a connection
DELETE /api/connections/:id Delete a connection
POST /api/connections/:id/test Test connection
GET /api/connections/:id/info Get database schema info

Backups

Method Endpoint Description
GET /api/backups List all backups
POST /api/backups Trigger a manual backup
GET /api/backups/:id/progress Backup progress (SSE)
POST /api/backups/:id/verify Verify backup integrity (works for S3-stored backups too)
GET /api/backups/:id/download Download backup file (streams from S3 if needed)
DELETE /api/backups/:id Delete a backup (removes the S3 object too)

Restores

Method Endpoint Description
POST /api/restore Queue a restore job β€” returns 202 with a jobId
GET /api/restore/:jobId/progress Restore progress (SSE)

Schedules

Method Endpoint Description
GET /api/schedules List all schedules
POST /api/schedules Create a schedule
PUT /api/schedules/:id Update a schedule
DELETE /api/schedules/:id Delete a schedule

Migrations

Method Endpoint Description
GET /api/migrations List all migrations
POST /api/migrations Start a migration
GET /api/migrations/:id Get migration details
GET /api/migrations/:id/progress Get migration progress (SSE)
POST /api/migrations/:id/verify Verify migration results
DELETE /api/migrations/:id Delete a migration

Exports

Method Endpoint Description
POST /api/connections/:id/export Export a table (JSON, CSV, or SQL)

Settings & Other

Method Endpoint Description
GET/PUT /api/notifications Notification settings
POST /api/notifications/test Send test notification
GET/PUT /api/storage Storage settings (S3 / Google Drive / backup encryption passphrase)
POST /api/storage/test Test storage connection (+ S3 bucket privacy probe)
GET /api/storage/usage Local / Drive / S3 usage vs threshold
GET /api/audit Activity log (filter by action / resource / date)
GET /api/connections/:id/heartbeat Heartbeat status, uptime %, history

πŸ”„ Updating an existing deployment

git pull
npm ci                       # exact dependencies from package-lock.json
npm run build                # client + server
(cd server && npx prisma migrate deploy)   # apply pending migrations (required)
pm2 restart dbbackup         # or start it the first time: pm2 start ecosystem.config.cjs && pm2 save

Running with pm2

Use the included ecosystem.config.cjs. It runs server/dist/index.js from the server/ folder (so server/.env is read) with NODE_ENV=production, in fork mode with one instance.

Do not use cluster mode or instances > 1. Passkey challenges, login lockouts, rate limits, real-time sync polling and restore drills are kept in process memory; a second process splits that state. Every pm2 instance other than the first refuses to start and logs why (override only if you know what you are doing: ALLOW_MULTIPLE_INSTANCES=true).

If you started the app another way before, switch once with pm2 delete <old-name> && pm2 start ecosystem.config.cjs && pm2 save.

Backwards compatibility: existing connections, backups, and unencrypted backups keep working; legacy encryption keys still decrypt existing rows; unencrypted backups remain readable alongside encrypted ones.

After deploying behind nginx, set PASSKEY_RP_ID (and ideally forward Host / X-Forwarded-* headers) β€” see SECURITY.md and server/.env.example.


🐳 Docker Services

Service Image Host Port Container Port
PostgreSQL postgres:16-alpine 5433 5432
Redis redis:7-alpine 6379 6379

Both services include health checks and persistent Docker volumes.


πŸ“ Scripts

Root

Command Description
npm run dev Start server + client concurrently
npm run build Build server + client for production
npm run install:all Install all workspace dependencies

Server (cd server)

Command Description
npm run dev Start dev server with tsx watch
npm run build Compile TypeScript
npm start Run compiled server
npm run prisma:generate Generate Prisma client
npm run prisma:migrate Run database migrations
npm run prisma:studio Open Prisma Studio
npm test Unit tests (no database needed)
npm run test:integration Prisma integration tests against TEST_DATABASE_URL (tables are wiped)
npm run test:e2e End-to-end tests against real databases and CLI tools β€” see server/src/test/e2e/README.md

Client (cd client)

Command Description
npm run dev Start Vite dev server
npm run build Build for production
npm run preview Preview production build

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Commit your changes (git commit -m 'Add my feature')
  4. Push to the branch (git push origin feature/my-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License.

About

πŸ€–πŸ—„οΈ The agent-ready, self-hosted database backup platform β€” MySQL, MariaDB & PostgreSQL over SSH tunnels, AES-256-GCM encryption at rest (local / S3 / Google Drive), passkeys, heartbeat monitoring, audit logs, alerts & a built-in MCP server for AI agents.

Topics

Resources

Security policy

Stars

7 stars

Watchers

0 watching

Forks

Packages

Contributors

Languages

0