forked from van-ibm/watsonworkspace-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
349 lines (295 loc) · 9.94 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
'use strict'
/**
* Watson Work Services Bot Framework
* @module watsonworkspace-bot
*/
require('dotenv').config()
const Bot = require('./bot')
const botRegistry = {
// bots added via create()
}
const SDK = require('watsonworkspace-sdk')
const bodyParser = require('body-parser')
const crypto = require('crypto')
const express = require('express')
const http = require('http')
const https = require('https')
const logger = require('winston')
const methodOverride = require('method-override')
const nonce = require('nonce')()
const oauth2 = require('simple-oauth2')
// set up express
var app = express()
// IBM Cloud uses hostname and port; do not change case or Express won't bind properly
const hostname = process.env.HOSTNAME || process.env.hostname || '0.0.0.0'
const port = process.env.PORT || process.env.port || 3000
// app.use('/config/:appId', configurer)
/**
* Creates an Express server to host bots.
* @param {Application} [express] Express server if already available (e.g. Node-RED)
*/
module.exports = (express) => {
app = express
}
/**
* Exports the Express server.
*/
module.exports.express = app
/**
* Creates and mounts a bot to the Express server.
*
* The bot's root path is /<appId> where appId corresponds to your application's ID.
* For example, https://myapp.mybluemix.net`/1023c56a-6751-4f70-8331-ad1cfc5ee800`.
* Webhooks in the Listen to Events page on Watson Work Services should point to use the /webhook route.
* For example, https://myapp.mybluemix.net`/1023c56a-6751-4f70-8331-ad1cfc5ee800/webhook`.
* Two mounts are provided for OAuth: /<appId>/oauth and /<appId>/callback.
* These respectively handle triggering the OAuth flow and the resulting callback from Watson Work Services.
* To utilize OAuth, you must update the Run as a User page from your app on Watson Work Services page.
* An example OAuth2 redirect URI is https://myapp.mybluemix.net/1023c56a-6751-4f70-8331-ad1cfc5ee800/callback.
* To trigger the OAuth flow, redirect the user's browser to
* https://myapp.mybluemix.net/1023c56a-6751-4f70-8331-ad1cfc5ee800/oauth.
*
* @param {string} appId The bot's app ID from Watson Work Services
* @param {string} appSecret The bot's app secret from Watson Work Services
* @param {string} webhookSecret The bot's webhook secret from Watson Work Services
* @param {string[]} routes Custom routes e.g. 'completed'
* @param {function[]} middleware Associated middleware to custom routes; follows (req, res) Express middleware
* @returns {Bot} The bot instance
*/
module.exports.create = (appId, appSecret, webhookSecret, routes, middleware) => {
// if undefined, assume the bot's info is in the runtime properties
if (appId === undefined) {
appId = process.env.APP_ID
appSecret = process.env.APP_SECRET
webhookSecret = process.env.WEBHOOK_SECRET
}
// the path will be the bot's appId; used to later emit events to bot
const path = `/${appId}`
logger.info(`Creating bot '${appId}' on path '${path}'`)
// standard middleware needed to handle JSON resonses from work services
app.use(path, bodyParser.urlencoded({
extended: false
}))
app.use(path, bodyParser.json({limit: '5mb'}))
app.use(path, methodOverride())
// watson work services specific middleware
const defaultHook = '/webhook'
logger.info(`Mounting ${defaultHook} middleware`)
app.use(`${path}${defaultHook}`, verifier)
app.use(`${path}${defaultHook}`, ignorer)
app.use(`${path}${defaultHook}`, webhook)
logger.info(`Mounting /oauth and /callback middleware`)
app.use(`${path}/oauth`, oauth)
app.use(`${path}/callback`, oauthCallback)
// custom middleware added by bot developers
if(routes && middleware) {
if(routes.length !== middleware.length) {
logger.warn(`Number of routes do not match middleware! Skipping custom middleware.`)
} else {
routes.forEach((route, i) => {
logger.info(`Mounting /${route} middleware`)
app.use(`${path}/${route}`, middleware[i])
})
}
}
// create the bot
const botInstance = new Bot(appId, appSecret, webhookSecret)
// add the bot to the registry
botRegistry[appId] = botInstance
// create the oauth client for the bot
botInstance.oauth = oauthClient(botInstance)
return botInstance
}
/**
* Sets the logging level for the bot framework.
* @param {string} level Level for debug e.g. error, info, warn, verbose, debug
*/
module.exports.level = level => {
logger.level = level
SDK.level(level) // TODO make this into a per bot logger not global
}
/**
* Starts the Express server. By default, the server will listen on HTTP.
*
* The hostname and port are inferred from process.env.
* process.env.HOSTNAME | process.env.hostname
* process.env.PORT | process.env.port
*
* To use SSL for local testing of OAuth, use the options object.
* { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') }
*
* @param {Object} [options] SSL options if applicable
* @returns {Server} The node HTTP server
*/
module.exports.startServer = (options) => {
const ssl = options && options.key && options.cert
const server = ssl ? https.createServer(options, app) : http.createServer(app)
return server.listen(port, hostname, () => {
logger.info(`watsonworkspace-bot framework listening on port ${port} using ssl ${ssl !== undefined}`)
})
}
/**
* Gets a bot's ID from a request (inferred from the URL).
* @param {Request} req The HTTP request
* @returns {string} The bot's ID
*/
function getBotId (req) {
// the baseUrl is /81279d4c-99a9-4326-8193-7e86787cfd8c/oauth
// get just the appId
return req.baseUrl.substring(1, 37)
}
/**
* Gets a Bot instance from a request (inferred from the URL).
* @param {Request} req The HTTP request
* @returns {Bot} The Bot instance
*/
function getBot (req) {
const botAppId = getBotId(req)
if (botRegistry[botAppId] === undefined) {
logger.error(`Failed to retrieve bot with ID '${botAppId}'`)
}
return botRegistry[botAppId]
}
/**
* Middleware function to handle Configuration URL parameters
*/
function configurer (req, res) {
const appId = req.params.appId
const bot = botRegistry[appId]
if (appId && bot) {
const token = req.query.configurationToken
logger.verbose(`Received configuration for appId ${appId} with configurationToken ${token}`)
bot.getConfigurationData(token)
.then(body => {
logger.verbose(body)
res.send(`Valid configurationToken`)
})
.catch(body => {
res.send(`Invalid configurationToken`)
logger.error(body)
})
// req.spaceId
// req.userId
} else {
res.send(`Invalid appId ${appId}`)
}
}
/**
* Ends the middleware chain. You must respond 200 or Watson Work Services will keep
* retrying to send messages.
*/
function end (req, res) {
// respond or watson work will keep sending the message
res.status(200).send().end()
}
/**
* Gets an OAuth URI using either the hostname:port of the process.
* If you are testing locally, set OAUTH_REDIRECT_URI to the endpoint of your choice.
*/
function oauthUri() {
return process.env.OAUTH_REDIRECT_URI || `${hostname}:${port}`
}
/**
* Middleware function to handle OAuth invocation
*/
function oauth (req, res) {
const bot = getBot(req)
const authorizationUri = bot.oauth.authorizationCode.authorizeURL({
redirect_uri: `https://${oauthUri()}/${bot.appId}/callback`,
state: nonce()
})
logger.verbose(`Redirecting to ${authorizationUri}`)
res.redirect(authorizationUri)
}
/**
* Middleware function to handle OAuth callback
*/
function oauthCallback (req, res) {
const bot = getBot(req)
const tokenConfig = {
code: req.query.code,
redirect_uri: `https://${oauthUri()}/${bot.appId}/callback`
}
bot.oauth.authorizationCode.getToken(tokenConfig,
(error, result) => {
if (error) {
logger.error(`Error with OAuth callback ${error.message}`)
res.send(error.message).end()
} else {
const accessToken = bot.oauth.accessToken.create(result)
logger.verbose(`Adding ${accessToken.token.displayName} to ${bot.appId} user registry`)
bot.addUser(accessToken.token.id, accessToken.token.access_token)
// TODO Need to handle refresh of tokens
res.send(`
<p>${accessToken.token.displayName}</p>
<p>${accessToken.token.id}</p>
<p>Valid until ${accessToken.token.expires_at}</p>
<p>${accessToken.token.access_token}</p>
<p>${accessToken.token.scope}</p>
`).end()
}
})
}
/**
* Creates the OAuth client to retrieve a user's token
*/
function oauthClient (bot) {
return oauth2.create({
client: {
id: bot.appId,
secret: bot.appSecret
},
auth: {
tokenHost: 'https://api.watsonwork.ibm.com'
}
})
}
/**
* Middleware function to handle the Watson Work challenge
*/
function verifier (req, res, next) {
if (req.body.type === 'verification') {
logger.verbose('Received webhook verification challenge ' + req.body.challenge)
const bot = getBot(req)
const bodyToSend = {
response: req.body.challenge
}
const hashToSend = crypto.createHmac('sha256', bot.webhookSecret)
.update(JSON.stringify(bodyToSend))
.digest('hex')
res.set('X-OUTBOUND-TOKEN', hashToSend)
res.send(bodyToSend)
bot.emitVerify()
} else {
next()
}
}
/**
* Middleware function to ignore messages from this bot
*/
function ignorer (req, res, next) {
const botAppId = getBotId(req)
// Ignore the bot's own messages
if (req.body.userId === botAppId) {
res.status(201).send().end()
} else {
next()
}
}
/**
* Middleware function to handle the webhook event
*/
function webhook (req, res, next) {
const body = req.body
if (body.type) {
logger.verbose(`Webhook event '${body.type}' for messageId ${body.messageId} with body`)
logger.debug(body)
// only handle messages that this bot has not seen before
// if (!marked(body.messageId)) {
// look up the bot in the registry
const bot = getBot(req)
bot.emitWebhook(body)
// }
}
end(req, res)
}