Add modern hubot 14 XMPP adapter on @xmpp/client

Port the old node-xmpp-client based adapter (xmppjs/hubot-xmpp 0.3.0) to
hubot 14 (ESM) using @xmpp/client 0.14:

- default `{ use }` entrypoint matching hubot 14's adapter loader
- MUC join/leave, groupchat and private chat handling, presence tracking
  (enter/leave, role, private JID mapping)
- keepalive pings; reconnection via @xmpp/client's built-in reconnect
- XHTML payload support via the @xmpp/xml parser
- node:test suite (45 tests)

Drops legacy options no longer applicable to @xmpp/client:
HUBOT_XMPP_LEGACYSSL, _PREFERRED_SASL_MECHANISM, _DISALLOW_TLS,
_RECONNECT_TRY, _RECONNECT_WAIT and HUBOT_XMPP_UUID_ON_JOIN.
This commit is contained in:
raucao committed 2026-10-27 17:40:17 +04:00
commit 1ac2ef3667
9 files changed
+2912

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
+39
View File
@@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage
coverage
*.lcov
.nyc_output
# Dependency directories
node_modules/
jspm_packages/
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# dotenv environment variable files
.env
.env.local
.env.*.local
# OS files
.DS_Store
Thumbs.db
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Kosmos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+81
View File
@@ -0,0 +1,81 @@
# Hubot XMPP
Connects [Hubot](https://hubot.github.com/) to your XMPP network (including MUC
group chats), built on [`@xmpp/client`](https://github.com/xmppjs/xmpp.js).
Requires **Hubot >= 14** and **Node >= 22.11** (ESM).
## Setup
```sh
npm install
```
## Configuration
The adapter requires these environment variables:
* `HUBOT_XMPP_USERNAME` – the bot's JID, optionally including a resource
(e.g. `hal8000@kosmos.org/hubot`).
* `HUBOT_XMPP_PASSWORD` – the bot account's password.
* `HUBOT_XMPP_ROOMS` – comma separated list of rooms to join. Rooms requiring a
password use the `jid:password` syntax. Room passwords cannot contain `,`.
Room names must be the full jid, e.g. `dev@conference.jabber.example.org`.
Optional:
* `HUBOT_XMPP_HOST` – the host name to connect to if it differs from the domain
in the username JID.
* `HUBOT_XMPP_PORT` – the port to connect to (default `5222`).
* `HUBOT_XMPP_PM_ADD_PREFIX` – make commands work in private messages to the bot
without the robot name/alias prefix.
* `HUBOT_XMPP_KEEPALIVE_INTERVAL` – keep-alive (XMPP ping) interval in ms
(default `30000`).
Reconnection is handled by `@xmpp/client`'s built-in reconnect support.
## Installation
Create a standalone hubot with the XMPP adapter:
```sh
mkdir -p ./my-bot
cd ./my-bot
npx -p yo -p generator-hubot -c 'yo hubot --adapter=xmpp'
```
See also https://hubot.github.com/docs/ .
## Group chat vs private JID
The XMPP protocol does not broadcast a real user JID in group chat presence
stanzas unless the server/room is configured to do so.
If you need to send a private chat in response to a group chat message, use
hubot's send method with the group chat jid and `envelope.user.type = 'direct'`.
hubot-xmpp will then automatically resolve the JID to a private chat JID and
private message the sender.
If you need to get the private chat JID, you can use
`msg.envelope.user.privateChatJID` where `msg` is the parameter of hubot's
`route` callback.
Example:
```js
robot.respond(/talk to me$/i, msg => {
// Simply reply
msg.reply(`Hello ${msg.envelope.user.name}. Your private JID is ${msg.envelope.user.privateChatJID}`);
});
robot.respond(/talk to me in private$/i, msg => {
msg.envelope.user.type = 'direct';
msg.send(`Hey ${msg.envelope.user.name}! You told me in room ${msg.envelope.user.room} to talk to you.`);
});
```
## Tests
```sh
npm test
```
+18
View File
@@ -0,0 +1,18 @@
import { XmppAdapter } from './src/XmppAdapter.mjs'
export default {
use(robot) {
robot.config = {
username: process.env.HUBOT_XMPP_USERNAME,
password: process.env.HUBOT_XMPP_PASSWORD,
rooms: process.env.HUBOT_XMPP_ROOMS?.split(','),
host: process.env.HUBOT_XMPP_HOST,
port: process.env.HUBOT_XMPP_PORT,
pmAddPrefix: process.env.HUBOT_XMPP_PM_ADD_PREFIX != null,
keepaliveInterval: Number(process.env.HUBOT_XMPP_KEEPALIVE_INTERVAL) || undefined
}
return new XmppAdapter(robot)
}
}
export { XmppAdapter }
+1544
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "hubot-xmpp",
"version": "1.0.0",
"description": "XMPP adapter for Hubot, built on @xmpp/client",
"main": "index.mjs",
"type": "module",
"scripts": {
"test": "node --test"
},
"repository": {
"type": "git",
"url": "git+https://gitea.kosmos.org/kosmos/hubot-xmpp.git"
},
"keywords": [
"hubot",
"xmpp",
"adapter",
"muc"
],
"author": "Kosmos",
"license": "MIT",
"bugs": {
"url": "https://gitea.kosmos.org/kosmos/hubot-xmpp/issues"
},
"homepage": "https://gitea.kosmos.org/kosmos/hubot-xmpp#readme",
"engines": {
"node": ">= 22.11"
},
"dependencies": {
"@xmpp/client": "^0.14.0"
},
"peerDependencies": {
"hubot": ">= 14"
},
"devDependencies": {
"hubot": "14.1.0"
}
}
+508
View File
@@ -0,0 +1,508 @@
import { Adapter, TextMessage, EnterMessage, LeaveMessage } from 'hubot'
import { client, xml, jid } from '@xmpp/client'
const NS_MUC = 'http://jabber.org/protocol/muc'
const NS_MUC_USER = 'http://jabber.org/protocol/muc#user'
const NS_NICK = 'http://jabber.org/protocol/nick'
const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items'
const NS_XHTML_IM = 'http://jabber.org/protocol/xhtml-im'
const NS_XHTML = 'http://www.w3.org/1999/xhtml'
const NS_PING = 'urn:xmpp:ping'
const DEFAULT_PORT = 5222
const DEFAULT_KEEPALIVE_INTERVAL = 30000
// Parse a string into an Element when it is a valid single-root XML fragment,
// otherwise return null. Used to detect XHTML payloads in send().
//
// @xmpp/xml's stream Parser does not attach the root element's direct children
// (the root represents the stream), so the fragment is wrapped two levels deep
// and the inner wrapper's children are inspected instead.
function parseXmlFragment(string) {
if (typeof string !== 'string') return null
const parser = new xml.Parser()
let inner = null
let failed = false
parser.on('element', (element) => {
if (!inner) inner = element
})
parser.on('error', () => {
failed = true
})
try {
parser.write(`<fragment><inner>${string}</inner></fragment>`)
parser.end()
} catch {
return null
}
if (failed || !inner) return null
const elements = inner.children.filter((child) => typeof child !== 'string')
if (elements.length !== 1) return null
return elements[0]
}
class XmppAdapter extends Adapter {
constructor(robot) {
super(robot)
this.client = null
// Flag to log a warning message about group chat configuration only once
this.anonymousGroupChatWarningLogged = false
// Store the room JID to private JID map.
// Key is the room JID, value is the private JID
this.roomToPrivateJID = {}
this.connected = false
this.everConnected = false
this.heardOwnPresence = false
this.currentIqId = 1001
this.keepaliveTimer = null
this.config = this.robot?.config ?? {}
this.options = {
username: this.config.username,
pmAddPrefix: this.config.pmAddPrefix,
keepaliveInterval: this.config.keepaliveInterval ?? DEFAULT_KEEPALIVE_INTERVAL,
rooms: this.parseRooms(this.config.rooms ?? [])
}
this.onError = this.onError.bind(this)
this.online = this.online.bind(this)
this.offline = this.offline.bind(this)
this.read = this.read.bind(this)
this.ping = this.ping.bind(this)
}
checkCanStart() {
if (!this.config.username) {
throw new Error("HUBOT_XMPP_USERNAME is not defined; try: export HUBOT_XMPP_USERNAME='user@xmpp.service'")
} else if (!this.config.password) {
throw new Error("HUBOT_XMPP_PASSWORD is not defined; try: export HUBOT_XMPP_PASSWORD='password'")
} else if (!this.config.rooms || this.config.rooms.length === 0) {
throw new Error("HUBOT_XMPP_ROOMS is not defined: try: export HUBOT_XMPP_ROOMS='room@conference.xmpp.service'")
}
}
async run() {
this.checkCanStart()
this.client = this.makeClient()
this.configClient()
try {
await this.client.start()
} catch (error) {
this.robot.logger.error(`Unable to connect to XMPP server: ${error}`)
throw error
}
}
makeClient() {
const address = jid(this.config.username)
const host = this.config.host || address.domain
const port = this.config.port || DEFAULT_PORT
const options = {
service: `xmpp://${host}:${port}`,
domain: address.domain,
username: address.local,
password: this.config.password,
resource: address.resource || this.robot.name
}
this.robot.logger.info(`Connecting to XMPP service ${options.service} as ${this.config.username}`)
return client(options)
}
configClient() {
this.client.on('error', this.onError)
this.client.on('offline', this.offline)
this.client.on('online', this.online)
this.client.on('stanza', this.read)
this.client.on('disconnect', () => {
this.connected = false
this.robot.logger.info('Disconnected from XMPP server, will attempt to reconnect')
})
if (this.keepaliveTimer) clearInterval(this.keepaliveTimer)
this.keepaliveTimer = setInterval(this.ping, this.options.keepaliveInterval)
this.keepaliveTimer.unref?.()
}
onError(error) {
this.robot.logger.error(`Received error ${error.toString()}`)
}
online() {
this.robot.logger.info('Hubot XMPP client online')
const presence = xml('presence', {}, xml('nick', { xmlns: NS_NICK }, this.robot.name))
this.client.send(presence)
this.robot.logger.info('Hubot XMPP sent initial presence')
for (const room of this.options.rooms) this.joinRoom(room)
this.emit(this.everConnected ? 'reconnected' : 'connected')
this.connected = true
this.everConnected = true
}
offline() {
this.connected = false
this.robot.logger.debug('Received offline event')
}
ping() {
if (!this.connected || !this.client) return
const id = this.currentIqId++
this.robot.logger.debug(`[sending ping] ${id}`)
return this.client.send(xml('iq', { type: 'get', id }, xml('ping', { xmlns: NS_PING })))
}
parseRooms(items) {
const rooms = []
for (const room of items) {
const index = room.indexOf(':')
rooms.push({
jid: room.slice(0, index > 0 ? index : room.length),
password: index > 0 ? room.slice(index + 1) : false
})
}
return rooms
}
// XMPP Joining a room - http://xmpp.org/extensions/xep-0045.html#enter-muc
joinRoom(room) {
this.robot.logger.debug(`Joining ${room.jid}/${this.robot.name}`)
// prevent the server from confusing us with old messages
// and it seems that servers don't reliably support maxchars
// or zero values
const x = xml('x', { xmlns: NS_MUC },
xml('history', { seconds: 1 }),
room.password ? xml('password', {}, room.password) : null)
return this.client.send(xml('presence', { to: `${room.jid}/${this.robot.name}` }, x))
}
// XMPP Leaving a room - http://xmpp.org/extensions/xep-0045.html#exit
leaveRoom(room) {
// messageFromRoom check for joined rooms so remove it from the list
const index = this.options.rooms.findIndex((joined) => joined.jid === room.jid)
if (index > -1) this.options.rooms.splice(index, 1)
this.robot.logger.debug(`Leaving ${room.jid}/${this.robot.name}`)
return this.client.send(xml('presence', {
to: `${room.jid}/${this.robot.name}`,
type: 'unavailable'
}))
}
// Send a query for users in the room and apply the callback against the
// retrieved data. callback should be of the form `(usersInRoom) => ...`
// where usersInRoom is an array of username strings.
async getUsersInRoom(room, callback) {
// http://xmpp.org/extensions/xep-0045.html#disco-roomitems
this.robot.logger.debug(`Fetching users in the room ${room.jid}`)
let usersInRoom = []
try {
const query = await this.client.iqCaller.get(xml('query', { xmlns: NS_DISCO_ITEMS }), room.jid)
// Note that this contains usernames and NOT the full user JID.
usersInRoom = query.getChildren('item').map((item) => item.attrs.name)
} catch (error) {
this.robot.logger.error(`Unable to fetch users in room ${room.jid}: ${error}`)
}
this.robot.logger.debug(`[users in room] ${room.jid} has ${usersInRoom}`)
if (typeof callback === 'function') callback(usersInRoom)
return usersInRoom
}
// XMPP invite to a room, directly - http://xmpp.org/extensions/xep-0249.html
sendInvite(room, invitee, reason) {
this.robot.logger.debug(`Inviting ${invitee} to ${room.jid}`)
return this.client.send(xml('message', { to: invitee },
xml('x', { xmlns: 'jabber:x:conference', jid: room.jid, reason })))
}
read(stanza) {
if (stanza.attrs.type === 'error') {
this.robot.logger.error(`[xmpp error] ${stanza}`)
return
}
switch (stanza.name) {
case 'message':
return this.readMessage(stanza)
case 'presence':
return this.readPresence(stanza)
}
}
readMessage(stanza) {
// ignore non-messages
let privateChatJID, room, user
if (!['groupchat', 'direct', 'chat'].includes(stanza.attrs.type)) { return }
if (stanza.attrs.from === undefined) { return }
// ignore empty bodies (i.e., topic changes -- maybe watch these someday)
const body = stanza.getChild('body')
if (!body) { return }
const from = stanza.attrs.from
let message = body.getText()
if (stanza.attrs.type === 'groupchat') {
// Everything before the / is the room name in groupchat JID
;[room, user] = from.split('/')
// ignore our own messages in rooms or messaged without user part
if ((user === undefined) || (user === '') || (user === this.robot.name)) { return }
// Convert the room JID to private JID if we have one
privateChatJID = this.roomToPrivateJID[from]
} else {
// Not sure how to get the user's alias. Use the username.
// The resource is not the user's alias but the unique client
// ID which is often the machine name
;[user] = from.split('@')
// Not from a room
room = undefined
// Also store the private JID so we can use it in the send method
privateChatJID = from
// For private messages, make the commands work even when they are not
// prefixed with hubot name or alias
if (this.options.pmAddPrefix && !this.startsWithNameOrAlias(message)) {
message = `${this.robot.name} ${message}`
}
}
// note that 'user' isn't a full JID in case of group chat,
// just the local user part
user = this.robot.brain.userForId(user)
user.type = stanza.attrs.type
user.room = room
if (privateChatJID) { user.privateChatJID = privateChatJID }
this.robot.logger.debug(`Received message: ${message} in room: ${user.room}, from: ${user.name}. Private chat JID is ${user.privateChatJID}`)
return this.receive(new TextMessage(user, message))
}
startsWithNameOrAlias(message) {
const lower = message.toLowerCase()
const name = this.robot.name.toLowerCase()
const alias = process.env.HUBOT_ALIAS?.toLowerCase()
if (lower.slice(0, name.length) === name) return true
if (alias && lower.slice(0, alias.length) === alias) return true
return false
}
readPresence(stanza) {
const fromJID = jid(stanza.attrs.from)
// xmpp doesn't add types for standard available mesages
// note that upon joining a room, server will send available
// presences for all members
// http://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.1
if (stanza.attrs.type == null) { stanza.attrs.type = 'available' }
switch (stanza.attrs.type) {
case 'subscribe':
this.robot.logger.debug(`${stanza.attrs.from} subscribed to me`)
return this.client.send(xml('presence', {
from: stanza.attrs.to,
to: stanza.attrs.from,
id: stanza.attrs.id,
type: 'subscribed'
}))
case 'probe':
this.robot.logger.debug(`${stanza.attrs.from} probed me`)
return this.client.send(xml('presence', {
from: stanza.attrs.to,
to: stanza.attrs.from,
id: stanza.attrs.id
}))
case 'available': {
// If the presence is from us, track that.
if ((fromJID.resource === this.robot.name) ||
(stanza.getChild('nick')?.getText() === this.robot.name)) {
this.heardOwnPresence = true
return
}
// ignore presence messages that sometimes get broadcast
// Group chat jid are of the form
// room_name@conference.hostname/Room specific id
const room = fromJID.bare().toString()
if (!this.messageFromRoom(room)) { return }
// Some servers send presence for the room itself, which needs to be
// ignored
if (room === fromJID.toString()) { return }
// Try to resolve the private JID
const privateChatJID = this.resolvePrivateJID(stanza)
// Try to resolve the user's role in the chat room
const userRole = this.resolveRole(stanza)
// Keep the room JID to private JID map in this class as there
// is an initialization race condition between the presence messages
// and the brain initial load.
// See https://github.com/github/hubot/issues/619
this.roomToPrivateJID[fromJID.toString()] = privateChatJID != null ? privateChatJID.toString() : undefined
this.robot.logger.debug(`Available received from ${fromJID.toString()} in room ${room} and private chat jid is ${privateChatJID?.toString()}`)
// Use the resource part from the room jid as this
// is most likely the user's name
const user = this.robot.brain.userForId(fromJID.resource, {
room,
jid: fromJID.toString(),
privateChatJID: privateChatJID != null ? privateChatJID.toString() : undefined,
role: userRole
})
// Xmpp sends presence for every person in a room, when join it
// Only after we've heard our own presence should we respond to
// presence messages.
if (this.heardOwnPresence) { return this.receive(new EnterMessage(user)) }
break
}
case 'unavailable': {
let [room, user] = stanza.attrs.from.split('/')
// ignore presence messages that sometimes get broadcast
if (!this.messageFromRoom(room)) { return }
// ignore our own messages in rooms
if (user === this.options.username) { return }
this.robot.logger.debug(`Unavailable received from ${user} in room ${room}`)
user = this.robot.brain.userForId(user, { room })
return this.receive(new LeaveMessage(user))
}
}
}
// Accept a stanza from a group chat
// return privateJID (a jid) or null when the
// http://jabber.org/protocol/muc#user extension was not provided
resolvePrivateJID(stanza) {
// room presence in group chat uses a jid which is not the real user jid
// To send private message to a user seen in a groupchat,
// you need to get the real jid. If the groupchat is configured to do so,
// the real jid is also sent as an extension
// http://xmpp.org/extensions/xep-0045.html#enter-nonanon
const privateJID = stanza.getChild('x', NS_MUC_USER)?.getChild('item')?.attrs?.jid
if (!privateJID) {
if (!this.anonymousGroupChatWarningLogged) {
this.robot.logger.warn('Could not get private JID from group chat. Make sure the server is configured to broadcast real jid for groupchat (see http://xmpp.org/extensions/xep-0045.html#enter-nonanon)')
this.anonymousGroupChatWarningLogged = true
}
return null
}
return jid(privateJID)
}
resolveRole(stanza) {
return stanza.getChild('x', NS_MUC_USER)?.getChild('item')?.attrs?.role
}
// Checks that the room parameter is a room the bot is in.
messageFromRoom(room) {
for (const joined of this.options.rooms) {
if (joined.jid.toUpperCase() === room.toUpperCase()) { return true }
}
return false
}
async send(envelope, ...messages) {
const results = []
for (const msg of messages) {
this.robot.logger.debug(`Sending to ${envelope.room}: ${msg}`)
let to = envelope.room
if (['direct', 'chat'].includes(envelope.user?.type)) {
to = envelope.user.privateChatJID != null ? envelope.user.privateChatJID : `${envelope.room}/${envelope.user.name}`
}
const type = envelope.user?.type || 'groupchat'
let message
if (msg instanceof xml.Element) {
message = msg.root()
if (message.attrs.to == null) { message.attrs.to = to }
if (message.attrs.type == null) { message.attrs.type = type }
} else {
const parsed = parseXmlFragment(msg)
message = xml('message', { to, type },
xml('body', {}, msg),
parsed
? xml('html', { xmlns: NS_XHTML_IM }, xml('body', { xmlns: NS_XHTML }, parsed))
: null)
}
results.push(this.client.send(message))
}
return Promise.all(results)
}
reply(envelope, ...messages) {
return Promise.all(messages.map((msg) =>
msg instanceof xml.Element
? this.send(envelope, msg)
: this.send(envelope, `${envelope.user.name}: ${msg}`)))
}
topic(envelope, ...strings) {
const subject = strings.join('\n')
return this.client.send(xml('message', {
to: envelope.room,
type: envelope.user?.type
}, xml('subject', {}, subject)))
}
async close() {
if (this.keepaliveTimer) {
clearInterval(this.keepaliveTimer)
this.keepaliveTimer = null
}
if (this.client) {
try {
await this.client.stop()
} catch (error) {
this.robot.logger.debug(`Error while stopping XMPP client: ${error}`)
}
}
super.close()
}
}
export { XmppAdapter }
export default XmppAdapter
+650
View File
@@ -0,0 +1,650 @@
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import { EventEmitter } from 'node:events'
import { xml } from '@xmpp/client'
import entry, { XmppAdapter } from '../index.mjs'
const NS_MUC = 'http://jabber.org/protocol/muc'
const NS_MUC_USER = 'http://jabber.org/protocol/muc#user'
const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items'
const NS_XHTML_IM = 'http://jabber.org/protocol/xhtml-im'
const NS_XHTML = 'http://www.w3.org/1999/xhtml'
const NS_PING = 'urn:xmpp:ping'
const baseConfig = {
username: 'bot@example.com/hubot',
password: 'secret',
rooms: ['test@example.com'],
host: 'example.com',
port: '5222',
pmAddPrefix: false,
keepaliveInterval: 30000
}
function createRobot({ config = {}, ...overrides } = {}) {
return {
name: 'bot',
receive() {},
logger: {
debug() {},
info() {},
warn() {},
error() {}
},
brain: {
userForId(id, options) {
const user = { name: id }
Object.assign(user, options || {})
return user
}
},
config: { ...baseConfig, ...config },
...overrides
}
}
class MockClient extends EventEmitter {
constructor() {
super()
this.sent = []
this.status = 'online'
this.iqCaller = {
get: async () => xml('query', { xmlns: NS_DISCO_ITEMS })
}
}
send(element) {
this.sent.push(element)
return Promise.resolve(element)
}
start() {
return Promise.resolve()
}
stop() {
return Promise.resolve()
}
}
function createAdapter(robotOverrides = {}) {
const adapter = new XmppAdapter(createRobot(robotOverrides))
adapter.client = new MockClient()
return adapter
}
describe('XmppAdapter', () => {
describe('#parseRooms()', () => {
it('splits passwords', () => {
const adapter = createAdapter({ config: { rooms: ['secretroom:password', 'room'] } })
const rooms = adapter.options.rooms
assert.equal(rooms.length, 2)
assert.equal(rooms[0].jid, 'secretroom')
assert.equal(rooms[0].password, 'password')
assert.equal(rooms[1].jid, 'room')
assert.equal(rooms[1].password, false)
})
})
describe('#joinRoom()', () => {
it('sends a presence stanza with a muc x element', () => {
const adapter = createAdapter()
const room = { jid: 'test@example.com', password: false }
adapter.joinRoom(room)
const presence = adapter.client.sent[0]
assert.equal(presence.name, 'presence')
assert.equal(presence.attrs.to, `${room.jid}/${adapter.robot.name}`)
assert.equal(presence.attrs.type, undefined)
const x = presence.getChild('x')
assert.equal(x.attrs.xmlns, NS_MUC)
assert.equal(x.getChild('history').attrs.seconds, '1')
assert.equal(x.getChild('password'), undefined)
})
it('includes the password for protected rooms', () => {
const adapter = createAdapter()
const room = { jid: 'test@example.com', password: 'password' }
adapter.joinRoom(room)
const x = adapter.client.sent[0].getChild('x')
assert.equal(x.getChild('password').getText(), 'password')
})
})
describe('#leaveRoom()', () => {
it('removes the room and sends an unavailable presence', () => {
const adapter = createAdapter()
const room = { jid: 'test@example.com', password: false }
adapter.leaveRoom(room)
assert.deepEqual(adapter.options.rooms, [])
const presence = adapter.client.sent[0]
assert.equal(presence.name, 'presence')
assert.equal(presence.attrs.to, `${room.jid}/${adapter.robot.name}`)
assert.equal(presence.attrs.type, 'unavailable')
})
})
describe('#ping()', () => {
it('sends a ping iq when connected', () => {
const adapter = createAdapter()
adapter.connected = true
adapter.ping()
const iq = adapter.client.sent[0]
assert.equal(iq.name, 'iq')
assert.equal(iq.attrs.type, 'get')
assert.equal(iq.getChild('ping').attrs.xmlns, NS_PING)
})
it('does nothing when not connected', () => {
const adapter = createAdapter()
adapter.connected = false
adapter.ping()
assert.equal(adapter.client.sent.length, 0)
})
})
describe('#getUsersInRoom()', () => {
it('returns the users reported by the disco query', async () => {
const adapter = createAdapter()
adapter.client.iqCaller.get = async () =>
xml('query', { xmlns: NS_DISCO_ITEMS },
xml('item', { name: 'mark' }),
xml('item', { name: 'anup' }))
const users = await adapter.getUsersInRoom({ jid: 'test@example.com' })
assert.deepEqual(users, ['mark', 'anup'])
})
it('invokes the callback with the users', async () => {
const adapter = createAdapter()
adapter.client.iqCaller.get = async () =>
xml('query', { xmlns: NS_DISCO_ITEMS }, xml('item', { name: 'mark' }))
let calledWith = null
await adapter.getUsersInRoom({ jid: 'test@example.com' }, (users) => { calledWith = users })
assert.deepEqual(calledWith, ['mark'])
})
})
describe('#sendInvite()', () => {
it('sends a direct conference invite', () => {
const adapter = createAdapter()
const room = { jid: 'test@example.com', password: false }
const invitee = 'anup@example.com'
const reason = 'Inviting to test'
adapter.sendInvite(room, invitee, reason)
const message = adapter.client.sent[0]
assert.equal(message.attrs.to, invitee)
const x = message.getChild('x')
assert.equal(x.attrs.jid, room.jid)
assert.equal(x.attrs.reason, reason)
})
})
describe('#read()', () => {
it('logs error stanzas', () => {
const adapter = createAdapter()
let logged = null
adapter.robot.logger.error = (message) => { logged = message }
adapter.read(xml('message', { type: 'error' }, xml('body', {}, 'fail')))
assert.match(String(logged), /xmpp error/)
})
it('delegates message stanzas to readMessage', () => {
const adapter = createAdapter()
let received = null
adapter.readMessage = (stanza) => { received = stanza }
const stanza = xml('message', { type: 'chat', from: 'test@example.com/ernie' }, xml('body', {}, 'hi'))
adapter.read(stanza)
assert.equal(received, stanza)
})
it('delegates presence stanzas to readPresence', () => {
const adapter = createAdapter()
let received = null
adapter.readPresence = (stanza) => { received = stanza }
const stanza = xml('presence', { type: 'available', from: 'test@example.com/mark' })
adapter.read(stanza)
assert.equal(received, stanza)
})
})
describe('#readMessage()', () => {
function messageStanza({ type = 'chat', from = 'test@example.com/ernie', body = 'message text' } = {}) {
return xml('message', { type, from }, body != null ? xml('body', {}, body) : null)
}
let adapter, received
beforeEach(() => {
adapter = createAdapter()
received = null
adapter.receive = (message) => { received = message }
})
it('refuses unsupported types', () => {
assert.equal(adapter.readMessage(messageStanza({ type: 'other' })), undefined)
assert.equal(received, null)
})
it('ignores messages from self in a groupchat', () => {
adapter.readMessage(messageStanza({ type: 'groupchat', from: 'room@example.com/bot' }))
assert.equal(received, null)
})
it('ignores groupchat messages without a user part', () => {
adapter.readMessage(messageStanza({ type: 'groupchat', from: 'test@example.com' }))
assert.equal(received, null)
})
it('ignores messages with no body', () => {
adapter.readMessage(messageStanza({ body: null }))
assert.equal(received, null)
})
it('dispatches a private message', () => {
adapter.readMessage(messageStanza())
assert.equal(received.user.type, 'chat')
assert.equal(received.user.name, 'test')
assert.equal(received.user.privateChatJID, 'test@example.com/ernie')
assert.equal(received.user.room, undefined)
assert.equal(received.text, 'message text')
})
it('adds the bot name prefix to private messages when pmAddPrefix is set', () => {
adapter.options.pmAddPrefix = true
adapter.readMessage(messageStanza())
assert.equal(received.text, 'bot message text')
})
it('does not add the prefix when the message already starts with the bot name', () => {
adapter.options.pmAddPrefix = true
adapter.readMessage(messageStanza({ body: 'bot message text' }))
assert.equal(received.text, 'bot message text')
})
it('does not add the prefix when the message starts with the alias', () => {
process.env.HUBOT_ALIAS = ':'
adapter.options.pmAddPrefix = true
adapter.readMessage(messageStanza({ body: ':message text' }))
delete process.env.HUBOT_ALIAS
assert.equal(received.text, ':message text')
})
it('dispatches a groupchat message', () => {
adapter.readMessage(messageStanza({ type: 'groupchat' }))
assert.equal(received.user.type, 'groupchat')
assert.equal(received.user.name, 'ernie')
assert.equal(received.user.room, 'test@example.com')
assert.equal(received.text, 'message text')
})
})
describe('#readPresence()', () => {
let adapter, received
beforeEach(() => {
adapter = createAdapter()
received = null
adapter.receive = (message) => { received = message }
})
it('replies to subscribe presences', () => {
adapter.readPresence(xml('presence', {
type: 'subscribe',
to: 'bot@example.com',
from: 'room@example.com/mark',
id: '12345'
}))
const presence = adapter.client.sent[0]
assert.equal(presence.attrs.from, 'bot@example.com')
assert.equal(presence.attrs.to, 'room@example.com/mark')
assert.equal(presence.attrs.type, 'subscribed')
})
it('replies to probe presences', () => {
adapter.readPresence(xml('presence', {
type: 'probe',
to: 'bot@example.com',
from: 'room@example.com/mark',
id: '12345'
}))
const presence = adapter.client.sent[0]
assert.equal(presence.attrs.from, 'bot@example.com')
assert.equal(presence.attrs.to, 'room@example.com/mark')
assert.equal(presence.attrs.type, undefined)
})
it('sets heardOwnPresence when the bot presence is received by resource', () => {
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'test@example.com/bot'
}))
assert.equal(adapter.heardOwnPresence, true)
})
it('sets heardOwnPresence when the bot presence is received by nick', () => {
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'test@example.com/2578936351142164331380805'
}, xml('nick', { xmlns: 'http://jabber.org/protocol/nick' }, 'bot')))
assert.equal(adapter.heardOwnPresence, true)
})
it('does not dispatch an enter message before our own presence is heard', () => {
adapter.heardOwnPresence = false
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'test@example.com/mark'
}, xml('x', { xmlns: NS_MUC_USER }, xml('item', { jid: 'mark@example.com/mark' }))))
assert.equal(received, null)
})
it('dispatches an enter message for a user joining a joined room', () => {
adapter.heardOwnPresence = true
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'test@example.com/mark'
}, xml('x', { xmlns: NS_MUC_USER }, xml('item', { jid: 'mark@example.com/mark', role: 'participant' }))))
assert.equal(received.user.name, 'mark')
assert.equal(received.user.room, 'test@example.com')
assert.equal(received.user.privateChatJID, 'mark@example.com/mark')
assert.equal(received.user.role, 'participant')
})
it('ignores presence from a room the bot is not in', () => {
adapter.heardOwnPresence = true
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'other@example.com/mark'
}, xml('x', { xmlns: NS_MUC_USER }, xml('item', { jid: 'mark@example.com/mark' }))))
assert.equal(received, null)
})
it('dispatches a leave message when a user leaves', () => {
adapter.readPresence(xml('presence', {
type: 'unavailable',
to: 'bot@example.com',
from: 'test@example.com/mark'
}))
assert.equal(received.user.name, 'mark')
assert.equal(received.user.room, 'test@example.com')
})
it('maps the room jid to the private jid for later messages', () => {
adapter.heardOwnPresence = true
adapter.readPresence(xml('presence', {
type: 'available',
to: 'bot@example.com',
from: 'test@example.com/mark'
}, xml('x', { xmlns: NS_MUC_USER }, xml('item', { jid: 'mark@example.com/mark' }))))
adapter.readMessage(xml('message', { type: 'groupchat', from: 'test@example.com/mark' }, xml('body', {}, 'message text')))
assert.equal(received.user.privateChatJID, 'mark@example.com/mark')
})
})
describe('#reply()', () => {
it('prefixes messages with the user name', async () => {
const adapter = createAdapter()
const sent = []
adapter.send = (envelope, message) => { sent.push(message) }
await adapter.reply({ user: { name: 'mark' } }, 'one')
assert.deepEqual(sent, ['mark: one'])
})
it('sends multiple messages', async () => {
const adapter = createAdapter()
let called = 0
adapter.send = () => { called += 1 }
await adapter.reply({ user: { name: 'mark' } }, 'one', 'two')
assert.equal(called, 2)
})
})
describe('#topic()', () => {
it('sends a subject message to the room', () => {
const adapter = createAdapter()
const envelope = { user: { name: 'mark' }, room: 'test@example.com' }
adapter.topic(envelope, 'test')
const message = adapter.client.sent[0]
assert.equal(message.attrs.to, envelope.room)
assert.equal(message.getChild('subject').getText(), 'test')
})
it('joins multiple strings with newlines', () => {
const adapter = createAdapter()
const envelope = { user: { name: 'mark' }, room: 'test@example.com' }
adapter.topic(envelope, 'one', 'two')
assert.equal(adapter.client.sent[0].getChild('subject').getText(), 'one\ntwo')
})
})
describe('#send()', () => {
it('defaults to a groupchat message to the room', async () => {
const adapter = createAdapter()
const envelope = { user: { id: 'mark' }, room: 'test@example.com' }
await adapter.send(envelope, 'testing')
const message = adapter.client.sent[0]
assert.equal(message.name, 'message')
assert.equal(message.attrs.to, 'test@example.com')
assert.equal(message.attrs.type, 'groupchat')
assert.equal(message.getChild('body').getText(), 'testing')
})
it('sends directly to the private chat JID when the message was private', async () => {
const adapter = createAdapter()
const envelope = {
user: { id: 'mark', type: 'direct', privateChatJID: 'mark@example.com' },
room: null
}
await adapter.send(envelope, 'testing')
const message = adapter.client.sent[0]
assert.equal(message.attrs.to, 'mark@example.com')
assert.equal(message.attrs.type, 'direct')
})
it('falls back to the room JID with the user name when no private JID is known', async () => {
const adapter = createAdapter()
const envelope = {
user: { name: 'mark', room: 'room@example.com', type: 'direct' },
room: 'room@example.com'
}
await adapter.send(envelope, 'testing')
const message = adapter.client.sent[0]
assert.equal(message.attrs.to, 'room@example.com/mark')
assert.equal(message.attrs.type, 'direct')
})
it('accepts an ltx Element as a message', async () => {
const adapter = createAdapter()
const envelope = { user: { name: 'mark', type: 'groupchat' }, room: 'test@example.com' }
await adapter.send(envelope, xml('message', {}, xml('body', {}, 'testing')))
const message = adapter.client.sent[0]
assert.equal(message.name, 'message')
assert.equal(message.attrs.to, 'test@example.com')
assert.equal(message.attrs.type, 'groupchat')
assert.equal(message.getChild('body').getText(), 'testing')
})
it('wraps valid XML fragments as XHTML', async () => {
const adapter = createAdapter()
const envelope = { user: { name: 'mark', type: 'groupchat' }, room: 'test@example.com' }
await adapter.send(envelope, "<p><span style='color: #0000ff;'>testing</span></p>")
const message = adapter.client.sent[0]
assert.equal(message.attrs.to, 'test@example.com')
assert.equal(message.attrs.type, 'groupchat')
assert.equal(message.getChild('body').getText(), "<p><span style='color: #0000ff;'>testing</span></p>")
const html = message.getChild('html')
assert.equal(html.attrs.xmlns, NS_XHTML_IM)
const body = html.getChild('body')
assert.equal(body.attrs.xmlns, NS_XHTML)
assert.equal(body.getChild('p').getChild('span').getText(), 'testing')
})
it('sends plain text as a body only', async () => {
const adapter = createAdapter()
const envelope = { user: { name: 'mark', type: 'groupchat' }, room: 'test@example.com' }
await adapter.send(envelope, 'plain < not xml')
const message = adapter.client.sent[0]
assert.equal(message.getChild('body').getText(), 'plain < not xml')
assert.equal(message.getChild('html'), undefined)
})
})
describe('#online()', () => {
it('sends a nick presence, joins rooms and emits connected', () => {
const adapter = createAdapter()
let connected = false
adapter.on('connected', () => { connected = true })
adapter.online()
assert.equal(connected, true)
const presence = adapter.client.sent[0]
assert.equal(presence.name, 'presence')
assert.equal(presence.getChild('nick').getText(), 'bot')
const join = adapter.client.sent[1]
assert.equal(join.attrs.to, 'test@example.com/bot')
})
it('emits reconnected when already connected before', () => {
const adapter = createAdapter()
adapter.everConnected = true
let reconnected = false
adapter.on('reconnected', () => { reconnected = true })
adapter.online()
assert.equal(reconnected, true)
})
})
describe('#configClient()', () => {
it('registers listeners and starts the keepalive timer', () => {
const adapter = createAdapter()
adapter.configClient()
assert.equal(adapter.client.listenerCount('error'), 1)
assert.equal(adapter.client.listenerCount('offline'), 1)
assert.equal(adapter.client.listenerCount('online'), 1)
assert.equal(adapter.client.listenerCount('stanza'), 1)
assert.notEqual(adapter.keepaliveTimer, null)
adapter.close()
assert.equal(adapter.keepaliveTimer, null)
})
})
describe('#run()', () => {
it('throws when required configuration is missing', async () => {
const adapter = new XmppAdapter(createRobot({ config: { username: undefined } }))
await assert.rejects(() => adapter.run(), /HUBOT_XMPP_USERNAME/)
})
})
describe('entrypoint', () => {
afterEach(() => {
delete process.env.HUBOT_XMPP_USERNAME
delete process.env.HUBOT_XMPP_PASSWORD
delete process.env.HUBOT_XMPP_ROOMS
delete process.env.HUBOT_XMPP_HOST
delete process.env.HUBOT_XMPP_PORT
delete process.env.HUBOT_XMPP_PM_ADD_PREFIX
delete process.env.HUBOT_XMPP_KEEPALIVE_INTERVAL
})
it('builds an adapter and stores the config on the robot', () => {
process.env.HUBOT_XMPP_USERNAME = 'bot@example.com/hubot'
process.env.HUBOT_XMPP_PASSWORD = 'secret'
process.env.HUBOT_XMPP_ROOMS = 'test@example.com,dev@example.com:pass'
process.env.HUBOT_XMPP_HOST = 'example.com'
process.env.HUBOT_XMPP_PORT = '5222'
process.env.HUBOT_XMPP_PM_ADD_PREFIX = '1'
process.env.HUBOT_XMPP_KEEPALIVE_INTERVAL = '10000'
const robot = createRobot()
const adapter = entry.use(robot)
assert.ok(adapter instanceof XmppAdapter)
assert.equal(robot.config.username, 'bot@example.com/hubot')
assert.equal(robot.config.rooms.length, 2)
assert.equal(robot.config.pmAddPrefix, true)
assert.equal(adapter.options.rooms[1].password, 'pass')
assert.equal(adapter.options.keepaliveInterval, 10000)
})
})
})