e-subs / db.js
000x's picture
Upload 18 files
8a636d7 verified
Raw History Blame Contribute Delete
15.3 kB
'use strict';
// Single database: PostgreSQL (DATABASE_URL).
// bot_files - the file list (codes, titles, URLs)
// bot_wa_auth - the WhatsApp session, ENCRYPTED with SESSION_KEY
const crypto = require('crypto');
const { Pool } = require('pg');
const { BufferJSON, initAuthCreds, proto } = require('@whiskeysockets/baileys');
// ---------------------------------------------------------------------------
// Connection
// SSL is ON by default for public hosts (Neon, Supabase, Railway public URL...).
// Localhost and Railway private URLs (*.railway.internal) are off by default.
// DATABASE_SSL (optional):
// (unset) -> SSL on for remote hosts, off for localhost, certificate checked
// false -> no SSL (local database only)
// insecure -> SSL on, certificate NOT checked (use only if the host's certificate fails the check)
// Any sslmode= in the URL is removed, so pg does not print its SSL warning.
// ---------------------------------------------------------------------------
function poolConfig() {
const raw = process.env.DATABASE_URL;
if (!raw) throw new Error('DATABASE_URL is not set. Add your PostgreSQL URL to .env (or Hugging Face Space secrets).');
const url = new URL(raw);
for (const k of ['sslmode', 'ssl', 'uselibpqcompat', 'sslrootcert']) url.searchParams.delete(k);
// Railway's private network (*.railway.internal) does not use SSL, so it is treated like localhost.
const isLocal = ['localhost', '127.0.0.1', '::1'].includes(url.hostname) || url.hostname.endsWith('.railway.internal');
const mode = String(process.env.DATABASE_SSL ?? '').trim().toLowerCase();
let ssl;
if (mode === 'false' || mode === '0' || mode === 'off') ssl = undefined;
else if (mode === 'insecure') ssl = { rejectUnauthorized: false };
else if (mode === 'true' || mode === '1' || mode === 'on' || (mode === '' && !isLocal)) ssl = { rejectUnauthorized: true };
return { connectionString: url.toString(), ssl, max: 5 };
}
const pool = new Pool(poolConfig());
pool.on('error', (e) => console.error('Postgres pool error:', e.message));
// ---------------------------------------------------------------------------
// Encryption for the WhatsApp session (AES-256-GCM).
// SESSION_KEY must be a long random string. Generate one with: make gen-key
// Keep the same key forever: changing it makes the saved session unreadable.
// ---------------------------------------------------------------------------
const SESSION_KEY = process.env.SESSION_KEY || '';
if (SESSION_KEY.length < 32) {
throw new Error('SESSION_KEY is missing or too short (min 32 characters). Generate one with: make gen-key');
}
const aesKey = crypto.createHash('sha256').update(SESSION_KEY).digest();
const SEAL_PREFIX = 'enc:v1:';
function seal(text) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
const body = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
return SEAL_PREFIX + Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64');
}
function open(value) {
if (!value.startsWith(SEAL_PREFIX)) return value; // legacy plain-text row, re-saved encrypted on next write
const buf = Buffer.from(value.slice(SEAL_PREFIX.length), 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', aesKey, buf.subarray(0, 12));
decipher.setAuthTag(buf.subarray(12, 28));
return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
}
async function init() {
await pool.query(`
CREATE TABLE IF NOT EXISTS bot_files (
code TEXT NOT NULL,
title TEXT NOT NULL,
url TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'document',
sent INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
delete_after_send BOOLEAN NOT NULL DEFAULT FALSE
);
ALTER TABLE bot_files ADD COLUMN IF NOT EXISTS delete_after_send BOOLEAN NOT NULL DEFAULT FALSE;
CREATE UNIQUE INDEX IF NOT EXISTS bot_files_code_lower ON bot_files (lower(code));
CREATE TABLE IF NOT EXISTS bot_users (
phone TEXT PRIMARY KEY,
lang TEXT NOT NULL DEFAULT 'en',
role TEXT NOT NULL DEFAULT 'free' CHECK (role IN ('free', 'premium', 'admin')),
blocked BOOLEAN NOT NULL DEFAULT FALSE,
daily_limit INTEGER,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_seen TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS bot_downloads (
id BIGSERIAL PRIMARY KEY,
phone TEXT NOT NULL,
code TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS bot_downloads_phone_time ON bot_downloads (phone, created_at);
CREATE TABLE IF NOT EXISTS bot_sent_messages (
id BIGSERIAL PRIMARY KEY,
jid TEXT NOT NULL,
msg_id TEXT NOT NULL,
delete_at TIMESTAMPTZ NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT
);
CREATE INDEX IF NOT EXISTS bot_sent_messages_due ON bot_sent_messages (delete_at);
CREATE TABLE IF NOT EXISTS bot_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
ALTER TABLE bot_files ADD COLUMN IF NOT EXISTS listed BOOLEAN NOT NULL DEFAULT TRUE;
CREATE TABLE IF NOT EXISTS bot_wa_auth (
id TEXT PRIMARY KEY,
data TEXT NOT NULL
);
`);
}
// ---------------------------------------------------------------------------
// File list
// ---------------------------------------------------------------------------
const toItem = (r) => ({
code: r.code,
title: r.title,
url: r.url,
type: r.type,
sent: r.sent,
listed: r.listed,
deleteAfterSend: r.delete_after_send,
createdAt: r.created_at.toISOString(),
});
async function listFiles() {
const { rows } = await pool.query('SELECT * FROM bot_files ORDER BY created_at, code');
return rows.map(toItem);
}
async function findFile(code) {
const { rows } = await pool.query('SELECT * FROM bot_files WHERE lower(code) = lower($1)', [code]);
return rows[0] ? toItem(rows[0]) : null;
}
// Throws with code 23505 if the code is already used (unique index).
async function addFile({ code, title, url, type, deleteAfterSend = false }) {
const { rows } = await pool.query(
'INSERT INTO bot_files (code, title, url, type, delete_after_send) VALUES ($1, $2, $3, $4, $5) RETURNING *',
[code, title, url, type, !!deleteAfterSend]
);
return toItem(rows[0]);
}
async function setListed(code, listed) {
const { rows } = await pool.query(
'UPDATE bot_files SET listed = $2 WHERE lower(code) = lower($1) RETURNING *',
[code, !!listed]
);
return rows[0] ? toItem(rows[0]) : null;
}
// Public file list: codes and titles only (never the download URL).
async function listCatalog() {
const { rows } = await pool.query('SELECT code, title, type FROM bot_files WHERE listed ORDER BY lower(title)');
return rows;
}
async function deleteFile(code) {
const { rowCount } = await pool.query('DELETE FROM bot_files WHERE lower(code) = lower($1)', [code]);
return rowCount;
}
// Called after a file was sent. Counts the send and, for one-time files,
// deletes the file in the same step. Returns true if the file was deleted.
async function recordSend(code) {
await pool.query('UPDATE bot_files SET sent = sent + 1 WHERE lower(code) = lower($1)', [code]);
const { rowCount } = await pool.query(
'DELETE FROM bot_files WHERE lower(code) = lower($1) AND delete_after_send = TRUE',
[code]
);
return rowCount > 0;
}
// ---------------------------------------------------------------------------
// Users, roles and download counts
// ---------------------------------------------------------------------------
const toUser = (r) => ({
id: r.phone,
lang: r.lang,
role: r.role,
blocked: r.blocked,
dailyLimit: r.daily_limit,
createdAt: r.created_at?.toISOString?.() ?? null,
lastSeen: r.last_seen?.toISOString?.() ?? null,
today: r.today ?? undefined,
});
// Creates the user on first contact. Returns { user, isNew }.
// lang is only changed when a Sinhala message is detected (or set by /lang).
async function touchUser(phone, detectedLang = null) {
const { rows } = await pool.query(
`INSERT INTO bot_users (phone, lang) VALUES ($1::text, COALESCE($2::text, 'en'))
ON CONFLICT (phone) DO UPDATE SET last_seen = now(), lang = COALESCE($2::text, bot_users.lang)
RETURNING *, (xmax = 0) AS inserted`,
[phone, detectedLang]
);
return { user: toUser(rows[0]), isNew: rows[0].inserted };
}
async function getUser(phone) {
const { rows } = await pool.query('SELECT * FROM bot_users WHERE phone = $1', [phone]);
return rows[0] ? toUser(rows[0]) : null;
}
async function listUsers(q = '') {
const { rows } = await pool.query(
`SELECT u.*, (SELECT count(*)::int FROM bot_downloads d
WHERE d.phone = u.phone AND d.created_at > now() - interval '24 hours') AS today
FROM bot_users u
WHERE $1::text = '' OR u.phone LIKE '%' || $1::text || '%'
ORDER BY u.last_seen DESC LIMIT 200`,
[q]
);
return rows.map(toUser);
}
// Only these fields can be changed through updateUser.
const USER_FIELDS = { role: 'role', blocked: 'blocked', dailyLimit: 'daily_limit', lang: 'lang' };
async function updateUser(phone, patch) {
const sets = [];
const vals = [];
for (const [key, col] of Object.entries(USER_FIELDS)) {
if (patch[key] !== undefined) {
vals.push(patch[key]);
sets.push(`${col} = $${vals.length}`);
}
}
if (!sets.length) return null;
vals.push(phone);
const { rows } = await pool.query(
`UPDATE bot_users SET ${sets.join(', ')} WHERE phone = $${vals.length} RETURNING *`,
vals
);
return rows[0] ? toUser(rows[0]) : null;
}
async function downloadsToday(phone) {
const { rows } = await pool.query(
`SELECT count(*)::int AS n FROM bot_downloads WHERE phone = $1 AND created_at > now() - interval '24 hours'`,
[phone]
);
return rows[0].n;
}
async function recordDownload(phone, code) {
await pool.query('INSERT INTO bot_downloads (phone, code) VALUES ($1, $2)', [phone, code]);
}
async function stats() {
const { rows } = await pool.query(`
SELECT
(SELECT count(*)::int FROM bot_users) AS users,
(SELECT count(*)::int FROM bot_users WHERE role = 'premium') AS premium,
(SELECT count(*)::int FROM bot_users WHERE role = 'admin') AS admins,
(SELECT count(*)::int FROM bot_users WHERE blocked) AS blocked,
(SELECT count(*)::int FROM bot_downloads WHERE created_at > now() - interval '24 hours') AS downloads_today,
(SELECT count(*)::int FROM bot_downloads) AS downloads_total,
(SELECT count(*)::int FROM bot_files) AS files
`);
return rows[0];
}
// ---------------------------------------------------------------------------
// Settings (set in the dashboard). limits: downloads per 24h per role.
// null for admin = unlimited.
// ---------------------------------------------------------------------------
const DEFAULT_SETTINGS = {
limits: { free: 3, premium: 30, admin: null },
autoDeleteHours: Number(process.env.AUTO_DELETE_HOURS ?? 24),
};
async function getSettings() {
const { rows } = await pool.query("SELECT value FROM bot_settings WHERE key = 'main'");
const raw = rows[0] ? JSON.parse(rows[0].value) : {};
return {
limits: { ...DEFAULT_SETTINGS.limits, ...(raw.limits || {}) },
autoDeleteHours: raw.autoDeleteHours ?? DEFAULT_SETTINGS.autoDeleteHours,
};
}
async function setSettings(patch) {
const current = await getSettings();
const next = {
limits: { ...current.limits, ...(patch.limits || {}) },
autoDeleteHours: patch.autoDeleteHours ?? current.autoDeleteHours,
};
await pool.query(
`INSERT INTO bot_settings (key, value) VALUES ('main', $1)
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
[JSON.stringify(next)]
);
return next;
}
// ---------------------------------------------------------------------------
// Scheduled "delete for everyone" of bot messages
// ---------------------------------------------------------------------------
async function scheduleDeletes(items, deleteAt) {
for (const it of items) {
if (!it || !it.msgId) continue;
await pool.query(
'INSERT INTO bot_sent_messages (jid, msg_id, delete_at) VALUES ($1, $2, $3)',
[it.jid, it.msgId, deleteAt]
);
}
}
async function dueDeletes(limit = 20) {
const { rows } = await pool.query(
'SELECT id, jid, msg_id FROM bot_sent_messages WHERE delete_at <= now() ORDER BY delete_at LIMIT $1',
[limit]
);
return rows;
}
async function removeDelete(id) {
await pool.query('DELETE FROM bot_sent_messages WHERE id = $1', [id]);
}
// Gives up after 5 failed attempts so one broken message cannot block the queue.
async function failDelete(id, message) {
await pool.query(
`UPDATE bot_sent_messages SET attempts = attempts + 1, last_error = $2,
delete_at = now() + interval '5 minutes' WHERE id = $1`,
[id, String(message).slice(0, 300)]
);
await pool.query('DELETE FROM bot_sent_messages WHERE id = $1 AND attempts >= 5', [id]);
}
// ---------------------------------------------------------------------------
// WhatsApp session (Baileys auth state, encrypted in bot_wa_auth)
// ---------------------------------------------------------------------------
async function useSqlAuthState() {
const read = async (id) => {
const { rows } = await pool.query('SELECT data FROM bot_wa_auth WHERE id = $1', [id]);
return rows[0] ? JSON.parse(open(rows[0].data), BufferJSON.reviver) : null;
};
const write = (id, value) => pool.query(
'INSERT INTO bot_wa_auth (id, data) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data',
[id, seal(JSON.stringify(value, BufferJSON.replacer))]
);
const remove = (id) => pool.query('DELETE FROM bot_wa_auth WHERE id = $1', [id]);
const creds = (await read('creds')) || initAuthCreds();
const keys = {
get: async (type, ids) => {
const out = {};
await Promise.all(ids.map(async (id) => {
let value = await read(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.fromObject(value);
}
out[id] = value;
}));
return out;
},
set: async (data) => {
const jobs = [];
for (const category of Object.keys(data)) {
for (const id of Object.keys(data[category])) {
const value = data[category][id];
const name = `${category}-${id}`;
jobs.push(value ? write(name, value) : remove(name));
}
}
await Promise.all(jobs);
},
};
return {
state: { creds, keys },
saveCreds: () => write('creds', creds),
};
}
async function clearAuth() {
await pool.query('DELETE FROM bot_wa_auth');
}
module.exports = {
pool, init,
listFiles, findFile, addFile, deleteFile, recordSend,
touchUser, getUser, listUsers, updateUser, downloadsToday, recordDownload, stats,
setListed, listCatalog, getSettings, setSettings, DEFAULT_SETTINGS,
scheduleDeletes, dueDeletes, removeDelete, failDelete,
useSqlAuthState, clearAuth,
};