-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathchallenges.js
More file actions
567 lines (482 loc) · 17.2 KB
/
challenges.js
File metadata and controls
567 lines (482 loc) · 17.2 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/**
Copyright 2017-2018 Trend Micro
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this work except in compliance with the License.
You may obtain a copy of the License at
https://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.
*/
const path = require('path');
const fs = require('fs');
const util = require(path.join(__dirname, 'util'));
const config = util.getConfig();
const db = require(path.join(__dirname, 'db'));
const validator = require('validator');
const crypto = require('crypto');
const aescrypto = require(path.join(__dirname, 'aescrypto'));
const https = require('https');
const qna = require(path.join(__dirname, 'qna'));
var modules = {};
var moduleVer = 0;
var challengeDefinitions = [];
var challengeNames = [];
var solutions = [];
var descriptions = [];
var masterSalt = "";
let loadModules = () => {
let modsPath;
if(!util.isNullOrUndefined(process.env.DATA_DIR)){
modsPath = path.join(process.env.DATA_DIR, "modules.json");
}
if(util.isNullOrUndefined(modsPath) || !fs.existsSync(modsPath)){
modsPath = path.join(__dirname, "static/lessons/modules.json");
}
let moduleDefs = require(modsPath);
let localModules = {};
let moduleIds = Object.keys(moduleDefs);
for(let moduleId of moduleIds){
if(moduleId === "version"){
moduleVer = moduleDefs[moduleId];
continue;
}
let disabled = config.disabledModules;
if(util.isNullOrUndefined(disabled) || !disabled.includes(moduleId)){
localModules[moduleId] = moduleDefs[moduleId];
}
}
return Object.freeze(localModules);
}
let getModulePath = (moduleId) => {
return path.join('static/lessons/', moduleId);
}
let getDefinitionsForModule = (moduleId) => {
try {
var defs = Object.freeze(require(path.join(__dirname, getModulePath(moduleId), '/definitions.json')));
return defs;
} catch (error) {
console.log(error.message)
}
return [];
}
/**
* Initializes challenges when this module is loaded
*/
let init = async () => {
modules = loadModules();
for(let moduleId in modules){
let moduleDefinitions = getDefinitionsForModule(moduleId);
var modulePath = getModulePath(moduleId);
for(let level of moduleDefinitions){
challengeDefinitions.push(level);
for(let challenge of level.challenges){
if(!util.isNullOrUndefined(challengeNames[challenge.id])){
throw new Error(`Duplicate challenge id: '${challenge.id}'!`);
}
challengeNames[challenge.id] = challenge.name;
descriptions[challenge.id] = path.join(modulePath, challenge.description);
if(!util.isNullOrUndefined(challenge.solution)){
solutions[challenge.id] = path.join(modulePath, challenge.solution);
}
}
}
}
if(util.isNullOrUndefined(process.env.CHALLENGE_MASTER_SALT)){
util.log("WARNING. CHALLENGE_MASTER_SALT not set. Challenges may be bypassed.");
}
else{
masterSalt=process.env.CHALLENGE_MASTER_SALT;
}
try {
let dbModuleVersion = await db.getModuleVersion();
if(dbModuleVersion < moduleVer){
util.log("New training modules version, updating module completion for all users.")
recreateBadgesOnModulesUpdate();
db.updateModuleVersion(moduleVer);
if(dbModuleVersion < moduleVer){
util.log("New training modules version, updating module completion for all users.")
recreateBadgesOnModulesUpdate();
db.updateModuleVersion(moduleVer);
}
}
} catch (error) {
console.log(`Error handling module version ${error.message}`);
}
}
init();
let getModules = function(){ return modules; }
let getChallengeNames = function(){ return challengeNames; }
let isPermittedModule = async (user, moduleId) => {
let badges = await db.fetchBadges(user.id);
if(util.isNullOrUndefined(modules[moduleId])){
return false;
}
let requiredModules = modules[moduleId].requiredModules;
for(let moduleId of requiredModules){
let found = false;
for(let badge of badges){
if(badge.moduleId === moduleId){
found = true;
break;
}
}
if(!found){
return false;
}
}
return true;
}
/**
* Get the user level based on the amount of passed challenges
*/
let getUserLevelForModule = async (user,moduleId) => {
let moduleDefinitions = getDefinitionsForModule(moduleId);
let passedChallenges = await db.fetchChallengeEntriesForUser(user);
let userLevel=-1;
for(let level of moduleDefinitions){
let passCount = 0;
for(let chDef of level.challenges) {
for(let passedCh of passedChallenges){
if(chDef.id===passedCh.challengeId){
passCount++;
}
}
}
if(passCount===level.challenges.length){
userLevel = level.level;
}
else{
break;
}
}
return userLevel;
}
/**
* Get permitted challenges for module
*/
let getPermittedChallengesForUser = async (user, moduleId) => {
if(util.isNullOrUndefined(moduleId)) return [];
if(util.isNullOrUndefined(modules[moduleId])) return [];
var permittedLevel = await getUserLevelForModule(user, moduleId) + 1;
var moduleDefinitions = getDefinitionsForModule(moduleId);
for(let level of moduleDefinitions){
if (permittedLevel === level.level) {
return level.challenges;
}
}
return [];
}
/**
* Construct the challenge definitions loaded on the client side based on the users level
* @param {Array} moduleIds The lesson module ids
*/
let getChallengeDefinitions = async (moduleId) => {
var returnChallenges = [];
if(util.isNullOrUndefined(moduleId)) return [];
if(util.isNullOrUndefined(modules[moduleId])) return [];
var modulePath = getModulePath(moduleId);
var moduleDefinitions = getDefinitionsForModule(moduleId);
for(let level of moduleDefinitions){
for(let challenge of level.challenges) {
//update the play link if it exists
if (!util.isNullOrUndefined(config.playLinks)) {
var playLink = config.playLinks[challenge.id];
if (!util.isNullOrUndefined(playLink)) {
challenge.playLink = playLink;
}
}
var description = challenge.description;
if(!util.isNullOrUndefined(description) && description.indexOf(modulePath) === -1){
challenge.description = path.join(modulePath, description);
}
if(challenge.type === "quiz"){
challenge.question = qna.getCode(challenge.id);
}
}
returnChallenges.push(level);
}
return returnChallenges;
}
/**
* Returns the solution html (converted from markdown)
* @param {The challenge id} challengeId
*/
let getSolution = function (challengeId) {
var solution = solutions[challengeId];
var solutionHtml = "";
if(!util.isNullOrUndefined(solution)){
var solutionMarkDown = fs.readFileSync(path.join(__dirname, solution),'utf8');
solutionHtml = util.parseMarkdown(solutionMarkDown);
}
return solutionHtml;
}
/**
* Returns the description html (converted from markdown if applicable)
* @param {The challenge id} challengeId
*/
let getDescription = function (challengeId) {
var description = descriptions[challengeId];
var descriptionHtml = "";
if(util.isNullOrUndefined(description)) return "";
var descriptionPath = path.join(__dirname, description);
if(!fs.existsSync(descriptionPath)) return "";
var descriptionText = fs.readFileSync(descriptionPath,'utf8');
if(description.endsWith(".md")){
descriptionHtml = util.parseMarkdown(descriptionText);
}
else{
descriptionHtml = descriptionText;
}
return descriptionHtml;
}
/**
* Checks if the user has completed the module and issue a badge
*/
let verifyModuleCompletion = async (user, moduleId) => {
var userLevel = await getUserLevelForModule(user, moduleId);
let moduleDefinitions = getDefinitionsForModule(moduleId);
var lastLevel = moduleDefinitions[moduleDefinitions.length-1];
if(lastLevel.level===userLevel){
//training module complete
let badges = await db.fetchBadges(user.id);
let found = false;
for(let badge of badges){
if(badge.moduleId===moduleId){
found = true;
break;
}
}
if(!found){
util.log(`WARN: Fixed badge for module ${moduleId} for user.`, user);
await db.insertBadge(user.id, moduleId);
}
return true;
}
return false;
}
/**
* Iterates through the entire list of users to insert badges where needed
*/
let recreateBadgesOnModulesUpdate = async () => {
let users = await db.fetchUsersWithId();
for(let user of users){
let entries = await db.fetchChallengeEntriesForUser(user);
var passedChallenges = [];
for(let entry of entries){
passedChallenges.push(entry.challengeId);
}
user.passedChallenges = passedChallenges;
for(let moduleId in modules){
try {
await verifyModuleCompletion(user, moduleId);
} catch (error) {
util.log("Error with badge verification.", user);
}
}
}
}
/**
* Retrieves a code to verify completion of the level
* @param {Badge} badge
*/
let getBadgeCode = (badge, user) => {
let module = modules[badge.moduleId];
if(util.isNullOrUndefined(module) || util.isNullOrUndefined(module.badgeInfo)) return null;
let info = {
badgeInfo: module.badgeInfo,
givenName: user.givenName,
familyName: user.familyName,
completion: badge.timestamp,
idHash: crypto.createHash('sha256').update(user.id+masterSalt).digest('hex').substr(0,10)
}
let infoStr = JSON.stringify(info);
let buf = Buffer.from(infoStr);
let encoded = buf.toString('base64');
let integrity = crypto.createHash('sha256').update(encoded+masterSalt).digest('base64');
let code = `${encoded}.${integrity}`;
return encodeURIComponent(code);
}
/**
* Verifies a badge code and returns parsed info
* @param {Base64} badgeCode
*/
let verifyBadgeCode = (badgeCode) => {
urlDecoded = decodeURIComponent(badgeCode);
let parts = urlDecoded.split(".");
if(parts.length !== 2) return null;
//verify the hash matches
let vfHash = crypto.createHash('sha256').update(parts[0]+masterSalt).digest('base64');
if(vfHash !== parts[1]) return null;
try {
let decoded = Buffer.from(parts[0],"Base64").toString();
let parsed = JSON.parse(decoded);
return parsed;
} catch {
}
return null;
}
/**
* Issue a badge for achieving a level
* @param {*} badgrInfo
* @param {*} user
*/
let badgrCall = function(badgrInfo, user){
if(!util.isNullOrUndefined(badgrInfo) && !util.isNullOrUndefined(config.encBadgrToken)){
if(user.email===null){
util.log("Cannot issue badge for this user. E-mail is null.", user);
}
else{
var token = aescrypto.decrypt(config.encBadgrToken);
badgrInfo.recipient_identifier = user.email;
badgrInfo.narrative+=" Awarded to "+user.givenName+" "+user.familyName+".";
var postData = JSON.stringify(badgrInfo);
var postOptions = {
host: 'api.badgr.io',
port: '443',
path: '/v1/issuer/issuers/'+badgrInfo.issuer+'/badges/'+badgrInfo.badge_class+'/assertions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'Authorization':'Token '+token
}
};
try
{
// Set up the request
var postReq = https.request(postOptions, function(res) {
if(res!==null && !util.isNullOrUndefined(res.statusCode) && res.statusCode === 201){
util.log("Badgr Open Badge issued successfully.");
}
else{
util.log("Badgr Open Badge could not be issued.");
}
});
// post the data
postReq.write(postData);
postReq.end();
}
catch(ex){
util.log(ex);
}
}
}
}
/**
* Logic to for the api challenge code
*/
let apiChallengeCode = async (req) => {
if(util.isNullOrUndefined(req.body.challengeId) ||
util.isNullOrUndefined(req.body.challengeCode) ||
util.isNullOrUndefined(req.body.moduleId)){
throw Error("invalidRequest");
}
var moduleId = req.body.moduleId.trim();
var challengeId = req.body.challengeId.trim();
var challengeCode = req.body.challengeCode.trim();
let challengeType = "page";
if(!util.isNullOrUndefined(req.body.challengeType)){
challengeType = req.body.challengeType;
}
if(["page","quiz"].indexOf(challengeType) === -1){
throw Error("invalidChallengeType");
}
let answer = null;
if(!util.isNullOrUndefined(req.body.answer)){
answer = req.body.answer.trim();
}
if(util.isNullOrUndefined(challengeCode) ||
(validator.isAlphanumeric(challengeCode) === false && validator.isBase64(challengeCode) === false) ){
throw Error("invalidCode");
}
if(util.isNullOrUndefined(moduleId) || validator.isAlphanumeric(moduleId) === false){
throw Error("invalidModuleId");
}
if(util.isNullOrUndefined(challengeId) || util.isAlphanumericOrUnderscore(challengeId) === false){
throw Error("invalidChallengeId");
}
//check id
var availableChallenges = null;
var curChallengeObj = null;
//identify the current challenge object and also the available challenges for the current user level
var availableChallenges = await getPermittedChallengesForUser(req.user, moduleId);
//search for the current challenge id
for(let availableChallenge of availableChallenges){
if(challengeId === availableChallenge.id){
curChallengeObj = availableChallenge;
break;
}
}
if(curChallengeObj===null){
throw Error("challengeNotAvailable");
}
//calculate the hash
let ms = "";
if(util.isNullOrUndefined(modules[moduleId].skipMasterSalt) || modules[moduleId].skipMasterSalt===false){
ms = masterSalt;
}
if(challengeType !== "quiz"){
answer = challengeId+req.user.codeSalt;
}
//either hex or base64 formats should work
let verificationHashB64 = crypto.createHash('sha256').update(answer+ms).digest('base64');
let verificationHashHex = crypto.createHash('sha256').update(answer+ms).digest('hex');
if(challengeCode.indexOf(verificationHashB64)!==0 && challengeCode.indexOf(verificationHashHex)!==0){
if(challengeType === "quiz"){
throw Error("invalidAnswer");
}
else{
throw Error("invalidCode");
}
}
//success update challenge
curChallengeObj.moduleId = moduleId;
return insertChallengeEntry(req.user, curChallengeObj, moduleId);
}
/**
* Inserts a challenge entry
*/
let insertChallengeEntry = async (user,curChallengeObj, moduleId) => {
await db.getPromise(db.insertChallengeEntry, [user.id,curChallengeObj.id]);
//issue badgr badge if enabled
badgrCall(curChallengeObj.badgrInfo,user);
let isModuleComplete = await verifyModuleCompletion(user,moduleId);
//check to see if the user levelled up
curChallengeObj.moduleComplete = isModuleComplete;
if(isModuleComplete){
util.log(`User has solved the challenge ${curChallengeObj.name} and completed the module!`, user);
//issue badgr badge if enabled for module
badgrCall(modules[moduleId].badgrInfo,user);
return {
"message":"Congratulations you solved the challenge and completed the module! You can now get your badge of completion.",
"data":curChallengeObj
}
}
else{
util.log(`User has solved the challenge ${curChallengeObj.name}!`, user);
return {
"message":"Congratulations you solved the challenge!",
"data": curChallengeObj
}
}
}
module.exports = {
apiChallengeCode,
badgrCall,
getBadgeCode,
getChallengeNames,
getChallengeDefinitions,
getDescription,
getModules,
getPermittedChallengesForUser,
getUserLevelForModule,
getSolution,
insertChallengeEntry,
isPermittedModule,
verifyBadgeCode,
verifyModuleCompletion,
recreateBadgesOnModulesUpdate
}