|
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +// Copyright (c) 2025-2026 Ravi Singh (Techposts) |
| 3 | + |
| 4 | +import { randomBytes } from 'crypto'; |
| 5 | +import { execSync } from 'child_process'; |
| 6 | +import { readFileSync, writeFileSync } from 'fs'; |
| 7 | +import db from './db.js'; |
| 8 | + |
| 9 | +const PASSWD_FILE = '/etc/mosquitto/tanksync_passwd'; |
| 10 | +const ACL_FILE = '/etc/mosquitto/tanksync_acl.conf'; |
| 11 | +const MQTT_PUBLIC_HOST = process.env.MQTT_PUBLIC_HOST || 'mqtt.smartghar.org'; |
| 12 | +const MQTT_PUBLIC_PORT = parseInt(process.env.MQTT_PUBLIC_PORT || '8883'); |
| 13 | + |
| 14 | +/** |
| 15 | + * Generate MQTT credentials for a user+site, add to Mosquitto, push to receiver. |
| 16 | + * Returns { mqtt_username, mqtt_password, mqtt_host, mqtt_port } |
| 17 | + */ |
| 18 | +export async function generateMqttCredentials(userId, siteId, deviceId) { |
| 19 | + // Check if credentials already exist for this site |
| 20 | + const existing = await db.get( |
| 21 | + 'SELECT * FROM mqtt_credentials WHERE site_id = $1', siteId |
| 22 | + ); |
| 23 | + if (existing) { |
| 24 | + return { |
| 25 | + mqtt_username: existing.mqtt_username, |
| 26 | + mqtt_password: existing.mqtt_password, |
| 27 | + mqtt_host: MQTT_PUBLIC_HOST, |
| 28 | + mqtt_port: MQTT_PUBLIC_PORT, |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + // Generate unique username and password |
| 33 | + const shortId = deviceId.slice(0, 6); |
| 34 | + const mqtt_username = `ts_u${userId}_${shortId}`; |
| 35 | + const mqtt_password = randomBytes(16).toString('base64url'); |
| 36 | + |
| 37 | + // Add to Mosquitto password file |
| 38 | + try { |
| 39 | + execSync(`sudo mosquitto_passwd -b ${PASSWD_FILE} "${mqtt_username}" "${mqtt_password}"`, { timeout: 5000 }); |
| 40 | + } catch (err) { |
| 41 | + console.error(`[MQTT-CRED] Failed to add password: ${err.message}`); |
| 42 | + throw new Error('Failed to create MQTT credentials'); |
| 43 | + } |
| 44 | + |
| 45 | + // Store in database |
| 46 | + await db.run( |
| 47 | + 'INSERT INTO mqtt_credentials (user_id, site_id, mqtt_username, mqtt_password, device_id) VALUES ($1, $2, $3, $4, $5)', |
| 48 | + userId, siteId, mqtt_username, mqtt_password, deviceId |
| 49 | + ); |
| 50 | + |
| 51 | + // Regenerate ACL file |
| 52 | + await regenerateAcl(); |
| 53 | + |
| 54 | + // Reload Mosquitto config |
| 55 | + try { |
| 56 | + execSync('sudo kill -HUP $(pidof mosquitto)', { timeout: 5000 }); |
| 57 | + } catch { |
| 58 | + console.warn('[MQTT-CRED] Could not reload Mosquitto — may need manual restart'); |
| 59 | + } |
| 60 | + |
| 61 | + return { mqtt_username, mqtt_password, mqtt_host: MQTT_PUBLIC_HOST, mqtt_port: MQTT_PUBLIC_PORT }; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Push MQTT config to receiver via its local HTTP API. |
| 66 | + */ |
| 67 | +export async function pushMqttToReceiver(receiverIp, mqttCreds) { |
| 68 | + try { |
| 69 | + const res = await fetch(`http://${receiverIp}/api/mqtt`, { |
| 70 | + method: 'POST', |
| 71 | + headers: { 'Content-Type': 'application/json' }, |
| 72 | + body: JSON.stringify({ |
| 73 | + host: mqttCreds.mqtt_host, |
| 74 | + port: mqttCreds.mqtt_port, |
| 75 | + user: mqttCreds.mqtt_username, |
| 76 | + pass: mqttCreds.mqtt_password, |
| 77 | + enabled: true, |
| 78 | + ha_discovery: false, |
| 79 | + use_tls: true, |
| 80 | + }), |
| 81 | + signal: AbortSignal.timeout(5000), |
| 82 | + }); |
| 83 | + return res.ok; |
| 84 | + } catch (err) { |
| 85 | + console.warn(`[MQTT-CRED] Could not push to receiver ${receiverIp}: ${err.message}`); |
| 86 | + return false; |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +/** |
| 91 | + * Revoke MQTT credentials for a site (called when site is deleted). |
| 92 | + */ |
| 93 | +export async function revokeMqttCredentials(siteId) { |
| 94 | + const cred = await db.get('SELECT * FROM mqtt_credentials WHERE site_id = $1', siteId); |
| 95 | + if (!cred) return; |
| 96 | + |
| 97 | + // Remove from Mosquitto password file |
| 98 | + try { |
| 99 | + execSync(`sudo mosquitto_passwd -D ${PASSWD_FILE} "${cred.mqtt_username}"`, { timeout: 5000 }); |
| 100 | + } catch {} |
| 101 | + |
| 102 | + // Remove from DB |
| 103 | + await db.run('DELETE FROM mqtt_credentials WHERE site_id = $1', siteId); |
| 104 | + |
| 105 | + // Regenerate ACL and reload |
| 106 | + await regenerateAcl(); |
| 107 | + try { execSync('sudo kill -HUP $(pidof mosquitto)', { timeout: 5000 }); } catch {} |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * Regenerate the ACL file from all credentials in the database. |
| 112 | + */ |
| 113 | +async function regenerateAcl() { |
| 114 | + const allCreds = await db.all('SELECT * FROM mqtt_credentials'); |
| 115 | + |
| 116 | + let acl = `# TankSync MQTT ACL — auto-generated, do not edit manually |
| 117 | +# Server account — full access |
| 118 | +user tanksync_server |
| 119 | +topic readwrite tanksync/# |
| 120 | +
|
| 121 | +`; |
| 122 | + |
| 123 | + for (const cred of allCreds) { |
| 124 | + acl += `# User ${cred.user_id}, Site ${cred.site_id}\n`; |
| 125 | + acl += `user ${cred.mqtt_username}\n`; |
| 126 | + acl += `topic readwrite tanksync/${cred.device_id}/#\n\n`; |
| 127 | + } |
| 128 | + |
| 129 | + writeFileSync(ACL_FILE, acl); |
| 130 | +} |
0 commit comments