feat(S2-a): ingest durable app MQTT points securely

This commit is contained in:
Brent Perteet
2026-08-20 15:22:40 -05:00
parent daa3407b9d
commit 8bcc12ec96
14 changed files with 979 additions and 59 deletions

View File

@@ -1,4 +1,9 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { connect, MqttClient } from 'mqtt';
export type MqttMessageListener = (topic: string, payload: Buffer) => void;
@@ -12,19 +17,29 @@ export class MqttClientService implements OnModuleInit, OnModuleDestroy {
onModuleInit() {
const host = process.env.MQTT_HOST || 'mosquitto';
const port = Number(process.env.MQTT_PORT || 1883);
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
if (!username || !password) {
throw new Error(
'MQTT_USERNAME and MQTT_PASSWORD are required; refusing to use a default broker credential.',
);
}
this.client = connect(`mqtt://${host}:${port}`, {
username: process.env.MQTT_USERNAME || 'backend',
password: process.env.MQTT_PASSWORD || 'backendpass',
username,
password,
clientId: `ulhub-backend-${Math.random().toString(16).slice(2)}`,
});
this.client.on('connect', () => {
this.logger.log(`Connected to MQTT broker at ${host}:${port}`);
this.client!.subscribe('devices/#', (err) => {
// devices/# = legacy device-direct namespace; ul/# = SRS §3.4.2 topic scheme
// (app + device-direct). QoS 1 so the broker redelivers durable log records the
// backend missed while disconnected (broker loss ≠ capture loss, SRS-SYN-1/7).
this.client!.subscribe(['devices/#', 'ul/#'], { qos: 1 }, (err) => {
if (err) {
this.logger.error('Failed to subscribe to devices/#', err);
this.logger.error('Failed to subscribe to devices/# + ul/#', err);
} else {
this.logger.log('Subscribed to devices/#');
this.logger.log('Subscribed to devices/# and ul/#');
}
});
});