-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathindex.js
More file actions
220 lines (195 loc) · 6.63 KB
/
index.js
File metadata and controls
220 lines (195 loc) · 6.63 KB
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
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
// [START functions_slack_setup]
const functions = require('@google-cloud/functions-framework');
const google = require('@googleapis/kgsearch');
const crypto = require('crypto');
// Get a reference to the Knowledge Graph Search component
const kgsearch = google.kgsearch('v1');
// [END functions_slack_setup]
// [START functions_slack_format]
/**
* Format the Knowledge Graph API response into a richly formatted Slack message.
*
* @param {string} query The user's search query.
* @param {object} response The response from the Knowledge Graph API.
* @returns {object} The formatted message.
*/
const formatSlackMessage = (query, response) => {
let entity;
// Extract the first entity from the result list, if any
if (
response &&
response.data &&
response.data.itemListElement &&
response.data.itemListElement.length > 0
) {
entity = response.data.itemListElement[0].result;
}
// Prepare a rich Slack message
// See https://api.slack.com/docs/message-formatting
const slackMessage = {
response_type: 'in_channel',
text: `Query: ${query}`,
attachments: [],
};
if (entity) {
const attachment = {
color: '#3367d6',
};
if (entity.name) {
attachment.title = entity.name;
if (entity.description) {
attachment.title = `${attachment.title}: ${entity.description}`;
}
}
if (entity.detailedDescription) {
if (entity.detailedDescription.url) {
attachment.title_link = entity.detailedDescription.url;
}
if (entity.detailedDescription.articleBody) {
attachment.text = entity.detailedDescription.articleBody;
}
}
if (entity.image && entity.image.contentUrl) {
attachment.image_url = entity.image.contentUrl;
}
slackMessage.attachments.push(attachment);
} else {
slackMessage.attachments.push({
text: 'No results match your query...',
});
}
return slackMessage;
};
// [END functions_slack_format]
// [START functions_verify_webhook]
/**
* Verify that the webhook request came from Slack by validating its signature.
*
* This function follows the official Slack verification process:
* https://api.slack.com/authentication/verifying-requests-from-slack
*
* @param {object} req Cloud Function request object.
* @param {string} req.headers Headers Slack SDK uses to authenticate request.
* @param {string} req.rawBody Raw body of webhook request to check signature against.
*/
const verifyWebhook = req => {
const slackSigningSecret = process.env.SLACK_SECRET;
const requestSignature = req.headers['x-slack-signature'];
const requestTimestamp = req.headers['x-slack-request-timestamp'];
if (!requestSignature || !requestTimestamp) {
const error = new Error('Missing Slack signature or timestamp headers');
error.code = 401;
throw error;
}
// Protect against replay sttacks by ensuring the request is recent (within 5 minutes)
const fiveMinutesAgo = Math.floor(Date.now() / 1000) - 300;
if (parseInt(requestTimestamp, 10) < fiveMinutesAgo) {
throw new Error('Slack request timestamp is too old');
}
// Create the base string as Slack expects: version + ':' timestamp + ':' + raw body
const basestring = `v0:${requestTimestamp}:${req.rawBody}`;
// Create a HMAC SHA256 hash using the Slack signing secret
const hmac = crypto.createHmac('sha256', slackSigningSecret);
hmac.update(basestring, 'utf-8');
const digest = `v0=${hmac.digest('hex')}`;
// Convert digest and signature to Buffers for secure comparison
const digestBuf = Buffer.from(digest, 'utf-8');
const sigBuf = Buffer.from(requestSignature, 'utf-8');
if (digestBuf.length !== sigBuf.length) {
const error = new Error('Invalid Slack signature (length mismatch)');
error.code = 401;
throw error;
}
// Perform a constant-time comparison to prevent timing attacks
if (!crypto.timingSafeEqual(digestBuf, sigBuf)) {
const error = new Error('Invalid Slack signature');
error.code = 401;
throw error;
}
};
// [END functions_verify_webhook]
// [START functions_slack_request]
/**
* Send the user's search query to the Knowledge Graph API.
*
* @param {string} query The user's search query.
*/
const makeSearchRequest = query => {
return new Promise((resolve, reject) => {
kgsearch.entities.search(
{
auth: process.env.KG_API_KEY,
query: query,
limit: 1,
},
(err, response) => {
console.log(err);
if (err) {
reject(err);
return;
}
// Return a formatted message
resolve(formatSlackMessage(query, response));
}
);
});
};
// [END functions_slack_request]
// [START functions_slack_search]
/**
* Receive a Slash Command request from Slack.
*
* Trigger this function by creating a Slack slash command with the HTTP Trigger URL.
* You can find the HTTP URL in the Cloud Console or using `gcloud functions describe`
*
* @param {object} req Cloud Function request object.
* @param {object} req.body The request payload.
* @param {string} req.rawBody Raw request payload used to validate Slack's message signature.
* @param {string} req.body.text The user's search query.
* @param {object} res Cloud Function response object.
*/
const kgSearchHandler = async (req, res) => {
try {
if (req.method !== 'POST') {
const error = new Error('Only POST requests are accepted');
error.code = 405;
throw error;
}
if (!req.body.text) {
const error = new Error('No text found in body.');
error.code = 400;
throw error;
}
// Verify that this request came from Slack
verifyWebhook(req);
// Make the request to the Knowledge Graph Search API
const response = await makeSearchRequest(req.body.text);
// Send the formatted message back to Slack
res.json(response);
return Promise.resolve();
} catch (err) {
console.error(err);
res.status(err.code || 500).send(err);
return Promise.reject(err);
}
};
functions.http('kgsearch', kgSearchHandler);
// [END functions_slack_search]
module.exports = {
verifyWebhook,
kgSearchHandler,
};