-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
401 lines (312 loc) · 9.71 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
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
const express = require('express');
const party = require('ssb-party');
const ssbHelpers = require('./lib/ssb-helpers');
const serveStatic = require('serve-static');
const compression = require('compression');
const history = require('connect-history-api-fallback');
const parseJsonBody = require('body-parser').json()
const parsePlaintextBody = require('body-parser').text()
const argv = require('yargs').argv
// passport
const passport = require('passport');
const jwt = require('jsonwebtoken')
const passportJWT = require("passport-jwt");
const ExtractJwt = passportJWT.ExtractJwt;
const JwtStrategy = passportJWT.Strategy;
var sbot = null;
var login = require('./lib/login')
// parse CLI args
const imagePort = argv.imageport || process.argv.IMAGEPORT || 8081;
const mainPort = argv.port || process.env.PORT || 8080;
// setting the domain is required for hosting because we need to set the URL where images are stored
// in production this should probably be a subdomain or something
// but not required for a single local machine
// TODO this is a bit of a cluster
const domain = argv.domain || process.env.DOMAIN || '/';
var imageDomain = argv.imagedomain || process.env.IMAGEDOMAIN || 'http://localhost:'+imagePort;
const listenAddress = argv.listenaddress || process.env.LISTENADDRESS || '127.0.0.1'
ssbHelpers.configure({
domain,
imageDomain,
listenAddress
});
// create express apps
const compressionMiddleware = compression({});
const imageApp = express();
imageApp.use(compressionMiddleware);
const app = express();
app.use(compressionMiddleware)// defaults for now
app.set('view engine', 'ejs');
// Passport config
var jwtOptions = {
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey : login.getSessionSecretSync(),
algorithms:['HS512']
}
// where the magic happens
passport.use(new JwtStrategy(jwtOptions,function(payload, done) {
// it's fine
return done(null,payload);
}
));
var ensureAuthenticated = passport.authenticate('jwt', { session: false });
app.use(passport.initialize());
app.post('/login',parseJsonBody,function(req,res,next){
var password;
var newPassword;
if(req.body.password && req.body.newPassword){
password = req.body.password;
newPassword = req.body.newPassword;
}else if(req.body.password){
password = req.body.password;
}else{
return next(new Error('password not provided'))
}
function passwordChecked(er,ok){
if(er){
res.status(500)
res.send('error authenticating, please try again '+er);
return;
}else{
if(ok){// password matched
// NOW we need to check whoami to get the userid and B Out
ssbHelpers.whoami(sbot,function(er,id){
if(er){
res.status(500);
res.send('server error while authenticating, please try again '+er);
return;
}
var payload = {userid:id};
var token = jwt.sign(payload, jwtOptions.secretOrKey, {algorithm:'HS512'});
res.status(200);
res.json({token: token, userid:id});
})
}else{// password didn't match
res.status(401)
res.send("Incorrect Login")
}
}
}
if (newPassword){
// try change password
login.changePassword(password,newPassword,passwordChecked);
}else{
// try login
login.authorize(password,passwordChecked);
}
});
// simple callbacky methods to get stuff
app.get('/entries',ensureAuthenticated,function(req,res,next){
var n = 100;
var start = Date.now() + 60*1000;
if(req.query && req.query.count){
n = Number(req.query.count);
}
if(req.query && req.query.start){
start = Number(req.query.start);
}
ssbHelpers.getEntries(sbot,{start:start,count:n},function(er,results){
if(er){return next(er);}
res.status(200).json(results);
})
});
app.get('/posts',ensureAuthenticated,function(req,res,next){
var n = 100;
var start = Date.now() + 60*1000;
if(req.query && req.query.count){
n = Number(req.query.count);
}
if(req.query && req.query.start){
start = Number(req.query.start);
}
ssbHelpers.getPosts(sbot,{start:start,count:n},function(er,results){
if(er){return next(er);}
res.status(200).json(results);
})
});
app.get('/friendsPosts',ensureAuthenticated,function(req,res,next){
var n = 100;
var start = Date.now() + 60*1000;
if(req.query && req.query.count){
n = Number(req.query.count);
}
if(req.query && req.query.start){
start = Number(req.query.start);
}
ssbHelpers.getFriendsPosts(sbot,{start:start,count:n},function(er,results){
if(er){return next(er);}
res.status(200).json(results);
})
});
app.get('/userPosts',ensureAuthenticated,function(req,res,next){
var count = 100;
var start = Infinity;
var id='';
if(req.query && req.query.count){
count = Number(req.query.count);
}
if(req.query && req.query.start){
start = Number(req.query.start);
}
if(req.query && req.query.id){
id = req.query.id;
}else{
throw new Error('ID parameter is required')
}
ssbHelpers.getUserPosts(sbot,{id,start,count},function(er,results){
if(er){return next(er);}
res.status(200).json(results);
})
});
app.put('/post',ensureAuthenticated,parseJsonBody,function(req,res,next){
if(!req.body){
return next(new Error('bad request body'))
}
ssbHelpers.createPost(sbot,req.body,function(er,post){
if(er){
return next(er);
}
res.status(200);
return res.json(post);
})
});
app.get('/thread/:id',ensureAuthenticated,function(req,res,next){
ssbHelpers.getThread(sbot,req.params.id,function(er,data){
if(er){return next(er)}
res.status(200);
res.json(data);
})
})
app.put('/addInvite',ensureAuthenticated,parsePlaintextBody,function(req,res,next){
if(!req.body){
return next(new Error('bad request body'))
}
ssbHelpers.addInvite(sbot,req.body,function(er){
if(er){return next(er)}
res.status(200).send();
});
})
app.put('/follow',ensureAuthenticated,parsePlaintextBody,function(req,res,next){
if(!req.body){
return next(new Error('bad request body'))
}
ssbHelpers.follow(sbot,req.body,function(er){
if(er){
return next(er);
}
res.status(200);
res.send();
})
})
app.put('/unfollow',ensureAuthenticated,parsePlaintextBody,function(req,res,next){
if(!req.body){
return next(new Error('bad request body'))
}
ssbHelpers.unfollow(sbot,req.body,function(er){
if(er){
return next(er);
}
res.status(200);
res.send();
})
})
app.put('/like',ensureAuthenticated,parseJsonBody,function(req,res,next){
if(!req.body){
return next(new Error('bad request body'))
}
ssbHelpers.createLike(sbot,req.body,function(er,post){
if(er){
return next(er);
}
res.status(200);
return res.json(post);
})
})
app.get('/authorData/:id',ensureAuthenticated,function(req,res,next){
ssbHelpers.getAuthorData(sbot,req.params.id,function(er,data){
if(er){return next(er)}
return res.json(data);
})
})
app.get('/whoami',ensureAuthenticated,function(req,res,next){
ssbHelpers.whoami(sbot,function(er,id){
if(er){return next(er);}
res.status(200);
return res.send(id);
})
})
app.get('/channelPosts/:id',ensureAuthenticated,function(req,res,next){
var count = 100;
var start = Date.now() + 60*1000;
var channel = req.params.id;
if(req.query && req.query.count){
count = Number(req.query.count);
}
if(req.query && req.query.start){
start = Number(req.query.start);
}
ssbHelpers.getChannel(sbot,{start,count,channel},function(er,results){
if(er){return next(er);}
res.status(200).json(results);
})
})
app.put('/profile',ensureAuthenticated,parseJsonBody,function(req,res,next){
if(!req.body || !req.body.id || !req.body.value || !req.body.key){
return next(new Error('bad request body'))
}
ssbHelpers.setProfileData(sbot,req.body,function(er){
if(er){
res.status(500).send(er);
}else{
res.status(200).send()
}
})
});
// NOTE: cannot authenticate img requests 🤔
imageApp.get('/blob/:id',function(req,res,next){
var ct = 'text/plain';
if(req.query.contenttype){
ct = req.query.contenttype;
}
// blacklist certain content types
var baddies = [
'application/javascript',
'application/x-javascript',
'application/ecmascript',
'application/json',
'text/ecmascript',
'text/javascript',
'text/json',
'text/css'
];
if (baddies.indexOf(ct.toLowerCase) > -1){
return next(new Error('a malicious content-type was requested'))
}
if(!req.params.id){return next(new Error('missing blob ID'))}
ssbHelpers.pipeBlobToStream(sbot,req.params.id,res);
})
const spaRoutes = ['/','/index.html','login','/friends','/settings','/new','/me','/profile/:id','/channel/:id','/post/:id'];
spaRoutes.forEach(route=>{
// render home
app.get(route,function(req,res,next){
return res.render('index',{imageDomain})
})
});
// SPA fallback then serve static files
app.use(history());
app.use(serveStatic('public',{dotfiles:'deny'}))
//party then run the app
party(function(er,ssb){
if(er){
throw er;
}
// ready with ssb!
console.log('ssb ready');
sbot = ssb;
app.listen(mainPort,listenAddress,function(er){
console.log(`listenin' on ${listenAddress}:${mainPort} :)`)
})
imageApp.listen(imagePort,listenAddress,function(er){
console.log(`serving blobs on ${listenAddress}:${imagePort} :)`)
})
});