Files
mercado.clube67.com/backend/plugins/newwhats/auth.js
T

43 lines
1.4 KiB
JavaScript

'use strict'
const { timingSafeEqual } = require('crypto')
const { queryOne } = require('../../database/postgres')
/**
* Middleware de autenticação das rotas /nw/*.
* Valida a integration_key enviada pelo motor NewWhats em cada requisição.
* Aceita via header: x-nw-key ou Authorization: Bearer <key>
*/
async function nwAuth(req, res, next) {
const key = req.headers['x-nw-key']
|| (req.headers['authorization'] || '').replace(/^Bearer\s+/i, '').trim()
if (!key) {
return res.status(401).json({ error: 'Chave de integração ausente. Use o header x-nw-key.' })
}
try {
const stored = await queryOne(
"SELECT value FROM plugin_configs WHERE plugin_id = 'newwhats' AND key = 'integration_key'"
)
if (!stored?.value) {
return res.status(503).json({ error: 'Plugin NewWhats não configurado. Defina a integration_key no admin.' })
}
const storedBuf = Buffer.from(stored.value)
const keyBuf = Buffer.from(key)
const valid = storedBuf.length === keyBuf.length && timingSafeEqual(storedBuf, keyBuf)
if (!valid) {
return res.status(403).json({ error: 'Chave de integração inválida.' })
}
next()
} catch (err) {
console.error('[nwAuth] Erro ao verificar integration_key:', err.message)
return res.status(500).json({ error: 'Erro interno ao validar autenticação.' })
}
}
module.exports = { nwAuth }