Recipe: a webhook relay
Mirror the announcements of one channel into another one, or into a channel of a second Mnema Talk server: an outgoing webhook sends the events, a 40-line Node server checks the signature and posts them through an incoming webhook. No bot account needed.
Set up
- In the source channel: Webhooks > Outgoing, URL
https://relay.example.org/mnema, eventMESSAGE_CREATE. Copy the signing secret (whsec_…, shown once). - In the target channel (same or another server): Webhooks > Incoming, name "Relay". Copy its URL (shown once).
- Run the relay with both secrets in its environment.
The code
import { createServer } from 'node:http'
import { createHmac, timingSafeEqual } from 'node:crypto'
const SECRET = process.env.SIGNING_SECRET // whsec_...
const TARGET = process.env.TARGET_WEBHOOK // https://chat.example.com/api/webhooks/<id>/<token>
const seen = new Set()
function verify(header, raw, toleranceSeconds = 300) {
const { t, v1 } = Object.fromEntries((header ?? '').split(',').map((p) => p.split('=')))
if (!t || !v1 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false
const expected = createHmac('sha256', SECRET).update(`${t}.`).update(raw).digest('hex')
return expected.length === v1.length && timingSafeEqual(Buffer.from(expected), Buffer.from(v1))
}
createServer((req, res) => {
const chunks = []
req.on('data', (c) => chunks.push(c))
req.on('end', async () => {
const raw = Buffer.concat(chunks)
if (!verify(req.headers['x-mnema-signature'], raw)) return res.writeHead(401).end()
res.writeHead(204).end() // answer within 10 seconds, then work
const event = JSON.parse(raw.toString('utf8'))
if (event.t !== 'MESSAGE_CREATE' || seen.has(event.id)) return
seen.add(event.id)
await fetch(TARGET, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: event.d.content, allowed_mentions: { parse: [] } }),
})
})
}).listen(8787)
Notes
- Verify over the raw body, before parsing, and refuse old timestamps.
- Deliveries are at least once: deduplicate on the event
id(the same value as theX-Mnema-Deliveryheader), asseendoes. allowed_mentions: { parse: [] }relays the text without notifying anyone in the target channel.- Messages posted by an incoming webhook are never sent to outgoing webhooks, so two relays cannot feed each other in a loop.
- The server only sends to public addresses. A relay inside your own network needs the operator to list it in
WEBHOOK_ALLOW_PRIVATE_TARGETS.