// Middleware de auth das rotas /nw/* — valida a integration_key enviada pelo // motor NewWhats. Aceita header x-nw-key ou Authorization: Bearer . import { timingSafeEqual } from 'crypto' import { getConfig } from './config.js' export 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.' }) } const stored = getConfig().integrationKey if (!stored) { return res.status(503).json({ error: 'Integração NewWhats não configurada (NEWWHATS_INTEGRATION_KEY).' }) } const a = Buffer.from(stored) const b = Buffer.from(key) if (a.length !== b.length || !timingSafeEqual(a, b)) { return res.status(403).json({ error: 'Chave de integração inválida.' }) } next() }