-
Notifications
You must be signed in to change notification settings - Fork 74
/
app.js
411 lines (352 loc) · 13 KB
/
app.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
var express = require('express')
, path = require('path')
, favicon = require('serve-favicon')
, cookieParser = require('cookie-parser')
, bodyParser = require('body-parser')
, session = require('express-session')
, passport = require('passport')
, swig = require('swig')
, Auth0Strategy = require('passport-auth0')
, logger = require('./logger')
, crypto = require('crypto')
, base64url = require('base64url');
var keys = {};
var provider_friendly_name = {
'facebook': 'Facebook',
'google-oauth2': 'Google',
'windowslive': 'Microsoft Account',
'twitter': 'Twitter',
'github': 'GitHub',
'yahoo': 'Yahoo'
};
var strategy = new Auth0Strategy({
domain: process.env.AUTH0_DOMAIN,
clientID: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
callbackURL: process.env.AUTH0_CALLBACK
}, function(accessToken, refreshToken, extraParams, profile, done) {
// accessToken is the token to call Auth0 API (not needed in the most cases)
// extraParams.id_token has the JSON Web Token
// profile has all the information from the user
return done(null, profile);
});
passport.use(strategy);
// This is not a best practice, but we want to keep things simple for now
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', swig.renderFile);
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.set('trust proxy', true);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(function (req, res, next) {
req.start_time = Date.now();
res.on('finish', function () {
var meta = {
code: res.statusCode,
time: new Date(),
duration: Date.now() - req.start_time,
path: req.path,
method: req.method
};
if (res.statusCode >= 400)
logger.warn(meta, res.statusCode);
else
logger.info(meta, res.statusCode);
});
next();
});
if (process.env.FORCE_HTTPS === '1') {
logger.info('turning on HTTPS enforcement');
app.use(function (req, res, next) {
if (req.protocol === 'https' || req.headers['x-arr-ssl'])
next();
else
return res.redirect('https://' + req.host + req.url);
});
}
app.use(cookieParser());
app.use(session({ secret: process.env.COOKIE_SECRET, resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/callback',
passport.authenticate('auth0', { failureRedirect: '/unauthorized' }),
function (req, res, next) {
if (!req.user)
res.send(403);
else {
var url = req.session.bookmark || '/';
delete req.session.bookmark;
res.redirect(url);
}
}
);
app.get('/logout',
function (req, res, next) {
req.session.destroy();
res.redirect(req.query.r || '/');
});
app.get('/', function (req, res, next) {
res.render('landing');
});
app.post('/create',
bodyParser.json(),
bodyParser.urlencoded({ extended: false }),
current_create());
// app.get('/test/500', function(req, res, next) {
// if (app.get('env') === 'development') {
// throw new Error('Internal Server Error');
// }
// next();
// });
app.get(/^\/(\w{1,10})\/(.+)$/,
v1_get());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
res.status(404);
res.render('404');
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('500', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('500', {
message: err.message,
error: {}
});
});
function current_create() {
// current signature, encryption keys, and version
var current_keys = ensure_key(process.env.CURRENT_KEY);
var version_prefix = '/' + process.env.CURRENT_KEY + '/';
return function (req, res, next) {
if (!req.body.d)
req.body.d = req.query.d;
if (!req.body.a)
req.body.a = req.query.a;
if (typeof req.body.d !== 'string' || req.body.d.length === 0)
return res.status(400).send('Missing data to secure. Use `d` parameter.');
if (req.body.d.length > 500)
return res.status(400).send('Data too large. Max 500 characters.');
if (typeof req.body.a !== 'string' || req.body.a.length === 0)
return res.status(400).send('Missing ACLs. Use `a` parameter.');
if (req.body.a.length > 200)
return res.status(400).send('ACLs too long. Max 200 characters.');
var resource = {
d: req.body.d,
a: []
};
var tokens = req.body.a.split(/[\ \n\,\r]/);
for (var i in tokens) {
var token = tokens[i].trim();
if (token.length === 0)
continue;
var match = token.match(/^\@([^\.]+)$/);
if (match) {
// twitter
resource.a.push({
k: 't',
v: match[1]
});
continue;
}
match = token.match(/^\@([^\.]+\..+)$/);
if (match) {
// email domain
resource.a.push({
k: 'd',
v: token
});
continue;
}
match = token.match(/^[^\@]+\@[^\.]+\..+$/);
if (match) {
// email
resource.a.push({
k: 'e',
v: token
});
continue;
}
return res.status(400).send('I don\'t understand what `' + token + '` means. You can say `@johnexample` for Twitter handle, `[email protected]` for e-mail address, or `@example.com` for e-mail domain.');
}
if (resource.a.length === 0)
return res.status(400).send('At least one person allowed to access the secret must be specified.');
var plaintext = JSON.stringify(resource);
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv('aes-256-ctr', current_keys.encryption_key, iv);
var encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
var signature = crypto.createHmac('sha256', current_keys.signature_key).update(encrypted).update(iv).digest('base64');
resource =
base64url.fromBase64(signature)
+ '.' + base64url.fromBase64(encrypted.toString('base64'))
+ '.' + base64url.fromBase64(iv.toString('base64'));
var split_resource = version_prefix;
for (var i = 0; i < resource.length; i++) {
split_resource += resource[i];
if (((i + 1) % 50) === 0)
split_resource += '/';
}
res.status(200).send(split_resource);
};
}
function v1_get() {
return function (req, res, next) {
res.set('Cache-Control', 'no-cache');
logger.info({ user: req.user ? req.user._json : undefined }, 'sharelock access request');
var request_keys;
try {
request_keys = ensure_key(req.params[0]);
}
catch (e) {
return res.render('invalid', { details: 'For security reasons this sharelock is no longer supported.'});
}
var resource = req.params[1].replace(/\//g, '');
var tokens = resource.split('.');
if (tokens.length !== 3 || tokens[0].length === 0 || tokens[1].length === 0 || tokens[2].length === 0)
return res.render('invalid', { details: 'The URL is malformed and cannot be processed.'});
try {
tokens[0] = base64url.toBase64(tokens[0]); // signature
tokens[1] = new Buffer(base64url.toBase64(tokens[1]), 'base64'); // encrypted data
tokens[2] = new Buffer(base64url.toBase64(tokens[2]), 'base64'); // iv
var signature = crypto.createHmac('sha256', request_keys.signature_key).update(tokens[1]).update(tokens[2]).digest('base64');
if (signature !== tokens[0])
throw null;
}
catch (e) {
return res.render('invalid', { details: 'Signature verification failed: the data could have been tampered with.'});
}
try {
var cipher = crypto.createDecipheriv('aes-256-ctr', request_keys.encryption_key, tokens[2]);
var plaintext = cipher.update(tokens[1], 'base64', 'utf8') + cipher.final('utf8');
resource = JSON.parse(plaintext);
if (!resource || typeof resource !== 'object' || typeof resource.d !== 'string'
|| !Array.isArray(resource.a))
throw null;
}
catch (e) {
return res.render('invalid', { details: 'Encrypted data is malformed.' });
}
var allowed;
var email = get_email(req.user);
var twitter;
var email_domains = {};
for (var i in resource.a) {
var acl = resource.a[i];
if (acl.k === 'e') {
if (email === acl.v)
allowed = true;
else
email_domains[acl.v.substring(acl.v.indexOf('@'))] = 1;
}
else if (acl.k === 'd') {
if (email && email.indexOf(acl.v, email.length - acl.v.length) !== -1)
allowed = true;
else
email_domains[acl.v] = 1;
}
else if (acl.k === 't') {
if (req.user && req.user.provider === 'twitter' && req.user._json.screen_name === acl.v)
allowed = true;
else
twitter = true;
}
if (allowed) break;
}
if (allowed) {
var model = {
data: resource.d,
user: req.user,
provider: provider_friendly_name[req.user.provider] || req.user.provider,
logout_url: '/logout'
};
res.render('data', model);
}
else {
email_domains = Object.getOwnPropertyNames(email_domains);
var model = {
auth0_client_id: process.env.AUTH0_CLIENT_ID,
auth0_domain: process.env.AUTH0_DOMAIN,
auth0_callback: process.env.AUTH0_CALLBACK,
user: req.user,
email: req.user ? get_email(req.user) : undefined,
providers: get_provider_config(twitter, email_domains, req.user ? req.user.provider : undefined),
allow_twitter: twitter,
allow_domains: email_domains,
provider: req.user ? (provider_friendly_name[req.user.provider] || req.user.provider) : undefined,
logout_url: '/logout?r=' + req.originalUrl
};
req.session.bookmark = req.originalUrl;
res.render('login', model);
}
};
}
var domain_provider_map = {
'@gmail.com': 'google-oauth2',
'@hotmail.com': 'windowslive',
'@live.com': 'windowslive',
'@outlook.com': 'windowslive',
'@msn.com': 'windowslive',
'@yahoo.com': 'yahoo'
};
function get_provider_config(twitter, email_domains, provider) {
var config = {
preferred: {},
other: []
};
if (twitter && provider !== 'twitter')
config.preferred['twitter'] = 1;
email_domains.forEach(function (domain) {
var pref = domain_provider_map[domain.toLowerCase()];
if (pref && pref !== provider)
config.preferred[pref] = 1;
});
if (email_domains.length > 0) {
for (var other in provider_friendly_name) {
if (other !== provider && !config.preferred[other])
config.other.push(other);
}
}
config.preferred = Object.getOwnPropertyNames(config.preferred);
return config;
}
function get_email(user) {
if (user && (user._json.email_verified || user.provider === 'windowslive'))
return user._json.email;
else
return undefined;
}
function ensure_key(key_name) {
if (!keys[key_name]) {
if (!process.env['SIGNATURE_KEY_' + key_name] || !process.env['ENCRYPTION_KEY_' + key_name])
throw new Error('Cryptographic credentials are not available.');
keys[key_name] = {
signature_key: new Buffer(process.env['SIGNATURE_KEY_' + process.env.CURRENT_KEY], 'hex'),
encryption_key: new Buffer(process.env['ENCRYPTION_KEY_' + process.env.CURRENT_KEY], 'hex')
};
}
return keys[key_name];
}
module.exports = app;