forked from chris-rock/node-xmpp-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
370 lines (340 loc) · 12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
'use strict';
var Session = require('./lib/session')
, Connection = require('node-xmpp-core').Connection
, JID = require('node-xmpp-core').JID
, ltx = require('node-xmpp-core').ltx
, sasl = require('./lib/sasl')
, exec = require('child_process').exec
, util = require('util')
, debug = require('debug')('xmpp:client')
var NS_CLIENT = 'jabber:client'
var NS_REGISTER = 'jabber:iq:register'
var NS_XMPP_SASL = 'urn:ietf:params:xml:ns:xmpp-sasl'
var NS_XMPP_BIND = 'urn:ietf:params:xml:ns:xmpp-bind'
var NS_XMPP_SESSION = 'urn:ietf:params:xml:ns:xmpp-session'
var STATE_PREAUTH = 0
, STATE_AUTH = 1
, STATE_AUTHED = 2
, STATE_BIND = 3
, STATE_SESSION = 4
, STATE_ONLINE = 5
var IQID_SESSION = 'sess'
, IQID_BIND = 'bind'
/* jshint latedef: false */
/* jshint -W079 */
/* jshint -W020 */
var decode64, encode64, Buffer
if (typeof btoa === 'undefined') {
var btoa = null
var atob = null
}
if (typeof btoa === 'function') {
decode64 = function(encoded) {
return atob(encoded)
}
} else {
Buffer = require('buffer').Buffer
decode64 = function(encoded) {
return (new Buffer(encoded, 'base64')).toString('utf8')
}
}
if (typeof atob === 'function') {
encode64 = function(decoded) {
return btoa(decoded)
}
} else {
Buffer = require('buffer').Buffer
encode64 = function(decoded) {
return (new Buffer(decoded, 'utf8')).toString('base64')
}
}
/**
* params object:
* jid: String (required)
* password: String (required)
* host: String (optional)
* port: Number (optional)
* reconnect: Boolean (optional)
* register: Boolean (option) - register account before authentication
* legacySSL: Boolean (optional) - connect to the legacy SSL port, requires at least the host to be specified
* credentials: Dictionary (optional) - TLS or SSL key and certificate credentials
* actAs: String (optional) - if admin user act on behalf of another user (just user)
* disallowTLS: Boolean (optional) - prevent upgrading the connection to a secure one via TLS
* preferred: String (optional) - Preferred SASL mechanism to use
* bosh.url: String (optional) - BOSH endpoint to use
* bosh.prebind: Function(error, data) (optional) - Just prebind a new BOSH session for browser client use
* error String - Result of XMPP error. Ex : [Error: XMPP authentication failure]
* data Object - Result of XMPP BOSH connection.
*
* Examples:
* var cl = new xmpp.Client({
* jid: "[email protected]",
* password: "secret"
* })
* var facebook = new xmpp.Client({
* jid: '-' + fbUID + '@chat.facebook.com',
* api_key: '54321', // api key of your facebook app
* access_token: 'abcdefg', // user access token
* host: 'chat.facebook.com'
* })
* var gtalk = new xmpp.Client({
* jid: '[email protected]',
* oauth2_token: 'xxxx.xxxxxxxxxxx', // from OAuth2
* oauth2_auth: 'http://www.google.com/talk/protocol/auth',
* host: 'talk.google.com'
* })
* var prebind = new xmpp.Client({
* jid: "[email protected]",
* password: "secret",
* bosh: {
* url: "http://example.com/http-bind",
* prebind: function(error, data) {
* if (error) {}
* res.send({ rid: data.rid, sid: data.sid })
* }
* }
* })
*
* Example SASL EXTERNAL:
*
* var myCredentials = {
* // These are necessary only if using the client certificate authentication
* key: fs.readFileSync('key.pem'),
* cert: fs.readFileSync('cert.pem'),
* // passphrase: 'optional'
* }
* var cl = new xmppClient({
* jid: "[email protected]",
* credentials: myCredentials
* preferred: 'EXTERNAL' // not really required, but possible
* })
*
*/
function Client(opts) {
if (opts.bosh && opts.bosh.prebind) {
debug('load bosh prebind')
var cb = opts.bosh.prebind
delete opts.bosh.prebind
var cmd = 'node ' + process.cwd() +
'/node_modules/node-xmpp-client/lib/prebind.js '
for (var o in opts) {
cmd += '--' + o + ' ' + opts[o] + ' '
}
exec(
cmd,
function (error, stdout, stderr) {
if (error || stderr) {
cb(error || stderr, null)
} else {
var r = stdout.match(/rid:+[ 0-9]*/i)
r = (r[0].split(':'))[1].trim()
var s = stdout.match(/sid:+[ a-z+'"-_A-Z+0-9]*/i)
s = (s[0].split(':'))[1]
.replace('\'','')
.replace('\'','')
.trim()
cb(null, { rid: r, sid: s })
}
})
} else {
opts.xmlns = NS_CLIENT
/* jshint camelcase: false */
delete this.did_bind
delete this.did_session
this.state = STATE_PREAUTH
this.on('end', function() {
this.state = STATE_PREAUTH
delete this.did_bind
delete this.did_session
})
Session.call(this, opts)
opts.jid = this.jid
this.connection.on('disconnect', function(error) {
this.state = STATE_PREAUTH
if (!this.connection.reconnect) {
if (error) this.emit('error', error)
this.emit('offline')
}
delete this.did_bind
delete this.did_session
}.bind(this))
// If server and client have multiple possible auth mechanisms
// we try to select the preferred one
if (opts.preferred) {
this.preferredSaslMechanism = opts.preferred
} else {
this.preferredSaslMechanism = 'DIGEST-MD5'
}
this.availableSaslMechanisms = sasl.detectMechanisms(opts)
}
}
util.inherits(Client, Session)
Client.NS_CLIENT = NS_CLIENT
Client.prototype.onStanza = function(stanza) {
/* Actually, we shouldn't wait for <stream:features/> if
this.streamAttrs.version is missing, but who uses pre-XMPP-1.0
these days anyway? */
if ((this.state !== STATE_ONLINE) && stanza.is('features')) {
this.streamFeatures = stanza
this.useFeatures()
} else if (this.state === STATE_PREAUTH) {
this.emit('stanza:preauth', stanza)
} else if (this.state === STATE_AUTH) {
this._handleAuthState(stanza)
} else if ((this.state === STATE_BIND) && stanza.is('iq') && (stanza.attrs.id === IQID_BIND)) {
this._handleBindState(stanza)
} else if ((this.state === STATE_SESSION) && (true === stanza.is('iq')) &&
(stanza.attrs.id === IQID_SESSION)) {
this._handleSessionState(stanza)
} else if (stanza.name === 'stream:error') {
if (!this.reconnect)
this.emit('error', stanza)
} else if (this.state === STATE_ONLINE) {
this.emit('stanza', stanza)
}
}
Client.prototype._handleSessionState = function(stanza) {
if (stanza.attrs.type === 'result') {
this.state = STATE_AUTHED
/* jshint camelcase: false */
this.did_session = true
/* no stream restart, but next feature (most probably
we'll go online next) */
this.useFeatures()
} else {
this.emit('error', 'Cannot bind resource')
}
}
Client.prototype._handleBindState = function(stanza) {
if (stanza.attrs.type === 'result') {
this.state = STATE_AUTHED
/*jshint camelcase: false */
this.did_bind = true
var bindEl = stanza.getChild('bind', NS_XMPP_BIND)
if (bindEl && bindEl.getChild('jid')) {
this.jid = new JID(bindEl.getChild('jid').getText())
}
/* no stream restart, but next feature */
this.useFeatures()
} else {
this.emit('error', 'Cannot bind resource')
}
}
Client.prototype._handleAuthState = function(stanza) {
if (stanza.is('challenge', NS_XMPP_SASL)) {
var challengeMsg = decode64(stanza.getText())
var responseMsg = encode64(this.mech.challenge(challengeMsg))
var response = new ltx.Element(
'response', { xmlns: NS_XMPP_SASL }
).t(responseMsg)
this.send(response)
} else if (stanza.is('success', NS_XMPP_SASL)) {
this.mech = null
this.state = STATE_AUTHED
this.emit('auth')
} else {
this.emit('error', 'XMPP authentication failure')
}
}
Client.prototype._handlePreAuthState = function() {
this.state = STATE_AUTH
var offeredMechs = this.streamFeatures.
getChild('mechanisms', NS_XMPP_SASL).
getChildren('mechanism', NS_XMPP_SASL).
map(function(el) { return el.getText() })
this.mech = sasl.selectMechanism(
offeredMechs,
this.preferredSaslMechanism,
this.availableSaslMechanisms
)
if (this.mech) {
this.mech.authzid = this.jid.bare().toString()
this.mech.authcid = this.jid.user
this.mech.password = this.password
/*jshint camelcase: false */
this.mech.api_key = this.api_key
this.mech.access_token = this.access_token
this.mech.oauth2_token = this.oauth2_token
this.mech.oauth2_auth = this.oauth2_auth
this.mech.realm = this.jid.domain // anything?
if (this.actAs) this.mech.actAs = this.actAs.user
this.mech.digest_uri = 'xmpp/' + this.jid.domain
var authMsg = encode64(this.mech.auth())
var attrs = this.mech.authAttrs()
attrs.xmlns = NS_XMPP_SASL
attrs.mechanism = this.mech.name
this.send(new ltx.Element('auth', attrs)
.t(authMsg))
} else {
this.emit('error', 'No usable SASL mechanism')
}
}
/**
* Either we just received <stream:features/>, or we just enabled a
* feature and are looking for the next.
*/
Client.prototype.useFeatures = function() {
/* jshint camelcase: false */
if ((this.state === STATE_PREAUTH) && this.register) {
delete this.register
this.doRegister()
} else if ((this.state === STATE_PREAUTH) &&
this.streamFeatures.getChild('mechanisms', NS_XMPP_SASL)) {
this._handlePreAuthState()
} else if ((this.state === STATE_AUTHED) &&
!this.did_bind &&
this.streamFeatures.getChild('bind', NS_XMPP_BIND)) {
this.state = STATE_BIND
var bindEl = new ltx.Element(
'iq',
{ type: 'set', id: IQID_BIND }
).c('bind', { xmlns: NS_XMPP_BIND })
if (this.jid.resource)
bindEl.c('resource').t(this.jid.resource)
this.send(bindEl)
} else if ((this.state === STATE_AUTHED) &&
!this.did_session &&
this.streamFeatures.getChild('session', NS_XMPP_SESSION)) {
this.state = STATE_SESSION
var stanza = new ltx.Element(
'iq',
{ type: 'set', to: this.jid.domain, id: IQID_SESSION }
).c('session', { xmlns: NS_XMPP_SESSION })
this.send(stanza)
} else if (this.state === STATE_AUTHED) {
/* Ok, we're authenticated and all features have been
processed */
this.state = STATE_ONLINE
this.emit('online', { jid: this.jid })
}
}
Client.prototype.doRegister = function() {
var id = 'register' + Math.ceil(Math.random() * 99999)
var iq = new ltx.Element(
'iq',
{ type: 'set', id: id, to: this.jid.domain }
).c('query', { xmlns: NS_REGISTER })
.c('username').t(this.jid.user).up()
.c('password').t(this.password)
this.send(iq)
var self = this
var onReply = function(reply) {
if (reply.is('iq') && (reply.attrs.id === id)) {
self.removeListener('stanza', onReply)
if (reply.attrs.type === 'result') {
/* Registration successful, proceed to auth */
self.useFeatures()
} else {
self.emit('error', new Error('Registration error'))
}
}
}
this.on('stanza:preauth', onReply)
}
Client.prototype.registerSaslMechanism = function () {
var args = arguments.length > 0 ? Array.prototype.slice.call(arguments) : []
this.availableSaslMechanisms = this.availableSaslMechanisms.concat(args)
}
Client.SASL = sasl
Client.Client = Client
module.exports = Client