MQTT clients: shared open role, stored/revealable passwords, reset + open-access
New clients join a shared 'open' role (pub/sub on #, $CONTROL stays protected) instead of per-client topic-scoped roles. All passwords are now stored encrypted with admin reveal + reset endpoints so one login can be reused across device batches. Username is the name slug (no random suffix). Legacy scoped clients can be moved onto the open role. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
704c1aa7fa
commit
e74308f5e2
3 changed files with 115 additions and 56 deletions
|
|
@ -1,8 +1,10 @@
|
|||
import crypto from 'crypto'
|
||||
import { pool } from '../db.js'
|
||||
import { requireAdmin } from '../auth.js'
|
||||
import { encrypt, decrypt } from '../crypto.js'
|
||||
import { createDynsecClient, addTopicsToRole, deleteDynsecClient, slugify, randomPassword } from '../lib/mqtt-dynsec.js'
|
||||
import {
|
||||
createDynsecClient, addTopicsToRole, deleteDynsecClient, setClientPassword, grantOpenAccess,
|
||||
slugify, randomPassword, OPEN_ROLE,
|
||||
} from '../lib/mqtt-dynsec.js'
|
||||
|
||||
const TOPIC_CHAR_RE = /^[a-zA-Z0-9/_+#-]+$/
|
||||
const MQTT_BROKER_HOST = process.env.MQTT_BROKER_HOST || '10.10.10.104'
|
||||
|
|
@ -59,26 +61,19 @@ export async function mqttClientRoutes(app) {
|
|||
}
|
||||
})
|
||||
|
||||
// POST /settings/api/mqtt-clients — creates the broker identity, returns the
|
||||
// password once. It is never persisted anywhere after this response.
|
||||
// POST /settings/api/mqtt-clients — creates the broker identity on the shared
|
||||
// open role (full pub/sub, no per-client topic scope). The password is stored
|
||||
// encrypted so an admin can reveal it later and reuse it on a batch of devices.
|
||||
app.post('/mqtt-clients', { preHandler: requireAdmin }, async (req, reply) => {
|
||||
const { name, topic_scope, can_publish, can_subscribe, is_service } = req.body || {}
|
||||
const { name, is_service } = req.body || {}
|
||||
if (!name || typeof name !== 'string' || !name.trim()) {
|
||||
return reply.status(400).send({ error: 'Name is required' })
|
||||
}
|
||||
const { topics, error: topicError } = parseTopics(topic_scope)
|
||||
if (topicError) return reply.status(400).send({ error: topicError })
|
||||
if (!can_publish && !can_subscribe) {
|
||||
return reply.status(400).send({ error: 'At least one of publish or subscribe must be enabled' })
|
||||
}
|
||||
|
||||
// Service clients get a STABLE username = the name's slug (no random suffix),
|
||||
// so the consuming app can look its credential up by a known id (e.g. an app
|
||||
// named "hvac-backend" is reachable at /internal/mqtt-client/hvac-backend).
|
||||
// Device clients keep the random suffix to avoid collisions.
|
||||
const svc = !!is_service
|
||||
const username = svc ? slugify(name) : `${slugify(name)}-${crypto.randomBytes(2).toString('hex')}`
|
||||
const rolename = `${username}-role`
|
||||
// Username is the name's slug — stable and memorable, so a service app can
|
||||
// look its credential up by a known id (e.g. "hvac-backend") and a device
|
||||
// batch ("tasmota-lights") shares one login.
|
||||
const username = slugify(name)
|
||||
const password = randomPassword()
|
||||
|
||||
const { rows: [dup] } = await pool.query('SELECT id FROM mqtt_clients WHERE username = $1', [username])
|
||||
|
|
@ -87,31 +82,76 @@ export async function mqttClientRoutes(app) {
|
|||
}
|
||||
|
||||
try {
|
||||
await createDynsecClient({
|
||||
username, password, rolename, topics,
|
||||
canPublish: !!can_publish, canSubscribe: !!can_subscribe,
|
||||
})
|
||||
await createDynsecClient({ username, password })
|
||||
} catch (e) {
|
||||
// Best-effort cleanup of whatever partially got created before the failure.
|
||||
deleteDynsecClient(username, rolename).catch(() => {})
|
||||
deleteDynsecClient(username, OPEN_ROLE).catch(() => {})
|
||||
return reply.status(502).send({ error: `Broker error: ${e.message}` })
|
||||
}
|
||||
|
||||
const { rows: [row] } = await pool.query(
|
||||
`INSERT INTO mqtt_clients (name, username, rolename, topic_scope, can_publish, can_subscribe, is_service, secret_enc)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING ${CLIENT_COLS}`,
|
||||
[name.trim(), username, rolename, topics.join('\n'), !!can_publish, !!can_subscribe, svc, svc ? encrypt(password) : null]
|
||||
VALUES ($1, $2, $3, '#', true, true, $4, $5) RETURNING ${CLIENT_COLS}`,
|
||||
[name.trim(), username, OPEN_ROLE, !!is_service, encrypt(password)]
|
||||
)
|
||||
return { ...row, password }
|
||||
})
|
||||
|
||||
// PATCH /settings/api/mqtt-clients/:id — add more topic scopes to an existing
|
||||
// client's role, e.g. when a service client's needs grow. Additive only — this
|
||||
// GET /settings/api/mqtt-clients/:id/password — admin reveal. Legacy clients
|
||||
// created before passwords were stored have none; they need a reset.
|
||||
app.get('/mqtt-clients/:id/password', { preHandler: requireAdmin }, async (req, reply) => {
|
||||
const { rows: [row] } = await pool.query('SELECT active, secret_enc FROM mqtt_clients WHERE id = $1', [req.params.id])
|
||||
if (!row) return reply.status(404).send({ error: 'Not found' })
|
||||
if (!row.active) return reply.status(400).send({ error: 'Client is revoked' })
|
||||
if (!row.secret_enc) return reply.status(404).send({ error: 'No stored password for this client — reset it to set a new one' })
|
||||
return { password: decrypt(row.secret_enc) }
|
||||
})
|
||||
|
||||
// POST /settings/api/mqtt-clients/:id/password — generate a new password,
|
||||
// apply it on the broker and store it. Anything using the old one must be
|
||||
// updated with the new value.
|
||||
app.post('/mqtt-clients/:id/password', { preHandler: requireAdmin }, async (req, reply) => {
|
||||
const { rows: [row] } = await pool.query('SELECT username, active FROM mqtt_clients WHERE id = $1', [req.params.id])
|
||||
if (!row) return reply.status(404).send({ error: 'Not found' })
|
||||
if (!row.active) return reply.status(400).send({ error: 'Client is revoked' })
|
||||
const password = randomPassword()
|
||||
try {
|
||||
await setClientPassword(row.username, password)
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `Broker error: ${e.message}` })
|
||||
}
|
||||
await pool.query('UPDATE mqtt_clients SET secret_enc = $1 WHERE id = $2', [encrypt(password), req.params.id])
|
||||
return { password }
|
||||
})
|
||||
|
||||
// POST /settings/api/mqtt-clients/:id/open-access — move a legacy
|
||||
// topic-scoped client onto the shared open role.
|
||||
app.post('/mqtt-clients/:id/open-access', { preHandler: requireAdmin }, async (req, reply) => {
|
||||
const { rows: [row] } = await pool.query(`SELECT ${CLIENT_COLS} FROM mqtt_clients WHERE id = $1`, [req.params.id])
|
||||
if (!row) return reply.status(404).send({ error: 'Not found' })
|
||||
if (!row.active) return reply.status(400).send({ error: 'Client is revoked' })
|
||||
if (row.rolename === OPEN_ROLE) return row
|
||||
try {
|
||||
await grantOpenAccess(row.username, row.rolename)
|
||||
} catch (e) {
|
||||
return reply.status(502).send({ error: `Broker error: ${e.message}` })
|
||||
}
|
||||
const { rows: [updated] } = await pool.query(
|
||||
`UPDATE mqtt_clients SET rolename = $1, topic_scope = '#', can_publish = true, can_subscribe = true
|
||||
WHERE id = $2 RETURNING ${CLIENT_COLS}`,
|
||||
[OPEN_ROLE, req.params.id]
|
||||
)
|
||||
return updated
|
||||
})
|
||||
|
||||
// PATCH /settings/api/mqtt-clients/:id — add more topic scopes to a legacy
|
||||
// topic-scoped client's role, e.g. when a service client's needs grow. Additive only — this
|
||||
// never removes an existing grant (revoke/delete the whole client for that).
|
||||
app.patch('/mqtt-clients/:id', { preHandler: requireAdmin }, async (req, reply) => {
|
||||
const { rows: [row] } = await pool.query(`SELECT ${CLIENT_COLS} FROM mqtt_clients WHERE id = $1`, [req.params.id])
|
||||
if (!row) return reply.status(404).send({ error: 'Not found' })
|
||||
if (!row.active) return reply.status(400).send({ error: 'Client is revoked' })
|
||||
if (row.rolename === OPEN_ROLE) return reply.status(400).send({ error: 'Client already has access to all topics' })
|
||||
|
||||
const { topics: newTopics, error: topicError } = parseTopics(req.body?.add_topic_scope)
|
||||
if (topicError) return reply.status(400).send({ error: topicError })
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue