-
Notifications
You must be signed in to change notification settings - Fork 85
/
index.js
306 lines (275 loc) · 7.7 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
// their code
import express from 'express';
import sockets from 'socket.io';
import { json } from 'body-parser';
import { Server as http } from 'http';
import { readFileSync as read } from 'fs';
import remail from 'email-regex';
import cors from 'cors';
import request from 'superagent';
import dbg from 'debug';
import tinycolor from 'tinycolor2';
import match from 'micromatch';
// our code
import Slack from './slack';
import invite from './slack-invite';
import themes from './themes';
const mainLog = dbg('slackin:main');
const inviteLog = dbg('slackin:invite');
const slackLog = dbg('slackin:slack');
export default function slackin({
token,
org,
path = '/',
interval = 60000,
cors: useCors = false,
recaptcha = {},
analytics,
theme: themeID,
accent,
css,
channels: channelFilter,
emails,
coc,
proxy,
redirectFQDN,
letsencrypt,
silent,
server,
}) {
// must haves
if (!token) throw new Error('Must provide a `token`.');
if (!org) throw new Error('Must provide an `org`.');
if (
!!(recaptcha.secret || recaptcha.sitekey || recaptcha.invisible) !==
!!(recaptcha.secret && recaptcha.sitekey)
) {
throw new Error('Both `recaptcha-secret` and `recaptcha-sitekey` must be defined to enable reCAPTCHA.');
}
let relativePath;
if (path.slice(-1) !== '/') {
relativePath = `${path}/`;
} else {
relativePath = path;
}
if (!silent) {
inviteLog.enabled = true;
slackLog.enabled = true;
mainLog.enabled = true;
}
let channels;
if (channelFilter) {
channels = channels.split(',').map(channel => (
channel[0] === '#' ? channel.substr(1) : channel
));
}
let acceptedEmails;
if (emails) {
acceptedEmails = emailFilter.split(',');
}
let theme;
if (themeID) {
if (themeID in themes) {
theme = themes[themeID];
} else {
mainLog(`Specified theme (${themeID}) not found, falling back to default`);
}
} else {
theme = themes.default;
}
mainLog(`Theme: ${theme.name}`);
if (accent) {
theme.accent = tinycolor(accent).toHexString();
mainLog(`Using a custom theme accent: ${accent}`);
}
theme.accentDark = tinycolor(theme.accent).darken(10).toHexString();
// setup
const app = express();
const srv = server || http(app);
srv.app = app;
app.set('views', `${__dirname}/../views`);
app.set('view engine', 'pug');
if (useCors) {
app.options('*', cors());
app.use(cors());
}
if (proxy) {
app.enable('trust proxy');
if (redirectFQDN) {
app.use((req, res, next) => {
if (req.headers['x-forwarded-proto'] === 'http') {
res.redirect(`https://${redirectFQDN}${req.url}`);
} else {
next();
}
});
}
}
// static files
const assets = `${__dirname}/assets`;
app.use('/assets', express.static(assets));
app.use('/slackin.js', express.static(`${assets}/badge.js`));
if (letsencrypt) {
app.get('/.well-known/acme-challenge/:id', (req, res) => {
res.send(letsencrypt);
});
}
// fetch data
mainLog('Establishing connection with Slack');
const slack = new Slack({
token, interval, org, logger: slackLog,
});
slack.setMaxListeners(Infinity);
// middleware for waiting for slack
app.use((req, res, next) => {
if (slack.ready) return next();
return slack.once('ready', next);
});
app.get('/', (req, res) => {
const { name, logo } = slack.org;
const { active, total } = slack.users;
if (!name) return res.send(404);
return res
.type('html')
.render('main', {
coc,
path: relativePath,
name,
org,
logo,
active,
total,
recaptcha,
css,
analytics,
channels,
theme,
});
});
app.get('/data', (req, res) => {
const { name, logo } = slack.org;
const { active, total } = slack.users;
res.send({
name,
org,
coc,
logo,
active,
total,
channels,
});
});
// invite endpoint
app.post('/invite', json(), (req, res) => {
const { channel, email } = req.body;
const captchaResponse = req.body['g-recaptcha-response'];
let errorMessage = null;
if (channels && !channels.includes(channel)) {
errorMessage = 'Not a permitted channel';
} else if (channels && !slack.getChannelId(channel)) {
errorMessage = `Channel "${channel}" not found`;
} else if (!email) {
errorMessage = 'No email provided';
} else if (recaptcha.secret && (!captchaResponse || !captchaResponse.length)) {
errorMessage = 'Invalid captcha';
} else if (!remail().test(email)) {
errorMessage = 'Invalid email';
} else if (emails && !match.any(email, acceptedEmails)) {
errorMessage = 'Your email is not on the accepted list.';
} else if (coc && req.body.coc != 1) {
errorMessage = 'Agreement to CoC is mandatory';
}
if (errorMessage) {
return res.status(400).json({ msg: errorMessage });
}
const captchaData = {
secret: recaptcha.secret,
response: captchaResponse,
remoteip: req.connection.remoteAddress,
};
const captchaCallback = (err) => {
if (err) return res.status(400).send({ msg: err });
return invite({
token, org, email, logger: inviteLog, channel: slack.channel ? slack.channel.id : null,
}, (inviteErr) => {
if (inviteErr) {
if (inviteErr.message === 'Sending you to Slack...') {
return res.status(303).json({ msg: inviteErr.message, redirectUrl: `https://${org}.slack.com` });
}
return res.status(400).json({ msg: inviteErr.message });
}
return res.status(200).json({ msg: 'WOOT. Check your email!' });
});
};
if (recaptcha.secret) {
return request.post('https://www.google.com/recaptcha/api/siteverify')
.type('form')
.send(captchaData)
.end(captchaCallback);
}
return captchaCallback();
});
// iframe
app.get('/iframe', (req, res) => {
const logo = read(`${__dirname}/assets/slack.svg`).toString('base64');
const js = read(`${__dirname}/assets/iframe.js`).toString();
const extraCss = read(`${__dirname}/assets/iframe-button.css`).toString();
const large = 'large' in req.query;
const { active, total } = slack.users;
res.type('html');
res.render('iframe', {
path: relativePath, active, total, large, logo, js, extraCss, css,
});
});
app.get('/iframe/dialog', (req, res) => {
const large = 'large' in req.query;
const { name } = slack.org;
const { active, total } = slack.users;
if (!name) {
res.sendStatus(404);
return;
}
res.type('html');
res.render('main', {
coc,
path: relativePath,
name,
org,
active,
total,
large,
recaptcha,
analytics,
channels,
theme,
iframe: true,
});
});
// badge rendering
app.get('/badge.svg', (req, res) => {
res.type('svg');
res.set('Cache-Control', 'max-age=0, no-cache');
res.set('Pragma', 'no-cache');
const options = {
total: slack.users.total,
active: slack.users.active,
bg: req.query.bg ? tinycolor(req.query.bg).toHexString() : theme.accent,
};
if (req.query.fg) {
options.fg = tinycolor(req.query.fg).toHexString();
} else {
options.fg = tinycolor(options.bg).isDark() ? '#fff' : '#333';
}
res.render('badge-svg', options);
});
// realtime
sockets(srv, { path: `${relativePath}socket.io` }).on('connection', (socket) => {
const change = (key, val) => socket.emit(key, val);
slack.on('change', change);
socket.emit('data', slack.users);
socket.on('disconnect', () => {
slack.removeListener('change', change);
});
});
return srv;
}