-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWebhook.js
208 lines (188 loc) · 5.86 KB
/
Webhook.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
/*
* This is a Webhook End-point for Watson Workspace. You will need to modify the credentials below
* to contain the actual credentials for your Watson Workspace App.
*
* This action will perform all the necesary validation and hand-shaking to Watson Work Services.
* Actual events will be published on the EventTrigger trigger
* The following package parameters are used:
* WWAppId - The Watson Workspace appId
* WWAppSecret - The Watson Workspace App AppSecret
* WWWebhookSecret - The Watson Workspace Webhook Secret
* WWEventTopic - The name of the topic to send events to
*/
var crypto = require("crypto");
var openwhisk = require("openwhisk");
var util = require("util");
var _ = require("lodash");
var mustache = require("mustache");
var annotationGQL = {
GraphQLExpansion: `
query {
message(id: "{{messageId}}") {
content
id
created
createdBy {
displayName
id
emailAddresses
photoUrl
}
}
}`
};
var expansion = {
"message-annotation-added": annotationGQL,
"message-annotation-edited": annotationGQL,
"message-annotation-removed": annotationGQL,
};
function samePackage(action) {
return (process.env.__OW_ACTION_NAME.replace(/\/[^\/]+$/,"") + "/" + action).replace(/^\/[^\/]+\//,"");
}
async function expandEvent(body, params, ow) {
// Check to see if there is an expansion GraphQL expression to run
if (body.hasOwnProperty("type") && expansion.hasOwnProperty(body.type)) {
var exp = expansion[body.type];
var resp = await ow.actions.invoke({
name: samePackage("GraphQL"),
blocking: true,
result: true,
params: {
string: mustache.render(exp.GraphQLExpansion, body)
}
});
// If annotation, mark it as generated by my app if it was
/* istanbul ignore else */
if (body.type.startsWith("message-annotation"))
body.appEvent = resp.data.message.createdBy.id === params.AppId;
return _.merge(body, resp.data);
} else {
return body;
}
}
function cleanUpEvent(event, params) {
// expand annotationPayload into JSON obejct if it exists.
if (event.hasOwnProperty("annotationPayload") && typeof event.annotationPayload === "string")
event.annotationPayload = JSON.parse(event.annotationPayload);
// Was this event generated by my app?
if (_.get(event,"annotationPayload.targetAppId"))
event.appEvent = event.annotationPayload.targetAppId === params.AppId;
else
event.appEvent = event.userId === params.AppId;
// Cleanup time field
/* istanbul ignore else */
if (event.hasOwnProperty("time"))
event.time = Date(event.time).toString();
}
function closeAction(annotation, params, ow) {
var card = {
type: 'INFORMATION',
title: 'Action Completed',
text: "You can close this action.",
buttons: []
};
/* istanbul ignore else */
if (_.has(annotation,"annotationPayload.actionId.response")) {
_.merge(card, annotation.annotationPayload.actionId.response);
}
ow.actions.invoke ({
name: samePackage("TargetedMessage"),
params: {cards: card, annotation: annotation}
});
}
async function main(params) {
var ow = openwhisk(
_.get(params,"WatsonWorkspace.OWArgs",{})
);
var rawBody =Buffer.from(params.__ow_body, "base64").toString();
var req = {
rawBody: rawBody,
body: JSON.parse(rawBody),
headers: params.__ow_headers
};
// separate Workspace paramaters
var workspaceParams = params.WatsonWorkspace;
_.omit(params,"WatsonWorkspace");
if (!validateSender(params, req)) {
return Promise.reject({
statusCode: 401,
body: "Invalid Request Signature"
});
}
if (_.get(req.body, "type") === "verification") {
var body = {
response: req.body.challenge
};
var strBody = JSON.stringify(body);
var validationToken = crypto.createHmac("sha256", workspaceParams.WebhookSecret).update(strBody).digest("hex");
return {
statusCode: 200,
headers: {
"Content-Type": "text/plain; charset=utf-8",
"X-OUTBOUND-TOKEN": validationToken
},
body: strBody
};
} else {
// Clean up the event
cleanUpEvent(req.body,workspaceParams);
if (_.get(req.body, "annotationType") === "actionSelected" && req.body.appEvent) {
var triggerName = "WWActionSelected";
var prefix = "BUTTON_SELECTED: ";
if (req.body.annotationPayload.actionId.startsWith(prefix)) {
triggerName = "WWButtonSelected";
var action = req.body.annotationPayload.actionId.substr(prefix.length)
try {
req.body.annotationPayload.actionId = JSON.parse(action);
}
catch (err) {
req.body.annotationPayload.actionId = action;
}
closeAction(req.body, params.workspaceParams,ow);
}
// Send event to topic
ow.triggers.invoke({
name: triggerName,
params: req.body
})
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: {
status: "OK!"
}
};
}
else {
// Expand Event
var body = await expandEvent(req.body, workspaceParams, ow);
// Send event to topic
/* istanbul ignore next */
const target = body.appEvent ? "WWApplicationEvents" : "WWWebhookEvents";
ow.triggers.invoke({
name: target,
params: body
});
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: {
status: "OK!"
}
};
}
}
}
function validateSender(params, req) {
var ob_token = req.headers["x-outbound-token"];
var calculated = crypto.createHmac("sha256", params.WatsonWorkspace.WebhookSecret).update(req.rawBody).digest("hex");
return ob_token == calculated;
}
exports.main = main;
exports.setOpenwhisk = function(obj) {
openwhisk = obj;
}