Run your own proxy so LunoDB Mobile reaches your databases through infrastructure you control.
LunoDB Mobile connects to remote databases through a proxy server. By default, connections route through LunoDB Cloud, our secure connection gateway. If you want complete control over your data flow, you can build and host your own proxy server.
Turso and local SQLite databases connect directly from the app, with no proxy. Turso uses HTTPS API calls, and SQLite files are stored on your device.
Why self-host?
Complete control. All database traffic routes through your infrastructure.
Compliance. Meet internal security policies or regulatory requirements.
Network access. Connect to databases inside private networks without exposing them.
Peace of mind. Know exactly how your connections are handled.
Advanced setup required. Self-hosting needs Node.js development experience and server administration knowledge. For most people, LunoDB Cloud provides secure, encrypted connections with zero setup.
How the app, your proxy and your databases talk to each other.
The proxy sits between LunoDB Mobile and your databases. The app can’t open direct TCP socket connections to traditional databases, so the proxy bridges that gap securely.
Needs a proxy
These databases use TCP socket connections that require a proxy server.
MySQLPostgreSQLMariaDBSQL ServerMongoDB
Connects directly
These connect over HTTPS or from local storage, with no proxy.
TursoSQLite
Diagram
┌─────────────────────┐ HTTPS ┌──────────────────────┐
│ LunoDB Mobile │◄──────────────────────►│ Your Proxy Server │
│ (iOS/Android) │ REST API │ (Node.js) │
└─────────────────────┘ └──────────┬───────────┘
│
┌──────────────────────┼──────────────────────┐
│ │ │
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
│ MySQL │ │ PostgreSQL│ │ MariaDB │
│ Server │ │ Server │ │ Server │
└───────────┘ └───────────┘ └───────────┘
How it works
1
Connection request
The app sends database credentials to your proxy.
2
Session creation
The proxy opens the connection and returns a session ID.
3
Query execution
The app sends queries using the session ID.
4
Results return
The proxy runs each query and returns the results to the app.
5
Session cleanup
Sessions expire after inactivity or an explicit disconnect.
Session-based design
The proxy uses session tokens to keep database connections open. Credentials are only sent once, during connection setup, not with every query. On LunoDB Cloud, sessions expire 30 minutes after they’re created.
When a session is gone, the app reconnects automatically, as long as your proxy answers with a 404 and a SESSION_NOT_FOUND code or a “Session not found” message.
Return one page of rows from a table. The app uses this to browse table data, so your proxy needs it too. Query parameters: database, limit, offset, orderBy and orderDir (asc or desc). LunoDB Cloud defaults to 100 rows and caps a page at 1,000.
Response: the same shape as the execute endpoint (rows, fields, rowCount, executionTime).
Error codes
Return errors as JSON with a non-2xx status. The app shows the error field as the message and reads the optional code field, for example { "code": "SESSION_NOT_FOUND", "error": "Session expired or not found" }. SESSION_NOT_FOUND and SESSION_EXPIRED make the app reconnect automatically.
This sample covers MySQL, PostgreSQL and MariaDB. To add SQL Server and MongoDB, see SQL Server and MongoDB.
Production recommendations
Use Redis for sessions
Replace the in-memory Map with Redis for multi-instance support.
Connection pooling
Use connection pools instead of a single connection per session.
Rate limiting
Add rate limiting middleware to prevent abuse.
Request logging
Log queries for audit trails, without sensitive parameters.
Health checks
Add a /health endpoint for load balancer monitoring.
Proxy guideBuild itDatabase SSL
Database SSL
Encrypt the connection from your proxy to the database: require, verify-ca and verify-full.
Many hosted databases only accept encrypted connections: sslmode=require in PostgreSQL terms. A connection request can carry an optional ssl object that says how your proxy should encrypt its connection to the database. This is separate from the HTTPS between the app and your proxy, which is always required.
LunoDB Cloud already honours the ssl object. The SSL setting in the app arrives in an upcoming update. Until then the app sends no ssl object and your proxy’s defaults apply.
The ssl object
It’s sent alongside the other fields on POST /proxy/connections and POST /proxy/connections/test. Every field is optional. Certificates arrive as PEM text, and a client cert always comes with its key.
The modes use PostgreSQL’s names. Map them onto each database’s own settings:
disableNever use TLS.
preferUse TLS when the server offers it. Treat this the same as no mode at all: your proxy’s default.
requireUse TLS or fail. The certificate isn’t checked, so self-signed certificates work.
verify-caUse TLS, and the certificate must chain to the CA (the one sent in ca, or the system trust store).
verify-fullverify-ca, and the certificate must also match the hostname.
Never fall back to plaintext under require or stricter. Retrying without TLS is fine for prefer, but under require it would quietly send the password unencrypted to a server that was meant to be encrypted.
When no mode is sent
Pick a default that still reaches common hosts. LunoDB Cloud uses:
PostgreSQL: libpq’s prefer, plus require for hosts that mandate TLS (Neon *.neon.tech, Supabase *.supabase.co).
MySQL and MariaDB: TLS without certificate checks, falling back to plaintext only when the server can’t do TLS.
SQL Server: encrypted, trusting the server’s certificate (self-hosted servers use a self-signed one). Azure SQL is verified.
MongoDB: the driver’s default: TLS for mongodb+srv:// (Atlas), plaintext otherwise.
Implementation with Node.js drivers
The Node drivers take PEM text directly, so a Node proxy never has to write certificates to disk:
ssl-options.js
// Map the request's ssl object onto each Node driver's options.
// Node drivers take PEM text directly, so nothing touches the disk.
function sslOptions(type, ssl = {}) {
const mode = ssl.mode === 'prefer' ? undefined : ssl.mode; // prefer = your default
const pems = { ca: ssl.ca, cert: ssl.cert, key: ssl.key };
const verify = mode === 'verify-ca' || mode === 'verify-full';
switch (type) {
case 'postgresql': // pg: pass as { ssl }
if (!mode) return {};
if (mode === 'disable') return { ssl: false };
return {
ssl: {
...pems,
rejectUnauthorized: verify,
// verify-ca: check the chain, not the hostname
...(mode === 'verify-ca' && { checkServerIdentity: () => undefined }),
},
};
case 'mysql':
case 'mariadb': // mysql2: pass as { ssl }
if (!mode || mode === 'disable') return {};
return { ssl: { ...pems, rejectUnauthorized: verify } };
case 'sqlserver': // mssql: merge into options
return {
options: {
encrypt: mode !== 'disable',
trustServerCertificate: !verify,
},
};
case 'mongodb': // mongodb: MongoClient options
if (!mode) return {};
if (mode === 'disable') return { tls: false };
return {
tls: true,
...pems,
tlsAllowInvalidCertificates: mode === 'require',
tlsAllowInvalidHostnames: mode === 'verify-ca',
};
}
}
mysql2 checks the hostname whenever it verifies, so verify-ca behaves like verify-full.
mssql can’t take a CA file. Verify modes check against the system trust store, and ca, cert and key are ignored (SQL Server has no client-certificate login).
Drivers that need certificate files
libpq (PHP’s pdo_pgsql, Python’s psycopg), PHP’s mysqlnd and the MongoDB C driver only take file paths. Write each PEM to a private temp file (mode 600: libpq refuses a world-readable key), connect, then delete it. A lazily-connecting client like MongoDB’s reads the files on its first command, so keep them until the request ends.
Hostname checks and DNS pinning
If your proxy resolves the host and connects to the IP (to stop DNS rebinding, see Security), verify-full fails, because the certificate names the host, not the IP. In libpq, pass the IP as hostaddr and keep the name in host: libpq connects to the IP but checks the certificate against the name. Drivers without that split need to connect by hostname in the verify modes.
Reach databases behind a bastion host or private network.
Many databases sit behind firewalls and are only reachable through a bastion host or jump server. SSH tunneling lets your proxy reach them through an encrypted tunnel via the SSH server.
When to use it
Private networks. The database is on a private subnet with no public IP.
Bastion hosts. Access requires jumping through an SSH gateway.
Cloud security. AWS RDS, GCP Cloud SQL or Azure databases in private VPCs.
Firewall rules. The database only accepts connections from specific IPs.
const { Client } = require('ssh2');
const mysql = require('mysql2/promise');
const net = require('net');
async function createSSHTunnel(sshConfig, dbConfig) {
return new Promise((resolve, reject) => {
const ssh = new Client();
ssh.on('ready', () => {
// Forward connection to database through tunnel
ssh.forwardOut(
'127.0.0.1', // Source address
0, // Source port (auto-assign)
dbConfig.host,
dbConfig.port,
async (err, stream) => {
if (err) {
ssh.end();
return reject(err);
}
// Create database connection through the tunnel
const connection = await mysql.createConnection({
...dbConfig,
stream: stream, // Use SSH stream instead of TCP
});
resolve({ connection, ssh });
}
);
});
ssh.on('error', reject);
// Connect to SSH server
const connectConfig = {
host: sshConfig.host,
port: sshConfig.port || 22,
username: sshConfig.username,
};
if (sshConfig.authType === 'key') {
connectConfig.privateKey = sshConfig.privateKey;
if (sshConfig.passphrase) {
connectConfig.passphrase = sshConfig.passphrase;
}
} else {
connectConfig.password = sshConfig.password;
}
ssh.connect(connectConfig);
});
}
// Usage in your connection endpoint
app.post('/proxy/connections', async (req, res) => {
const { ssh, ...dbConfig } = req.body;
try {
let connection, sshClient;
if (ssh?.enabled) {
const tunnel = await createSSHTunnel(ssh, dbConfig);
connection = tunnel.connection;
sshClient = tunnel.ssh;
} else {
connection = await mysql.createConnection(dbConfig);
}
const sessionId = uuidv4();
sessions.set(sessionId, {
connection,
sshClient, // Store SSH client for cleanup
lastActivity: Date.now()
});
res.json({ sessionId, /* ... */ });
} catch (error) {
if (error.message.includes('authentication')) {
res.status(502).json({ error: 'SSH_AUTH_FAILED', message: error.message });
} else {
res.status(502).json({ error: 'SSH_CONNECTION_FAILED', message: error.message });
}
}
});
Clean up SSH connections. When closing a session, close both the database connection and the SSH client. Leaving the tunnel open leaves orphaned connections on your bastion host.
Alternative: CLI-based tunneling
Instead of port forwarding, you can run queries by calling the mysql or psql CLI directly on the SSH server. This is simpler and works well for stateless PHP/Laravel proxies.
Response format. The app expects rows as objects keyed by column name, not indexed arrays. For tunneled connections, parse the CLI output and map values to their column names. The fields array should hold column metadata with at least a name.
Passwords. Use the MYSQL_PWD environment variable for MySQL/MariaDB and PGPASSWORD for PostgreSQL instead of passing passwords on the command line. This avoids the “Using a password on the command line interface can be insecure” warning and keeps the password out of process listings.
CLI command format
For MySQL/MariaDB, use batch mode (-B) for tab-separated output, and include column headers so you can build objects:
Commands
# MySQL - with headers (for SELECT queries)
MYSQL_PWD='password' mysql -h host -P 3306 -u user database -B -e 'SELECT * FROM users'
# MySQL - without headers (for internal queries like SHOW DATABASES)
MYSQL_PWD='password' mysql -h host -P 3306 -u user database -N -B -e 'SHOW DATABASES'
# PostgreSQL - with headers
PGPASSWORD='password' psql -h host -p 5432 -U user database -A -F $'\t' -c 'SELECT * FROM users'
# PostgreSQL - without headers (tuples only)
PGPASSWORD='password' psql -h host -p 5432 -U user database -t -A -F $'\t' -c 'SELECT 1'
Parsing CLI output
The first line holds the column headers. Parse the following lines and map each value to its column:
Parsing
// Example CLI output (tab-separated):
// id name status
// 1 John active
// 2 Jane \N
// Should be parsed to:
{
"rows": [
{ "id": "1", "name": "John", "status": "active" },
{ "id": "2", "name": "Jane", "status": null }
],
"fields": [
{ "name": "id", "type": "string" },
{ "name": "name", "type": "string" },
{ "name": "status", "type": "string" }
]
}
// Note: \N in MySQL output represents NULL values
SSL with the CLI clients
When a request carries an ssl object, pass it on as client flags. Certificates have to exist as files on the SSH host, so write them to a private temp directory for the length of the command and remove it on exit. Run everything under sh -c: the SSH user’s login shell may not be POSIX.
Commands
# Write the PEMs to a private temp dir on the SSH host, removed on exit
sh -c '
umask 077; d=$(mktemp -d) || exit 1; trap "rm -rf \"$d\"" EXIT
printf "%s\n" "<CA PEM>" > "$d/ca.pem"
# PostgreSQL: libpq reads SSL settings from the environment
PGSSLMODE=verify-full PGSSLROOTCERT="$d/ca.pem" PGPASSWORD=... psql -h db -U user -c "SELECT 1"
# MySQL client vs MariaDB client spell the flags differently
if mysql --version | grep -qi mariadb; then
set -- --ssl --ssl-verify-server-cert --ssl-ca="$d/ca.pem"
else
set -- --ssl-mode=VERIFY_IDENTITY --ssl-ca="$d/ca.pem"
fi
MYSQL_PWD=... mysql -h db -u user "$@" -B -e "SELECT 1"
# MongoDB
mongosh --host db --tls --tlsCAFile "$d/ca.pem" --eval "db.version()"
'
psql takes PGSSLMODE, PGSSLROOTCERT, PGSSLCERT and PGSSLKEY. With no CA, verify-full can use PGSSLROOTCERT=system (psql 16+); verify-ca needs the CA.
mysql (Oracle)--ssl-mode=DISABLED|REQUIRED|VERIFY_CA|VERIFY_IDENTITY with --ssl-ca, --ssl-cert and --ssl-key. Both verify modes need the CA.
mysql (MariaDB)--skip-ssl, or --ssl with --ssl-verify-server-cert (verify) or --skip-ssl-verify-server-cert (require). It has no CA-only check, so verify-ca also checks the hostname.
mongosh--tls, plus --tlsAllowInvalidCertificates (require) or --tlsAllowInvalidHostnames (verify-ca), --tlsCAFile, and --tlsCertificateKeyFile holding the client certificate and key in one PEM.
Write the PEMs with printf, a shell builtin, so they never show up in another process’s arguments.
Error detection
You need to spot database errors in the CLI output. Use regex patterns, not simple string matching, to avoid false positives from table names that contain words like “error” (for example price_errors or audit_errors).
Error patterns
// ❌ BAD: Simple string matching causes false positives
// This would match table names like "price_errors"
if (output.toLowerCase().includes('error')) {
throw new Error('Query failed');
}
// ✅ GOOD: Use specific regex patterns
const errorPatterns = [
/^ERROR \d+/m, // MySQL: "ERROR 1045 (28000)..."
/^error:/im, // Error prefix at line start only
/Access denied for user/i, // MySQL access denied
/Connection refused/i, // Connection error
/Unknown database/i, // MySQL unknown database
/command not found/i, // CLI not installed
/^FATAL:/m, // PostgreSQL fatal errors
/authentication failed/i, // Auth failure
/Can't connect to/i, // MySQL connection error
/^psql: error:/m, // libpq connection and SSL failures
/^mysql: unknown (variable|option)/m, // client too old for the SSL flags
/MongoServerSelectionError/, // mongosh couldn't connect (often TLS)
];
for (const pattern of errorPatterns) {
if (pattern.test(output)) {
throw new Error(`Query error: ${output}`);
}
}
Avoid false positives. Schemas often have tables like error_logs, sync_errors or validation_errors. A check like includes('error') wrongly flags these as failed queries. Always match the specific format of database error messages.
Proxy guideRun itSecurity
Security
Keep credentials safe and control what the app is allowed to run.
Security is critical. Your proxy server handles database credentials. Follow these practices carefully.
Required security measures
HTTPS only
Always use TLS 1.2+ encryption. Never accept plain HTTP connections.
TLS
# Use Let's Encrypt for free TLS certificates
certbot certonly --standalone -d proxy.yourdomain.com
# Or use a reverse proxy like nginx with TLS termination
Never store credentials
Credentials should only exist in memory during the session. Never log or persist them; store only the session ID reference to the connection.
Session expiration
Expire sessions after 30 minutes of inactivity, and clean them up promptly to release database connections.
Network isolation
Deploy the proxy in the same network as your databases. Use firewall rules to limit which databases it can reach, and consider a VPN or private networking.
SSH tunnel security
Prefer keys over passwords
Key authentication is far more secure. Use Ed25519 or RSA 4096-bit keys, and never use password authentication on production systems.
Protect private keys
Never log or store private keys in plain text. Keep them in memory only while connected, and consider a secrets manager like HashiCorp Vault.
Restrict bastion access
Only allow connections from your proxy server’s IP. Use fail2ban against brute-force attempts, and disable password authentication on the SSH server.
Close idle tunnels
SSH connections use resources on the bastion host. Make sure session cleanup closes tunnels too, and watch for orphaned connections.
Database SSL
Client keys are credentials
A client key in the ssl object is as sensitive as the password. Keep it in memory with the session, never log it, and delete any temp file as soon as the driver has read it.
No silent downgrade
Under require or stricter, fail the connection rather than retrying without TLS. See SSL modes.
Pin the resolved IP
Check the host against private and metadata ranges, then connect to the IP you checked, so a DNS change between the two can’t redirect the connection. For verify-full, see hostname checks.
Safe Mode and query restrictions
The proxy enforces query restrictions to protect against accidental data loss. Some operations are always blocked in the mobile app; others are controlled by Safe Mode.
Always blocked (use the desktop app)
These server-level operations are never allowed from the mobile app. Use the LunoDB desktop app for full access.
The app turns Safe Mode on by default for new connections. If a request leaves out safeMode, treat it as off. Keep it on for shared or production databases where you want an extra layer of protection.
SQL Server and MongoDB
The sample server covers MySQL, PostgreSQL and MariaDB. The app sends SQL Server and MongoDB through the same endpoints, so to support them add a driver (such as mssql or mongodb) and handle their type values: sqlserver and mongodb.
SQL Server queries arrive as T-SQL text in sql, just like the other SQL databases. The app doesn’t offer SSH tunnels for SQL Server.
MongoDB queries arrive in sql as shell-style text, for example db.users.find({"active": true}). LunoDB Cloud supports find, findOne, countDocuments, estimatedDocumentCount, aggregate, distinct, insertOne, insertMany, updateOne, updateMany, replaceOne, deleteOne and deleteMany.
Restricting access
The App Store version of LunoDB Mobile only sends standard Content-Type and Accept headers, and has no setting for custom headers. That means API key authentication like the example below won’t work with the app as shipped. To keep strangers off your proxy, put it behind a VPN (such as Tailscale or WireGuard) or allow only the IP addresses you trust.
If you build your own client, you can require an API key like this:
API key middleware
// API Key middleware
const apiKeyAuth = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey || apiKey !== process.env.PROXY_API_KEY) {
return res.status(401).json({
code: 'UNAUTHORIZED',
error: 'Invalid or missing API key'
});
}
next();
};
app.use('/proxy', apiKeyAuth);
Proxy guideRun itConnect the app
Connect the app
Point LunoDB Mobile at your proxy, and switch back to LunoDB Cloud any time.
Once your proxy server is running, point LunoDB Mobile at it.
Set the server URL
1
Open Settings
In LunoDB Mobile, go to Settings → Connection and scroll to the Proxy Server section.
2
Enter your proxy’s base URL
Enter the base URL your /proxy/* routes live under in Server URL. The app adds /proxy/... itself, so for the sample server enter https://proxy.yourdomain.com.
3
Test a connection
Open or test a connection to make sure everything works.
The app can’t send an API key or other custom headers. Protect a self-hosted proxy with a VPN or an IP allowlist instead.
Turn on Safe Mode
Safe Mode protects against accidental data loss by blocking DROP, TRUNCATE, ALTER DATABASE and DELETE operations.
1
Open the connection’s menu
On the Connections screen, open the menu for the connection.
2
Tap Edit
This opens the connection settings.
3
Turn on Safe Mode
It’s on by default for new connections.
4
Reconnect
Changes take effect the next time you connect.
Safe Mode is set per connection, so some connections can have it on and others off.
Switch back to LunoDB Cloud
To return to the default LunoDB Cloud proxy, tap Reset next to Server URL in Settings → Connection. This sets the proxy URL back to https://lunodb.app/api.